From eb5031bf4c29418cff978f3bdbb5d4639fd3a07a Mon Sep 17 00:00:00 2001 From: josetr <37419832+josetr@users.noreply.github.com> Date: Sat, 12 Mar 2022 21:54:39 +0000 Subject: [PATCH] Format files --- src/AST/ASTContext.cs | 2 +- src/AST/ASTVisitor.cs | 10 +- src/AST/ClassExtensions.cs | 2 +- src/AST/ClassLayout.cs | 2 +- src/AST/Comment.cs | 76 +- src/AST/Declaration.cs | 8 +- src/AST/DeclarationsList.cs | 4 +- src/AST/Field.cs | 2 +- src/AST/FunctionExtensions.cs | 48 +- src/AST/Method.cs | 2 +- src/AST/Namespace.cs | 16 +- src/AST/Property.cs | 6 +- src/AST/PropertyExtensions.cs | 2 +- src/AST/Template.cs | 16 +- src/AST/Type.cs | 78 +- src/AST/TypeExtensions.cs | 26 +- src/CLI/CLI.cs | 60 +- src/CLI/Generator.cs | 8 +- src/CLI/Options.cs | 2 +- src/Core/Compilation.cs | 2 +- src/Core/Diagnostics.cs | 4 +- src/Core/Platform.cs | 6 +- src/Core/Toolchains/MSVCToolchain.cs | 4 +- src/Core/Toolchains/ManagedToolchain.cs | 8 +- src/Core/Toolchains/XcodeToolchain.cs | 19 +- src/CppParser/Bootstrap/Bootstrap.cs | 2 +- src/Generator.Tests/AST/TestAST.cs | 16 +- src/Generator.Tests/ASTTestFixture.cs | 2 +- src/Generator.Tests/Passes/TestPasses.cs | 2 +- src/Generator.Tests/ReadNativeSymbolsTest.cs | 2 +- src/Generator/AST/ASTRecord.cs | 12 +- src/Generator/AST/Utils.cs | 4 +- src/Generator/AST/VTables.cs | 12 +- .../Extensions/FunctionExtensions.cs | 2 +- src/Generator/Generator.cs | 4 +- src/Generator/Generators/C/CCodeGenerator.cs | 8 +- src/Generator/Generators/C/CppHeaders.cs | 12 +- src/Generator/Generators/C/CppMarshal.cs | 108 +- src/Generator/Generators/C/CppSources.cs | 14 +- src/Generator/Generators/C/CppTypePrinter.cs | 162 +- src/Generator/Generators/CLI/CLIHeaders.cs | 12 +- src/Generator/Generators/CLI/CLIMarshal.cs | 34 +- src/Generator/Generators/CLI/CLISources.cs | 90 +- src/Generator/Generators/CLI/CLITemplate.cs | 2 +- .../Generators/CLI/CLITypePrinter.cs | 8 +- .../Generators/CLI/CLITypeReferences.cs | 6 +- .../Generators/CSharp/CSharpCommentPrinter.cs | 12 +- .../CSharp/CSharpExpressionPrinter.cs | 8 +- .../Generators/CSharp/CSharpMarshal.cs | 4 +- .../Generators/CSharp/CSharpSources.cs | 117 +- .../Generators/CSharp/CSharpTypePrinter.cs | 28 +- src/Generator/Generators/CodeGenerator.cs | 8 +- src/Generator/Generators/ITypePrinter.cs | 8 +- src/Generator/Generators/NAPI/NAPIMarshal.cs | 476 +-- src/Generator/Generators/NAPI/NAPISources.cs | 8 +- .../Generators/NAPI/NAPITypeCheckGen.cs | 88 +- .../Generators/NAPI/NAPITypeCheckPass.cs | 26 +- .../Generators/QuickJS/QuickJSHeaders.cs | 2 +- .../Generators/QuickJS/QuickJSMarshal.cs | 272 +- .../Generators/QuickJS/QuickJSSources.cs | 24 +- .../Generators/QuickJS/QuickJSTypeCheckGen.cs | 116 +- src/Generator/Generators/TS/TSSources.cs | 6 +- src/Generator/Generators/TS/TSTypePrinter.cs | 38 +- src/Generator/Library.cs | 10 +- src/Generator/Passes/CheckAbiParameters.cs | 20 +- .../Passes/CheckAmbiguousFunctions.cs | 4 +- src/Generator/Passes/CheckIgnoredDecls.cs | 8 +- src/Generator/Passes/CheckMacrosPass.cs | 2 +- .../Passes/CheckOperatorsOverloads.cs | 34 +- src/Generator/Passes/CheckStaticClass.cs | 4 +- src/Generator/Passes/CleanCommentsPass.cs | 4 +- .../ConstructorToConversionOperatorPass.cs | 12 +- src/Generator/Passes/DelegatesPass.cs | 36 +- src/Generator/Passes/ExpressionHelper.cs | 2 +- .../Passes/FlattenAnonymousTypesToFields.cs | 16 +- .../Passes/FunctionToInstanceMethodPass.cs | 30 +- .../GenerateAbstractImplementationsPass.cs | 26 +- src/Generator/Passes/GenerateSymbolsPass.cs | 4 +- .../Passes/GetterSetterToPropertyPass.cs | 10 +- .../Passes/HandleDefaultParamValuesPass.cs | 2 +- .../MakeProtectedNestedTypesPublicPass.cs | 2 +- .../Passes/MultipleInheritancePass.cs | 4 +- .../Passes/ParamTypeToInterfacePass.cs | 2 +- src/Generator/Passes/Pass.cs | 38 +- src/Generator/Passes/RenamePass.cs | 32 +- ...izationMethodsWithDependentPointersPass.cs | 4 +- src/Generator/Passes/SymbolsCodeGenerator.cs | 10 +- src/Generator/Passes/ValidateOperatorsPass.cs | 2 +- src/Generator/Types/DeclMapDatabase.cs | 2 +- src/Generator/Types/Std/Stdlib.CLI.cs | 26 +- src/Generator/Types/Std/Stdlib.CSharp.cs | 8 +- src/Generator/Types/TypeMap.cs | 68 +- src/Generator/Types/TypeMapDatabase.cs | 2 +- src/Generator/Utils/BlockGenerator.cs | 8 +- src/Generator/Utils/ExpressionEvaluator.cs | 14 +- src/Generator/Utils/FSM/ConsoleWriter.cs | 35 +- src/Generator/Utils/FSM/DFSM.cs | 262 +- src/Generator/Utils/FSM/Minimize.cs | 128 +- src/Generator/Utils/FSM/NDFSM.cs | 146 +- src/Generator/Utils/FSM/Program.cs | 27 +- src/Generator/Utils/FSM/Transition.cs | 32 +- src/Generator/Utils/HtmlEncoder.cs | 963 ++++--- src/Generator/Utils/IEnumerableExtensions.cs | 2 +- src/Generator/Utils/Options.cs | 2560 ++++++++--------- src/Generator/Utils/TextGenerator.cs | 2 +- src/Parser/ASTConverter.cs | 212 +- src/Parser/Parser.cs | 8 +- src/Parser/ParserOptions.cs | 760 ++--- src/Runtime/SymbolResolver.cs | 56 +- src/Runtime/UTF8Marshaller.cs | 6 +- tests/CSharp/CSharp.Gen.cs | 20 +- tests/CSharp/CSharp.Tests.cs | 50 +- tests/Common/Common.Tests.cs | 24 +- .../NamespacesDerived.Tests.cs | 4 +- tests/StandardLib/StandardLib.Tests.cs | 1 - 115 files changed, 4017 insertions(+), 3895 deletions(-) diff --git a/src/AST/ASTContext.cs b/src/AST/ASTContext.cs index 42302939..9aafd38a 100644 --- a/src/AST/ASTContext.cs +++ b/src/AST/ASTContext.cs @@ -144,7 +144,7 @@ namespace CppSharp.AST public void SetEnumAsFlags(string name) { var enums = FindEnum(name); - foreach(var @enum in enums) + foreach (var @enum in enums) @enum.SetFlags(); } diff --git a/src/AST/ASTVisitor.cs b/src/AST/ASTVisitor.cs index 9e6c2756..78ecb58a 100644 --- a/src/AST/ASTVisitor.cs +++ b/src/AST/ASTVisitor.cs @@ -438,7 +438,7 @@ namespace CppSharp.AST { if (property.GetMethod != null) property.GetMethod.Visit(this); - + if (property.SetMethod != null) property.SetMethod.Visit(this); } @@ -478,8 +478,8 @@ namespace CppSharp.AST public virtual bool VisitParameterDecl(Parameter parameter) { if (!VisitDeclaration(parameter)) - return false; - + return false; + return parameter.Type.Visit(this, parameter.QualifiedType.Qualifiers); } @@ -600,7 +600,7 @@ namespace CppSharp.AST template.TemplatedVariable.Visit(this); - return true; + return true; } public virtual bool VisitVarTemplateSpecializationDecl(VarTemplateSpecialization specialization) @@ -631,7 +631,7 @@ namespace CppSharp.AST if (VisitOptions.VisitNamespaceEnums) foreach (var decl in context.Enums) - decl.Visit(this); + decl.Visit(this); if (VisitOptions.VisitNamespaceTemplates) foreach (var decl in context.Templates) diff --git a/src/AST/ClassExtensions.cs b/src/AST/ClassExtensions.cs index 178418de..ccf318c5 100644 --- a/src/AST/ClassExtensions.cs +++ b/src/AST/ClassExtensions.cs @@ -39,7 +39,7 @@ namespace CppSharp.AST foreach (var @base in @class.Bases) { if (!@base.IsClass) continue; - foreach(var elem in @base.Class.FindHierarchy(func)) + foreach (var elem in @base.Class.FindHierarchy(func)) yield return elem; } } diff --git a/src/AST/ClassLayout.cs b/src/AST/ClassLayout.cs index 65824e8f..f22a278d 100644 --- a/src/AST/ClassLayout.cs +++ b/src/AST/ClassLayout.cs @@ -99,7 +99,7 @@ namespace CppSharp.AST /// Provides native argument ABI information. public RecordArgABI ArgABI { get; set; } - + /// Virtual function tables in Microsoft mode. public List VFTables { get; set; } diff --git a/src/AST/Comment.cs b/src/AST/Comment.cs index c74cbb16..e45db3ee 100644 --- a/src/AST/Comment.cs +++ b/src/AST/Comment.cs @@ -131,17 +131,17 @@ namespace CppSharp.AST { switch (kind) { - case CommentKind.BCPL: - case CommentKind.BCPLExcl: - return "//"; - case CommentKind.C: - case CommentKind.JavaDoc: - case CommentKind.Qt: - return " *"; - case CommentKind.BCPLSlash: - return "///"; - default: - throw new ArgumentOutOfRangeException(); + case CommentKind.BCPL: + case CommentKind.BCPLExcl: + return "//"; + case CommentKind.C: + case CommentKind.JavaDoc: + case CommentKind.Qt: + return " *"; + case CommentKind.BCPLSlash: + return "///"; + default: + throw new ArgumentOutOfRangeException(); } } @@ -149,19 +149,19 @@ namespace CppSharp.AST { switch (kind) { - case CommentKind.BCPL: - case CommentKind.BCPLSlash: - return string.Empty; - case CommentKind.C: - return "/*"; - case CommentKind.BCPLExcl: - return "//!"; - case CommentKind.JavaDoc: - return "/**"; - case CommentKind.Qt: - return "/*!"; - default: - throw new ArgumentOutOfRangeException(); + case CommentKind.BCPL: + case CommentKind.BCPLSlash: + return string.Empty; + case CommentKind.C: + return "/*"; + case CommentKind.BCPLExcl: + return "//!"; + case CommentKind.JavaDoc: + return "/**"; + case CommentKind.Qt: + return "/*!"; + default: + throw new ArgumentOutOfRangeException(); } } @@ -169,16 +169,16 @@ namespace CppSharp.AST { switch (kind) { - case CommentKind.BCPL: - case CommentKind.BCPLSlash: - case CommentKind.BCPLExcl: - return string.Empty; - case CommentKind.C: - case CommentKind.JavaDoc: - case CommentKind.Qt: - return " */"; - default: - throw new ArgumentOutOfRangeException(); + case CommentKind.BCPL: + case CommentKind.BCPLSlash: + case CommentKind.BCPLExcl: + return string.Empty; + case CommentKind.C: + case CommentKind.JavaDoc: + case CommentKind.Qt: + return " */"; + default: + throw new ArgumentOutOfRangeException(); } } } @@ -227,7 +227,7 @@ namespace CppSharp.AST public CommentCommandKind CommandKind { - get { return (CommentCommandKind) CommandId; } + get { return (CommentCommandKind)CommandId; } } public ParagraphComment ParagraphComment { get; set; } @@ -310,7 +310,7 @@ namespace CppSharp.AST Kind = DocumentationCommentKind.TParamCommandComment; Position = new List(); } - + public override void Visit(ICommentVisitor visitor) { visitor.VisitTParamCommand(this); @@ -364,7 +364,7 @@ namespace CppSharp.AST public class ParagraphComment : BlockContentComment { public List Content; - + public bool IsWhitespace; public ParagraphComment() @@ -489,7 +489,7 @@ namespace CppSharp.AST public CommentCommandKind CommandKind { - get { return (CommentCommandKind) CommandId; } + get { return (CommentCommandKind)CommandId; } } public RenderKind CommentRenderKind; diff --git a/src/AST/Declaration.cs b/src/AST/Declaration.cs index 405f1f8c..02176d6a 100644 --- a/src/AST/Declaration.cs +++ b/src/AST/Declaration.cs @@ -115,7 +115,7 @@ namespace CppSharp.AST public int LineNumberEnd { get; set; } public bool IsImplicit { get; set; } public int AlignAs { get; set; } - public int MaxFieldAlignment { get; set; } + public int MaxFieldAlignment { get; set; } private DeclarationContext @namespace; public DeclarationContext OriginalNamespace; @@ -213,7 +213,7 @@ namespace CppSharp.AST var currentNamespace = @namespace; while (currentNamespace != null) { - var isInlineNamespace = currentNamespace is Namespace {IsInline: true}; + var isInlineNamespace = currentNamespace is Namespace { IsInline: true }; if (!isInlineNamespace) namespaces.Push(currentNamespace); currentNamespace = currentNamespace.Namespace; @@ -242,7 +242,7 @@ namespace CppSharp.AST public string QualifiedLogicalName { get - { + { return GetQualifiedName( decl => GetDeclName(decl, decl.LogicalName), decl => decl.Namespace); } @@ -295,7 +295,7 @@ namespace CppSharp.AST public ISet ExcludeFromPasses; // List of preprocessed entities attached to this declaration. - public IList PreprocessedEntities; + public IList PreprocessedEntities; // Pointer to the original declaration from Clang. public IntPtr OriginalPtr; diff --git a/src/AST/DeclarationsList.cs b/src/AST/DeclarationsList.cs index a4bbbe2e..53d08386 100644 --- a/src/AST/DeclarationsList.cs +++ b/src/AST/DeclarationsList.cs @@ -82,7 +82,7 @@ namespace CppSharp.AST var offset = offsets[kind]; for (var i = GetStart(kind); i < offset; i++) { - yield return (T) this[i]; + yield return (T)this[i]; } } @@ -99,7 +99,7 @@ namespace CppSharp.AST Variable _ => Kind.Variable, Friend _ => Kind.Friend, Event _ => Kind.Event, - _ => throw new System.ArgumentOutOfRangeException(nameof(item), "Unsupported type of declaration.") + _ => throw new System.ArgumentOutOfRangeException(nameof(item), "Unsupported type of declaration.") }; } diff --git a/src/AST/Field.cs b/src/AST/Field.cs index 961088b2..70bad804 100644 --- a/src/AST/Field.cs +++ b/src/AST/Field.cs @@ -28,7 +28,7 @@ namespace CppSharp.AST Access = access; } - public Field(Field field): base(field) + public Field(Field field) : base(field) { QualifiedType = field.QualifiedType; Class = field.Class; diff --git a/src/AST/FunctionExtensions.cs b/src/AST/FunctionExtensions.cs index 5666d000..ae87e1a8 100644 --- a/src/AST/FunctionExtensions.cs +++ b/src/AST/FunctionExtensions.cs @@ -20,11 +20,11 @@ namespace CppSharp.AST (!isItaniumLikeAbi || !function.HasIndirectReturnTypeParameter)) { @params.Add(new Parameter - { - QualifiedType = pointer, - Name = "__instance", - Namespace = function - }); + { + QualifiedType = pointer, + Name = "__instance", + Namespace = function + }); } var i = 0; @@ -32,40 +32,40 @@ namespace CppSharp.AST p => p.Kind != ParameterKind.OperatorParameter && p.Kind != ParameterKind.Extension)) { @params.Add(new Parameter - { - QualifiedType = universalDelegate && + { + QualifiedType = universalDelegate && (param.Kind == ParameterKind.IndirectReturnType || param.Type.Desugar().IsPointerTo(out FunctionType functionType)) ? pointer : param.QualifiedType, - Kind = param.Kind, - Usage = param.Usage, - Name = universalDelegate ? $"arg{++i}": param.Name, - Namespace = param.Namespace - }); + Kind = param.Kind, + Usage = param.Usage, + Name = universalDelegate ? $"arg{++i}" : param.Name, + Namespace = param.Namespace + }); if (param.Kind == ParameterKind.IndirectReturnType && isInstanceMethod && isItaniumLikeAbi) { @params.Add(new Parameter - { - QualifiedType = pointer, - Name = "__instance", - Namespace = function - }); + { + QualifiedType = pointer, + Name = "__instance", + Namespace = function + }); } } if (method != null && method.IsConstructor) { - var @class = (Class) method.Namespace; + var @class = (Class)method.Namespace; if (!isItaniumLikeAbi && @class.Layout.HasVirtualBases) { @params.Add(new Parameter - { - QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.Int)), - Name = "__forBases", - Namespace = function - }); + { + QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.Int)), + Name = "__forBases", + Namespace = function + }); } } @@ -95,7 +95,7 @@ namespace CppSharp.AST public static bool NeedsSymbol(this Method method) { - Class @class = (Class) (method.OriginalFunction ?? method).Namespace; + Class @class = (Class)(method.OriginalFunction ?? method).Namespace; // virtual functions cannot really be inlined and // we don't need their symbols anyway as we call them through the v-table return (!method.IsVirtual && !method.IsSynthetized && diff --git a/src/AST/Method.cs b/src/AST/Method.cs index 0f577a24..286eb01a 100644 --- a/src/AST/Method.cs +++ b/src/AST/Method.cs @@ -112,7 +112,7 @@ namespace CppSharp.AST public Method(Function function) : base(function) { - + } public bool IsVirtual { get; set; } diff --git a/src/AST/Namespace.cs b/src/AST/Namespace.cs index 14afdf8f..ef1e9b5f 100644 --- a/src/AST/Namespace.cs +++ b/src/AST/Namespace.cs @@ -31,7 +31,7 @@ namespace CppSharp.AST public IEnumerable Events => Declarations.Events; // Used to keep track of anonymous declarations. - public Dictionary Anonymous; + public Dictionary Anonymous; // True if the context is inside an extern "C" context. public bool IsExternCContext; @@ -116,10 +116,10 @@ namespace CppSharp.AST if (@namespace == null) { @namespace = new Namespace - { - Name = name, - Namespace = this, - }; + { + Name = name, + Namespace = this, + }; Declarations.Add(@namespace); } @@ -162,7 +162,7 @@ namespace CppSharp.AST public IEnumerable FindFunction(string name, bool createDecl = false) { - if (string.IsNullOrEmpty(name)) + if (string.IsNullOrEmpty(name)) return Enumerable.Empty(); var entries = name.Split(new string[] { "::" }, @@ -177,7 +177,7 @@ namespace CppSharp.AST var function = new Function() { Name = name, Namespace = this }; Declarations.Add(function); } - + return functions; } @@ -218,7 +218,7 @@ namespace CppSharp.AST Namespaces.Select(n => n.FindClass(name, stringComparison)).FirstOrDefault(c => c != null); if (@class != null) return @class.CompleteDeclaration == null ? - @class : (Class) @class.CompleteDeclaration; + @class : (Class)@class.CompleteDeclaration; return null; } diff --git a/src/AST/Property.cs b/src/AST/Property.cs index e688013b..9b78ea7d 100644 --- a/src/AST/Property.cs +++ b/src/AST/Property.cs @@ -84,9 +84,9 @@ namespace CppSharp.AST { get { - return (SetMethod != null && + return (SetMethod != null && SetMethod.GenerationKind != GenerationKind.None) || - (Field != null && + (Field != null && (!Field.QualifiedType.IsConst() || Field.Type.IsConstCharString()) && Field.GenerationKind != GenerationKind.None); @@ -99,7 +99,7 @@ namespace CppSharp.AST public Class ExplicitInterfaceImpl { get; set; } private readonly List parameters = new List(); - + /// /// Only applicable to index ([]) properties. /// diff --git a/src/AST/PropertyExtensions.cs b/src/AST/PropertyExtensions.cs index 21345f3c..f1425994 100644 --- a/src/AST/PropertyExtensions.cs +++ b/src/AST/PropertyExtensions.cs @@ -6,7 +6,7 @@ namespace CppSharp.AST { public static bool IsInRefTypeAndBackedByValueClassField(this Property p) { - if (p.Field == null || ((Class) p.Namespace).IsRefType) + if (p.Field == null || ((Class)p.Namespace).IsRefType) return false; Type type; diff --git a/src/AST/Template.cs b/src/AST/Template.cs index 6af7fc6a..062254ee 100644 --- a/src/AST/Template.cs +++ b/src/AST/Template.cs @@ -140,8 +140,8 @@ namespace CppSharp.AST public override string Name { get => TemplatedDecl != null ? TemplatedDecl.Name : base.Name; - set - { + set + { base.Name = value; if (TemplatedDecl != null) TemplatedDecl.Name = value; @@ -208,9 +208,9 @@ namespace CppSharp.AST public override string Name { get => TemplatedDecl != null ? TemplatedClass.Name : base.Name; - set - { - if(TemplatedDecl != null) + set + { + if (TemplatedDecl != null) TemplatedClass.Name = value; else base.Name = value; @@ -220,9 +220,9 @@ namespace CppSharp.AST public override string OriginalName { get => TemplatedDecl != null ? TemplatedClass.OriginalName : base.OriginalName; - set - { - if(TemplatedDecl != null) + set + { + if (TemplatedDecl != null) TemplatedClass.OriginalName = value; else base.OriginalName = value; diff --git a/src/AST/Type.cs b/src/AST/Type.cs index 4071e966..831b9f67 100644 --- a/src/AST/Type.cs +++ b/src/AST/Type.cs @@ -92,7 +92,7 @@ namespace CppSharp.AST { if (!(obj is QualifiedType)) return false; - var type = (QualifiedType) obj; + var type = (QualifiedType)obj; return Type.Equals(type.Type) && Qualifiers.Equals(type.Qualifiers); } @@ -190,7 +190,7 @@ namespace CppSharp.AST public ArrayType(ArrayType type) : base(type) { - QualifiedType = new QualifiedType((Type) type.QualifiedType.Type.Clone(), + QualifiedType = new QualifiedType((Type)type.QualifiedType.Type.Clone(), type.QualifiedType.Qualifiers); SizeType = type.SizeType; Size = type.Size; @@ -264,7 +264,7 @@ namespace CppSharp.AST public FunctionType(FunctionType type) : base(type) { - ReturnType = new QualifiedType((Type) type.ReturnType.Type.Clone(), type.ReturnType.Qualifiers); + ReturnType = new QualifiedType((Type)type.ReturnType.Type.Clone(), type.ReturnType.Qualifiers); Parameters.AddRange(type.Parameters.Select(p => new Parameter(p))); CallingConvention = type.CallingConvention; IsDependent = type.IsDependent; @@ -326,7 +326,7 @@ namespace CppSharp.AST public PointerType(PointerType type) : base(type) { - QualifiedPointee = new QualifiedType((Type) type.QualifiedPointee.Type.Clone(), + QualifiedPointee = new QualifiedType((Type)type.QualifiedPointee.Type.Clone(), type.QualifiedPointee.Qualifiers); Modifier = type.Modifier; } @@ -341,7 +341,7 @@ namespace CppSharp.AST } public QualifiedType QualifiedPointee; - public Type Pointee { get { return QualifiedPointee.Type; } } + public Type Pointee { get { return QualifiedPointee.Type; } } public TypeModifier Modifier; @@ -382,7 +382,7 @@ namespace CppSharp.AST public MemberPointerType(MemberPointerType type) : base(type) { - QualifiedPointee = new QualifiedType((Type) type.QualifiedPointee.Type.Clone(), + QualifiedPointee = new QualifiedType((Type)type.QualifiedPointee.Type.Clone(), type.QualifiedPointee.Qualifiers); } @@ -481,8 +481,8 @@ namespace CppSharp.AST public AttributedType(AttributedType type) : base(type) { - Modified = new QualifiedType((Type) type.Modified.Type.Clone(), type.Modified.Qualifiers); - Equivalent = new QualifiedType((Type) type.Equivalent.Type.Clone(), type.Equivalent.Qualifiers); + Modified = new QualifiedType((Type)type.Modified.Type.Clone(), type.Modified.Qualifiers); + Equivalent = new QualifiedType((Type)type.Equivalent.Type.Clone(), type.Equivalent.Qualifiers); } public override T Visit(ITypeVisitor visitor, TypeQualifiers quals = new TypeQualifiers()) @@ -495,8 +495,8 @@ namespace CppSharp.AST return new AttributedType { IsDependent = IsDependent, - Modified = new QualifiedType((Type) Modified.Type.Clone(), Modified.Qualifiers), - Equivalent = new QualifiedType((Type) Equivalent.Type.Clone(), Equivalent.Qualifiers) + Modified = new QualifiedType((Type)Modified.Type.Clone(), Modified.Qualifiers), + Equivalent = new QualifiedType((Type)Equivalent.Type.Clone(), Equivalent.Qualifiers) }; } @@ -529,11 +529,11 @@ namespace CppSharp.AST public DecayedType(DecayedType type) : base(type) { - Decayed = new QualifiedType((Type) type.Decayed.Type.Clone(), + Decayed = new QualifiedType((Type)type.Decayed.Type.Clone(), type.Decayed.Qualifiers); - Original = new QualifiedType((Type) type.Original.Type.Clone(), + Original = new QualifiedType((Type)type.Original.Type.Clone(), type.Original.Qualifiers); - Pointee = new QualifiedType((Type) type.Pointee.Type.Clone(), + Pointee = new QualifiedType((Type)type.Pointee.Type.Clone(), type.Pointee.Qualifiers); } @@ -608,22 +608,22 @@ namespace CppSharp.AST public override bool Equals(object obj) { if (!(obj is TemplateArgument)) return false; - var arg = (TemplateArgument) obj; + var arg = (TemplateArgument)obj; if (Kind != arg.Kind) return false; switch (Kind) { - case ArgumentKind.Type: - return Type.Equals(arg.Type); - case ArgumentKind.Declaration: - return Declaration.Equals(arg.Declaration); - case ArgumentKind.Integral: - return Integral.Equals(arg.Integral); - case ArgumentKind.Expression: - return true; - default: - throw new Exception("Unknown TemplateArgument Kind"); + case ArgumentKind.Type: + return Type.Equals(arg.Type); + case ArgumentKind.Declaration: + return Declaration.Equals(arg.Declaration); + case ArgumentKind.Integral: + return Integral.Equals(arg.Integral); + case ArgumentKind.Expression: + return true; + default: + throw new Exception("Unknown TemplateArgument Kind"); } } @@ -669,11 +669,11 @@ namespace CppSharp.AST Declaration = t.Declaration, Integral = t.Integral, Kind = t.Kind, - Type = new QualifiedType((Type) t.Type.Type.Clone(), t.Type.Qualifiers) + Type = new QualifiedType((Type)t.Type.Type.Clone(), t.Type.Qualifiers) }).ToList(); Template = type.Template; if (type.Desugared.Type != null) - Desugared = new QualifiedType((Type) type.Desugared.Type.Clone(), + Desugared = new QualifiedType((Type)type.Desugared.Type.Clone(), type.Desugared.Qualifiers); } @@ -749,9 +749,9 @@ namespace CppSharp.AST Declaration = t.Declaration, Integral = t.Integral, Kind = t.Kind, - Type = new QualifiedType((Type) t.Type.Type.Clone(), t.Type.Qualifiers) + Type = new QualifiedType((Type)t.Type.Type.Clone(), t.Type.Qualifiers) }).ToList(); - Desugared = new QualifiedType((Type) type.Desugared.Type.Clone(), type.Desugared.Qualifiers); + Desugared = new QualifiedType((Type)type.Desugared.Type.Clone(), type.Desugared.Qualifiers); } public List Arguments; @@ -860,8 +860,8 @@ namespace CppSharp.AST public TemplateParameterSubstitutionType(TemplateParameterSubstitutionType type) : base(type) { - Replacement = new QualifiedType((Type) type.Replacement.Type.Clone(), type.Replacement.Qualifiers); - ReplacedParameter = (TemplateParameterType) type.ReplacedParameter.Clone(); + Replacement = new QualifiedType((Type)type.Replacement.Type.Clone(), type.Replacement.Qualifiers); + ReplacedParameter = (TemplateParameterType)type.ReplacedParameter.Clone(); } public override T Visit(ITypeVisitor visitor, @@ -905,9 +905,9 @@ namespace CppSharp.AST : base(type) { if (type.TemplateSpecialization != null) - TemplateSpecialization = (TemplateSpecializationType) type.TemplateSpecialization.Clone(); + TemplateSpecialization = (TemplateSpecializationType)type.TemplateSpecialization.Clone(); InjectedSpecializationType = new QualifiedType( - (Type) type.InjectedSpecializationType.Type.Clone(), + (Type)type.InjectedSpecializationType.Type.Clone(), type.InjectedSpecializationType.Qualifiers); Class = type.Class; } @@ -1227,13 +1227,13 @@ namespace CppSharp.AST { switch (Type) { - case PrimitiveType.Bool: - case PrimitiveType.UChar: - case PrimitiveType.UShort: - case PrimitiveType.UInt: - case PrimitiveType.ULong: - case PrimitiveType.ULongLong: - return true; + case PrimitiveType.Bool: + case PrimitiveType.UChar: + case PrimitiveType.UShort: + case PrimitiveType.UInt: + case PrimitiveType.ULong: + case PrimitiveType.ULongLong: + return true; } return false; diff --git a/src/AST/TypeExtensions.cs b/src/AST/TypeExtensions.cs index 40890f40..ed740fb4 100644 --- a/src/AST/TypeExtensions.cs +++ b/src/AST/TypeExtensions.cs @@ -33,7 +33,7 @@ public static bool IsEnumType(this Type t) { var tag = t.Desugar() as TagType; - + if (tag == null) return false; @@ -131,20 +131,20 @@ type.Desugared.Type.TryGetDeclaration(out decl, value); return decl != null; case ClassTemplate classTemplate: - { - var templatedClass = classTemplate.TemplatedClass; - decl = templatedClass.CompleteDeclaration == null - ? templatedClass as T - : (T) templatedClass.CompleteDeclaration; + { + var templatedClass = classTemplate.TemplatedClass; + decl = templatedClass.CompleteDeclaration == null + ? templatedClass as T + : (T)templatedClass.CompleteDeclaration; - if (decl == null) - return false; + if (decl == null) + return false; - if (value != null) - type.Template = new ClassTemplate { TemplatedDecl = value }; + if (value != null) + type.Template = new ClassTemplate { TemplatedDecl = value }; - return true; - } + return true; + } case TemplateTemplateParameter templateTemplateParameter: return (decl = templateTemplateParameter.TemplatedDecl as T) != null; } @@ -316,7 +316,7 @@ if (type == null) return null; - + var pointee = type.Desugar().GetPointee(); if (pointee.IsPointer()) diff --git a/src/CLI/CLI.cs b/src/CLI/CLI.cs index 4306ca7d..54b2ed6c 100644 --- a/src/CLI/CLI.cs +++ b/src/CLI/CLI.cs @@ -10,36 +10,36 @@ namespace CppSharp { private static OptionSet optionSet = new OptionSet(); private static Options options = new Options(); - + static bool ParseCommandLineArgs(string[] args, List errorMessages, ref bool helpShown) { var showHelp = false; optionSet.Add("I=", "the {PATH} of a folder to search for include files", (i) => { AddIncludeDirs(i, errorMessages); }); - optionSet.Add("l=", "{LIBRARY} that that contains the symbols of the generated code", l => options.Libraries.Add(l) ); - optionSet.Add("L=", "the {PATH} of a folder to search for additional libraries", l => options.LibraryDirs.Add(l) ); - optionSet.Add("D:", "additional define with (optional) value to add to be used while parsing the given header files", (n, v) => AddDefine(n, v, errorMessages) ); - optionSet.Add("A=", "additional Clang arguments to pass to the compiler while parsing the given header files", (v) => AddArgument(v, errorMessages) ); + optionSet.Add("l=", "{LIBRARY} that that contains the symbols of the generated code", l => options.Libraries.Add(l)); + optionSet.Add("L=", "the {PATH} of a folder to search for additional libraries", l => options.LibraryDirs.Add(l)); + optionSet.Add("D:", "additional define with (optional) value to add to be used while parsing the given header files", (n, v) => AddDefine(n, v, errorMessages)); + optionSet.Add("A=", "additional Clang arguments to pass to the compiler while parsing the given header files", (v) => AddArgument(v, errorMessages)); - optionSet.Add("o=|output=", "the {PATH} for the generated bindings file (doesn't need the extension since it will depend on the generator)", v => HandleOutputArg(v, errorMessages) ); - optionSet.Add("on=|outputnamespace=", "the {NAMESPACE} that will be used for the generated code", on => options.OutputNamespace = on ); + optionSet.Add("o=|output=", "the {PATH} for the generated bindings file (doesn't need the extension since it will depend on the generator)", v => HandleOutputArg(v, errorMessages)); + optionSet.Add("on=|outputnamespace=", "the {NAMESPACE} that will be used for the generated code", on => options.OutputNamespace = on); optionSet.Add("m=|module=", "the name for the generated {MODULE}", a => { options.OutputFileName = a; }); - optionSet.Add("iln=|inputlibraryname=|inputlib=", "the {NAME} of the shared library that contains the symbols of the generated code", iln => options.InputLibraryName = iln ); + optionSet.Add("iln=|inputlibraryname=|inputlib=", "the {NAME} of the shared library that contains the symbols of the generated code", iln => options.InputLibraryName = iln); optionSet.Add("d|debug", "enables debug mode which generates more verbose code to aid debugging", v => options.Debug = true); optionSet.Add("c|compile", "enables automatic compilation of the generated code", v => options.Compile = true); - optionSet.Add("g=|gen=|generator=", "the {TYPE} of generated code: 'csharp' or 'cli' ('cli' supported only for Windows)", g => { GetGeneratorKind(g, errorMessages); } ); - optionSet.Add("p=|platform=", "the {PLATFORM} that the generated code will target: 'win', 'osx' or 'linux'", p => { GetDestinationPlatform(p, errorMessages); } ); - optionSet.Add("a=|arch=", "the {ARCHITECTURE} that the generated code will target: 'x86' or 'x64'", a => { GetDestinationArchitecture(a, errorMessages); } ); + optionSet.Add("g=|gen=|generator=", "the {TYPE} of generated code: 'csharp' or 'cli' ('cli' supported only for Windows)", g => { GetGeneratorKind(g, errorMessages); }); + optionSet.Add("p=|platform=", "the {PLATFORM} that the generated code will target: 'win', 'osx' or 'linux'", p => { GetDestinationPlatform(p, errorMessages); }); + optionSet.Add("a=|arch=", "the {ARCHITECTURE} that the generated code will target: 'x86' or 'x64'", a => { GetDestinationArchitecture(a, errorMessages); }); optionSet.Add("prefix=", "sets a string prefix to the names of generated files", a => { options.Prefix = a; }); optionSet.Add("exceptions", "enables support for C++ exceptions in the parser", v => { options.EnableExceptions = true; }); optionSet.Add("rtti", "enables support for C++ RTTI in the parser", v => { options.EnableRTTI = true; }); - optionSet.Add("c++11", "enables GCC C++ 11 compilation (valid only for Linux platform)", cpp11 => { options.Cpp11ABI = (cpp11 != null); } ); - optionSet.Add("cs|checksymbols", "enable the symbol check for the generated code", cs => { options.CheckSymbols = (cs != null); } ); - optionSet.Add("ub|unitybuild|unity", "enable unity build", ub => { options.UnityBuild = (ub != null); } ); + optionSet.Add("c++11", "enables GCC C++ 11 compilation (valid only for Linux platform)", cpp11 => { options.Cpp11ABI = (cpp11 != null); }); + optionSet.Add("cs|checksymbols", "enable the symbol check for the generated code", cs => { options.CheckSymbols = (cs != null); }); + optionSet.Add("ub|unitybuild|unity", "enable unity build", ub => { options.UnityBuild = (ub != null); }); optionSet.Add("v|verbose", "enables verbose mode", v => { options.Verbose = true; }); optionSet.Add("h|help", "shows the help", hl => { showHelp = (hl != null); }); @@ -55,7 +55,7 @@ namespace CppSharp Console.WriteLine(e.Message); return false; } - + if (showHelp || additionalArguments != null && additionalArguments.Count == 0) { helpShown = true; @@ -63,7 +63,7 @@ namespace CppSharp return false; } - foreach(string s in additionalArguments) + foreach (string s in additionalArguments) HandleAdditionalArgument(s, errorMessages); return true; @@ -117,7 +117,7 @@ namespace CppSharp var dir = Path.HasExtension(arg) ? Path.GetDirectoryName(arg) : Path.GetFullPath(arg); options.OutputDir = dir; } - catch(Exception e) + catch (Exception e) { errorMessages.Add(e.Message); @@ -159,7 +159,7 @@ namespace CppSharp errorMessages.Add($"File '{args}' could not be found."); } } - catch(Exception) + catch (Exception) { errorMessages.Add($"Error while looking for files inside path '{args}'. Ignoring."); } @@ -278,23 +278,23 @@ namespace CppSharp List errorMessages = new List(); bool helpShown = false; - if (!ParseCommandLineArgs(args, errorMessages, ref helpShown)) - { - PrintErrorMessages(errorMessages); + if (!ParseCommandLineArgs(args, errorMessages, ref helpShown)) + { + PrintErrorMessages(errorMessages); - // Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown - return; - } + // Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown + return; + } - Generator gen = new Generator(options); + Generator gen = new Generator(options); - bool validOptions = gen.ValidateOptions(errorMessages); - PrintErrorMessages(errorMessages); + bool validOptions = gen.ValidateOptions(errorMessages); + PrintErrorMessages(errorMessages); - if (errorMessages.Any() || !validOptions) - Environment.Exit(1); + if (errorMessages.Any() || !validOptions) + Environment.Exit(1); - gen.Run(); + gen.Run(); } } } \ No newline at end of file diff --git a/src/CLI/Generator.cs b/src/CLI/Generator.cs index d84954b1..5c6f72be 100644 --- a/src/CLI/Generator.cs +++ b/src/CLI/Generator.cs @@ -45,7 +45,7 @@ namespace CppSharp if (options.Architecture == TargetArchitecture.x64) tripleBuilder.Append("x86_64-"); - else if(options.Architecture == TargetArchitecture.x86) + else if (options.Architecture == TargetArchitecture.x86) tripleBuilder.Append("i686-"); if (options.Platform == TargetPlatform.Windows) @@ -63,7 +63,7 @@ namespace CppSharp tripleBuilder.Append("linux-gnu"); abi = CppAbi.Itanium; - if(options.Cpp11ABI) + if (options.Cpp11ABI) tripleBuilder.Append("-cxx11abi"); } @@ -118,7 +118,7 @@ namespace CppSharp driverOptions.GeneratorKind = options.Kind; var module = driverOptions.AddModule(options.OutputFileName); - if(!string.IsNullOrEmpty(options.InputLibraryName)) + if (!string.IsNullOrEmpty(options.InputLibraryName)) module.SharedLibraryName = options.InputLibraryName; module.Headers.AddRange(options.HeaderFiles); @@ -143,7 +143,7 @@ namespace CppSharp foreach (KeyValuePair d in options.Defines) { - if(string.IsNullOrEmpty(d.Value)) + if (string.IsNullOrEmpty(d.Value)) parserOptions.AddDefines(d.Key); else parserOptions.AddDefines(d.Key + "=" + d.Value); diff --git a/src/CLI/Options.cs b/src/CLI/Options.cs index 0caa2b6b..f679287c 100644 --- a/src/CLI/Options.cs +++ b/src/CLI/Options.cs @@ -32,7 +32,7 @@ namespace CppSharp public string InputLibraryName { get; set; } public string Prefix { get; set; } - + public TargetPlatform? Platform { get; set; } public TargetArchitecture Architecture { get; set; } = TargetArchitecture.x86; diff --git a/src/Core/Compilation.cs b/src/Core/Compilation.cs index 4b3dcf28..011ab982 100644 --- a/src/Core/Compilation.cs +++ b/src/Core/Compilation.cs @@ -29,5 +29,5 @@ namespace CppSharp // If true, will force the generation of debug metadata for the native // and managed code. public bool DebugMode; - } + } } diff --git a/src/Core/Diagnostics.cs b/src/Core/Diagnostics.cs index a89b3bb7..a7f40ac6 100644 --- a/src/Core/Diagnostics.cs +++ b/src/Core/Diagnostics.cs @@ -120,11 +120,11 @@ namespace CppSharp var currentIndentation = Indents.Sum(); var message = new string(' ', currentIndentation) + info.Message; - if(info.Kind == DiagnosticKind.Error) + if (info.Kind == DiagnosticKind.Error) { Console.Error.WriteLine(message); } - else + else { Console.WriteLine(message); } diff --git a/src/Core/Platform.cs b/src/Core/Platform.cs index 093f19da..d0500f29 100644 --- a/src/Core/Platform.cs +++ b/src/Core/Platform.cs @@ -84,13 +84,13 @@ namespace CppSharp { if (IsWindows) return TargetPlatform.Windows; - + if (IsMacOS) return TargetPlatform.MacOS; - + if (IsLinux) return TargetPlatform.Linux; - + throw new NotImplementedException(); } } diff --git a/src/Core/Toolchains/MSVCToolchain.cs b/src/Core/Toolchains/MSVCToolchain.cs index 6ec99c43..605825c3 100644 --- a/src/Core/Toolchains/MSVCToolchain.cs +++ b/src/Core/Toolchains/MSVCToolchain.cs @@ -55,7 +55,7 @@ namespace CppSharp switch (vsVersion) { case VisualStudioVersion.VS2012: - clVersion = new Version { Major = 17, Minor = 0}; + clVersion = new Version { Major = 17, Minor = 0 }; break; case VisualStudioVersion.VS2013: clVersion = new Version { Major = 18, Minor = 0 }; @@ -108,7 +108,7 @@ namespace CppSharp int windowsSdkMajorVer, List windowsSdks) { var majorWindowsSdk = windowsSdks.Find( - version => (int) Math.Floor(version.Version) == windowsSdkMajorVer); + version => (int)Math.Floor(version.Version) == windowsSdkMajorVer); var windowsSdkDirs = majorWindowsSdk.Directory != null ? new[] { majorWindowsSdk.Directory } : windowsSdks.Select(w => w.Directory).Reverse(); diff --git a/src/Core/Toolchains/ManagedToolchain.cs b/src/Core/Toolchains/ManagedToolchain.cs index 7038f6bc..9ae43193 100644 --- a/src/Core/Toolchains/ManagedToolchain.cs +++ b/src/Core/Toolchains/ManagedToolchain.cs @@ -10,18 +10,18 @@ namespace CppSharp { public static string ReadMonoPathFromWindowsRegistry(bool prefer64bits = false) { - using (var baseKey = RegistryKey.OpenBaseKey (RegistryHive.LocalMachine, + using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, prefer64bits ? RegistryView.Registry64 : RegistryView.Registry32)) { if (baseKey == null) return null; - using (var subKey = baseKey.OpenSubKey (@"SOFTWARE\Mono")) + using (var subKey = baseKey.OpenSubKey(@"SOFTWARE\Mono")) { if (subKey == null) return null; - return (string)subKey.GetValue ("SdkInstallRoot", ""); + return (string)subKey.GetValue("SdkInstallRoot", ""); } } } @@ -33,7 +33,7 @@ namespace CppSharp // Try to lookup the Mono SDK path from registry. string path = ReadMonoPathFromWindowsRegistry(prefer64bits); if (!string.IsNullOrEmpty(path)) - return path; + return path; // If that fails, then lets try a default location. return @"C:\Program Files (x86)\Mono"; diff --git a/src/Core/Toolchains/XcodeToolchain.cs b/src/Core/Toolchains/XcodeToolchain.cs index e6f8549d..89e03f36 100644 --- a/src/Core/Toolchains/XcodeToolchain.cs +++ b/src/Core/Toolchains/XcodeToolchain.cs @@ -25,7 +25,7 @@ namespace CppSharp throw new Exception("Could not find a valid Xcode toolchain"); return toolchainPath; - } + } public static string GetXcodeCppIncludesFolder() { @@ -68,30 +68,33 @@ namespace CppSharp return Path.Combine(sdkPath, "usr/include"); } - private static string GetXcodePathFromXcodeSelect() + private static string GetXcodePathFromXcodeSelect() { - try + try { - var xcodeSelect = Process.Start(new ProcessStartInfo("xcode-select", "--print-path") { + var xcodeSelect = Process.Start(new ProcessStartInfo("xcode-select", "--print-path") + { RedirectStandardOutput = true, UseShellExecute = false }); var result = xcodeSelect.StandardOutput.ReadToEnd(); - if(!string.IsNullOrEmpty(result)) + if (!string.IsNullOrEmpty(result)) { var extraStuffIndex = result.LastIndexOf("/Contents/Developer"); - if(extraStuffIndex >= 0) + if (extraStuffIndex >= 0) return result.Remove(extraStuffIndex); } - } catch { + } + catch + { // TODO: Log exception? } return null; } - private static string GetXcodePathFromFileSystem() + private static string GetXcodePathFromFileSystem() { var toolchains = Directory.EnumerateDirectories("/Applications", "Xcode*") .ToList(); diff --git a/src/CppParser/Bootstrap/Bootstrap.cs b/src/CppParser/Bootstrap/Bootstrap.cs index 77dc78dc..2e8b4d63 100644 --- a/src/CppParser/Bootstrap/Bootstrap.cs +++ b/src/CppParser/Bootstrap/Bootstrap.cs @@ -803,7 +803,7 @@ namespace CppSharp UnindentAndWriteCloseBrace(); } - + WriteLine($"default:"); WriteLineIndent($"throw new System.NotImplementedException(" + $"{ParamName}.StmtClass.ToString());"); diff --git a/src/Generator.Tests/AST/TestAST.cs b/src/Generator.Tests/AST/TestAST.cs index 968e7e7d..098057e7 100644 --- a/src/Generator.Tests/AST/TestAST.cs +++ b/src/Generator.Tests/AST/TestAST.cs @@ -251,11 +251,11 @@ namespace CppSharp.Generator.Tests.AST Assert.IsInstanceOf(twoParamMethod.Parameters[0].Type); Assert.IsInstanceOf(twoParamMethod.Parameters[1].Type); Assert.AreEqual(twoParamMethodTemplate.Parameters[0], - ((TemplateParameterType) twoParamMethod.Parameters[0].Type).Parameter); + ((TemplateParameterType)twoParamMethod.Parameters[0].Type).Parameter); Assert.AreEqual(twoParamMethodTemplate.Parameters[1], - ((TemplateParameterType) twoParamMethod.Parameters[1].Type).Parameter); - Assert.AreEqual(0, ((TemplateParameterType) twoParamMethod.Parameters[0].Type).Index); - Assert.AreEqual(1, ((TemplateParameterType) twoParamMethod.Parameters[1].Type).Index); + ((TemplateParameterType)twoParamMethod.Parameters[1].Type).Parameter); + Assert.AreEqual(0, ((TemplateParameterType)twoParamMethod.Parameters[0].Type).Index); + Assert.AreEqual(1, ((TemplateParameterType)twoParamMethod.Parameters[1].Type).Index); } [Test] @@ -436,20 +436,20 @@ namespace CppSharp.Generator.Tests.AST Assert.IsTrue(constExpr.IsConstExpr); var noExcept = AstContext.FindFunction("noExcept").First(); - Assert.That(((FunctionType) noExcept.FunctionType.Type).ExceptionSpecType, + Assert.That(((FunctionType)noExcept.FunctionType.Type).ExceptionSpecType, Is.EqualTo(ExceptionSpecType.BasicNoexcept)); var noExceptTrue = AstContext.FindFunction("noExceptTrue").First(); - Assert.That(((FunctionType) noExceptTrue.FunctionType.Type).ExceptionSpecType, + Assert.That(((FunctionType)noExceptTrue.FunctionType.Type).ExceptionSpecType, Is.EqualTo(ExceptionSpecType.NoexceptTrue)); var noExceptFalse = AstContext.FindFunction("noExceptFalse").First(); - Assert.That(((FunctionType) noExceptFalse.FunctionType.Type).ExceptionSpecType, + Assert.That(((FunctionType)noExceptFalse.FunctionType.Type).ExceptionSpecType, Is.EqualTo(ExceptionSpecType.NoexceptFalse)); var regular = AstContext.FindFunction("testSignature").First(); Assert.IsFalse(regular.IsConstExpr); - var regularFunctionType = (FunctionType) regular.FunctionType.Type; + var regularFunctionType = (FunctionType)regular.FunctionType.Type; Assert.That(regularFunctionType.ExceptionSpecType, Is.EqualTo(ExceptionSpecType.None)); } diff --git a/src/Generator.Tests/ASTTestFixture.cs b/src/Generator.Tests/ASTTestFixture.cs index e6130d46..2ef8aeea 100644 --- a/src/Generator.Tests/ASTTestFixture.cs +++ b/src/Generator.Tests/ASTTestFixture.cs @@ -14,7 +14,7 @@ namespace CppSharp.Generator.Tests protected Driver Driver; protected ASTContext AstContext; protected BindingContext Context; - + public ASTTestFixture(params string[] files) { this.files = files; diff --git a/src/Generator.Tests/Passes/TestPasses.cs b/src/Generator.Tests/Passes/TestPasses.cs index ae21670d..bc3e145e 100644 --- a/src/Generator.Tests/Passes/TestPasses.cs +++ b/src/Generator.Tests/Passes/TestPasses.cs @@ -273,7 +273,7 @@ namespace CppSharp.Generator.Tests.Passes static IEnumerable GetExpressionEvaluatorTestCases() { - var testNumber = 100; + var testNumber = 100; foreach (var tc in TestExpressionEvaluatorTestCases) { // "testNumber" is just used to cause the test runner to show the tests in the order diff --git a/src/Generator.Tests/ReadNativeSymbolsTest.cs b/src/Generator.Tests/ReadNativeSymbolsTest.cs index 0dc0b518..f17575f4 100644 --- a/src/Generator.Tests/ReadNativeSymbolsTest.cs +++ b/src/Generator.Tests/ReadNativeSymbolsTest.cs @@ -106,7 +106,7 @@ namespace CppSharp.Generator.Tests { var symbols = GetSymbols("linux", "libexpat"); Assert.That(symbols, Is.EquivalentTo( - new [] + new[] { ".init", "free", diff --git a/src/Generator/AST/ASTRecord.cs b/src/Generator/AST/ASTRecord.cs index 4fa9b9df..4fd44815 100644 --- a/src/Generator/AST/ASTRecord.cs +++ b/src/Generator/AST/ASTRecord.cs @@ -21,7 +21,7 @@ namespace CppSharp.Generators.AST if (!(v is T)) return false; - @out = (T) v; + @out = (T)v; return true; } @@ -48,14 +48,14 @@ namespace CppSharp.Generators.AST return true; } - return Parent != null + return Parent != null && Parent.GetAncestors(ref ancestors); } } public class ASTRecord : ASTRecord { - public T Value => (T) Object; + public T Value => (T)Object; public override string ToString() { @@ -132,7 +132,7 @@ namespace CppSharp.Generators.AST public static bool IsFieldValueType(this ASTRecord record) { var ancestors = new Stack(); - if(!record.GetAncestors(ref ancestors)) + if (!record.GetAncestors(ref ancestors)) return false; var field = (Field)ancestors.Pop(); @@ -154,7 +154,7 @@ namespace CppSharp.Generators.AST public static bool FunctionReturnsClassByValue(this ASTRecord record) { var ancestors = new Stack(); - if(!record.GetAncestors(ref ancestors)) + if (!record.GetAncestors(ref ancestors)) return false; var function = (Function)ancestors.Pop(); @@ -231,5 +231,5 @@ namespace CppSharp.Generators.AST // translation unit is encountered. return decl.Namespace.TranslationUnit == translationUnit; } - } + } } diff --git a/src/Generator/AST/Utils.cs b/src/Generator/AST/Utils.cs index d697ce40..986b5585 100644 --- a/src/Generator/AST/Utils.cs +++ b/src/Generator/AST/Utils.cs @@ -132,7 +132,7 @@ namespace CppSharp.AST template = specialization.TemplatedDecl.TemplatedClass; else { - template = (Class) method.Namespace; + template = (Class)method.Namespace; if (!template.IsDependent) return false; } @@ -219,7 +219,7 @@ namespace CppSharp.AST { public static CXXOperatorArity ClassifyOperator(Function function) { - switch(function.Parameters.Count) + switch (function.Parameters.Count) { case 0: return CXXOperatorArity.Zero; case 1: return CXXOperatorArity.Unary; diff --git a/src/Generator/AST/VTables.cs b/src/Generator/AST/VTables.cs index 8f4017ff..13add5b8 100644 --- a/src/Generator/AST/VTables.cs +++ b/src/Generator/AST/VTables.cs @@ -12,10 +12,10 @@ namespace CppSharp.AST { switch (@class.Layout.ABI) { - case CppAbi.Microsoft: - return GatherVTableMethodsMS(@class); - case CppAbi.Itanium: - return GatherVTableMethodsItanium(@class); + case CppAbi.Microsoft: + return GatherVTableMethodsMS(@class); + case CppAbi.Itanium: + return GatherVTableMethodsItanium(@class); } throw new NotSupportedException( @@ -57,7 +57,7 @@ namespace CppSharp.AST public static int GetVTableIndex(Function function) { - var @class = (Class) function.Namespace; + var @class = (Class)function.Namespace; switch (@class.Layout.ABI) { case CppAbi.Microsoft: @@ -77,7 +77,7 @@ namespace CppSharp.AST return entry.Method != null && (entry.Method.IsOperator || (!entry.Method.IsDeclared && - ((Class) entry.Method.Namespace).GetPropertyByConstituentMethod(entry.Method) == null)); + ((Class)entry.Method.Namespace).GetPropertyByConstituentMethod(entry.Method) == null)); } } } diff --git a/src/Generator/Extensions/FunctionExtensions.cs b/src/Generator/Extensions/FunctionExtensions.cs index e710f6d2..471cef08 100644 --- a/src/Generator/Extensions/FunctionExtensions.cs +++ b/src/Generator/Extensions/FunctionExtensions.cs @@ -7,7 +7,7 @@ namespace CppSharp.Extensions public static bool IsNativeMethod(this Function function) { var method = function as Method; - if (method == null) + if (method == null) return false; return method.Conversion == MethodConversionKind.None; diff --git a/src/Generator/Generator.cs b/src/Generator/Generator.cs index 4b135948..e9bcc3e8 100644 --- a/src/Generator/Generator.cs +++ b/src/Generator/Generator.cs @@ -85,7 +85,7 @@ namespace CppSharp.Generators // TODO: Remove this once file per module works for C++ backend if (!Context.Options.IsCSharpGenerator) outputMode = GenerationOutputMode.FilePerUnit; - + var outputs = new List(); if (outputMode == GenerationOutputMode.FilePerModule) @@ -115,7 +115,7 @@ namespace CppSharp.Generators } } - var generateSystemModule = Context.Options.SystemModule != null && + var generateSystemModule = Context.Options.SystemModule != null && Context.Options.GeneratorKind == GeneratorKind.CSharp; if (generateSystemModule) { diff --git a/src/Generator/Generators/C/CCodeGenerator.cs b/src/Generator/Generators/C/CCodeGenerator.cs index 4fea70b9..f0bf231d 100644 --- a/src/Generator/Generators/C/CCodeGenerator.cs +++ b/src/Generator/Generators/C/CCodeGenerator.cs @@ -402,15 +402,15 @@ namespace CppSharp.Generators.C if (isDeclaration) { if (method.IsPure) - Write(" = 0"); + Write(" = 0"); else if (method.IsOverride) - Write(" override"); + Write(" override"); } } public virtual void GenerateMethodParameters(Function function) { - Write(CTypePrinter.VisitParameters(function.Parameters)); + Write(CTypePrinter.VisitParameters(function.Parameters)); } public override bool VisitMethodDecl(Method method) @@ -440,7 +440,7 @@ namespace CppSharp.Generators.C GeneratePropertySetter(property.SetMethod); //if (Options.GenerateMSDeclspecProperties) - //GenerateMSDeclspecProperty(property); + //GenerateMSDeclspecProperty(property); return true; } diff --git a/src/Generator/Generators/C/CppHeaders.cs b/src/Generator/Generators/C/CppHeaders.cs index ef0ba7c1..eb87f4fd 100644 --- a/src/Generator/Generators/C/CppHeaders.cs +++ b/src/Generator/Generators/C/CppHeaders.cs @@ -302,7 +302,7 @@ namespace CppSharp.Generators.Cpp return false; //if (@class.IsOpaque) - // return false; + // return false; PushBlock(BlockKind.Class, @class); @@ -392,8 +392,8 @@ namespace CppSharp.Generators.Cpp Name = Generator.GeneratedIdentifier("ExternalData"), QualifiedType = new QualifiedType(new ArrayType { - QualifiedType = new QualifiedType(voidPtrType), - SizeType = ArrayType.ArraySize.Constant, + QualifiedType = new QualifiedType(voidPtrType), + SizeType = ArrayType.ArraySize.Constant, Size = 2 }), Namespace = @class @@ -567,7 +567,7 @@ namespace CppSharp.Generators.Cpp Indent(); - var @class = (Class) methods[0].Namespace; + var @class = (Class)methods[0].Namespace; if (@class.IsValueType) foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore)) @@ -591,7 +591,7 @@ namespace CppSharp.Generators.Cpp method.Visit(this); } - foreach(var method in staticMethods) + foreach (var method in staticMethods) method.Visit(this); Unindent(); @@ -686,7 +686,7 @@ namespace CppSharp.Generators.Cpp var @delegate = string.Format(CTypePrinter.VisitDelegate(functionType), typedef.Name); WriteLine($"{@delegate};"); - + PopBlock(NewLineKind.BeforeNextBlock); return true; diff --git a/src/Generator/Generators/C/CppMarshal.cs b/src/Generator/Generators/C/CppMarshal.cs index 51e0c77a..e0425e9f 100644 --- a/src/Generator/Generators/C/CppMarshal.cs +++ b/src/Generator/Generators/C/CppMarshal.cs @@ -36,13 +36,13 @@ namespace CppSharp.Generators.Cpp { switch (array.SizeType) { - case ArrayType.ArraySize.Constant: - case ArrayType.ArraySize.Incomplete: - case ArrayType.ArraySize.Variable: - Context.Return.Write("nullptr"); - break; - default: - throw new System.NotImplementedException(); + case ArrayType.ArraySize.Constant: + case ArrayType.ArraySize.Incomplete: + case ArrayType.ArraySize.Variable: + Context.Return.Write("nullptr"); + break; + default: + throw new System.NotImplementedException(); } return true; @@ -76,7 +76,7 @@ namespace CppSharp.Generators.Cpp Context.ReturnType.Qualifiers.IsConst) { var nativeTypePrinter = new CppTypePrinter(Context.Context) - { PrintTypeQualifiers = false }; + { PrintTypeQualifiers = false }; var returnType = Context.ReturnType.Type.Desugar(); var constlessPointer = new PointerType() { @@ -137,28 +137,28 @@ namespace CppSharp.Generators.Cpp { switch (primitive) { - case PrimitiveType.Void: - return true; - case PrimitiveType.Bool: - case PrimitiveType.Char: - case PrimitiveType.Char16: - case PrimitiveType.WideChar: - case PrimitiveType.SChar: - case PrimitiveType.UChar: - case PrimitiveType.Short: - case PrimitiveType.UShort: - case PrimitiveType.Int: - case PrimitiveType.UInt: - case PrimitiveType.Long: - case PrimitiveType.ULong: - case PrimitiveType.LongLong: - case PrimitiveType.ULongLong: - case PrimitiveType.Float: - case PrimitiveType.Double: - case PrimitiveType.LongDouble: - case PrimitiveType.Null: - Context.Return.Write(Context.ReturnVarName); - return true; + case PrimitiveType.Void: + return true; + case PrimitiveType.Bool: + case PrimitiveType.Char: + case PrimitiveType.Char16: + case PrimitiveType.WideChar: + case PrimitiveType.SChar: + case PrimitiveType.UChar: + case PrimitiveType.Short: + case PrimitiveType.UShort: + case PrimitiveType.Int: + case PrimitiveType.UInt: + case PrimitiveType.Long: + case PrimitiveType.ULong: + case PrimitiveType.LongLong: + case PrimitiveType.ULongLong: + case PrimitiveType.Float: + case PrimitiveType.Double: + case PrimitiveType.LongDouble: + case PrimitiveType.Null: + Context.Return.Write(Context.ReturnVarName); + return true; } throw new NotSupportedException(); @@ -330,7 +330,7 @@ namespace CppSharp.Generators.Cpp public class CppMarshalManagedToNativePrinter : MarshalPrinter { - public CppMarshalManagedToNativePrinter(MarshalContext ctx) + public CppMarshalManagedToNativePrinter(MarshalContext ctx) : base(ctx) { Context.MarshalToNative = this; @@ -363,9 +363,9 @@ namespace CppSharp.Generators.Cpp switch (array.SizeType) { - default: - Context.Return.Write("nullptr"); - break; + default: + Context.Return.Write("nullptr"); + break; } return true; @@ -447,26 +447,26 @@ namespace CppSharp.Generators.Cpp { switch (primitive) { - case PrimitiveType.Void: - return true; - case PrimitiveType.Bool: - case PrimitiveType.Char: - case PrimitiveType.UChar: - case PrimitiveType.Short: - case PrimitiveType.UShort: - case PrimitiveType.Int: - case PrimitiveType.UInt: - case PrimitiveType.Long: - case PrimitiveType.ULong: - case PrimitiveType.LongLong: - case PrimitiveType.ULongLong: - case PrimitiveType.Float: - case PrimitiveType.Double: - case PrimitiveType.WideChar: - Context.Return.Write(Context.Parameter.Name); - return true; - default: - throw new NotImplementedException(); + case PrimitiveType.Void: + return true; + case PrimitiveType.Bool: + case PrimitiveType.Char: + case PrimitiveType.UChar: + case PrimitiveType.Short: + case PrimitiveType.UShort: + case PrimitiveType.Int: + case PrimitiveType.UInt: + case PrimitiveType.Long: + case PrimitiveType.ULong: + case PrimitiveType.LongLong: + case PrimitiveType.ULongLong: + case PrimitiveType.Float: + case PrimitiveType.Double: + case PrimitiveType.WideChar: + Context.Return.Write(Context.Parameter.Name); + return true; + default: + throw new NotImplementedException(); } } diff --git a/src/Generator/Generators/C/CppSources.cs b/src/Generator/Generators/C/CppSources.cs index ff298bb8..64619c77 100644 --- a/src/Generator/Generators/C/CppSources.cs +++ b/src/Generator/Generators/C/CppSources.cs @@ -114,7 +114,7 @@ namespace CppSharp.Generators.Cpp } } - foreach(var childNamespace in context.Namespaces) + foreach (var childNamespace in context.Namespaces) VisitDeclContext(childNamespace); PopBlock(); @@ -521,10 +521,10 @@ namespace CppSharp.Generators.Cpp WriteLine(");"); } - foreach(var paramInfo in @params) + foreach (var paramInfo in @params) { var param = paramInfo.Param; - if(param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut) + if (param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut) continue; if (param.Type.IsPointer() && !param.Type.GetFinalPointee().IsPrimitiveType()) @@ -541,7 +541,7 @@ namespace CppSharp.Generators.Cpp var marshal = new CppMarshalNativeToManagedPrinter(ctx); param.Visit(marshal); - + if (!string.IsNullOrWhiteSpace(marshal.Context.Before)) Write(marshal.Context.Before); @@ -575,7 +575,7 @@ namespace CppSharp.Generators.Cpp public static bool IsNativeMethod(Function function) { var method = function as Method; - if (method == null) + if (method == null) return false; return method.Conversion == MethodConversionKind.None; @@ -584,7 +584,7 @@ namespace CppSharp.Generators.Cpp public bool IsNativeFunctionOrStaticMethod(Function function) { var method = function as Method; - if (method == null) + if (method == null) return true; if (!IsCLIGenerator && method.IsOperator) @@ -602,7 +602,7 @@ namespace CppSharp.Generators.Cpp public string Prefix; public Parameter Param; - } + } public List GenerateFunctionParamsMarshal(IEnumerable @params, Function function = null) diff --git a/src/Generator/Generators/C/CppTypePrinter.cs b/src/Generator/Generators/C/CppTypePrinter.cs index 015a28fd..28b9334e 100644 --- a/src/Generator/Generators/C/CppTypePrinter.cs +++ b/src/Generator/Generators/C/CppTypePrinter.cs @@ -94,16 +94,16 @@ namespace CppSharp.Generators.C string arraySuffix; switch (array.SizeType) { - case ArrayType.ArraySize.Constant: - arraySuffix = $"[{array.Size}]"; - break; - case ArrayType.ArraySize.Variable: - case ArrayType.ArraySize.Dependent: - case ArrayType.ArraySize.Incomplete: - arraySuffix = $"{(PrintVariableArrayAsPointers ? "*" : "[]")}"; - break; - default: - throw new NotImplementedException(); + case ArrayType.ArraySize.Constant: + arraySuffix = $"[{array.Size}]"; + break; + case ArrayType.ArraySize.Variable: + case ArrayType.ArraySize.Dependent: + case ArrayType.ArraySize.Incomplete: + arraySuffix = $"{(PrintVariableArrayAsPointers ? "*" : "[]")}"; + break; + default: + throw new NotImplementedException(); } return new TypePrinterResult @@ -199,32 +199,32 @@ namespace CppSharp.Generators.C return PrintFlavorKind == CppTypePrintFlavorKind.Cpp ? "std::nullptr_t" : "NULL"; case PrimitiveType.String: - { - switch (PrintFlavorKind) { - case CppTypePrintFlavorKind.C: - return "const char*"; - case CppTypePrintFlavorKind.Cpp: - return "std::string"; - case CppTypePrintFlavorKind.ObjC: - return "NSString"; - default: - throw new ArgumentOutOfRangeException(); + switch (PrintFlavorKind) + { + case CppTypePrintFlavorKind.C: + return "const char*"; + case CppTypePrintFlavorKind.Cpp: + return "std::string"; + case CppTypePrintFlavorKind.ObjC: + return "NSString"; + default: + throw new ArgumentOutOfRangeException(); + } } - } case PrimitiveType.Decimal: - { - switch (PrintFlavorKind) { - case CppTypePrintFlavorKind.C: - case CppTypePrintFlavorKind.Cpp: - return "_Decimal32"; - case CppTypePrintFlavorKind.ObjC: - return "NSDecimalNumber"; - default: - throw new ArgumentOutOfRangeException(); + switch (PrintFlavorKind) + { + case CppTypePrintFlavorKind.C: + case CppTypePrintFlavorKind.Cpp: + return "_Decimal32"; + case CppTypePrintFlavorKind.ObjC: + return "NSDecimalNumber"; + default: + throw new ArgumentOutOfRangeException(); + } } - } } throw new NotSupportedException(); @@ -237,8 +237,12 @@ namespace CppSharp.Generators.C if (ResolveTypedefs && !typedef.Declaration.Type.IsPointerTo(out FunctionType _)) { TypePrinterResult type = typedef.Declaration.QualifiedType.Visit(this); - return new TypePrinterResult { Type = $"{qual}{type.Type}", - NamePrefix = type.NamePrefix, NameSuffix = type.NameSuffix }; + return new TypePrinterResult + { + Type = $"{qual}{type.Type}", + NamePrefix = type.NamePrefix, + NameSuffix = type.NameSuffix + }; } var result = typedef.Declaration.Visit(this); @@ -469,59 +473,59 @@ namespace CppSharp.Generators.C { switch (scope) { - case TypePrintScopeKind.Local: - { - if (ContextKind == TypePrinterContextKind.Managed) - { - return PrintLogicalNames ? declaration.LogicalName : declaration.Name; - } + case TypePrintScopeKind.Local: + { + if (ContextKind == TypePrinterContextKind.Managed) + { + return PrintLogicalNames ? declaration.LogicalName : declaration.Name; + } - if (PrefixSpecialFunctions) - { - if (declaration is Function {IsOperator: true} function) - return $"operator_{function.OperatorKind}"; - } + if (PrefixSpecialFunctions) + { + if (declaration is Function { IsOperator: true } function) + return $"operator_{function.OperatorKind}"; + } - return PrintLogicalNames ? declaration.LogicalOriginalName - : declaration.OriginalName; - } - case TypePrintScopeKind.Qualified: - { - if (ContextKind == TypePrinterContextKind.Managed) - { - var outputNamespace = GlobalNamespace(declaration); - if (!string.IsNullOrEmpty(outputNamespace)) - { - return $"{outputNamespace}{NamespaceSeparator}{declaration.QualifiedName}"; + return PrintLogicalNames ? declaration.LogicalOriginalName + : declaration.OriginalName; } + case TypePrintScopeKind.Qualified: + { + if (ContextKind == TypePrinterContextKind.Managed) + { + var outputNamespace = GlobalNamespace(declaration); + if (!string.IsNullOrEmpty(outputNamespace)) + { + return $"{outputNamespace}{NamespaceSeparator}{declaration.QualifiedName}"; + } - return declaration.QualifiedName; - } + return declaration.QualifiedName; + } - if (declaration.Namespace is Class) - { - var declName = GetDeclName(declaration, TypePrintScopeKind.Local); - bool printTags = PrintTags; - PrintTags = false; - TypePrinterResult declContext = declaration.Namespace.Visit(this); - PrintTags = printTags; - return $"{declContext}{NamespaceSeparator}{declName}"; - } + if (declaration.Namespace is Class) + { + var declName = GetDeclName(declaration, TypePrintScopeKind.Local); + bool printTags = PrintTags; + PrintTags = false; + TypePrinterResult declContext = declaration.Namespace.Visit(this); + PrintTags = printTags; + return $"{declContext}{NamespaceSeparator}{declName}"; + } - return PrintLogicalNames ? declaration.QualifiedLogicalOriginalName - : declaration.QualifiedOriginalName; - } - case TypePrintScopeKind.GlobalQualified: - { - var name = (ContextKind == TypePrinterContextKind.Managed) ? - declaration.Name : declaration.OriginalName; + return PrintLogicalNames ? declaration.QualifiedLogicalOriginalName + : declaration.QualifiedOriginalName; + } + case TypePrintScopeKind.GlobalQualified: + { + var name = (ContextKind == TypePrinterContextKind.Managed) ? + declaration.Name : declaration.OriginalName; - if (declaration.Namespace is Class) - return $"{declaration.Namespace.Visit(this)}{NamespaceSeparator}{name}"; + if (declaration.Namespace is Class) + return $"{declaration.Namespace.Visit(this)}{NamespaceSeparator}{name}"; - var qualifier = HasGlobalNamespacePrefix ? NamespaceSeparator : string.Empty; - return qualifier + GetDeclName(declaration, TypePrintScopeKind.Qualified); - } + var qualifier = HasGlobalNamespacePrefix ? NamespaceSeparator : string.Empty; + return qualifier + GetDeclName(declaration, TypePrintScopeKind.Qualified); + } } throw new NotSupportedException(); @@ -619,7 +623,7 @@ namespace CppSharp.Generators.C FunctionType functionType; CppSharp.AST.Type desugared = function.FunctionType.Type.Desugar(); if (!desugared.IsPointerTo(out functionType)) - functionType = (FunctionType) desugared; + functionType = (FunctionType)desugared; string exceptionType = Print(functionType.ExceptionSpecType); var @return = function.OriginalReturnType.Visit(this); diff --git a/src/Generator/Generators/CLI/CLIHeaders.cs b/src/Generator/Generators/CLI/CLIHeaders.cs index 1d0ea407..602ff98a 100644 --- a/src/Generator/Generators/CLI/CLIHeaders.cs +++ b/src/Generator/Generators/CLI/CLIHeaders.cs @@ -70,7 +70,7 @@ namespace CppSharp.Generators.CLI if (unit != null && !unit.IsDeclared) continue; - if(!string.IsNullOrEmpty(include.File) && include.InHeader) + if (!string.IsNullOrEmpty(include.File) && include.InHeader) includes.Add(include.ToString()); } @@ -507,7 +507,7 @@ namespace CppSharp.Generators.CLI Indent(); - var @class = (Class) methods[0].Namespace; + var @class = (Class)methods[0].Namespace; if (@class.IsValueType) foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore)) @@ -531,7 +531,7 @@ namespace CppSharp.Generators.CLI GenerateMethod(method); } - foreach(var method in staticMethods) + foreach (var method in staticMethods) GenerateMethod(method); Unindent(); @@ -541,7 +541,7 @@ namespace CppSharp.Generators.CLI { Indent(); - foreach(var variable in @class.Variables) + foreach (var variable in @class.Variables) { if (!variable.IsGenerated) continue; @@ -720,7 +720,7 @@ namespace CppSharp.Generators.CLI if (method.OperatorKind == CXXOperatorKind.EqualEqual) { - GenerateEquals(method, (Class) method.Namespace); + GenerateEquals(method, (Class)method.Namespace); } PopBlock(NewLineKind.BeforeNextBlock); @@ -759,7 +759,7 @@ namespace CppSharp.Generators.CLI : ((FunctionType)attributedType).CallingConvention; var interopCallConv = callingConvention.ToInteropCallConv(); if (interopCallConv != System.Runtime.InteropServices.CallingConvention.Winapi) - WriteLine("[::System::Runtime::InteropServices::UnmanagedFunctionPointer" + + WriteLine("[::System::Runtime::InteropServices::UnmanagedFunctionPointer" + "(::System::Runtime::InteropServices::CallingConvention::{0})] ", interopCallConv); diff --git a/src/Generator/Generators/CLI/CLIMarshal.cs b/src/Generator/Generators/CLI/CLIMarshal.cs index c89f84cf..1376592c 100644 --- a/src/Generator/Generators/CLI/CLIMarshal.cs +++ b/src/Generator/Generators/CLI/CLIMarshal.cs @@ -391,7 +391,7 @@ namespace CppSharp.Generators.CLI public readonly TextGenerator VarPrefix; public readonly TextGenerator ArgumentPrefix; - public CLIMarshalManagedToNativePrinter(MarshalContext ctx) + public CLIMarshalManagedToNativePrinter(MarshalContext ctx) : base(ctx) { VarPrefix = new TextGenerator(); @@ -466,7 +466,7 @@ namespace CppSharp.Generators.CLI isPointerToPrimitive || isPrimitive ? string.Empty : "*", Context.Parameter.Name, nativeVal); - supportBefore.UnindentAndWriteCloseBrace(); + supportBefore.UnindentAndWriteCloseBrace(); break; default: Context.Return.Write("null"); @@ -521,7 +521,7 @@ namespace CppSharp.Generators.CLI Context.Parameter.Usage == ParameterUsage.Out || Context.Parameter.Usage == ParameterUsage.InOut; - if(!isRef) + if (!isRef) { ArgumentPrefix.Write("&"); } @@ -759,7 +759,7 @@ namespace CppSharp.Generators.CLI MarshalValueClassProperties(@base.Class, marshalVar); } - foreach (var property in @class.Properties.Where( p => !ASTUtils.CheckIgnoreProperty(p))) + foreach (var property in @class.Properties.Where(p => !ASTUtils.CheckIgnoreProperty(p))) { if (property.Field == null) continue; @@ -773,11 +773,11 @@ namespace CppSharp.Generators.CLI var fieldRef = $"{Context.Parameter.Name}.{property.Name}"; var marshalCtx = new MarshalContext(Context.Context, Context.Indentation) - { - ArgName = fieldRef, - ParameterIndex = Context.ParameterIndex++, - ReturnVarName = $"{marshalVar}.{property.Field.OriginalName}" - }; + { + ArgName = fieldRef, + ParameterIndex = Context.ParameterIndex++, + ReturnVarName = $"{marshalVar}.{property.Field.OriginalName}" + }; var marshal = new CLIMarshalManagedToNativePrinter(marshalCtx); property.Visit(marshal); @@ -812,10 +812,10 @@ namespace CppSharp.Generators.CLI public override bool VisitFieldDecl(Field field) { Context.Parameter = new Parameter - { - Name = Context.ArgName, - QualifiedType = field.QualifiedType - }; + { + Name = Context.ArgName, + QualifiedType = field.QualifiedType + }; return field.Type.Visit(this); } @@ -823,10 +823,10 @@ namespace CppSharp.Generators.CLI public override bool VisitProperty(Property property) { Context.Parameter = new Parameter - { - Name = Context.ArgName, - QualifiedType = property.QualifiedType - }; + { + Name = Context.ArgName, + QualifiedType = property.QualifiedType + }; return base.VisitProperty(property); } diff --git a/src/Generator/Generators/CLI/CLISources.cs b/src/Generator/Generators/CLI/CLISources.cs index f24d04c7..3be397f7 100644 --- a/src/Generator/Generators/CLI/CLISources.cs +++ b/src/Generator/Generators/CLI/CLISources.cs @@ -64,7 +64,7 @@ namespace CppSharp.Generators.CLI continue; var include = typeRef.Include; - if(!string.IsNullOrEmpty(include.File) && !include.InHeader) + if (!string.IsNullOrEmpty(include.File) && !include.InHeader) includes.Add(include.ToString()); } @@ -113,7 +113,7 @@ namespace CppSharp.Generators.CLI } } - foreach(var childNamespace in @namespace.Namespaces) + foreach (var childNamespace in @namespace.Namespaces) GenerateDeclContext(childNamespace); PopBlock(); @@ -305,7 +305,7 @@ namespace CppSharp.Generators.CLI typeNames = "typename " + string.Join(", typename ", paramNames); WriteLine("generic<{0}>", typeNames); - WriteLine("{0} {1}::{2}({3})", retType, + WriteLine("{0} {1}::{2}({3})", retType, QualifiedIdentifier(function.Namespace), function.Name, GenerateParametersList(function.Parameters)); @@ -348,7 +348,7 @@ namespace CppSharp.Generators.CLI GeneratePropertySetter(property.SetMethod, realOwner, property.Name, property.Type); } - PopBlock(); + PopBlock(); } private void GeneratePropertySetter(T decl, Class @class, string name, Type type, Parameter indexParameter = null) @@ -502,7 +502,7 @@ namespace CppSharp.Generators.CLI WriteLine($"return {marshal.Context.Return};"); } - + UnindentAndWriteCloseBrace(); NewLine(); @@ -593,10 +593,10 @@ namespace CppSharp.Generators.CLI foreach (var param in @event.Parameters) { var ctx = new MarshalContext(Context, CurrentIndentation) - { - ReturnVarName = param.Name, - ReturnType = param.QualifiedType - }; + { + ReturnVarName = param.Name, + ReturnType = param.QualifiedType + }; var marshal = new CLIMarshalNativeToManagedPrinter(ctx); param.Visit(marshal); @@ -685,7 +685,7 @@ namespace CppSharp.Generators.CLI } int paramIndex = 0; - foreach (var property in @class.Properties.Where( + foreach (var property in @class.Properties.Where( p => !ASTUtils.CheckIgnoreProperty(p) && !CLIHeaders.TypeIgnored(p.Type))) { if (property.Field == null) @@ -849,12 +849,12 @@ namespace CppSharp.Generators.CLI foreach (var param in method.Parameters) { var ctx = new MarshalContext(Context, CurrentIndentation) - { - Function = method, - Parameter = param, - ArgName = param.Name, - ParameterIndex = paramIndex++ - }; + { + Function = method, + Parameter = param, + ArgName = param.Name, + ParameterIndex = paramIndex++ + }; var marshal = new CLIMarshalManagedToNativePrinter(ctx); param.Visit(marshal); @@ -885,10 +885,10 @@ namespace CppSharp.Generators.CLI var varName = $"_native.{property.Field.OriginalName}"; var ctx = new MarshalContext(Context, CurrentIndentation) - { - ReturnVarName = varName, - ReturnType = property.QualifiedType - }; + { + ReturnVarName = varName, + ReturnType = property.QualifiedType + }; var marshal = new CLIMarshalNativeToManagedPrinter(ctx); property.Visit(marshal); @@ -959,11 +959,11 @@ namespace CppSharp.Generators.CLI { WriteLine($"auto {valueMarshalName} = {typePrinter.PrintTag(@class)}::{@class.QualifiedOriginalName}();"); - var param = new Parameter { Name = "(*this)" , Namespace = function.Namespace }; + var param = new Parameter { Name = "(*this)", Namespace = function.Namespace }; var ctx = new MarshalContext(Context, CurrentIndentation) - { - Parameter = param - }; + { + Parameter = param + }; ctx.VarPrefix.Write(valueMarshalName); var marshal = new CLIMarshalManagedToNativePrinter(ctx); @@ -982,7 +982,7 @@ namespace CppSharp.Generators.CLI else Write("auto {0} = ", returnIdentifier); - if (function.OperatorKind == CXXOperatorKind.Conversion || + if (function.OperatorKind == CXXOperatorKind.Conversion || function.OperatorKind == CXXOperatorKind.ExplicitConversion) { var method = function as Method; @@ -996,12 +996,12 @@ namespace CppSharp.Generators.CLI switch (Operators.ClassifyOperator(function)) { - case CXXOperatorArity.Unary: - WriteLine("{0} {1};", opName, @params[0].Name); - break; - case CXXOperatorArity.Binary: - WriteLine("{0} {1} {2};", @params[0].Name, opName, @params[1].Name); - break; + case CXXOperatorArity.Unary: + WriteLine("{0} {1};", opName, @params[0].Name); + break; + case CXXOperatorArity.Binary: + WriteLine("{0} {1} {2};", @params[0].Name, opName, @params[1].Name); + break; } } else @@ -1023,10 +1023,10 @@ namespace CppSharp.Generators.CLI WriteLine(");"); } - foreach(var paramInfo in @params) + foreach (var paramInfo in @params) { var param = paramInfo.Param; - if(param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut) + if (param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut) continue; if (param.Type.IsPointer() && !param.Type.GetFinalPointee().IsPrimitiveType()) @@ -1035,19 +1035,19 @@ namespace CppSharp.Generators.CLI var nativeVarName = paramInfo.Name; var ctx = new MarshalContext(Context, CurrentIndentation) - { - ArgName = nativeVarName, - ReturnVarName = nativeVarName, - ReturnType = param.QualifiedType - }; + { + ArgName = nativeVarName, + ReturnVarName = nativeVarName, + ReturnType = param.QualifiedType + }; var marshal = new CLIMarshalNativeToManagedPrinter(ctx); param.Visit(marshal); - + if (!string.IsNullOrWhiteSpace(marshal.Context.Before)) Write(marshal.Context.Before); - WriteLine("{0} = {1};",param.Name,marshal.Context.Return); + WriteLine("{0} = {1};", param.Name, marshal.Context.Return); } if (isValueType && !IsNativeFunctionOrStaticMethod(function)) @@ -1082,7 +1082,7 @@ namespace CppSharp.Generators.CLI // Special case for indexer - needs to dereference if the internal // function is a pointer type and the property is not. - if (retType.Type.IsPointer() && + if (retType.Type.IsPointer() && retType.Type.GetPointee().Equals(publicRetType) && publicRetType.IsPrimitiveType()) WriteLine("return *({0});", marshal.Context.Return); @@ -1104,7 +1104,7 @@ namespace CppSharp.Generators.CLI // C++/CLI can actually handle char -> sbyte in all case, this is for compatibility with the C# generator WriteLineIndent( "throw gcnew ::System::OverflowException(\"{0} must be in the range {1} - {2}.\");", - param.Name, (int) char.MinValue, sbyte.MaxValue); + param.Name, (int)char.MinValue, sbyte.MaxValue); } } } @@ -1112,7 +1112,7 @@ namespace CppSharp.Generators.CLI private static bool IsNativeMethod(Function function) { var method = function as Method; - if (method == null) + if (method == null) return false; return method.Conversion == MethodConversionKind.None; @@ -1121,7 +1121,7 @@ namespace CppSharp.Generators.CLI private static bool IsNativeFunctionOrStaticMethod(Function function) { var method = function as Method; - if (method == null) + if (method == null) return true; if (method.IsOperator && Operators.IsBuiltinOperator(method.OperatorKind)) @@ -1136,7 +1136,7 @@ namespace CppSharp.Generators.CLI public string Prefix; public Parameter Param; - } + } public List GenerateFunctionParamsMarshal(IEnumerable @params, Function function = null) diff --git a/src/Generator/Generators/CLI/CLITemplate.cs b/src/Generator/Generators/CLI/CLITemplate.cs index 63387d04..405f31ed 100644 --- a/src/Generator/Generators/CLI/CLITemplate.cs +++ b/src/Generator/Generators/CLI/CLITemplate.cs @@ -28,7 +28,7 @@ namespace CppSharp.Generators.CLI if (method.IsConstructor || method.IsDestructor) { - var @class = (Class) method.Namespace; + var @class = (Class)method.Namespace; return @class.Name; } diff --git a/src/Generator/Generators/CLI/CLITypePrinter.cs b/src/Generator/Generators/CLI/CLITypePrinter.cs index 27af84f5..50ff8d46 100644 --- a/src/Generator/Generators/CLI/CLITypePrinter.cs +++ b/src/Generator/Generators/CLI/CLITypePrinter.cs @@ -74,14 +74,14 @@ namespace CppSharp.Generators.CLI Parameter = null; var str = string.Empty; - if(param.Usage == ParameterUsage.Out) + if (param.Usage == ParameterUsage.Out) str += "[::System::Runtime::InteropServices::Out] "; else if (param.Usage == ParameterUsage.InOut) str += "[::System::Runtime::InteropServices::In, ::System::Runtime::InteropServices::Out] "; str += type; - if(param.Usage == ParameterUsage.Out || + if (param.Usage == ParameterUsage.Out || param.Usage == ParameterUsage.InOut) str += "%"; @@ -110,7 +110,7 @@ namespace CppSharp.Generators.CLI MarshalKind = MarshalKind, Type = pointer }; - + return typeMap.CLISignatureType(typePrinterContext).Visit(this); } @@ -150,7 +150,7 @@ namespace CppSharp.Generators.CLI var typeName = VisitDeclaration(@enum, quals); // Skip one indirection if passed by reference - if (Parameter != null && (Parameter.Type.IsReference() + if (Parameter != null && (Parameter.Type.IsReference() || ((Parameter.IsOut || Parameter.IsInOut) && pointee == finalPointee))) return typeName; diff --git a/src/Generator/Generators/CLI/CLITypeReferences.cs b/src/Generator/Generators/CLI/CLITypeReferences.cs index 701f9ac8..885279e2 100644 --- a/src/Generator/Generators/CLI/CLITypeReferences.cs +++ b/src/Generator/Generators/CLI/CLITypeReferences.cs @@ -123,7 +123,7 @@ namespace CppSharp.Generators.CLI // Find a type map for the declaration and use it if it exists. TypeMap typeMap; - if (TypeMapDatabase.FindTypeMap(record.Value, out typeMap) + if (TypeMapDatabase.FindTypeMap(record.Value, out typeMap) || (typedefType != null && TypeMapDatabase.FindTypeMap(typedefType.Type.Desugar(), out typeMap))) { typeMap.CLITypeReference(this, record); @@ -131,7 +131,7 @@ namespace CppSharp.Generators.CLI } var typeRef = GetTypeReference(decl); - if(typeRef != null) + if (typeRef != null) { typeRef.Include.InHeader |= IsIncludeInHeader(record); } @@ -176,7 +176,7 @@ namespace CppSharp.Generators.CLI return false; if (@class.IsIncomplete && @class.CompleteDeclaration != null) - @class = (Class) @class.CompleteDeclaration; + @class = (Class)@class.CompleteDeclaration; if (@class.TranslationUnit == TranslationUnit) GeneratedDeclarations.Add(@class); diff --git a/src/Generator/Generators/CSharp/CSharpCommentPrinter.cs b/src/Generator/Generators/CSharp/CSharpCommentPrinter.cs index 7129fda1..dc7ec6ce 100644 --- a/src/Generator/Generators/CSharp/CSharpCommentPrinter.cs +++ b/src/Generator/Generators/CSharp/CSharpCommentPrinter.cs @@ -23,12 +23,12 @@ namespace CppSharp.Generators.CSharp switch (comment.Kind) { case DocumentationCommentKind.FullComment: - var fullComment = (FullComment) comment; + var fullComment = (FullComment)comment; foreach (var block in fullComment.Blocks) block.GetCommentSections(sections); break; case DocumentationCommentKind.BlockCommandComment: - var blockCommandComment = (BlockCommandComment) comment; + var blockCommandComment = (BlockCommandComment)comment; if (blockCommandComment.ParagraphComment == null) break; switch (blockCommandComment.CommandKind) @@ -58,7 +58,7 @@ namespace CppSharp.Generators.CSharp break; case DocumentationCommentKind.ParamCommandComment: - var paramCommandComment = (ParamCommandComment) comment; + var paramCommandComment = (ParamCommandComment)comment; var param = new Section(CommentElement.Param); sections.Add(param); if (paramCommandComment.Arguments.Count > 0) @@ -82,7 +82,7 @@ namespace CppSharp.Generators.CSharp break; case DocumentationCommentKind.ParagraphComment: var summaryParagraph = sections.Count == 1; - var paragraphComment = (ParagraphComment) comment; + var paragraphComment = (ParagraphComment)comment; var lastParagraphSection = sections.Last(); foreach (var inlineContentComment in paragraphComment.Content) { @@ -117,7 +117,7 @@ namespace CppSharp.Generators.CSharp break; case DocumentationCommentKind.InlineCommandComment: var lastInlineSection = sections.Last(); - var inlineCommand = (InlineCommandComment) comment; + var inlineCommand = (InlineCommandComment)comment; if (inlineCommand.CommandKind == CommentCommandKind.B) { @@ -132,7 +132,7 @@ namespace CppSharp.Generators.CSharp private static string GetText(Comment comment, bool trim = false) { - var textComment = ((TextComment) comment); + var textComment = ((TextComment)comment); var text = textComment.Text; if (trim) text = text.Trim(); diff --git a/src/Generator/Generators/CSharp/CSharpExpressionPrinter.cs b/src/Generator/Generators/CSharp/CSharpExpressionPrinter.cs index 3782650c..c4c2f1d5 100644 --- a/src/Generator/Generators/CSharp/CSharpExpressionPrinter.cs +++ b/src/Generator/Generators/CSharp/CSharpExpressionPrinter.cs @@ -40,7 +40,7 @@ namespace CppSharp.Generators.CSharp switch (expr.Class) { case StatementClass.Call: - var callExpr = (CallExprObsolete) expr; + var callExpr = (CallExprObsolete)expr; switch (callExpr.Declaration.GenerationKind) { case GenerationKind.Generate: @@ -48,7 +48,7 @@ namespace CppSharp.Generators.CSharp return $"{typePrinter.VisitDeclaration(callExpr.Declaration.Namespace)}.{callExpr.Declaration.Name}({args})"; case GenerationKind.Internal: // a non-ctor can only be internal if it's been converted to a property - var property = ((Class) callExpr.Declaration.Namespace).Properties.First( + var property = ((Class)callExpr.Declaration.Namespace).Properties.First( p => p.GetMethod == callExpr.Declaration); return $"{typePrinter.VisitDeclaration(callExpr.Declaration.Namespace)}.{property.Name}"; default: @@ -59,7 +59,7 @@ namespace CppSharp.Generators.CSharp return expr.Declaration.Visit(typePrinter).Type; goto default; case StatementClass.BinaryOperator: - var binaryOperator = (BinaryOperatorObsolete) expr; + var binaryOperator = (BinaryOperatorObsolete)expr; var lhsResult = binaryOperator.LHS.String; if (binaryOperator.LHS.Declaration is Enumeration.Item) @@ -71,7 +71,7 @@ namespace CppSharp.Generators.CSharp return $"{lhsResult} {binaryOperator.OpcodeStr} {rhsResult}"; case StatementClass.ConstructorReference: - var constructorExpr = (CXXConstructExprObsolete) expr; + var constructorExpr = (CXXConstructExprObsolete)expr; if (constructorExpr.Arguments.Count == 1 && constructorExpr.Arguments[0].Declaration is Enumeration.Item) return constructorExpr.Arguments[0].Declaration.Visit(typePrinter).Type; diff --git a/src/Generator/Generators/CSharp/CSharpMarshal.cs b/src/Generator/Generators/CSharp/CSharpMarshal.cs index 7c843f9f..6b6e6534 100644 --- a/src/Generator/Generators/CSharp/CSharpMarshal.cs +++ b/src/Generator/Generators/CSharp/CSharpMarshal.cs @@ -74,7 +74,7 @@ namespace CppSharp.Generators.CSharp Context.Return.Write($"new Span<{arrayType}>({Context.ReturnVarName}, {array.Size})"); else Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetArray<{arrayType}>({Context.ReturnVarName}, {array.Size})"); - } + } else if (array.Type.IsPrimitiveType(PrimitiveType.Char) && Context.Context.Options.MarshalCharAsManagedChar) Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetCharArray({Context.ReturnVarName}, {array.Size})"); else if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void)) @@ -386,7 +386,7 @@ namespace CppSharp.Generators.CSharp { var originalClass = @class.OriginalClass ?? @class; var ret = Generator.GeneratedIdentifier("result") + Context.ParameterIndex; - + if (originalClass.IsRefType) { var dtor = originalClass.Destructors.FirstOrDefault(); diff --git a/src/Generator/Generators/CSharp/CSharpSources.cs b/src/Generator/Generators/CSharp/CSharpSources.cs index 882a3a95..40f8eeec 100644 --- a/src/Generator/Generators/CSharp/CSharpSources.cs +++ b/src/Generator/Generators/CSharp/CSharpSources.cs @@ -228,7 +228,7 @@ namespace CppSharp.Generators.CSharp GenerateNamespaceFunctionsAndVariables(context); - foreach(var childNamespace in context.Namespaces) + foreach (var childNamespace in context.Namespaces) childNamespace.Visit(this); return true; @@ -411,7 +411,7 @@ namespace CppSharp.Generators.CSharp if (@class.IsDependent && !@class.IsGenerated) return true; - + // disable the type maps, if any, for this class because of copy ctors, operators and others this.DisableTypeMap(@class); @@ -480,7 +480,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat managed = default; return NativeToManagedMap.TryGetValue(native, out var wr) && wr.TryGetTarget(out managed); }}"); - } + } else { WriteLines($@" @@ -512,7 +512,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat if (@class.IsDynamic) GenerateVTable(@class); - exit: + exit: UnindentAndWriteCloseBrace(); PopBlock(NewLineKind.BeforeNextBlock); @@ -542,7 +542,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat foreach (var method in @class.Methods.Where(m => (m.OriginalFunction == null || !ASTUtils.CheckIgnoreFunction(m.OriginalFunction)) && - m.Access == AccessSpecifier.Public && + m.Access == AccessSpecifier.Public && (!shouldInheritFromIDisposable || !IsDisposeMethod(m)))) { PushBlock(BlockKind.Method); @@ -568,7 +568,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat PushBlock(BlockKind.Property); var type = prop.Type; if (prop.Parameters.Count > 0 && prop.Type.IsPointerToPrimitiveType()) - type = ((PointerType) prop.Type).Pointee; + type = ((PointerType)prop.Type).Pointee; GenerateDeclarationCommon(prop); Write($"{type} {GetPropertyName(prop)} {{ "); if (prop.HasGetter) @@ -596,7 +596,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat PushBlock(BlockKind.InternalsClass); if (@class.Layout.Size > 0) - { + { var layout = sequentialLayout ? "Sequential" : "Explicit"; var pack = @class.MaxFieldAlignment > 0 ? $", Pack = {@class.MaxFieldAlignment}" : string.Empty; WriteLine($"[StructLayout(LayoutKind.{layout}, Size = {@class.Layout.Size}{pack})]"); @@ -847,7 +847,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat var fields = @class.Layout.Fields; if (fields.Count > 1) - { + { for (var i = 1; i < fields.Count; ++i) { if (fields[i].Offset == fields[i - 1].Offset) @@ -916,7 +916,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat PopBlock(NewLineKind.BeforeNextBlock); } -#endregion + #endregion private void GeneratePropertySetter(T decl, Class @class, bool isAbstract = false, Property property = null) @@ -1063,11 +1063,12 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat } else { - var name = ((Class) field.Namespace).Layout.Fields.First( + var name = ((Class)field.Namespace).Layout.Fields.First( f => f.FieldPtr == field.OriginalPtr).Name; if (@class.IsValueType) returnVar = $"{Helpers.InstanceField}.{name}"; - else { + else + { var typeName = TypePrinter.PrintNative(@class); if (IsInternalClassNested(field.Class)) typeName.RemoveNamespace(); @@ -1141,7 +1142,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat else type = originalType.ToString(); - var name = ((Class) field.Namespace).Layout.Fields.First( + var name = ((Class)field.Namespace).Layout.Fields.First( f => f.FieldPtr == field.OriginalPtr).Name; WriteLine(string.Format("fixed ({0} {1} = {2}.{3})", type, arrPtr, Helpers.InstanceField, name)); @@ -1276,7 +1277,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat { NewLine(); WriteOpenBraceAndIndent(); - var to = ((Class) property.OriginalNamespace).OriginalClass; + var to = ((Class)property.OriginalNamespace).OriginalClass; var baseOffset = GetOffsetToBase(@class, to); WriteLine("return {0} + {1};", Helpers.InstanceIdentifier, baseOffset); UnindentAndWriteCloseBrace(); @@ -1379,7 +1380,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat QualifiedType type = default; if (actualProperty != property || // indexers - (property.QualifiedType.Type.IsPrimitiveType() && + (property.QualifiedType.Type.IsPrimitiveType() && actualProperty.GetMethod.ReturnType.Type.IsPointerToPrimitiveType())) { type = property.QualifiedType; @@ -1415,7 +1416,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat private void GenerateFieldGetter(Field field, Class @class, QualifiedType returnType) { - var name = ((Class) field.Namespace).Layout.Fields.First( + var name = ((Class)field.Namespace).Layout.Fields.First( f => f.FieldPtr == field.OriginalPtr).Name; string returnVar; Type fieldType = field.Type.Desugar(); @@ -1473,11 +1474,11 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat !final.IsPrimitiveType(PrimitiveType.Char16) && !final.IsPrimitiveType(PrimitiveType.Char32)) || (!Context.Options.MarshalCharAsManagedChar && - !((PointerType) fieldType).QualifiedPointee.Qualifiers.IsConst)) && + !((PointerType)fieldType).QualifiedPointee.Qualifiers.IsConst)) && templateSubstitution == null) || - (!((PointerType) fieldType).QualifiedPointee.Qualifiers.IsConst && - (final.IsPrimitiveType(PrimitiveType.WideChar) || - final.IsPrimitiveType(PrimitiveType.Char16) || + (!((PointerType)fieldType).QualifiedPointee.Qualifiers.IsConst && + (final.IsPrimitiveType(PrimitiveType.WideChar) || + final.IsPrimitiveType(PrimitiveType.Char16) || final.IsPrimitiveType(PrimitiveType.Char32)))) Write($"({fieldType.GetPointee().Desugar()}*) "); } @@ -1512,7 +1513,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat if (methods.Count == 0) return; - var @class = (Class) methods[0].Namespace; + var @class = (Class)methods[0].Namespace; if (@class.IsValueType) foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore)) @@ -1649,7 +1650,8 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat if (!isIndexer) return prop.Name; - var @params = prop.Parameters.Select(param => { + var @params = prop.Parameters.Select(param => + { var p = new Parameter(param); p.Usage = ParameterUsage.In; return p; @@ -1671,7 +1673,8 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat if (variable.Initializer != null && !string.IsNullOrWhiteSpace(variable.Initializer.String)) GeneratePropertyGetterForVariableWithInitializer(variable, signature); - else { + else + { WriteLine(signature); WriteOpenBraceAndIndent(); @@ -1687,7 +1690,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat PopBlock(NewLineKind.BeforeNextBlock); } -#region Virtual Tables + #region Virtual Tables public List GetUniqueVTableMethodEntries(Class @class) { @@ -1718,7 +1721,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat // Generate a delegate type for each method. foreach (var method in wrappedEntries.Select(e => e.Method).Where(m => !m.Ignore)) GenerateVTableMethodDelegates(containingClass, method.Namespace.IsDependent ? - (Method) method.InstantiatedFrom : method); + (Method)method.InstantiatedFrom : method); var hasVirtualDtor = wrappedEntries.Any(e => e.Method.IsDestructor); bool hasDynamicBase = @class.NeedsBase && @class.BaseClass.IsDynamic; @@ -1839,7 +1842,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat {{ if (__VTables.IsTransient) __VTables = VTableLoader.SetupVTables(__Instance, destructorOnly); - }}", trimIndentation : true); + }}", trimIndentation: true); WriteLine("#endregion"); PopBlock(NewLineKind.BeforeNextBlock); @@ -1865,7 +1868,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat private void AllocateNewVTablesMS(Class @class, IList wrappedEntries, bool destructorOnly, string table) - { + { for (int i = 0; i < @class.Layout.VFTables.Count; i++) { VFTableInfo vftable = @class.Layout.VFTables[i]; @@ -1892,9 +1895,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat { string suffix = (destructorOnly ? "_dtor" : string.Empty) + (tableIndex == 0 ? string.Empty : tableIndex.ToString(CultureInfo.InvariantCulture)); - + WriteLine($"{table}[{tableIndex}] = CppSharp.Runtime.VTables.CloneTable(SafeHandles, instance, {vptrOffset}, {entries.Count});"); - + // fill the newly allocated v-table for (var i = 0; i < entries.Count; i++) { @@ -1908,7 +1911,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat // patch with pointers to managed code where needed WriteLine("{0}[{1}][{2}] = Thunks[{3}];", table, tableIndex, i - offsetRTTI, wrappedEntries.IndexOf(entry)); } - + if (!destructorOnly) WriteLine($"VTables.Methods[{tableIndex}] = new Delegate[{entries.Count}];"); } @@ -1974,7 +1977,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat Type returnType = method.OriginalReturnType.Type.Desugar(); bool isPrimitive = returnType.IsPrimitiveType(); bool isVoid = returnType.IsPrimitiveType(PrimitiveType.Void); - var property = ((Class) method.Namespace).Properties.Find( + var property = ((Class)method.Namespace).Properties.Find( p => p.GetMethod == method || p.SetMethod == method); bool isSetter = property != null && property.SetMethod == method; var hasReturn = !isVoid && !isSetter; @@ -2097,9 +2100,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat return @class.IsGenerated && @class.IsDynamic && GetUniqueVTableMethodEntries(@class).Count > 0; } -#endregion + #endregion -#region Events + #region Events public override bool VisitEvent(Event @event) { @@ -2207,9 +2210,9 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat UnindentAndWriteCloseBrace(); } -#endregion + #endregion -#region Constructors + #region Constructors public void GenerateClassConstructors(Class @class) { @@ -2394,7 +2397,7 @@ internal static bool {Helpers.TryGetNativeToManagedMappingIdentifier}(IntPtr nat private bool GenerateDestructorCall(Method dtor) { - var @class = (Class) dtor.Namespace; + var @class = (Class)dtor.Namespace; GenerateVirtualFunctionCall(dtor, true); if (@class.IsAbstract) { @@ -2518,7 +2521,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty public void GenerateNativeConstructorByValue(Class @class, TypePrinterResult returnType) { var @internal = TypePrinter.PrintNative(@class.IsAbstractImpl ? @class.BaseClass : @class); - + if (IsInternalClassNested(@class)) @internal.RemoveNamespace(); @@ -2605,9 +2608,9 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty WriteLineIndent(": this()"); } -#endregion + #endregion -#region Methods / Functions + #region Methods / Functions public void GenerateFunction(Function function, string parentName) { @@ -2732,7 +2735,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty c, method, method.OriginalReturnType)); } - SkipImpl: + SkipImpl: UnindentAndWriteCloseBrace(); @@ -2829,7 +2832,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty { if (function.OriginalFunction.GenerationKind == GenerationKind.Internal) { - var property = ((Class) function.Namespace).Properties.First( + var property = ((Class)function.Namespace).Properties.First( p => p.SetMethod == function.OriginalFunction); WriteLine($@"{property.Name} = {ExpressionPrinter.VisitParameter( function.Parameters.First(p => p.Kind == ParameterKind.Regular))};"); @@ -2844,7 +2847,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty parameter.Type.IsPointerToPrimitiveType(out primitiveType) && parameter.Usage == ParameterUsage.InOut && parameter.HasDefaultValue) { - var pointeeType = ((PointerType) parameter.Type).Pointee.ToString(); + var pointeeType = ((PointerType)parameter.Type).Pointee.ToString(); WriteLine($@"{pointeeType} param{j++} = { (primitiveType == PrimitiveType.Bool ? "false" : "0")};"); } @@ -2927,16 +2930,16 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty { Function @virtual = method; if (method.OriginalFunction != null && - !((Class) method.OriginalFunction.Namespace).IsInterface) + !((Class)method.OriginalFunction.Namespace).IsInterface) @virtual = method.OriginalFunction; var i = VTables.GetVTableIndex(@virtual); int vtableIndex = 0; - var @class = (Class) method.Namespace; + var @class = (Class)method.Namespace; var thisParam = method.Parameters.Find( p => p.Kind == ParameterKind.Extension); if (thisParam != null) - @class = (Class) method.OriginalFunction.Namespace; + @class = (Class)method.OriginalFunction.Namespace; if (Context.ParserOptions.IsMicrosoftAbi) vtableIndex = @class.Layout.VFTables.IndexOf(@class.Layout.VFTables.First( @@ -3094,7 +3097,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty Parameter operatorParam = null; if (method != null) { - var @class = (Class) method.Namespace; + var @class = (Class)method.Namespace; isValueType = @class.IsValueType; operatorParam = method.Parameters.FirstOrDefault( @@ -3186,7 +3189,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty if (operatorParam == null) { WriteLine($@"fixed ({Helpers.InternalStruct}{ - Helpers.GetSuffixForInternal((Class) originalFunction.Namespace)}* __instancePtr = &{ + Helpers.GetSuffixForInternal((Class)originalFunction.Namespace)}* __instancePtr = &{ Helpers.InstanceField})"); WriteOpenBraceAndIndent(); } @@ -3200,10 +3203,10 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty Write("var {0} = ", Helpers.ReturnIdentifier); if (method != null && !method.IsConstructor && method.OriginalFunction != null && - ((Method) method.OriginalFunction).IsConstructor) + ((Method)method.OriginalFunction).IsConstructor) { WriteLine($@"Marshal.AllocHGlobal({ - ((Class) method.OriginalNamespace).Layout.Size});"); + ((Class)method.OriginalNamespace).Layout.Size});"); names.Insert(0, Helpers.ReturnIdentifier); } WriteLine("{0}({1});", functionName, string.Join(", ", names)); @@ -3241,19 +3244,19 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty UnindentAndWriteCloseBrace(); var numFixedBlocks = @params.Count(param => param.HasUsingBlock); - for(var i = 0; i < numFixedBlocks; ++i) + for (var i = 0; i < numFixedBlocks; ++i) UnindentAndWriteCloseBrace(); } private string GetInstanceParam(Function function) { - var from = (Class) function.Namespace; + var from = (Class)function.Namespace; var to = (function.OriginalFunction == null || // we don't need to offset the instance with Itanium if there's an existing interface impl (Context.ParserOptions.IsItaniumLikeAbi && - !((Class) function.OriginalNamespace).IsInterface)) && + !((Class)function.OriginalNamespace).IsInterface)) && function.SynthKind != FunctionSynthKind.AbstractImplCall ? - @from.BaseClass : (Class) function.OriginalFunction.Namespace; + @from.BaseClass : (Class)function.OriginalFunction.Namespace; var baseOffset = 0u; if (to != null) @@ -3320,7 +3323,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty { // Do not delete instance in MS ABI. var name = param.Name; - var function = (Function) param.Namespace; + var function = (Function)param.Namespace; param.Name = param.Kind == ParameterKind.ImplicitDestructorParameter ? "0" : ActiveBlock.Parent.Kind != BlockKind.Property || function.OperatorKind == CXXOperatorKind.Subscript ? name : "value"; @@ -3377,7 +3380,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty return TypePrinter.VisitParameters(@params, true).Type; } -#endregion + #endregion public override bool VisitTypedefNameDecl(TypedefNameDecl typedef) { @@ -3394,7 +3397,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty var attributedType = typedef.Type.GetPointee() as AttributedType; var callingConvention = attributedType == null ? functionType.CallingConvention - : ((FunctionType) attributedType.Equivalent.Type).CallingConvention; + : ((FunctionType)attributedType.Equivalent.Type).CallingConvention; TypePrinter.PushContext(TypePrinterContextKind.Native); var interopCallConv = callingConvention.ToInteropCallConv(); if (interopCallConv == System.Runtime.InteropServices.CallingConvention.Winapi) @@ -3530,7 +3533,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty PushBlock(BlockKind.InternalsClassMethod); var callConv = function.CallingConvention.ToInteropCallConv(); - WriteLine("[SuppressUnmanagedCodeSecurity, DllImport(\"{0}\", EntryPoint = \"{1}\", CallingConvention = __CallingConvention.{2})]", + WriteLine("[SuppressUnmanagedCodeSecurity, DllImport(\"{0}\", EntryPoint = \"{1}\", CallingConvention = __CallingConvention.{2})]", GetLibraryOf(function), function.Mangled, callConv); @@ -3555,7 +3558,7 @@ internal static{(@new ? " new" : string.Empty)} {printedClass} __GetInstance({Ty string libName = declaration.TranslationUnit.Module.SharedLibraryName; NativeLibrary library; - Context.Symbols.FindLibraryBySymbol(((IMangledDecl) declaration).Mangled, out library); + Context.Symbols.FindLibraryBySymbol(((IMangledDecl)declaration).Mangled, out library); if (library != null) libName = Path.GetFileNameWithoutExtension(library.FileName); diff --git a/src/Generator/Generators/CSharp/CSharpTypePrinter.cs b/src/Generator/Generators/CSharp/CSharpTypePrinter.cs index 9e09467d..c31a0df8 100644 --- a/src/Generator/Generators/CSharp/CSharpTypePrinter.cs +++ b/src/Generator/Generators/CSharp/CSharpTypePrinter.cs @@ -136,7 +136,7 @@ namespace CppSharp.Generators.CSharp } } - + var arraySuffix = array.SizeType != ArrayType.ArraySize.Constant && MarshalKind == MarshalKind.ReturnVariableArray ? (ContextKind == TypePrinterContextKind.Managed && @@ -303,7 +303,7 @@ namespace CppSharp.Generators.CSharp template.Arguments.All(IsValid)) { List args = template.Arguments; - var @class = (Class) template.Template.TemplatedDecl; + var @class = (Class)template.Template.TemplatedDecl; TemplateArgument lastArg = args.Last(); TypePrinterResult typePrinterResult = VisitDeclaration(decl); typePrinterResult.NameSuffix.Append($@"<{string.Join(", ", @@ -467,16 +467,20 @@ namespace CppSharp.Generators.CSharp case PrimitiveType.LongLong: case PrimitiveType.ULongLong: return GetIntString(primitive, Context.TargetInfo); - case PrimitiveType.Int128: return new TypePrinterResult("fixed byte", - "[16]"); // The type is always 128 bits wide - case PrimitiveType.UInt128: return new TypePrinterResult("fixed byte", - "[16]"); // The type is always 128 bits wide - case PrimitiveType.Half: return new TypePrinterResult("fixed byte", - $"[{Context.TargetInfo.HalfWidth}]"); + case PrimitiveType.Int128: + return new TypePrinterResult("fixed byte", +"[16]"); // The type is always 128 bits wide + case PrimitiveType.UInt128: + return new TypePrinterResult("fixed byte", +"[16]"); // The type is always 128 bits wide + case PrimitiveType.Half: + return new TypePrinterResult("fixed byte", +$"[{Context.TargetInfo.HalfWidth}]"); case PrimitiveType.Float: return "float"; case PrimitiveType.Double: return "double"; - case PrimitiveType.LongDouble: return new TypePrinterResult("fixed byte", - $"[{Context.TargetInfo.LongDoubleWidth}]"); + case PrimitiveType.LongDouble: + return new TypePrinterResult("fixed byte", +$"[{Context.TargetInfo.LongDoubleWidth}]"); case PrimitiveType.IntPtr: return IntPtrType; case PrimitiveType.UIntPtr: return QualifiedType("System.UIntPtr"); case PrimitiveType.Null: return "void*"; @@ -692,7 +696,7 @@ namespace CppSharp.Generators.CSharp var returnTypePrinter = new TypePrinterResult(); returnTypePrinter.NameSuffix.Append(fieldTypePrinted.NameSuffix); - returnTypePrinter.Type = $"{fieldTypePrinted.Type} {field.Name}"; + returnTypePrinter.Type = $"{fieldTypePrinted.Type} {field.Name}"; return returnTypePrinter; } @@ -766,7 +770,7 @@ namespace CppSharp.Generators.CSharp private void AddContextName(Stack names, Declaration ctx) { - var isInlineNamespace = ctx is Namespace && ((Namespace) ctx).IsInline; + var isInlineNamespace = ctx is Namespace && ((Namespace)ctx).IsInline; if (string.IsNullOrWhiteSpace(ctx.Name) || isInlineNamespace) return; diff --git a/src/Generator/Generators/CodeGenerator.cs b/src/Generator/Generators/CodeGenerator.cs index 758d076b..f6d7d1d9 100644 --- a/src/Generator/Generators/CodeGenerator.cs +++ b/src/Generator/Generators/CodeGenerator.cs @@ -34,10 +34,10 @@ namespace CppSharp.Generators { if (!Options.CommentKind.HasValue) return CommentKind.BCPL; - + return Options.CommentKind.Value; } - } + } /// /// Gets the comment style kind for documentation comments. @@ -164,7 +164,7 @@ namespace CppSharp.Generators public virtual void GenerateMultiLineComment(List lines, CommentKind kind) { PushBlock(BlockKind.BlockComment); - + var lineCommentPrologue = Comment.GetLineCommentPrologue(kind); if (!string.IsNullOrWhiteSpace(lineCommentPrologue)) WriteLine("{0}", lineCommentPrologue); @@ -410,7 +410,7 @@ namespace CppSharp.Generators { if (property.GetMethod != null) property.GetMethod.Visit(this); - + if (property.SetMethod != null) property.SetMethod.Visit(this); } diff --git a/src/Generator/Generators/ITypePrinter.cs b/src/Generator/Generators/ITypePrinter.cs index 00739af3..20d4bf87 100644 --- a/src/Generator/Generators/ITypePrinter.cs +++ b/src/Generator/Generators/ITypePrinter.cs @@ -52,7 +52,7 @@ namespace CppSharp.AST { if (Kind == TypePrinterContextKind.Template) { - var template = (Template) Declaration; + var template = (Template)Declaration; return string.Join(", ", template.Parameters.Select(p => p.Name)); } @@ -63,12 +63,12 @@ namespace CppSharp.AST templateArgs = templateSpecializationType.Arguments; else { - var declaration = ((TagType) type).Declaration; + var declaration = ((TagType)type).Declaration; var specialization = declaration as ClassTemplateSpecialization; if (specialization == null) return string.Join(", ", - ((Class) declaration).TemplateParameters.Select(t => t.Name)); - templateArgs = ((ClassTemplateSpecialization) declaration).Arguments; + ((Class)declaration).TemplateParameters.Select(t => t.Name)); + templateArgs = ((ClassTemplateSpecialization)declaration).Arguments; } var paramsList = new List(); diff --git a/src/Generator/Generators/NAPI/NAPIMarshal.cs b/src/Generator/Generators/NAPI/NAPIMarshal.cs index 71b23546..c0cf7008 100644 --- a/src/Generator/Generators/NAPI/NAPIMarshal.cs +++ b/src/Generator/Generators/NAPI/NAPIMarshal.cs @@ -37,13 +37,13 @@ namespace CppSharp.Generators.NAPI { switch (array.SizeType) { - case ArrayType.ArraySize.Constant: - case ArrayType.ArraySize.Incomplete: - case ArrayType.ArraySize.Variable: - Context.Return.Write("nullptr"); - break; - default: - throw new System.NotImplementedException(); + case ArrayType.ArraySize.Constant: + case ArrayType.ArraySize.Incomplete: + case ArrayType.ArraySize.Variable: + Context.Return.Write("nullptr"); + break; + default: + throw new System.NotImplementedException(); } return true; @@ -81,48 +81,48 @@ namespace CppSharp.Generators.NAPI public static (string type, string func) GetNAPIPrimitiveType(PrimitiveType type) { - switch(type) + switch (type) { - case PrimitiveType.Bool: - return ("napi_boolean", "napi_get_boolean"); - case PrimitiveType.WideChar: - case PrimitiveType.Char: - case PrimitiveType.SChar: - case PrimitiveType.Char16: - case PrimitiveType.Char32: - case PrimitiveType.Short: - case PrimitiveType.Int: - case PrimitiveType.Long: - return ("napi_number", "napi_create_int32"); - case PrimitiveType.UChar: - case PrimitiveType.UShort: - case PrimitiveType.UInt: - case PrimitiveType.ULong: - return ("napi_number", "napi_create_uint32"); - case PrimitiveType.LongLong: - return ("napi_number", "napi_create_bigint_int64"); - case PrimitiveType.ULongLong: - return ("napi_number", "napi_create_bigint_uint64"); - case PrimitiveType.Half: - case PrimitiveType.Float: - case PrimitiveType.Double: - case PrimitiveType.LongDouble: - return ("napi_number", "napi_create_double"); - case PrimitiveType.Int128: - case PrimitiveType.UInt128: - case PrimitiveType.Float128: - return ("napi_bigint", "napi_create_bigint_words"); - case PrimitiveType.String: - return ("napi_string", "napi_create_string_latin1"); - case PrimitiveType.Null: - return ("napi_null", "napi_get_null"); - case PrimitiveType.Void: - return ("napi_undefined", "napi_get_undefined"); - case PrimitiveType.IntPtr: - case PrimitiveType.UIntPtr: - case PrimitiveType.Decimal: - default: - throw new ArgumentOutOfRangeException(nameof(type), type, null); + case PrimitiveType.Bool: + return ("napi_boolean", "napi_get_boolean"); + case PrimitiveType.WideChar: + case PrimitiveType.Char: + case PrimitiveType.SChar: + case PrimitiveType.Char16: + case PrimitiveType.Char32: + case PrimitiveType.Short: + case PrimitiveType.Int: + case PrimitiveType.Long: + return ("napi_number", "napi_create_int32"); + case PrimitiveType.UChar: + case PrimitiveType.UShort: + case PrimitiveType.UInt: + case PrimitiveType.ULong: + return ("napi_number", "napi_create_uint32"); + case PrimitiveType.LongLong: + return ("napi_number", "napi_create_bigint_int64"); + case PrimitiveType.ULongLong: + return ("napi_number", "napi_create_bigint_uint64"); + case PrimitiveType.Half: + case PrimitiveType.Float: + case PrimitiveType.Double: + case PrimitiveType.LongDouble: + return ("napi_number", "napi_create_double"); + case PrimitiveType.Int128: + case PrimitiveType.UInt128: + case PrimitiveType.Float128: + return ("napi_bigint", "napi_create_bigint_words"); + case PrimitiveType.String: + return ("napi_string", "napi_create_string_latin1"); + case PrimitiveType.Null: + return ("napi_null", "napi_get_null"); + case PrimitiveType.Void: + return ("napi_undefined", "napi_get_undefined"); + case PrimitiveType.IntPtr: + case PrimitiveType.UIntPtr: + case PrimitiveType.Decimal: + default: + throw new ArgumentOutOfRangeException(nameof(type), type, null); } } @@ -133,55 +133,55 @@ namespace CppSharp.Generators.NAPI switch (primitive) { - case PrimitiveType.Bool: - case PrimitiveType.WideChar: - case PrimitiveType.Char: - case PrimitiveType.SChar: - case PrimitiveType.Char16: - case PrimitiveType.Char32: - case PrimitiveType.Short: - case PrimitiveType.Int: - case PrimitiveType.Long: - case PrimitiveType.UChar: - case PrimitiveType.UShort: - case PrimitiveType.UInt: - case PrimitiveType.ULong: - case PrimitiveType.LongLong: - case PrimitiveType.ULongLong: - case PrimitiveType.Half: - case PrimitiveType.Float: - case PrimitiveType.Double: - case PrimitiveType.LongDouble: - Context.Before.WriteLine($"napi_value {result};"); - Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, &{result});"); - Context.Before.WriteLine("assert(status == napi_ok);"); - Context.Return.Write(result); - return true; - - case PrimitiveType.Int128: - case PrimitiveType.UInt128: - case PrimitiveType.Float128: - return true; - - case PrimitiveType.String: - Context.Before.WriteLine($"napi_value {result};"); - Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, NAPI_AUTO_LENGTH, &{result});"); - Context.Before.WriteLine("assert(status == napi_ok);"); - Context.Return.Write(result); - return true; - - case PrimitiveType.Null: - Context.Before.WriteLine($"napi_value {result};"); - Context.Before.WriteLine($"status = {func}(env, &{result});"); - Context.Before.WriteLine("assert(status == napi_ok);"); - Context.Return.Write(result); - return true; - - case PrimitiveType.IntPtr: - case PrimitiveType.UIntPtr: - case PrimitiveType.Decimal: - default: - throw new NotImplementedException(); + case PrimitiveType.Bool: + case PrimitiveType.WideChar: + case PrimitiveType.Char: + case PrimitiveType.SChar: + case PrimitiveType.Char16: + case PrimitiveType.Char32: + case PrimitiveType.Short: + case PrimitiveType.Int: + case PrimitiveType.Long: + case PrimitiveType.UChar: + case PrimitiveType.UShort: + case PrimitiveType.UInt: + case PrimitiveType.ULong: + case PrimitiveType.LongLong: + case PrimitiveType.ULongLong: + case PrimitiveType.Half: + case PrimitiveType.Float: + case PrimitiveType.Double: + case PrimitiveType.LongDouble: + Context.Before.WriteLine($"napi_value {result};"); + Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, &{result});"); + Context.Before.WriteLine("assert(status == napi_ok);"); + Context.Return.Write(result); + return true; + + case PrimitiveType.Int128: + case PrimitiveType.UInt128: + case PrimitiveType.Float128: + return true; + + case PrimitiveType.String: + Context.Before.WriteLine($"napi_value {result};"); + Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, NAPI_AUTO_LENGTH, &{result});"); + Context.Before.WriteLine("assert(status == napi_ok);"); + Context.Return.Write(result); + return true; + + case PrimitiveType.Null: + Context.Before.WriteLine($"napi_value {result};"); + Context.Before.WriteLine($"status = {func}(env, &{result});"); + Context.Before.WriteLine("assert(status == napi_ok);"); + Context.Return.Write(result); + return true; + + case PrimitiveType.IntPtr: + case PrimitiveType.UIntPtr: + case PrimitiveType.Decimal: + default: + throw new NotImplementedException(); } } @@ -255,15 +255,15 @@ namespace CppSharp.Generators.NAPI Context.Before.WriteLine("assert(status == napi_ok);"); Context.Before.NewLine(); -/* - var refId = $"__{Context.ReturnVarName}_ref"; - Context.Before.WriteLine($"napi_ref {refId};"); + /* + var refId = $"__{Context.ReturnVarName}_ref"; + Context.Before.WriteLine($"napi_ref {refId};"); - var dtorId = $"dtor_{NAPISources.GetCIdentifier(Context.Context, ctor)}"; - Context.Before.WriteLine($"status = napi_wrap(env, _this, {instanceId}, {dtorId}" + - $", nullptr, &{refId});"); - Context.Before.WriteLine("assert(status == napi_ok);"); -*/ + var dtorId = $"dtor_{NAPISources.GetCIdentifier(Context.Context, ctor)}"; + Context.Before.WriteLine($"status = napi_wrap(env, _this, {instanceId}, {dtorId}" + + $", nullptr, &{refId});"); + Context.Before.WriteLine("assert(status == napi_ok);"); + */ Context.Return.Write($"{instanceId}"); return true; @@ -332,7 +332,7 @@ namespace CppSharp.Generators.NAPI public class NAPIMarshalManagedToNativePrinter : MarshalPrinter { - public NAPIMarshalManagedToNativePrinter(MarshalContext ctx) + public NAPIMarshalManagedToNativePrinter(MarshalContext ctx) : base(ctx) { Context.MarshalToNative = this; @@ -365,9 +365,9 @@ namespace CppSharp.Generators.NAPI switch (array.SizeType) { - default: - Context.Return.Write("nullptr"); - break; + default: + Context.Return.Write("nullptr"); + break; } return true; @@ -450,54 +450,54 @@ namespace CppSharp.Generators.NAPI public static (string func, string type, string cast) GetNAPIPrimitiveGetter(PrimitiveType type) { - switch(type) + switch (type) { - case PrimitiveType.Bool: - return ("napi_get_value_bool", "bool", "bool"); - case PrimitiveType.WideChar: - return ("napi_get_value_int32", "int32_t", "wchar_t"); - case PrimitiveType.Char: - case PrimitiveType.SChar: - return ("napi_get_value_int32", "int32_t", "char"); - case PrimitiveType.Char16: - return ("napi_get_value_int32", "int32_t", "char16_t"); - case PrimitiveType.Char32: - return ("napi_get_value_int32", "int32_t", "char32_t"); - case PrimitiveType.Short: - case PrimitiveType.Int: - case PrimitiveType.Long: - return ("napi_get_value_int32", "int32_t", null); - case PrimitiveType.UChar: - case PrimitiveType.UShort: - case PrimitiveType.UInt: - case PrimitiveType.ULong: - return ("napi_get_value_uint32", "uint32_t", null); - case PrimitiveType.LongLong: - return ("napi_get_value_bigint_int64", "int64_t", null); - case PrimitiveType.ULongLong: - return ("napi_get_value_bigint_uint64", "uint64_t", null); - case PrimitiveType.Half: - case PrimitiveType.Float: - return ("napi_get_value_double", "double", "float"); - case PrimitiveType.Double: - case PrimitiveType.LongDouble: - return ("napi_get_value_double", "double", null); - case PrimitiveType.Int128: - case PrimitiveType.UInt128: - case PrimitiveType.Float128: - return (null, null, null); - case PrimitiveType.String: - return ("napi_get_value_string_utf8", "char*", null); - case PrimitiveType.Null: - return ("napi_get_null", null, null); - case PrimitiveType.Void: - return (null, null, null); - case PrimitiveType.IntPtr: - case PrimitiveType.UIntPtr: - return (null, null, null); - case PrimitiveType.Decimal: - default: - throw new NotImplementedException(); + case PrimitiveType.Bool: + return ("napi_get_value_bool", "bool", "bool"); + case PrimitiveType.WideChar: + return ("napi_get_value_int32", "int32_t", "wchar_t"); + case PrimitiveType.Char: + case PrimitiveType.SChar: + return ("napi_get_value_int32", "int32_t", "char"); + case PrimitiveType.Char16: + return ("napi_get_value_int32", "int32_t", "char16_t"); + case PrimitiveType.Char32: + return ("napi_get_value_int32", "int32_t", "char32_t"); + case PrimitiveType.Short: + case PrimitiveType.Int: + case PrimitiveType.Long: + return ("napi_get_value_int32", "int32_t", null); + case PrimitiveType.UChar: + case PrimitiveType.UShort: + case PrimitiveType.UInt: + case PrimitiveType.ULong: + return ("napi_get_value_uint32", "uint32_t", null); + case PrimitiveType.LongLong: + return ("napi_get_value_bigint_int64", "int64_t", null); + case PrimitiveType.ULongLong: + return ("napi_get_value_bigint_uint64", "uint64_t", null); + case PrimitiveType.Half: + case PrimitiveType.Float: + return ("napi_get_value_double", "double", "float"); + case PrimitiveType.Double: + case PrimitiveType.LongDouble: + return ("napi_get_value_double", "double", null); + case PrimitiveType.Int128: + case PrimitiveType.UInt128: + case PrimitiveType.Float128: + return (null, null, null); + case PrimitiveType.String: + return ("napi_get_value_string_utf8", "char*", null); + case PrimitiveType.Null: + return ("napi_get_null", null, null); + case PrimitiveType.Void: + return (null, null, null); + case PrimitiveType.IntPtr: + case PrimitiveType.UIntPtr: + return (null, null, null); + case PrimitiveType.Decimal: + default: + throw new NotImplementedException(); } } @@ -507,79 +507,79 @@ namespace CppSharp.Generators.NAPI switch (primitive) { - case PrimitiveType.Bool: - case PrimitiveType.WideChar: - case PrimitiveType.Char: - case PrimitiveType.SChar: - case PrimitiveType.Char16: - case PrimitiveType.Char32: - case PrimitiveType.Short: - case PrimitiveType.Int: - case PrimitiveType.Long: - case PrimitiveType.UChar: - case PrimitiveType.UShort: - case PrimitiveType.UInt: - case PrimitiveType.ULong: - case PrimitiveType.Half: - case PrimitiveType.Float: - case PrimitiveType.Double: - case PrimitiveType.LongDouble: - Context.Before.WriteLine($"{type} {Context.Parameter.Name};"); - Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}," + - $" &{Context.Parameter.Name});"); - - if (!string.IsNullOrEmpty(cast)) - Context.Return.Write($"({cast})"); - - Context.Return.Write($"{Context.Parameter.Name}"); - return true; - - case PrimitiveType.LongLong: - case PrimitiveType.ULongLong: - case PrimitiveType.Int128: - case PrimitiveType.UInt128: - case PrimitiveType.Float128: - Context.Before.WriteLine($"{type} {Context.Parameter.Name};"); - Context.Before.WriteLine("bool lossless;"); - Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}," + - $" &{Context.Parameter.Name}, &lossless);"); - - if (!string.IsNullOrEmpty(cast)) - Context.Return.Write($"({cast})"); - - Context.Return.Write($"{Context.Parameter.Name}"); - return true; - - case PrimitiveType.String: - var size = $"_{Context.Parameter.Name}_size"; - Context.Before.WriteLine($"size_t {size};"); - Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, " + - $"nullptr, 0, &{size});"); - Context.Before.NewLine(); - - var buf = $"{Context.Parameter.Name}"; - Context.Before.WriteLine($"char* {buf} = (char*) malloc({size});"); - Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, " + - $"nullptr, 0, &{size});"); - Context.Before.WriteLine("assert(status == napi_ok);"); - - Context.Cleanup.WriteLine($"free({buf});"); - Context.Return.Write($"{buf}"); - return true; - - case PrimitiveType.Null: - return true; - - case PrimitiveType.Void: - return true; - - case PrimitiveType.IntPtr: - case PrimitiveType.UIntPtr: - return true; - - case PrimitiveType.Decimal: - default: - throw new NotImplementedException(); + case PrimitiveType.Bool: + case PrimitiveType.WideChar: + case PrimitiveType.Char: + case PrimitiveType.SChar: + case PrimitiveType.Char16: + case PrimitiveType.Char32: + case PrimitiveType.Short: + case PrimitiveType.Int: + case PrimitiveType.Long: + case PrimitiveType.UChar: + case PrimitiveType.UShort: + case PrimitiveType.UInt: + case PrimitiveType.ULong: + case PrimitiveType.Half: + case PrimitiveType.Float: + case PrimitiveType.Double: + case PrimitiveType.LongDouble: + Context.Before.WriteLine($"{type} {Context.Parameter.Name};"); + Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}," + + $" &{Context.Parameter.Name});"); + + if (!string.IsNullOrEmpty(cast)) + Context.Return.Write($"({cast})"); + + Context.Return.Write($"{Context.Parameter.Name}"); + return true; + + case PrimitiveType.LongLong: + case PrimitiveType.ULongLong: + case PrimitiveType.Int128: + case PrimitiveType.UInt128: + case PrimitiveType.Float128: + Context.Before.WriteLine($"{type} {Context.Parameter.Name};"); + Context.Before.WriteLine("bool lossless;"); + Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}," + + $" &{Context.Parameter.Name}, &lossless);"); + + if (!string.IsNullOrEmpty(cast)) + Context.Return.Write($"({cast})"); + + Context.Return.Write($"{Context.Parameter.Name}"); + return true; + + case PrimitiveType.String: + var size = $"_{Context.Parameter.Name}_size"; + Context.Before.WriteLine($"size_t {size};"); + Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, " + + $"nullptr, 0, &{size});"); + Context.Before.NewLine(); + + var buf = $"{Context.Parameter.Name}"; + Context.Before.WriteLine($"char* {buf} = (char*) malloc({size});"); + Context.Before.WriteLine($"status = {func}(env, {Context.ArgName}, " + + $"nullptr, 0, &{size});"); + Context.Before.WriteLine("assert(status == napi_ok);"); + + Context.Cleanup.WriteLine($"free({buf});"); + Context.Return.Write($"{buf}"); + return true; + + case PrimitiveType.Null: + return true; + + case PrimitiveType.Void: + return true; + + case PrimitiveType.IntPtr: + case PrimitiveType.UIntPtr: + return true; + + case PrimitiveType.Decimal: + default: + throw new NotImplementedException(); } } @@ -672,15 +672,15 @@ namespace CppSharp.Generators.NAPI { var type = Context.Parameter.Type.Desugar(); -/* - TypeMap typeMap; - if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && - typeMap.DoesMarshalling) - { - typeMap.NAPIMarshalToNative(Context); - return; - } -*/ + /* + TypeMap typeMap; + if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && + typeMap.DoesMarshalling) + { + typeMap.NAPIMarshalToNative(Context); + return; + } + */ var instance = $"{Context.Parameter.Name}_instance"; Context.Before.WriteLine($"{@class.QualifiedOriginalName}* {instance};"); Context.Before.WriteLine($"status = napi_unwrap(env, _this, (void**) &{instance});"); diff --git a/src/Generator/Generators/NAPI/NAPISources.cs b/src/Generator/Generators/NAPI/NAPISources.cs index 6becd0bc..b6676f8b 100644 --- a/src/Generator/Generators/NAPI/NAPISources.cs +++ b/src/Generator/Generators/NAPI/NAPISources.cs @@ -804,9 +804,9 @@ namespace CppSharp.Generators.Cpp .Select(p => p.Type).Distinct().ToList(); // Consider the alphabet as sequential ordered numbers, one per type. - var Sigma = Enumerable.Range(0, uniqueTypes.Count).Select(i => (char) i).ToArray(); + var Sigma = Enumerable.Range(0, uniqueTypes.Count).Select(i => (char)i).ToArray(); - var Q = new List {"S"}; + var Q = new List { "S" }; var overloadStates = Enumerable.Range(0, functionGroup.Count).Select(i => $"F{i}") .ToArray(); @@ -831,12 +831,12 @@ namespace CppSharp.Generators.Cpp if (!isLastTransition) Q.Add(nextState); - Delta.Add(new Transition(curState, (char) typeIndex, nextState)); + Delta.Add(new Transition(curState, (char)typeIndex, nextState)); curState = nextState; } } - var Q0 = new List {"S"}; + var Q0 = new List { "S" }; var F = overloadStates; var NDFSM = new NDFSM(Q, Sigma, Delta, Q0, F); diff --git a/src/Generator/Generators/NAPI/NAPITypeCheckGen.cs b/src/Generator/Generators/NAPI/NAPITypeCheckGen.cs index 77c26bf2..335585f6 100644 --- a/src/Generator/Generators/NAPI/NAPITypeCheckGen.cs +++ b/src/Generator/Generators/NAPI/NAPITypeCheckGen.cs @@ -25,50 +25,50 @@ namespace CppSharp.Generators.Cpp var condition = string.Empty; switch (primitive) { - case PrimitiveType.Bool: - condition = $"NAPI_IS_BOOL(types[{ParameterIndex}])"; - break; - case PrimitiveType.Char: - case PrimitiveType.SChar: - case PrimitiveType.UChar: - case PrimitiveType.WideChar: - case PrimitiveType.Short: - case PrimitiveType.UShort: - case PrimitiveType.Int: - case PrimitiveType.Long: - case PrimitiveType.ULong: - condition = $"NAPI_IS_INT32(types[{ParameterIndex}], args[{ParameterIndex}])"; - break; - case PrimitiveType.UInt: - condition = $"NAPI_IS_UINT32(types[{ParameterIndex}], args[{ParameterIndex}])"; - break; - case PrimitiveType.LongLong: - condition = $"NAPI_IS_INT64(types[{ParameterIndex}], args[{ParameterIndex}])"; - break; - case PrimitiveType.ULongLong: - condition = $"NAPI_IS_UINT64(types[{ParameterIndex}], args[{ParameterIndex}])"; - break; - case PrimitiveType.Null: - condition = $"NAPI_IS_NULL(types[{ParameterIndex}])"; - break; - case PrimitiveType.Half: - case PrimitiveType.Float: - case PrimitiveType.Double: - case PrimitiveType.LongDouble: - condition = $"NAPI_IS_NUMBER(types[{ParameterIndex}])"; - break; - case PrimitiveType.Void: - case PrimitiveType.Char16: - case PrimitiveType.Char32: - case PrimitiveType.Int128: - case PrimitiveType.UInt128: - case PrimitiveType.Float128: - case PrimitiveType.IntPtr: - case PrimitiveType.UIntPtr: - case PrimitiveType.String: - case PrimitiveType.Decimal: - default: - throw new NotImplementedException(); + case PrimitiveType.Bool: + condition = $"NAPI_IS_BOOL(types[{ParameterIndex}])"; + break; + case PrimitiveType.Char: + case PrimitiveType.SChar: + case PrimitiveType.UChar: + case PrimitiveType.WideChar: + case PrimitiveType.Short: + case PrimitiveType.UShort: + case PrimitiveType.Int: + case PrimitiveType.Long: + case PrimitiveType.ULong: + condition = $"NAPI_IS_INT32(types[{ParameterIndex}], args[{ParameterIndex}])"; + break; + case PrimitiveType.UInt: + condition = $"NAPI_IS_UINT32(types[{ParameterIndex}], args[{ParameterIndex}])"; + break; + case PrimitiveType.LongLong: + condition = $"NAPI_IS_INT64(types[{ParameterIndex}], args[{ParameterIndex}])"; + break; + case PrimitiveType.ULongLong: + condition = $"NAPI_IS_UINT64(types[{ParameterIndex}], args[{ParameterIndex}])"; + break; + case PrimitiveType.Null: + condition = $"NAPI_IS_NULL(types[{ParameterIndex}])"; + break; + case PrimitiveType.Half: + case PrimitiveType.Float: + case PrimitiveType.Double: + case PrimitiveType.LongDouble: + condition = $"NAPI_IS_NUMBER(types[{ParameterIndex}])"; + break; + case PrimitiveType.Void: + case PrimitiveType.Char16: + case PrimitiveType.Char32: + case PrimitiveType.Int128: + case PrimitiveType.UInt128: + case PrimitiveType.Float128: + case PrimitiveType.IntPtr: + case PrimitiveType.UIntPtr: + case PrimitiveType.String: + case PrimitiveType.Decimal: + default: + throw new NotImplementedException(); } Write(condition); diff --git a/src/Generator/Generators/NAPI/NAPITypeCheckPass.cs b/src/Generator/Generators/NAPI/NAPITypeCheckPass.cs index adce337f..abae42eb 100644 --- a/src/Generator/Generators/NAPI/NAPITypeCheckPass.cs +++ b/src/Generator/Generators/NAPI/NAPITypeCheckPass.cs @@ -32,19 +32,19 @@ namespace CppSharp.Generators.C { switch (primitive) { - case PrimitiveType.LongDouble: - case PrimitiveType.Char16: - case PrimitiveType.Char32: - case PrimitiveType.Int128: - case PrimitiveType.UInt128: - case PrimitiveType.Float128: - case PrimitiveType.IntPtr: - case PrimitiveType.UIntPtr: - case PrimitiveType.Decimal: - Diagnostics.Warning($"Unsupported decl: {decl.QualifiedName}"); - return false; - default: - return true; + case PrimitiveType.LongDouble: + case PrimitiveType.Char16: + case PrimitiveType.Char32: + case PrimitiveType.Int128: + case PrimitiveType.UInt128: + case PrimitiveType.Float128: + case PrimitiveType.IntPtr: + case PrimitiveType.UIntPtr: + case PrimitiveType.Decimal: + Diagnostics.Warning($"Unsupported decl: {decl.QualifiedName}"); + return false; + default: + return true; } } diff --git a/src/Generator/Generators/QuickJS/QuickJSHeaders.cs b/src/Generator/Generators/QuickJS/QuickJSHeaders.cs index aab93000..20f53039 100644 --- a/src/Generator/Generators/QuickJS/QuickJSHeaders.cs +++ b/src/Generator/Generators/QuickJS/QuickJSHeaders.cs @@ -16,7 +16,7 @@ namespace CppSharp.Generators.Cpp CTypePrinter.PushContext(TypePrinterContextKind.Managed); } - public override bool ShouldGenerateNamespaces => false; + public override bool ShouldGenerateNamespaces => false; public override void Process() { diff --git a/src/Generator/Generators/QuickJS/QuickJSMarshal.cs b/src/Generator/Generators/QuickJS/QuickJSMarshal.cs index 47b53cb7..5de2ad04 100644 --- a/src/Generator/Generators/QuickJS/QuickJSMarshal.cs +++ b/src/Generator/Generators/QuickJS/QuickJSMarshal.cs @@ -36,13 +36,13 @@ namespace CppSharp.Generators.Cpp { switch (array.SizeType) { - case ArrayType.ArraySize.Constant: - case ArrayType.ArraySize.Incomplete: - case ArrayType.ArraySize.Variable: - Context.Return.Write("nullptr"); - break; - default: - throw new System.NotImplementedException(); + case ArrayType.ArraySize.Constant: + case ArrayType.ArraySize.Incomplete: + case ArrayType.ArraySize.Variable: + Context.Return.Write("nullptr"); + break; + default: + throw new System.NotImplementedException(); } return true; @@ -78,7 +78,7 @@ namespace CppSharp.Generators.Cpp Context.ReturnType.Qualifiers.IsConst) { var nativeTypePrinter = new CppTypePrinter(Context.Context) - { PrintTypeQualifiers = false }; + { PrintTypeQualifiers = false }; var returnType = Context.ReturnType.Type.Desugar(); var constlessPointer = new PointerType() { @@ -148,53 +148,53 @@ namespace CppSharp.Generators.Cpp switch (primitive) { - case PrimitiveType.Void: - return true; - - case PrimitiveType.Bool: - Context.Before.WriteLine($"JS_NewBool(ctx, {Context.ArgName});"); - break; - - case PrimitiveType.Char: - case PrimitiveType.Char16: - case PrimitiveType.Char32: - case PrimitiveType.WideChar: - case PrimitiveType.SChar: - case PrimitiveType.UChar: - case PrimitiveType.Short: - case PrimitiveType.UShort: - case PrimitiveType.Int: - case PrimitiveType.Long: - Context.Before.WriteLine($"JS_NewInt32(ctx, {Context.ArgName});"); - break; - - case PrimitiveType.UInt: - case PrimitiveType.ULong: - Context.Before.WriteLine($"JS_NewUint32(ctx, {Context.ArgName});"); - break; - - case PrimitiveType.LongLong: - Context.Before.WriteLine($"JS_NewBigInt64(ctx, {Context.ArgName});"); - break; - - case PrimitiveType.ULongLong: - Context.Before.WriteLine($"JS_NewBigUint64(ctx, {Context.ArgName});"); - break; - - case PrimitiveType.Float: - case PrimitiveType.Double: - Context.Before.WriteLine($"JS_NewFloat64(ctx, {Context.ArgName});"); - break; - - case PrimitiveType.LongDouble: - throw new NotImplementedException(); - - case PrimitiveType.Null: - Context.Before.WriteLine($"JS_NULL;"); - break; - - default: - throw new NotImplementedException(); + case PrimitiveType.Void: + return true; + + case PrimitiveType.Bool: + Context.Before.WriteLine($"JS_NewBool(ctx, {Context.ArgName});"); + break; + + case PrimitiveType.Char: + case PrimitiveType.Char16: + case PrimitiveType.Char32: + case PrimitiveType.WideChar: + case PrimitiveType.SChar: + case PrimitiveType.UChar: + case PrimitiveType.Short: + case PrimitiveType.UShort: + case PrimitiveType.Int: + case PrimitiveType.Long: + Context.Before.WriteLine($"JS_NewInt32(ctx, {Context.ArgName});"); + break; + + case PrimitiveType.UInt: + case PrimitiveType.ULong: + Context.Before.WriteLine($"JS_NewUint32(ctx, {Context.ArgName});"); + break; + + case PrimitiveType.LongLong: + Context.Before.WriteLine($"JS_NewBigInt64(ctx, {Context.ArgName});"); + break; + + case PrimitiveType.ULongLong: + Context.Before.WriteLine($"JS_NewBigUint64(ctx, {Context.ArgName});"); + break; + + case PrimitiveType.Float: + case PrimitiveType.Double: + Context.Before.WriteLine($"JS_NewFloat64(ctx, {Context.ArgName});"); + break; + + case PrimitiveType.LongDouble: + throw new NotImplementedException(); + + case PrimitiveType.Null: + Context.Before.WriteLine($"JS_NULL;"); + break; + + default: + throw new NotImplementedException(); } Context.Return.Write(retName); @@ -296,7 +296,7 @@ namespace CppSharp.Generators.Cpp { WriteClassInstance(@class.CompleteDeclaration as Class, instance); return; - } + } if (!Context.ReturnType.Type.Desugar().IsPointer()) { @@ -371,7 +371,7 @@ namespace CppSharp.Generators.Cpp public readonly TextGenerator VarPrefix; public readonly TextGenerator ArgumentPrefix; - public QuickJSMarshalManagedToNativePrinter(MarshalContext ctx) + public QuickJSMarshalManagedToNativePrinter(MarshalContext ctx) : base(ctx) { VarPrefix = new TextGenerator(); @@ -407,9 +407,9 @@ namespace CppSharp.Generators.Cpp switch (array.SizeType) { - default: - Context.Return.Write("nullptr"); - break; + default: + Context.Return.Write("nullptr"); + break; } return true; @@ -496,82 +496,82 @@ namespace CppSharp.Generators.Cpp switch (primitive) { - case PrimitiveType.Void: - return true; - - case PrimitiveType.Bool: - Context.Before.WriteLine($"{argName} = JS_ToBool(ctx, argv[{Context.ParameterIndex}]);"); - Context.Before.WriteLine($"if ({argName} == -1)"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.Char: - case PrimitiveType.SChar: - case PrimitiveType.UChar: - Context.Before.WriteLine($"int32_t _{argName};"); - Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Before.WriteLine($"{argName} = ({type})_{argName};"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.Short: - case PrimitiveType.UShort: - Context.Before.WriteLine($"int32_t _{argName};"); - Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Before.WriteLine($"{argName} = ({type})_{argName};"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.Int: - case PrimitiveType.Long: - Context.Before.WriteLine($"if (JS_ToInt32(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.UInt: - case PrimitiveType.ULong: - Context.Before.WriteLine($"if (JS_ToUint32(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.LongLong: - Context.Before.WriteLine($"int64_t _{argName};"); - Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Before.WriteLine($"{argName} = ({type})_{argName};"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.ULongLong: - Context.Before.WriteLine($"int64_t _{argName};"); - Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Before.WriteLine($"{argName} = ({type})_{argName};"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.Float: - Context.Before.WriteLine($"double _{argName};"); - Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Before.WriteLine($"{argName} = ({type})_{argName};"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.Double: - Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); - Context.Before.WriteLineIndent("return JS_EXCEPTION;"); - Context.Return.Write($"{argName}"); - return true; - - case PrimitiveType.WideChar: - default: - throw new NotImplementedException(); + case PrimitiveType.Void: + return true; + + case PrimitiveType.Bool: + Context.Before.WriteLine($"{argName} = JS_ToBool(ctx, argv[{Context.ParameterIndex}]);"); + Context.Before.WriteLine($"if ({argName} == -1)"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.Char: + case PrimitiveType.SChar: + case PrimitiveType.UChar: + Context.Before.WriteLine($"int32_t _{argName};"); + Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Before.WriteLine($"{argName} = ({type})_{argName};"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.Short: + case PrimitiveType.UShort: + Context.Before.WriteLine($"int32_t _{argName};"); + Context.Before.WriteLine($"if (JS_ToInt32(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Before.WriteLine($"{argName} = ({type})_{argName};"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.Int: + case PrimitiveType.Long: + Context.Before.WriteLine($"if (JS_ToInt32(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.UInt: + case PrimitiveType.ULong: + Context.Before.WriteLine($"if (JS_ToUint32(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.LongLong: + Context.Before.WriteLine($"int64_t _{argName};"); + Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Before.WriteLine($"{argName} = ({type})_{argName};"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.ULongLong: + Context.Before.WriteLine($"int64_t _{argName};"); + Context.Before.WriteLine($"if (JS_ToInt64Ext(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Before.WriteLine($"{argName} = ({type})_{argName};"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.Float: + Context.Before.WriteLine($"double _{argName};"); + Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &_{argName}, argv[{Context.ParameterIndex}]))"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Before.WriteLine($"{argName} = ({type})_{argName};"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.Double: + Context.Before.WriteLine($"if (JS_ToFloat64(ctx, &{argName}, argv[{Context.ParameterIndex}]))"); + Context.Before.WriteLineIndent("return JS_EXCEPTION;"); + Context.Return.Write($"{argName}"); + return true; + + case PrimitiveType.WideChar: + default: + throw new NotImplementedException(); } } diff --git a/src/Generator/Generators/QuickJS/QuickJSSources.cs b/src/Generator/Generators/QuickJS/QuickJSSources.cs index c0d55f34..3facf63f 100644 --- a/src/Generator/Generators/QuickJS/QuickJSSources.cs +++ b/src/Generator/Generators/QuickJS/QuickJSSources.cs @@ -289,7 +289,7 @@ namespace CppSharp.Generators.Cpp //WriteLine($"printf(\"Calling finalizer for {@class.QualifiedOriginalName}\\n\");"); - if(ClassNeedsExtraData(@class)) + if (ClassNeedsExtraData(@class)) { // Remove the event connection from the delegate. // var invokeId = $"event_invoke_{@event.OriginalName}"; @@ -456,19 +456,19 @@ namespace CppSharp.Generators.Cpp //WriteLine($"{@class.QualifiedOriginalName}* instance = data->instance;"); -/* + /* - if (!isVoidReturn) - { - CTypePrinter.PushContext(TypePrinterContextKind.Native); - var returnType = function.ReturnType.Visit(CTypePrinter); - CTypePrinter.PopContext(); + if (!isVoidReturn) + { + CTypePrinter.PushContext(TypePrinterContextKind.Native); + var returnType = function.ReturnType.Visit(CTypePrinter); + CTypePrinter.PopContext(); - Write($"{returnType} {Helpers.ReturnIdentifier} = "); - } + Write($"{returnType} {Helpers.ReturnIdentifier} = "); + } - var @class = function.Namespace as Class; -*/ + var @class = function.Namespace as Class; + */ UnindentAndWriteCloseBrace(); } @@ -783,7 +783,7 @@ namespace CppSharp.Generators.Cpp { WriteLine($"{@class.QualifiedOriginalName}* instance;"); } - else if(QuickJSRegister.ClassNeedsExtraData(@class)) + else if (QuickJSRegister.ClassNeedsExtraData(@class)) { var classDataId = $"data_{GetCIdentifier(Context, @class)}"; WriteLine($"auto data = ({classDataId}*) JS_GetOpaque(this_val, 0);"); diff --git a/src/Generator/Generators/QuickJS/QuickJSTypeCheckGen.cs b/src/Generator/Generators/QuickJS/QuickJSTypeCheckGen.cs index c166c93e..39ddb515 100644 --- a/src/Generator/Generators/QuickJS/QuickJSTypeCheckGen.cs +++ b/src/Generator/Generators/QuickJS/QuickJSTypeCheckGen.cs @@ -29,64 +29,64 @@ namespace CppSharp.Generators.Cpp var arg = $"argv[{ParameterIndex}]"; switch (primitive) { - case PrimitiveType.Bool: - condition = $"JS_IsBool({arg})"; - break; - case PrimitiveType.Char: - case PrimitiveType.SChar: - condition = $"JS_IsInt8({arg})"; - break; - case PrimitiveType.UChar: - condition = $"JS_IsUInt8({arg})"; - break; - case PrimitiveType.WideChar: - condition = $"JS_IsUInt16({arg})"; - break; - case PrimitiveType.Short: - condition = $"JS_IsInt16({arg})"; - break; - case PrimitiveType.UShort: - condition = $"JS_IsUInt16({arg})"; - break; - case PrimitiveType.Int: - case PrimitiveType.Long: - condition = $"JS_IsInt32({arg})"; - break; - case PrimitiveType.ULong: - case PrimitiveType.UInt: - condition = $"JS_IsUInt32({arg})"; - break; - case PrimitiveType.LongLong: - case PrimitiveType.ULongLong: - case PrimitiveType.Int128: - case PrimitiveType.UInt128: - condition = $"JS_IsBigInt(ctx, {arg})"; - break; - case PrimitiveType.Half: - case PrimitiveType.Float: - case PrimitiveType.Double: - condition = $"JS_IsFloat({arg})"; - break; - case PrimitiveType.LongDouble: - case PrimitiveType.Float128: - condition = $"JS_IsBigFloat({arg})"; - break; - case PrimitiveType.String: - condition = $"JS_IsString({arg}) || JS_IsNull({arg})"; - break; - case PrimitiveType.Decimal: - condition = $"JS_IsBigDecimal({arg})"; - break; - case PrimitiveType.Null: - condition = $"JS_IsNull({arg})"; - break; - case PrimitiveType.Void: - case PrimitiveType.Char16: - case PrimitiveType.Char32: - case PrimitiveType.IntPtr: - case PrimitiveType.UIntPtr: - default: - throw new NotImplementedException(); + case PrimitiveType.Bool: + condition = $"JS_IsBool({arg})"; + break; + case PrimitiveType.Char: + case PrimitiveType.SChar: + condition = $"JS_IsInt8({arg})"; + break; + case PrimitiveType.UChar: + condition = $"JS_IsUInt8({arg})"; + break; + case PrimitiveType.WideChar: + condition = $"JS_IsUInt16({arg})"; + break; + case PrimitiveType.Short: + condition = $"JS_IsInt16({arg})"; + break; + case PrimitiveType.UShort: + condition = $"JS_IsUInt16({arg})"; + break; + case PrimitiveType.Int: + case PrimitiveType.Long: + condition = $"JS_IsInt32({arg})"; + break; + case PrimitiveType.ULong: + case PrimitiveType.UInt: + condition = $"JS_IsUInt32({arg})"; + break; + case PrimitiveType.LongLong: + case PrimitiveType.ULongLong: + case PrimitiveType.Int128: + case PrimitiveType.UInt128: + condition = $"JS_IsBigInt(ctx, {arg})"; + break; + case PrimitiveType.Half: + case PrimitiveType.Float: + case PrimitiveType.Double: + condition = $"JS_IsFloat({arg})"; + break; + case PrimitiveType.LongDouble: + case PrimitiveType.Float128: + condition = $"JS_IsBigFloat({arg})"; + break; + case PrimitiveType.String: + condition = $"JS_IsString({arg}) || JS_IsNull({arg})"; + break; + case PrimitiveType.Decimal: + condition = $"JS_IsBigDecimal({arg})"; + break; + case PrimitiveType.Null: + condition = $"JS_IsNull({arg})"; + break; + case PrimitiveType.Void: + case PrimitiveType.Char16: + case PrimitiveType.Char32: + case PrimitiveType.IntPtr: + case PrimitiveType.UIntPtr: + default: + throw new NotImplementedException(); } Write(condition); diff --git a/src/Generator/Generators/TS/TSSources.cs b/src/Generator/Generators/TS/TSSources.cs index 64a5b892..8642136c 100644 --- a/src/Generator/Generators/TS/TSSources.cs +++ b/src/Generator/Generators/TS/TSSources.cs @@ -146,7 +146,7 @@ namespace CppSharp.Generators.TS return false; //if (@class.IsOpaque) - // return false; + // return false; PushBlock(BlockKind.Class, @class); @@ -240,7 +240,7 @@ namespace CppSharp.Generators.TS Indent(); - var @class = (Class) methods[0].Namespace; + var @class = (Class)methods[0].Namespace; if (@class.IsValueType) foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore)) @@ -267,7 +267,7 @@ namespace CppSharp.Generators.TS method.Visit(this); } - foreach(var method in staticMethods) + foreach (var method in staticMethods) method.Visit(this); Unindent(); diff --git a/src/Generator/Generators/TS/TSTypePrinter.cs b/src/Generator/Generators/TS/TSTypePrinter.cs index d53107df..2c61cbfb 100644 --- a/src/Generator/Generators/TS/TSTypePrinter.cs +++ b/src/Generator/Generators/TS/TSTypePrinter.cs @@ -24,7 +24,7 @@ namespace CppSharp.Generators.TS return declaration.TranslationUnit?.Module?.LibraryName; } - public override TypePrinterResult GetDeclName(Declaration declaration, TypePrintScopeKind scope) + public override TypePrinterResult GetDeclName(Declaration declaration, TypePrintScopeKind scope) { var result = base.GetDeclName(declaration, scope); result.Type = result.Type.Replace("::", NamespaceSeparator); @@ -41,7 +41,7 @@ namespace CppSharp.Generators.TS return VisitPrimitiveType(builtin.Type); } - public override TypePrinterResult VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals) + public override TypePrinterResult VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals) { return VisitPrimitiveType(primitive); } @@ -142,23 +142,23 @@ namespace CppSharp.Generators.TS result.Name = param.Name; -/* - if (param.DefaultArgument != null && Options.GenerateDefaultValuesForArguments) - { - try - { - var expressionPrinter = new CSharpExpressionPrinter(this); - var defaultValue = expressionPrinter.VisitParameter(param); - return $"{result} = {defaultValue}"; - } - catch (Exception) - { - var function = param.Namespace as Function; - Diagnostics.Warning($"Error printing default argument expression: " + - $"{function.QualifiedOriginalName}({param.OriginalName})"); - } - } -*/ + /* + if (param.DefaultArgument != null && Options.GenerateDefaultValuesForArguments) + { + try + { + var expressionPrinter = new CSharpExpressionPrinter(this); + var defaultValue = expressionPrinter.VisitParameter(param); + return $"{result} = {defaultValue}"; + } + catch (Exception) + { + var function = param.Namespace as Function; + Diagnostics.Warning($"Error printing default argument expression: " + + $"{function.QualifiedOriginalName}({param.OriginalName})"); + } + } + */ return $"{result}"; } diff --git a/src/Generator/Library.cs b/src/Generator/Library.cs index dace412d..1c866235 100644 --- a/src/Generator/Library.cs +++ b/src/Generator/Library.cs @@ -286,7 +286,7 @@ namespace CppSharp { var units = list.Select(item => item.TranslationUnit) .GroupBy(x => x) - .Select(y => new {Element = y.Key, Counter = y.Count()}); + .Select(y => new { Element = y.Key, Counter = y.Count() }); var translationUnit = units.OrderByDescending(u => u.Counter) .FirstOrDefault()?.Element ?? null; @@ -341,7 +341,7 @@ namespace CppSharp maxValue = (ulong)@enum.Items.Max(i => Math.Max(0, unchecked((long)i.Value))); minValue = @enum.Items.Min(i => unchecked((long)i.Value)); } - + @enum.BuiltinType = new BuiltinType(GetUnderlyingTypeForEnumValue(maxValue, minValue)); @enum.Type = @enum.BuiltinType; @@ -493,8 +493,8 @@ namespace CppSharp string className, string methodName, int parameterCount, int parameterIndex, ParameterUsage usage) { - if (parameterIndex <= 0 ) - throw new ArgumentException("parameterIndex"); + if (parameterIndex <= 0) + throw new ArgumentException("parameterIndex"); var @class = context.FindCompleteClass(className); @@ -635,7 +635,7 @@ namespace CppSharp public static void IgnoreHeadersWithName(this ASTContext context, IEnumerable patterns) { - foreach(var pattern in patterns) + foreach (var pattern in patterns) context.IgnoreHeadersWithName(pattern); } diff --git a/src/Generator/Passes/CheckAbiParameters.cs b/src/Generator/Passes/CheckAbiParameters.cs index ca6beb3d..701c607c 100644 --- a/src/Generator/Passes/CheckAbiParameters.cs +++ b/src/Generator/Passes/CheckAbiParameters.cs @@ -33,20 +33,20 @@ namespace CppSharp.Passes var isReturnIndirect = function.IsReturnIndirect || ( Context.ParserOptions.IsMicrosoftAbi && function is Method && - !function.ReturnType.Type.Desugar().IsAddress() && - function.ReturnType.Type.Desugar().TryGetDeclaration(out Class returnTypeDecl) && - returnTypeDecl.IsPOD && + !function.ReturnType.Type.Desugar().IsAddress() && + function.ReturnType.Type.Desugar().TryGetDeclaration(out Class returnTypeDecl) && + returnTypeDecl.IsPOD && returnTypeDecl.Layout.Size <= 8); if (isReturnIndirect) { var indirectParam = new Parameter() - { - Kind = ParameterKind.IndirectReturnType, - QualifiedType = function.ReturnType, - Name = "return", - Namespace = function - }; + { + Kind = ParameterKind.IndirectReturnType, + QualifiedType = function.ReturnType, + Name = "return", + Namespace = function + }; function.Parameters.Insert(0, indirectParam); function.ReturnType = new QualifiedType(new BuiltinType( @@ -59,7 +59,7 @@ namespace CppSharp.Passes { // This flag should only be true on methods. var classType = new QualifiedType(new TagType(method.Namespace), - new TypeQualifiers {IsConst = true}); + new TypeQualifiers { IsConst = true }); function.ReturnType = new QualifiedType(new PointerType(classType)); } diff --git a/src/Generator/Passes/CheckAmbiguousFunctions.cs b/src/Generator/Passes/CheckAmbiguousFunctions.cs index 02481b27..09f848bb 100644 --- a/src/Generator/Passes/CheckAmbiguousFunctions.cs +++ b/src/Generator/Passes/CheckAmbiguousFunctions.cs @@ -46,7 +46,7 @@ namespace CppSharp.Passes if (!overload.IsGenerated) continue; - var ambiguous = + var ambiguous = function.OperatorKind == CXXOperatorKind.Conversion || function.OperatorKind == CXXOperatorKind.ExplicitConversion ? CheckConversionAmbiguity(function, overload) @@ -185,7 +185,7 @@ namespace CppSharp.Passes var type1 = method1.ReturnType.Type.Desugar(); var type2 = method2.ReturnType.Type.Desugar(); - if (type1 is PointerType pointerType1 && + if (type1 is PointerType pointerType1 && type2 is PointerType pointerType2) { type1 = pointerType1.GetPointee(); diff --git a/src/Generator/Passes/CheckIgnoredDecls.cs b/src/Generator/Passes/CheckIgnoredDecls.cs index 1fd8f2d6..5b9dfc5f 100644 --- a/src/Generator/Passes/CheckIgnoredDecls.cs +++ b/src/Generator/Passes/CheckIgnoredDecls.cs @@ -145,8 +145,8 @@ namespace CppSharp.Passes public override bool VisitFunctionTemplateDecl(FunctionTemplate decl) { - if (!base.VisitFunctionTemplateDecl(decl)) - return false; + if (!base.VisitFunctionTemplateDecl(decl)) + return false; if (decl.TemplatedFunction.IsDependent && !decl.IsExplicitlyGenerated) { @@ -454,7 +454,7 @@ namespace CppSharp.Passes /// private bool HasInvalidType(ITypedDecl decl, out string msg) { - return HasInvalidType(decl.Type, (Declaration) decl, out msg); + return HasInvalidType(decl.Type, (Declaration)decl, out msg); } private bool HasInvalidType(Type type, Declaration decl, out string msg) @@ -506,7 +506,7 @@ namespace CppSharp.Passes } var @class = decl as Class; - if (@class != null && @class.IsOpaque && !@class.IsDependent && + if (@class != null && @class.IsOpaque && !@class.IsDependent && !(@class is ClassTemplateSpecialization)) { msg = null; diff --git a/src/Generator/Passes/CheckMacrosPass.cs b/src/Generator/Passes/CheckMacrosPass.cs index a1063f27..4da8203a 100644 --- a/src/Generator/Passes/CheckMacrosPass.cs +++ b/src/Generator/Passes/CheckMacrosPass.cs @@ -177,7 +177,7 @@ namespace CppSharp.Passes var quals = field.QualifiedType.Qualifiers; quals.IsConst = true; - var qualType = field.QualifiedType; + var qualType = field.QualifiedType; qualType.Qualifiers = quals; field.QualifiedType = qualType; diff --git a/src/Generator/Passes/CheckOperatorsOverloads.cs b/src/Generator/Passes/CheckOperatorsOverloads.cs index 081259da..a2597fa5 100644 --- a/src/Generator/Passes/CheckOperatorsOverloads.cs +++ b/src/Generator/Passes/CheckOperatorsOverloads.cs @@ -81,24 +81,24 @@ namespace CppSharp.Passes private void CreateIndexer(Class @class, Method @operator) { var property = new Property - { - Name = "Item", - QualifiedType = @operator.ReturnType, - Access = @operator.Access, - Namespace = @class, - GetMethod = @operator - }; + { + Name = "Item", + QualifiedType = @operator.ReturnType, + Access = @operator.Access, + Namespace = @class, + GetMethod = @operator + }; var returnType = @operator.Type; if (returnType.IsAddress() && !returnType.GetQualifiedPointee().Type.Desugar().IsPrimitiveType(PrimitiveType.Void)) { - var pointer = (PointerType) returnType; + var pointer = (PointerType)returnType; var qualifiedPointee = pointer.QualifiedPointee; if (!qualifiedPointee.Qualifiers.IsConst) property.SetMethod = @operator; } - + // If we've a setter use the pointee as the type of the property. var pointerType = property.Type as PointerType; if (pointerType != null && property.HasSetter) @@ -130,14 +130,14 @@ namespace CppSharp.Passes continue; var method = new Method() - { - Name = Operators.GetOperatorIdentifier(missingKind), - Namespace = @class, - SynthKind = FunctionSynthKind.ComplementOperator, - Kind = CXXMethodKind.Operator, - OperatorKind = missingKind, - ReturnType = op.ReturnType - }; + { + Name = Operators.GetOperatorIdentifier(missingKind), + Namespace = @class, + SynthKind = FunctionSynthKind.ComplementOperator, + Kind = CXXMethodKind.Operator, + OperatorKind = missingKind, + ReturnType = op.ReturnType + }; method.Parameters.AddRange(op.Parameters.Select( p => new Parameter(p) { Namespace = method })); diff --git a/src/Generator/Passes/CheckStaticClass.cs b/src/Generator/Passes/CheckStaticClass.cs index 16d9743e..7b4e2844 100644 --- a/src/Generator/Passes/CheckStaticClass.cs +++ b/src/Generator/Passes/CheckStaticClass.cs @@ -31,7 +31,7 @@ namespace CppSharp.Passes { if (decl.Access != AccessSpecifier.Protected) return false; - + var @class = decl.Namespace as Class; return @class != null && @class.IsStatic; } @@ -58,7 +58,7 @@ namespace CppSharp.Passes if (tag == null) return false; - var @class = (Class) function.Namespace; + var @class = (Class)function.Namespace; var decl = tag.Declaration; if (!(decl is Class)) diff --git a/src/Generator/Passes/CleanCommentsPass.cs b/src/Generator/Passes/CleanCommentsPass.cs index 27c2226b..79039549 100644 --- a/src/Generator/Passes/CleanCommentsPass.cs +++ b/src/Generator/Passes/CleanCommentsPass.cs @@ -52,14 +52,14 @@ namespace CppSharp.Passes i + 1 < comment.Content.Count && comment.Content[i + 1].Kind == DocumentationCommentKind.TextComment) { - var textComment = (TextComment) comment.Content[i + 1]; + var textComment = (TextComment)comment.Content[i + 1]; textComment.Text = Helpers.RegexCommentCommandLeftover.Replace( textComment.Text, string.Empty); } } foreach (var item in comment.Content.Where(c => c.Kind == DocumentationCommentKind.TextComment)) { - var textComment = (TextComment) item; + var textComment = (TextComment)item; if (textComment.Text.StartsWith("<", StringComparison.Ordinal)) textComment.Text = $"{textComment.Text}>"; diff --git a/src/Generator/Passes/ConstructorToConversionOperatorPass.cs b/src/Generator/Passes/ConstructorToConversionOperatorPass.cs index 70d9a6c8..b6cb106f 100644 --- a/src/Generator/Passes/ConstructorToConversionOperatorPass.cs +++ b/src/Generator/Passes/ConstructorToConversionOperatorPass.cs @@ -82,12 +82,12 @@ namespace CppSharp.Passes FunctionType = method.FunctionType }; conversionOperator.Parameters.Add(new Parameter(parameter) - { - Namespace = conversionOperator, - DefaultArgument = null, - OriginalDefaultArgument = null - }); - ((Class) method.Namespace).Methods.Add(conversionOperator); + { + Namespace = conversionOperator, + DefaultArgument = null, + OriginalDefaultArgument = null + }); + ((Class)method.Namespace).Methods.Add(conversionOperator); return true; } diff --git a/src/Generator/Passes/DelegatesPass.cs b/src/Generator/Passes/DelegatesPass.cs index f647da57..591eb2d0 100644 --- a/src/Generator/Passes/DelegatesPass.cs +++ b/src/Generator/Passes/DelegatesPass.cs @@ -63,11 +63,11 @@ namespace CppSharp.Passes return false; var functionType = new FunctionType - { - CallingConvention = method.CallingConvention, - IsDependent = method.IsDependent, - ReturnType = method.ReturnType - }; + { + CallingConvention = method.CallingConvention, + IsDependent = method.IsDependent, + ReturnType = method.ReturnType + }; TypePrinter.PushMarshalKind(MarshalKind.VTableReturnValue); functionType.Parameters.AddRange( @@ -92,7 +92,7 @@ namespace CppSharp.Passes public override bool VisitParameterDecl(Parameter parameter) { - if(parameter.Namespace?.TranslationUnit?.Module == null && namespaces.Count > 0) + if (parameter.Namespace?.TranslationUnit?.Module == null && namespaces.Count > 0) parameter.Namespace = namespaces.Peek(); if (!base.VisitDeclaration(parameter) || parameter.Namespace == null || @@ -170,7 +170,7 @@ namespace CppSharp.Passes existingDelegate.Access = access; // Check if there is an existing delegate with a different calling convention - if (((FunctionType) existingDelegate.Type.GetPointee()).CallingConvention == + if (((FunctionType)existingDelegate.Type.GetPointee()).CallingConvention == functionType.CallingConvention) return existingDelegate; @@ -184,13 +184,13 @@ namespace CppSharp.Passes var namespaceDelegates = GetDeclContextForDelegates(declarationContext); var delegateType = new QualifiedType(new PointerType(new QualifiedType(functionType))); existingDelegate = new TypedefDecl - { - Access = access, - Name = delegateName, - Namespace = namespaceDelegates, - QualifiedType = delegateType, - IsSynthetized = true - }; + { + Access = access, + Name = delegateName, + Namespace = namespaceDelegates, + QualifiedType = delegateType, + IsSynthetized = true + }; delegates.Add(existingDelegate); return existingDelegate; @@ -235,10 +235,10 @@ namespace CppSharp.Passes parent = module.Units.Last(u => u.IsGenerated); var namespaceDelegates = new Namespace - { - Name = "Delegates", - Namespace = parent - }; + { + Name = "Delegates", + Namespace = parent + }; namespacesDelegates.Add(module, namespaceDelegates); return namespaceDelegates; diff --git a/src/Generator/Passes/ExpressionHelper.cs b/src/Generator/Passes/ExpressionHelper.cs index 90f71be9..435dbcf6 100644 --- a/src/Generator/Passes/ExpressionHelper.cs +++ b/src/Generator/Passes/ExpressionHelper.cs @@ -433,7 +433,7 @@ namespace CppSharp.Internal // ArgumentOutOfRangeException. var initialQuoteIndex = result.IndexOf("\""); if (initialQuoteIndex >= 0) - { + { result = result[initialQuoteIndex..]; return true; } diff --git a/src/Generator/Passes/FlattenAnonymousTypesToFields.cs b/src/Generator/Passes/FlattenAnonymousTypesToFields.cs index 7bfbc777..c15ef18f 100644 --- a/src/Generator/Passes/FlattenAnonymousTypesToFields.cs +++ b/src/Generator/Passes/FlattenAnonymousTypesToFields.cs @@ -44,7 +44,7 @@ namespace CppSharp.Passes !field.QualifiedType.Type.Desugar().TryGetClass(out fieldType) || !string.IsNullOrEmpty(fieldType.OriginalName)) continue; - + ReplaceLayoutField(@class, i, fieldType); fieldType.Fields.Clear(); fieldType.ExplicitlyIgnore(); @@ -77,13 +77,13 @@ namespace CppSharp.Passes { LayoutField nestedLayoutField = fieldType.Layout.Fields[j]; var layoutField = new LayoutField - { - Expression = nestedLayoutField.Expression, - FieldPtr = nestedLayoutField.FieldPtr, - Name = nestedLayoutField.Name, - Offset = nestedLayoutField.Offset + offset, - QualifiedType = nestedLayoutField.QualifiedType - }; + { + Expression = nestedLayoutField.Expression, + FieldPtr = nestedLayoutField.FieldPtr, + Name = nestedLayoutField.Name, + Offset = nestedLayoutField.Offset + offset, + QualifiedType = nestedLayoutField.QualifiedType + }; @class.Layout.Fields.Insert(i + j, layoutField); } } diff --git a/src/Generator/Passes/FunctionToInstanceMethodPass.cs b/src/Generator/Passes/FunctionToInstanceMethodPass.cs index 3f3014bd..57543028 100644 --- a/src/Generator/Passes/FunctionToInstanceMethodPass.cs +++ b/src/Generator/Passes/FunctionToInstanceMethodPass.cs @@ -46,21 +46,21 @@ namespace CppSharp.Passes // Create a new fake method so it acts as an instance method. var method = new Method - { - Namespace = @class, - OriginalNamespace = function.Namespace, - Name = function.Name, - OriginalName = function.OriginalName, - Mangled = function.Mangled, - Access = AccessSpecifier.Public, - Kind = CXXMethodKind.Normal, - ReturnType = function.ReturnType, - CallingConvention = function.CallingConvention, - IsVariadic = function.IsVariadic, - IsInline = function.IsInline, - Conversion = MethodConversionKind.FunctionToInstanceMethod, - FunctionType = function.FunctionType - }; + { + Namespace = @class, + OriginalNamespace = function.Namespace, + Name = function.Name, + OriginalName = function.OriginalName, + Mangled = function.Mangled, + Access = AccessSpecifier.Public, + Kind = CXXMethodKind.Normal, + ReturnType = function.ReturnType, + CallingConvention = function.CallingConvention, + IsVariadic = function.IsVariadic, + IsInline = function.IsInline, + Conversion = MethodConversionKind.FunctionToInstanceMethod, + FunctionType = function.FunctionType + }; method.Parameters.AddRange(function.Parameters.Select( p => new Parameter(p) { Namespace = method })); diff --git a/src/Generator/Passes/GenerateAbstractImplementationsPass.cs b/src/Generator/Passes/GenerateAbstractImplementationsPass.cs index 479d776e..c09ee737 100644 --- a/src/Generator/Passes/GenerateAbstractImplementationsPass.cs +++ b/src/Generator/Passes/GenerateAbstractImplementationsPass.cs @@ -64,13 +64,13 @@ namespace CppSharp.Passes foreach (var abstractMethod in abstractMethods) { var impl = new Method(abstractMethod) - { - Namespace = internalImpl, - OriginalFunction = abstractMethod, - IsPure = false, - SynthKind = abstractMethod.SynthKind == FunctionSynthKind.DefaultValueOverload ? + { + Namespace = internalImpl, + OriginalFunction = abstractMethod, + IsPure = false, + SynthKind = abstractMethod.SynthKind == FunctionSynthKind.DefaultValueOverload ? FunctionSynthKind.DefaultValueOverload : FunctionSynthKind.AbstractImplCall - }; + }; impl.OverriddenMethods.Clear(); impl.OverriddenMethods.Add(abstractMethod); if (abstractMethod.OriginalReturnType.Type.IsDependentPointer() || @@ -90,11 +90,11 @@ namespace CppSharp.Passes private static T GetInternalImpl(T @class) where T : Class, new() { var internalImpl = new T - { - Name = @class.Name + "Internal", - Access = AccessSpecifier.Private, - Namespace = @class.Namespace - }; + { + Name = @class.Name + "Internal", + Access = AccessSpecifier.Private, + Namespace = @class.Namespace + }; if (@class.IsDependent) { internalImpl.IsDependent = true; @@ -122,8 +122,8 @@ namespace CppSharp.Passes for (var i = abstractMethods.Count - 1; i >= 0; i--) { var @abstract = abstractMethods[i]; - var @override = overriddenMethods.Find(m => m.Name == @abstract.Name && - m.ReturnType == @abstract.ReturnType && + var @override = overriddenMethods.Find(m => m.Name == @abstract.Name && + m.ReturnType == @abstract.ReturnType && m.Parameters.SequenceEqual(@abstract.Parameters, ParameterTypeComparer.Instance)); if (@override != null) { diff --git a/src/Generator/Passes/GenerateSymbolsPass.cs b/src/Generator/Passes/GenerateSymbolsPass.cs index 8610a69b..385771ae 100644 --- a/src/Generator/Passes/GenerateSymbolsPass.cs +++ b/src/Generator/Passes/GenerateSymbolsPass.cs @@ -181,7 +181,7 @@ namespace CppSharp.Passes { if (symbolsCodeGenerators.ContainsKey(module)) return symbolsCodeGenerators[module]; - + var symbolsCodeGenerator = new SymbolsCodeGenerator(Context, module.Units); symbolsCodeGenerators[module] = symbolsCodeGenerator; symbolsCodeGenerator.Process(); @@ -237,7 +237,7 @@ namespace CppSharp.Passes Diagnostics.Error(errorMessage); else compiledLibraries[module] = new CompiledLibrary - { OutputDir = outputDir, Library = module.SymbolsLibraryName }; + { OutputDir = outputDir, Library = module.SymbolsLibraryName }; RemainingCompilationTasks--; }).Start(); } diff --git a/src/Generator/Passes/GetterSetterToPropertyPass.cs b/src/Generator/Passes/GetterSetterToPropertyPass.cs index 579a1ff3..62640744 100644 --- a/src/Generator/Passes/GetterSetterToPropertyPass.cs +++ b/src/Generator/Passes/GetterSetterToPropertyPass.cs @@ -119,7 +119,7 @@ namespace CppSharp.Passes string name, QualifiedType type, bool isSetter = false) { Type underlyingType = GetUnderlyingType(type); - Class @class = (Class) method.Namespace; + Class @class = (Class)method.Namespace; Property property = properties.Find( p => p.Field == null && @@ -144,10 +144,10 @@ namespace CppSharp.Passes property.QualifiedType = method.OriginalReturnType; } - property.Access = (AccessSpecifier) Math.Max( - (int) (property.GetMethod ?? property.SetMethod).Access, - (int) method.Access); - + property.Access = (AccessSpecifier)Math.Max( + (int)(property.GetMethod ?? property.SetMethod).Access, + (int)method.Access); + if (method.ExplicitInterfaceImpl != null) property.ExplicitInterfaceImpl = method.ExplicitInterfaceImpl; } diff --git a/src/Generator/Passes/HandleDefaultParamValuesPass.cs b/src/Generator/Passes/HandleDefaultParamValuesPass.cs index fe904fd2..38a512d6 100644 --- a/src/Generator/Passes/HandleDefaultParamValuesPass.cs +++ b/src/Generator/Passes/HandleDefaultParamValuesPass.cs @@ -80,7 +80,7 @@ namespace CppSharp.Passes overload.Parameters[i].DefaultArgument = null; if (method != null) - ((Class) function.Namespace).Methods.Add((Method) overload); + ((Class)function.Namespace).Methods.Add((Method)overload); else { List functions; diff --git a/src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs b/src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs index fdbec143..a86f340e 100644 --- a/src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs +++ b/src/Generator/Passes/MakeProtectedNestedTypesPublicPass.cs @@ -14,7 +14,7 @@ namespace CppSharp.Passes if (!base.VisitClassDecl(@class)) return false; - (from d in ((IEnumerable) @class.Classes).Concat(@class.Enums) + (from d in ((IEnumerable)@class.Classes).Concat(@class.Enums) where d.Access == AccessSpecifier.Protected select d).All(d => { d.Access = AccessSpecifier.Public; return true; }); diff --git a/src/Generator/Passes/MultipleInheritancePass.cs b/src/Generator/Passes/MultipleInheritancePass.cs index bf01fe77..96c0d450 100644 --- a/src/Generator/Passes/MultipleInheritancePass.cs +++ b/src/Generator/Passes/MultipleInheritancePass.cs @@ -72,7 +72,7 @@ namespace CppSharp.Passes protected Class GetInterface(Class @base) { if (@base.CompleteDeclaration != null) - @base = (Class) @base.CompleteDeclaration; + @base = (Class)@base.CompleteDeclaration; return interfaces.FirstOrDefault(i => i.OriginalClass == @base) ?? GetNewInterface("I" + @base.Name, @base); @@ -189,7 +189,7 @@ namespace CppSharp.Passes templatedInterfaces[@base] = @interface; foreach (var spec in @base.Specializations) @interface.Specializations.Add( - (ClassTemplateSpecialization) GetNewInterface(name, spec)); + (ClassTemplateSpecialization)GetNewInterface(name, spec)); } return @interface; } diff --git a/src/Generator/Passes/ParamTypeToInterfacePass.cs b/src/Generator/Passes/ParamTypeToInterfacePass.cs index 311d6f10..8a0a13f4 100644 --- a/src/Generator/Passes/ParamTypeToInterfacePass.cs +++ b/src/Generator/Passes/ParamTypeToInterfacePass.cs @@ -127,7 +127,7 @@ namespace CppSharp.Passes if (@interface == null) return; - type.Type = (Type) type.Type.Clone(); + type.Type = (Type)type.Type.Clone(); finalType = (type.Type.GetFinalPointee() ?? type.Type).Desugar(); finalType.TryGetClass(out @class, @interface); } diff --git a/src/Generator/Passes/Pass.cs b/src/Generator/Passes/Pass.cs index ad609ab0..877a1116 100644 --- a/src/Generator/Passes/Pass.cs +++ b/src/Generator/Passes/Pass.cs @@ -60,26 +60,26 @@ namespace CppSharp.Passes public virtual void HandleBlock(Block block) { - switch(block.Kind) + switch (block.Kind) { - case BlockKind.Class: - VisitClass(block); - break; - case BlockKind.Method: - VisitMethod(block); - break; - case BlockKind.Constructor: - VisitConstructor(block); - break; - case BlockKind.ConstructorBody: - VisitConstructorBody(block); - break; - case BlockKind.Namespace: - VisitNamespace(block); - break; - case BlockKind.Includes: - VisitIncludes(block); - break; + case BlockKind.Class: + VisitClass(block); + break; + case BlockKind.Method: + VisitMethod(block); + break; + case BlockKind.Constructor: + VisitConstructor(block); + break; + case BlockKind.ConstructorBody: + VisitConstructorBody(block); + break; + case BlockKind.Namespace: + VisitNamespace(block); + break; + case BlockKind.Includes: + VisitIncludes(block); + break; } foreach (var childBlock in block.Blocks) diff --git a/src/Generator/Passes/RenamePass.cs b/src/Generator/Passes/RenamePass.cs index d5c3d143..02f7ae94 100644 --- a/src/Generator/Passes/RenamePass.cs +++ b/src/Generator/Passes/RenamePass.cs @@ -47,7 +47,7 @@ namespace CppSharp.Passes { Method rootBaseMethod; if (method.OriginalNamespace is Class @class && @class.IsInterface) - rootBaseMethod = (Method) method.OriginalFunction; + rootBaseMethod = (Method)method.OriginalFunction; else rootBaseMethod = method.GetRootBaseMethod(); if (rootBaseMethod != null && rootBaseMethod != method) @@ -59,7 +59,7 @@ namespace CppSharp.Passes if (decl is Property property && !property.IsStatic) { - var rootBaseProperty = ((Class) property.Namespace).GetBasePropertyByName(property); + var rootBaseProperty = ((Class)property.Namespace).GetBasePropertyByName(property); if (rootBaseProperty != null && rootBaseProperty != property) { newName = rootBaseProperty.Name; @@ -121,7 +121,7 @@ namespace CppSharp.Passes { if (!Targets.HasFlag(RenameTargets.Field)) return false; - var fieldProperty = ((Class) field.Namespace).Properties.FirstOrDefault( + var fieldProperty = ((Class)field.Namespace).Properties.FirstOrDefault( p => p.Field == field); return (fieldProperty != null && fieldProperty.IsInRefTypeAndBackedByValueClassField()); @@ -217,7 +217,7 @@ namespace CppSharp.Passes var enumItem = decl as Enumeration.Item; if (enumItem != null) - return ((Enumeration) enumItem.Namespace).Items.Any( + return ((Enumeration)enumItem.Namespace).Items.Any( i => i != decl && i.Name == newName); return false; @@ -228,7 +228,7 @@ namespace CppSharp.Passes var method = function as Method; if (method != null) { - return ((Class) method.Namespace).Methods.Where( + return ((Class)method.Namespace).Methods.Where( m => !m.Ignore && m.Parameters.SequenceEqual(function.Parameters, new ParameterComparer())); } return function.Namespace.Functions.Where( @@ -295,17 +295,17 @@ namespace CppSharp.Passes [Flags] public enum RenameTargets { - Class = 1 << 0, - Field = 1 << 1, - Method = 1 << 2, - Function = 1 << 3, + Class = 1 << 0, + Field = 1 << 1, + Method = 1 << 2, + Function = 1 << 3, Parameter = 1 << 4, - Enum = 1 << 5, - EnumItem = 1 << 6, - Event = 1 << 7, - Property = 1 << 8, - Delegate = 1 << 9, - Variable = 1 << 10, + Enum = 1 << 5, + EnumItem = 1 << 6, + Event = 1 << 7, + Property = 1 << 8, + Delegate = 1 << 9, + Variable = 1 << 10, Any = Function | Method | Parameter | Class | Field | Enum | EnumItem | Event | Property | Delegate | Variable } @@ -466,7 +466,7 @@ namespace CppSharp.Passes decl.Visit(pass); } - public static void RenameDeclsCase(this PassBuilder builder, + public static void RenameDeclsCase(this PassBuilder builder, RenameTargets targets, RenameCasePattern pattern) { builder.AddPass(new CaseRenamePass(targets, pattern)); diff --git a/src/Generator/Passes/SpecializationMethodsWithDependentPointersPass.cs b/src/Generator/Passes/SpecializationMethodsWithDependentPointersPass.cs index 15af5dca..07ae0d79 100644 --- a/src/Generator/Passes/SpecializationMethodsWithDependentPointersPass.cs +++ b/src/Generator/Passes/SpecializationMethodsWithDependentPointersPass.cs @@ -141,7 +141,7 @@ namespace CppSharp.Passes var type = qualType.Type.Desugar(); while (type.IsAddress()) { - var pointee = ((PointerType) type).Pointee.Desugar( + var pointee = ((PointerType)type).Pointee.Desugar( resolveTemplateSubstitution: false); if (pointee.IsAddress()) type = pointee; @@ -149,7 +149,7 @@ namespace CppSharp.Passes { substitution = pointee as TemplateParameterSubstitutionType; if (substitution != null) - ((PointerType) type).QualifiedPointee.Type = substitution.Replacement.Type; + ((PointerType)type).QualifiedPointee.Type = substitution.Replacement.Type; break; } } diff --git a/src/Generator/Passes/SymbolsCodeGenerator.cs b/src/Generator/Passes/SymbolsCodeGenerator.cs index d2d11f7e..dedc7f71 100644 --- a/src/Generator/Passes/SymbolsCodeGenerator.cs +++ b/src/Generator/Passes/SymbolsCodeGenerator.cs @@ -45,7 +45,7 @@ namespace CppSharp.Passes public override bool VisitMethodDecl(Method method) { if (method.IsDestructor && - (!((Class) method.Namespace).HasNonTrivialDestructor || + (!((Class)method.Namespace).HasNonTrivialDestructor || method.Access == AccessSpecifier.Private)) return false; @@ -58,7 +58,7 @@ namespace CppSharp.Passes return true; } - Class @class = (Class) method.Namespace; + Class @class = (Class)method.Namespace; bool needSubclass = (method.Access == AccessSpecifier.Protected || @class.IsAbstract) && (method.IsConstructor || method.IsDestructor); string wrapper = GetWrapper(method); @@ -159,7 +159,7 @@ namespace CppSharp.Passes Write("extern \"C\" "); Write($"{GetExporting()}void {wrapper}({signature}) "); - bool isAbstract = ((Class) method.Namespace).IsAbstract; + bool isAbstract = ((Class)method.Namespace).IsAbstract; if (method.Access == AccessSpecifier.Protected || isAbstract) { Write($@"{{ ::new ({Helpers.InstanceField}) { @@ -197,7 +197,7 @@ namespace CppSharp.Passes } bool needSubclass = method.Access == AccessSpecifier.Protected || - ((Class) method.Namespace).IsAbstract; + ((Class)method.Namespace).IsAbstract; string @namespace = method.Namespace.Visit(cppTypePrinter); if (!needSubclass) Write("extern \"C\" "); @@ -318,7 +318,7 @@ namespace CppSharp.Passes string paramTypes, string functionName) { Stack parentsOpen = GenerateNamespace(function); - var functionType = (FunctionType) function.FunctionType.Type; + var functionType = (FunctionType)function.FunctionType.Type; Write($"{string.Concat(parentsOpen)}"); if (function.IsConstExpr) Write("constexpr "); diff --git a/src/Generator/Passes/ValidateOperatorsPass.cs b/src/Generator/Passes/ValidateOperatorsPass.cs index c6c71b2d..b1f86db1 100644 --- a/src/Generator/Passes/ValidateOperatorsPass.cs +++ b/src/Generator/Passes/ValidateOperatorsPass.cs @@ -74,7 +74,7 @@ namespace CppSharp.Passes returnType = (returnType.GetFinalPointee() ?? returnType).Desugar(); return returnType.TryGetClass(out @class) && @class.GetNonIgnoredRootBase() == - ((Class) @operator.Namespace).GetNonIgnoredRootBase() && + ((Class)@operator.Namespace).GetNonIgnoredRootBase() && @operator.Parameters.Count == 0; // Bitwise shift operators can only be overloaded if the second parameter is int diff --git a/src/Generator/Types/DeclMapDatabase.cs b/src/Generator/Types/DeclMapDatabase.cs index 26a98464..7cb891c3 100644 --- a/src/Generator/Types/DeclMapDatabase.cs +++ b/src/Generator/Types/DeclMapDatabase.cs @@ -44,7 +44,7 @@ namespace CppSharp.Types if (attr.GeneratorKind == 0 || attr.GeneratorKind == bindingContext.Options.GeneratorKind) { - var declMap = (DeclMap) Activator.CreateInstance(type); + var declMap = (DeclMap)Activator.CreateInstance(type); declMap.Context = bindingContext; declMap.DeclMapDatabase = this; diff --git a/src/Generator/Types/Std/Stdlib.CLI.cs b/src/Generator/Types/Std/Stdlib.CLI.cs index c68981b2..d067c958 100644 --- a/src/Generator/Types/Std/Stdlib.CLI.cs +++ b/src/Generator/Types/Std/Stdlib.CLI.cs @@ -135,8 +135,8 @@ namespace CppSharp.Types.Std var type = finalType as TemplateSpecializationType; if (type == null) { - var injectedClassNameType = (InjectedClassNameType) finalType; - type = (TemplateSpecializationType) injectedClassNameType.InjectedSpecializationType.Type; + var injectedClassNameType = (InjectedClassNameType)finalType; + type = (TemplateSpecializationType)injectedClassNameType.InjectedSpecializationType.Type; } var checker = new TypeIgnoreChecker(TypeMapDatabase); type.Arguments[0].Type.Visit(checker); @@ -182,10 +182,10 @@ namespace CppSharp.Types.Std }; var elementCtx = new MarshalContext(ctx.Context, ctx.Indentation) - { - Parameter = param, - ArgName = param.Name, - }; + { + Parameter = param, + ArgName = param.Name, + }; var marshal = new CLIMarshalManagedToNativePrinter(elementCtx); type.Type.Visit(marshal); @@ -203,7 +203,7 @@ namespace CppSharp.Types.Std ctx.Before.WriteLine("{0}.push_back(_marshalElement);", tmpVarName); } - + ctx.Before.UnindentAndWriteCloseBrace(); ctx.Return.Write(tmpVarName); @@ -219,7 +219,7 @@ namespace CppSharp.Types.Std ? new CILType(typeof(System.IntPtr)) : type.Type; var tmpVarName = "_tmp" + ctx.ArgName; - + ctx.Before.WriteLine( "auto {0} = gcnew ::System::Collections::Generic::List<{1}>();", tmpVarName, managedType); @@ -231,10 +231,10 @@ namespace CppSharp.Types.Std ctx.Before.WriteOpenBraceAndIndent(); { var elementCtx = new MarshalContext(ctx.Context, ctx.Indentation) - { - ReturnVarName = "_element", - ReturnType = type - }; + { + ReturnVarName = "_element", + ReturnType = type + }; var marshal = new CLIMarshalNativeToManagedPrinter(elementCtx); type.Type.Visit(marshal); @@ -315,7 +315,7 @@ namespace CppSharp.Types.Std public override void CLIMarshalToNative(MarshalContext ctx) { - var marshal = (CLIMarshalManagedToNativePrinter) ctx.MarshalToNative; + var marshal = (CLIMarshalManagedToNativePrinter)ctx.MarshalToNative; if (!ctx.Parameter.Type.Desugar().IsPointer()) marshal.ArgumentPrefix.Write("*"); var marshalCtxName = string.Format("ctx_{0}", ctx.Parameter.Name); diff --git a/src/Generator/Types/Std/Stdlib.CSharp.cs b/src/Generator/Types/Std/Stdlib.CSharp.cs index 6edfc8fc..9f46125c 100644 --- a/src/Generator/Types/Std/Stdlib.CSharp.cs +++ b/src/Generator/Types/Std/Stdlib.CSharp.cs @@ -145,8 +145,8 @@ namespace CppSharp.Types.Std // would be really helpful to have ctx hold a Decl property representing the // "appropriate" Decl when we get here. When MarshalKind == NativeField, Decl would // be set to the Field we're operating on. - var fieldName = ctx.ReturnVarName.Substring(ctx.ReturnVarName.LastIndexOf("->") + 2); - + var fieldName = ctx.ReturnVarName.Substring(ctx.ReturnVarName.LastIndexOf("->") + 2); + ctx.Before.WriteLine($"if (__{fieldName}_OwnsNativeMemory)"); ctx.Before.WriteLineIndent($"Marshal.FreeHGlobal({ctx.ReturnVarName});"); ctx.Before.WriteLine($"__{fieldName}_OwnsNativeMemory = true;"); @@ -355,7 +355,7 @@ namespace CppSharp.Types.Std var typePrinter = new CSharpTypePrinter(ctx.Context); string qualifiedBasicString = GetQualifiedBasicString(basicString); string varBasicString = $"__basicStringRet{ctx.ParameterIndex}"; - bool usePointer = type.IsAddress() || ctx.MarshalKind == MarshalKind.NativeField || + bool usePointer = type.IsAddress() || ctx.MarshalKind == MarshalKind.NativeField || ctx.MarshalKind == MarshalKind.ReturnVariableArray; ctx.Before.WriteLine($@"var {varBasicString} = { basicString.Visit(typePrinter)}.{Helpers.CreateInstanceIdentifier}({ @@ -397,7 +397,7 @@ namespace CppSharp.Types.Std var templateSpecializationType = template as TemplateSpecializationType; if (templateSpecializationType != null) return templateSpecializationType.GetClassTemplateSpecialization(); - return (ClassTemplateSpecialization) ((TagType) template).Declaration; + return (ClassTemplateSpecialization)((TagType)template).Declaration; } } diff --git a/src/Generator/Types/TypeMap.cs b/src/Generator/Types/TypeMap.cs index 10753f14..54d5cfa4 100644 --- a/src/Generator/Types/TypeMap.cs +++ b/src/Generator/Types/TypeMap.cs @@ -16,7 +16,7 @@ namespace CppSharp.Types { public string Type { get; } public GeneratorKind GeneratorKind { get; set; } - + public TypeMapAttribute(string type) : this(type, 0) { Type = type; @@ -55,15 +55,15 @@ namespace CppSharp.Types { switch (kind) { - case GeneratorKind.C: - case GeneratorKind.CPlusPlus: - return CppSignatureType(ctx); - case GeneratorKind.CLI: - return CLISignatureType(ctx); - case GeneratorKind.CSharp: - return CSharpSignatureType(ctx); - default: - throw new System.NotImplementedException(); + case GeneratorKind.C: + case GeneratorKind.CPlusPlus: + return CppSignatureType(ctx); + case GeneratorKind.CLI: + return CLISignatureType(ctx); + case GeneratorKind.CSharp: + return CSharpSignatureType(ctx); + default: + throw new System.NotImplementedException(); } } @@ -71,18 +71,18 @@ namespace CppSharp.Types { switch (kind) { - case GeneratorKind.C: - case GeneratorKind.CPlusPlus: - CppMarshalToNative(ctx); - return; - case GeneratorKind.CLI: - CLIMarshalToNative(ctx); - return; - case GeneratorKind.CSharp: - CSharpMarshalToNative(ctx as CSharpMarshalContext); - return; - default: - throw new System.NotImplementedException(); + case GeneratorKind.C: + case GeneratorKind.CPlusPlus: + CppMarshalToNative(ctx); + return; + case GeneratorKind.CLI: + CLIMarshalToNative(ctx); + return; + case GeneratorKind.CSharp: + CSharpMarshalToNative(ctx as CSharpMarshalContext); + return; + default: + throw new System.NotImplementedException(); } } @@ -90,18 +90,18 @@ namespace CppSharp.Types { switch (kind) { - case GeneratorKind.C: - case GeneratorKind.CPlusPlus: - CppMarshalToManaged(ctx); - return; - case GeneratorKind.CLI: - CLIMarshalToManaged(ctx); - return; - case GeneratorKind.CSharp: - CSharpMarshalToManaged(ctx as CSharpMarshalContext); - return; - default: - throw new System.NotImplementedException(); + case GeneratorKind.C: + case GeneratorKind.CPlusPlus: + CppMarshalToManaged(ctx); + return; + case GeneratorKind.CLI: + CLIMarshalToManaged(ctx); + return; + case GeneratorKind.CSharp: + CSharpMarshalToManaged(ctx as CSharpMarshalContext); + return; + default: + throw new System.NotImplementedException(); } } diff --git a/src/Generator/Types/TypeMapDatabase.cs b/src/Generator/Types/TypeMapDatabase.cs index 1a0edbac..fef279ab 100644 --- a/src/Generator/Types/TypeMapDatabase.cs +++ b/src/Generator/Types/TypeMapDatabase.cs @@ -43,7 +43,7 @@ namespace CppSharp.Types if (attr.GeneratorKind == 0 || attr.GeneratorKind == bindingContext.Options.GeneratorKind) { - var typeMap = (TypeMap) Activator.CreateInstance(type); + var typeMap = (TypeMap)Activator.CreateInstance(type); typeMap.Context = bindingContext; typeMap.TypeMapDatabase = this; diff --git a/src/Generator/Utils/BlockGenerator.cs b/src/Generator/Utils/BlockGenerator.cs index 0c83482e..f0bcfb67 100644 --- a/src/Generator/Utils/BlockGenerator.cs +++ b/src/Generator/Utils/BlockGenerator.cs @@ -319,15 +319,15 @@ namespace CppSharp if (trimIndentation) { - foreach(var line in lines) - { + foreach (var line in lines) + { for (int i = 0; i < line.Length; ++i) { if (char.IsWhiteSpace(line[i])) continue; - + if (i < indentation) - { + { indentation = i; break; } diff --git a/src/Generator/Utils/ExpressionEvaluator.cs b/src/Generator/Utils/ExpressionEvaluator.cs index 509929d0..88054e74 100644 --- a/src/Generator/Utils/ExpressionEvaluator.cs +++ b/src/Generator/Utils/ExpressionEvaluator.cs @@ -54,8 +54,8 @@ namespace CodingSeb.ExpressionEvaluator protected static readonly Regex initInNewBeginningRegex = new Regex(@"^(?>\s*){", RegexOptions.Compiled); // Depending on OptionInlineNamespacesEvaluationActive. Initialized in constructor - protected string InstanceCreationWithNewKeywordRegexPattern { get { return @"^new(?>\s*)((?[{{])|((?[\p{L}_][\p{L}_0-9"+ (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"]*)(?>\s*)(?[<](?>[^<>]+|(?[<])|(?<-gentag>[>]))*(?(gentag)(?!))[>])?(?>\s*)((?[(])|(?\[)|(?[{{]))?))"; } } - protected string CastRegexPattern { get { return @"^\((?>\s*)(?[\p{L}_][\p{L}_0-9"+ (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"\[\]<>]*[?]?)(?>\s*)\)"; } } + protected string InstanceCreationWithNewKeywordRegexPattern { get { return @"^new(?>\s*)((?[{{])|((?[\p{L}_][\p{L}_0-9" + (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"]*)(?>\s*)(?[<](?>[^<>]+|(?[<])|(?<-gentag>[>]))*(?(gentag)(?!))[>])?(?>\s*)((?[(])|(?\[)|(?[{{]))?))"; } } + protected string CastRegexPattern { get { return @"^\((?>\s*)(?[\p{L}_][\p{L}_0-9" + (OptionInlineNamespacesEvaluationActive ? @"\." : string.Empty) + @"\[\]<>]*[?]?)(?>\s*)\)"; } } // To remove comments in scripts based on https://stackoverflow.com/questions/3524317/regex-to-strip-line-comments-from-c-sharp/3524689#3524689 protected const string blockComments = @"/\*(.*?)\*/"; @@ -1578,7 +1578,7 @@ namespace CodingSeb.ExpressionEvaluator { string restOfExpression = expression.Substring(i); -// CPPSHARP + // CPPSHARP if (restOfExpression.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase)) { // This is in case the literal contains suffix @@ -1586,7 +1586,7 @@ namespace CodingSeb.ExpressionEvaluator i += restOfExpression.Length - cleanedUp.Length; restOfExpression = cleanedUp; } -// + // Match numberMatch = Regex.Match(restOfExpression, numberRegexPattern, RegexOptions.IgnoreCase); Match otherBaseMatch = otherBasesNumberRegex.Match(restOfExpression); @@ -1639,7 +1639,7 @@ namespace CodingSeb.ExpressionEvaluator } else { - string numberNoSign = numberMatch.Groups[1].Value.Replace("_", ""); + string numberNoSign = numberMatch.Groups[1].Value.Replace("_", ""); int sign = numberMatch.Groups["sign"].Success ? -1 : 1; stack.Push(ParseInteger(numberNoSign, 10, sign)); } @@ -1652,7 +1652,7 @@ namespace CodingSeb.ExpressionEvaluator } } -// CPPSHARP + // CPPSHARP /// /// Heuristically convert to an int, uint, long, or ulong @@ -1688,7 +1688,7 @@ namespace CodingSeb.ExpressionEvaluator if (number <= long.MaxValue) return (long)number; return number; } -// + // protected virtual bool EvaluateInstanceCreationWithNewKeyword(string expression, Stack stack, ref int i) { diff --git a/src/Generator/Utils/FSM/ConsoleWriter.cs b/src/Generator/Utils/FSM/ConsoleWriter.cs index 4c05ae95..43dce140 100644 --- a/src/Generator/Utils/FSM/ConsoleWriter.cs +++ b/src/Generator/Utils/FSM/ConsoleWriter.cs @@ -1,20 +1,25 @@ using System; -namespace CppSharp.Utils.FSM{ - public class ConsoleWriter{ - public static void Failure(string message){ - Console.ForegroundColor = ConsoleColor.DarkRed; - Write(message); - } +namespace CppSharp.Utils.FSM +{ + public class ConsoleWriter + { + public static void Failure(string message) + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Write(message); + } - public static void Success(string message){ - Console.ForegroundColor = ConsoleColor.DarkGreen; - Write(message); - } + public static void Success(string message) + { + Console.ForegroundColor = ConsoleColor.DarkGreen; + Write(message); + } - private static void Write(string message){ - Console.WriteLine(message); - Console.ResetColor(); - } - } + private static void Write(string message) + { + Console.WriteLine(message); + Console.ResetColor(); + } + } } diff --git a/src/Generator/Utils/FSM/DFSM.cs b/src/Generator/Utils/FSM/DFSM.cs index 8e15c84c..e49b1c32 100644 --- a/src/Generator/Utils/FSM/DFSM.cs +++ b/src/Generator/Utils/FSM/DFSM.cs @@ -4,136 +4,166 @@ using System.Text; namespace CppSharp.Utils.FSM { - public class DFSM{ - public readonly List Q = new List(); - public readonly List Sigma = new List(); - public readonly List Delta = new List(); - public List Q0 = new List(); - public List F = new List(); + public class DFSM + { + public readonly List Q = new List(); + public readonly List Sigma = new List(); + public readonly List Delta = new List(); + public List Q0 = new List(); + public List F = new List(); - public DFSM(IEnumerable q, IEnumerable sigma, IEnumerable delta, - IEnumerable q0, IEnumerable f){ - Q = q.ToList(); - Sigma = sigma.ToList(); - AddTransitions(delta); - AddInitialStates(q0); - AddFinalStates(f); - } + public DFSM(IEnumerable q, IEnumerable sigma, IEnumerable delta, + IEnumerable q0, IEnumerable f) + { + Q = q.ToList(); + Sigma = sigma.ToList(); + AddTransitions(delta); + AddInitialStates(q0); + AddFinalStates(f); + } - private void AddTransitions(IEnumerable transitions){ - foreach (var transition in transitions.Where(ValidTransition)){ - Delta.Add(transition); - } - } + private void AddTransitions(IEnumerable transitions) + { + foreach (var transition in transitions.Where(ValidTransition)) + { + Delta.Add(transition); + } + } - private bool ValidTransition(Transition transition){ - return Q.Contains(transition.StartState) && - Q.Contains(transition.EndState) && - Sigma.Contains(transition.Symbol) && - !TransitionAlreadyDefined(transition); - } + private bool ValidTransition(Transition transition) + { + return Q.Contains(transition.StartState) && + Q.Contains(transition.EndState) && + Sigma.Contains(transition.Symbol) && + !TransitionAlreadyDefined(transition); + } - private bool TransitionAlreadyDefined(Transition transition){ - return Delta.Any(t => t.StartState == transition.StartState && - t.Symbol == transition.Symbol); - } + private bool TransitionAlreadyDefined(Transition transition) + { + return Delta.Any(t => t.StartState == transition.StartState && + t.Symbol == transition.Symbol); + } - private void AddInitialStates(IEnumerable q0){ - foreach (var startingState in q0.Where(q => q != null && Q.Contains(q))){ - Q0.Add(startingState); - } - } + private void AddInitialStates(IEnumerable q0) + { + foreach (var startingState in q0.Where(q => q != null && Q.Contains(q))) + { + Q0.Add(startingState); + } + } - private void AddFinalStates(IEnumerable finalStates){ - foreach (var finalState in finalStates.Where(finalState => Q.Contains(finalState))){ - F.Add(finalState); - } - } + private void AddFinalStates(IEnumerable finalStates) + { + foreach (var finalState in finalStates.Where(finalState => Q.Contains(finalState))) + { + F.Add(finalState); + } + } - public void Accepts(string input){ - ConsoleWriter.Success("Trying to parse: " + input); - if (InvalidInputOrFSM(input)){ - return; - } - foreach (var q0 in Q0){ - var currentState = q0; - var steps = new StringBuilder(); - foreach (var symbol in input.ToCharArray()){ - var transition = Delta.Find(t => t.StartState == currentState && - t.Symbol == symbol); - if (transition == null){ - ConsoleWriter.Failure("No transitions for current state and symbol"); - ConsoleWriter.Failure(steps.ToString()); - continue; - } - currentState = transition.EndState; - steps.Append(transition + "\n"); + public void Accepts(string input) + { + ConsoleWriter.Success("Trying to parse: " + input); + if (InvalidInputOrFSM(input)) + { + return; } - if (F.Contains(currentState)){ - ConsoleWriter.Success("Accepted the input with steps:\n" + steps); - return; + foreach (var q0 in Q0) + { + var currentState = q0; + var steps = new StringBuilder(); + foreach (var symbol in input.ToCharArray()) + { + var transition = Delta.Find(t => t.StartState == currentState && + t.Symbol == symbol); + if (transition == null) + { + ConsoleWriter.Failure("No transitions for current state and symbol"); + ConsoleWriter.Failure(steps.ToString()); + continue; + } + currentState = transition.EndState; + steps.Append(transition + "\n"); + } + if (F.Contains(currentState)) + { + ConsoleWriter.Success("Accepted the input with steps:\n" + steps); + return; + } + ConsoleWriter.Failure("Stopped in state " + currentState + + " which is not a final state."); + ConsoleWriter.Failure(steps.ToString()); } - ConsoleWriter.Failure("Stopped in state " + currentState + - " which is not a final state."); - ConsoleWriter.Failure(steps.ToString()); - } - } + } - private bool InvalidInputOrFSM(string input){ - if (InputContainsNotDefinedSymbols(input)){ - return true; - } - if (InitialStateNotSet()){ - ConsoleWriter.Failure("No initial state has been set"); - return true; - } - if (NoFinalStates()){ - ConsoleWriter.Failure("No final states have been set"); - return true; - } - return false; - } + private bool InvalidInputOrFSM(string input) + { + if (InputContainsNotDefinedSymbols(input)) + { + return true; + } + if (InitialStateNotSet()) + { + ConsoleWriter.Failure("No initial state has been set"); + return true; + } + if (NoFinalStates()) + { + ConsoleWriter.Failure("No final states have been set"); + return true; + } + return false; + } - private bool InputContainsNotDefinedSymbols(string input){ - foreach (var symbol in input.ToCharArray().Where(symbol => !Sigma.Contains(symbol))){ - ConsoleWriter.Failure("Could not accept the input since the symbol " + symbol + " is not part of the alphabet"); - return true; - } - return false; - } + private bool InputContainsNotDefinedSymbols(string input) + { + foreach (var symbol in input.ToCharArray().Where(symbol => !Sigma.Contains(symbol))) + { + ConsoleWriter.Failure("Could not accept the input since the symbol " + symbol + " is not part of the alphabet"); + return true; + } + return false; + } - private bool InitialStateNotSet(){ - return Q0.Count == 0; - } + private bool InitialStateNotSet() + { + return Q0.Count == 0; + } - private bool NoFinalStates(){ - return F.Count == 0; - } + private bool NoFinalStates() + { + return F.Count == 0; + } - public void RemoveUnreachableStates(){ - var reachableStates = new HashSet(Q0); - var newStates = new HashSet(Q0); - do{ - var temp = new HashSet(); - foreach (var q in newStates){ - var reachableFromQ = Delta.FindAll(t => t.StartState == q).Select(t => t.EndState); - temp.UnionWith(reachableFromQ); + public void RemoveUnreachableStates() + { + var reachableStates = new HashSet(Q0); + var newStates = new HashSet(Q0); + do + { + var temp = new HashSet(); + foreach (var q in newStates) + { + var reachableFromQ = Delta.FindAll(t => t.StartState == q).Select(t => t.EndState); + temp.UnionWith(reachableFromQ); + } + temp.ExceptWith(reachableStates); + newStates = temp; + reachableStates.UnionWith(newStates); + } while (newStates.Count > 0); + var unreachableStates = Q.Where(q => !reachableStates.Contains(q)); + for (int i = Delta.Count - 1; i > 0; i--) + { + var transition = Delta[i]; + if (unreachableStates.Contains(transition.EndState) || + unreachableStates.Contains(transition.StartState)) + { + Delta.Remove(transition); + } } - temp.ExceptWith(reachableStates); - newStates = temp; - reachableStates.UnionWith(newStates); - } while (newStates.Count > 0); - var unreachableStates = Q.Where(q => !reachableStates.Contains(q)); - for (int i = Delta.Count - 1; i > 0; i--){ - var transition = Delta[i]; - if (unreachableStates.Contains(transition.EndState) || - unreachableStates.Contains(transition.StartState)){ - Delta.Remove(transition); + foreach (var unrechableState in unreachableStates) + { + Q.Remove(unrechableState); } - } - foreach (var unrechableState in unreachableStates){ - Q.Remove(unrechableState); - } - } - } + } + } } \ No newline at end of file diff --git a/src/Generator/Utils/FSM/Minimize.cs b/src/Generator/Utils/FSM/Minimize.cs index 71cb06ae..2cbdc557 100644 --- a/src/Generator/Utils/FSM/Minimize.cs +++ b/src/Generator/Utils/FSM/Minimize.cs @@ -1,71 +1,83 @@ using System.Collections.Generic; using System.Linq; -namespace CppSharp.Utils.FSM{ - internal class Minimize{ - public static DFSM MinimizeDFSM(DFSM fsm){ - var reversedNDFSM = Reverse(fsm); - var reversedDFSM = PowersetConstruction(reversedNDFSM); - var NDFSM = Reverse(reversedDFSM); - return PowersetConstruction(NDFSM); - } +namespace CppSharp.Utils.FSM +{ + internal class Minimize + { + public static DFSM MinimizeDFSM(DFSM fsm) + { + var reversedNDFSM = Reverse(fsm); + var reversedDFSM = PowersetConstruction(reversedNDFSM); + var NDFSM = Reverse(reversedDFSM); + return PowersetConstruction(NDFSM); + } - private static NDFSM Reverse(DFSM d){ - var delta = new List(); - foreach (var transition in d.Delta){ - delta.Add(new Transition(transition.EndState, transition.Symbol, transition.StartState)); - } - return new NDFSM(d.Q, d.Sigma, delta, d.F, d.Q0); - } + private static NDFSM Reverse(DFSM d) + { + var delta = new List(); + foreach (var transition in d.Delta) + { + delta.Add(new Transition(transition.EndState, transition.Symbol, transition.StartState)); + } + return new NDFSM(d.Q, d.Sigma, delta, d.F, d.Q0); + } - public static DFSM PowersetConstruction(NDFSM ndfsm){ - var Q = new List(); - var Sigma = ndfsm.Sigma.ToList(); - var Delta = new List(); - var Q0 = new List { string.Join(" ", ndfsm.Q0) }; - var F = new List(); + public static DFSM PowersetConstruction(NDFSM ndfsm) + { + var Q = new List(); + var Sigma = ndfsm.Sigma.ToList(); + var Delta = new List(); + var Q0 = new List { string.Join(" ", ndfsm.Q0) }; + var F = new List(); - var processed = new List(); - var queue = new Queue(); - queue.Enqueue(string.Join(",", ndfsm.Q0)); + var processed = new List(); + var queue = new Queue(); + queue.Enqueue(string.Join(",", ndfsm.Q0)); - while (queue.Count > 0){ - var setState = queue.Dequeue(); - processed.Add(setState); - Q.Add(CleanupState(setState)); + while (queue.Count > 0) + { + var setState = queue.Dequeue(); + processed.Add(setState); + Q.Add(CleanupState(setState)); - var statesInCurrentSetState = setState.Split(',').ToList(); - foreach (var state in statesInCurrentSetState){ - if (ndfsm.F.Contains(state)){ - F.Add(CleanupState(setState)); - break; - } - } - var symbols = ndfsm.Delta - .Where(t => statesInCurrentSetState.Contains(t.StartState)) - .Select(t => t.Symbol) - .Distinct(); - foreach (var symbol in symbols){ - var reachableStates = - ndfsm.Delta - .Where(t => t.Symbol == symbol && - statesInCurrentSetState.Contains(t.StartState)) - .OrderBy(t => t.EndState). - Select(t => t.EndState); - var reachableSetState = string.Join(",", reachableStates); + var statesInCurrentSetState = setState.Split(',').ToList(); + foreach (var state in statesInCurrentSetState) + { + if (ndfsm.F.Contains(state)) + { + F.Add(CleanupState(setState)); + break; + } + } + var symbols = ndfsm.Delta + .Where(t => statesInCurrentSetState.Contains(t.StartState)) + .Select(t => t.Symbol) + .Distinct(); + foreach (var symbol in symbols) + { + var reachableStates = + ndfsm.Delta + .Where(t => t.Symbol == symbol && + statesInCurrentSetState.Contains(t.StartState)) + .OrderBy(t => t.EndState). + Select(t => t.EndState); + var reachableSetState = string.Join(",", reachableStates); - Delta.Add(new Transition(CleanupState(setState), symbol, CleanupState(reachableSetState))); + Delta.Add(new Transition(CleanupState(setState), symbol, CleanupState(reachableSetState))); - if (!processed.Contains(reachableSetState)){ - queue.Enqueue(reachableSetState); - } + if (!processed.Contains(reachableSetState)) + { + queue.Enqueue(reachableSetState); + } + } } - } - return new DFSM(Q, Sigma, Delta, Q0, F); - } + return new DFSM(Q, Sigma, Delta, Q0, F); + } - private static string CleanupState(string state){ - return state.Replace(",", " "); - } - } + private static string CleanupState(string state) + { + return state.Replace(",", " "); + } + } } \ No newline at end of file diff --git a/src/Generator/Utils/FSM/NDFSM.cs b/src/Generator/Utils/FSM/NDFSM.cs index 9defe173..f784cdd4 100644 --- a/src/Generator/Utils/FSM/NDFSM.cs +++ b/src/Generator/Utils/FSM/NDFSM.cs @@ -2,78 +2,96 @@ using System.Linq; using System.Text; -namespace CppSharp.Utils.FSM{ - public class NDFSM{ - private readonly List Q = new List(); - public readonly List Sigma = new List(); - public readonly List Delta = new List(); - public List Q0 = new List(); - public readonly List F = new List(); +namespace CppSharp.Utils.FSM +{ + public class NDFSM + { + private readonly List Q = new List(); + public readonly List Sigma = new List(); + public readonly List Delta = new List(); + public List Q0 = new List(); + public readonly List F = new List(); - public NDFSM(IEnumerable q, IEnumerable sigma, - IEnumerable delta, IEnumerable q0, IEnumerable f){ - Q = q.ToList(); - Sigma = sigma.ToList(); - AddTransitions(delta); - AddInitialStates(q0); - AddFinalStates(f); - } + public NDFSM(IEnumerable q, IEnumerable sigma, + IEnumerable delta, IEnumerable q0, IEnumerable f) + { + Q = q.ToList(); + Sigma = sigma.ToList(); + AddTransitions(delta); + AddInitialStates(q0); + AddFinalStates(f); + } - private void AddTransitions(IEnumerable transitions){ - foreach (var transition in transitions.Where(ValidTransition)){ - Delta.Add(transition); - } - } + private void AddTransitions(IEnumerable transitions) + { + foreach (var transition in transitions.Where(ValidTransition)) + { + Delta.Add(transition); + } + } - private bool ValidTransition(Transition transition){ - return Q.Contains(transition.StartState) && - Q.Contains(transition.EndState) && - Sigma.Contains(transition.Symbol); - } + private bool ValidTransition(Transition transition) + { + return Q.Contains(transition.StartState) && + Q.Contains(transition.EndState) && + Sigma.Contains(transition.Symbol); + } - private void AddInitialStates(IEnumerable q0){ - foreach (var startingState in q0.Where(q => q != null && Q.Contains(q))){ - Q0.Add(startingState); - } - } + private void AddInitialStates(IEnumerable q0) + { + foreach (var startingState in q0.Where(q => q != null && Q.Contains(q))) + { + Q0.Add(startingState); + } + } - private void AddFinalStates(IEnumerable finalStates){ - foreach (var finalState in finalStates.Where(finalState => Q.Contains(finalState))){ - F.Add(finalState); - } - } + private void AddFinalStates(IEnumerable finalStates) + { + foreach (var finalState in finalStates.Where(finalState => Q.Contains(finalState))) + { + F.Add(finalState); + } + } - public void Accepts(string input){ - ConsoleWriter.Success("Trying to accept: " + input); - if (Q0.Any(q0 => Accepts(q0, input, new StringBuilder()))){ - return; - } - ConsoleWriter.Failure("Could not accept the input: " + input); - } + public void Accepts(string input) + { + ConsoleWriter.Success("Trying to accept: " + input); + if (Q0.Any(q0 => Accepts(q0, input, new StringBuilder()))) + { + return; + } + ConsoleWriter.Failure("Could not accept the input: " + input); + } - private bool Accepts(string currentState, string input, StringBuilder steps){ - if (input.Length > 0){ - var transitions = GetAllTransitions(currentState, input[0]); - foreach (var transition in transitions){ - var currentSteps = new StringBuilder(steps.ToString() + transition); - if (Accepts(transition.EndState, input.Substring(1), currentSteps)){ - return true; - } + private bool Accepts(string currentState, string input, StringBuilder steps) + { + if (input.Length > 0) + { + var transitions = GetAllTransitions(currentState, input[0]); + foreach (var transition in transitions) + { + var currentSteps = new StringBuilder(steps.ToString() + transition); + if (Accepts(transition.EndState, input.Substring(1), currentSteps)) + { + return true; + } + } + return false; + } + if (F.Contains(currentState)) + { + ConsoleWriter.Success("Successfully accepted the input " + input + " " + + "in the final state " + currentState + + " with steps:\n" + steps); + return true; } return false; - } - if (F.Contains(currentState)){ - ConsoleWriter.Success("Successfully accepted the input " + input + " " + - "in the final state " + currentState + - " with steps:\n" + steps); - return true; - } - return false; - } + } - private IEnumerable GetAllTransitions(string currentState, char symbol){ - return Delta.FindAll(t => t.StartState == currentState && - t.Symbol == symbol); - } - } + private IEnumerable GetAllTransitions(string currentState, char symbol) + { + return Delta.FindAll(t => t.StartState == currentState && + t.Symbol == symbol); + } + } } \ No newline at end of file diff --git a/src/Generator/Utils/FSM/Program.cs b/src/Generator/Utils/FSM/Program.cs index 6b0cf528..fe3522f7 100644 --- a/src/Generator/Utils/FSM/Program.cs +++ b/src/Generator/Utils/FSM/Program.cs @@ -1,21 +1,24 @@ using System.Collections.Generic; -namespace CppSharp.Utils.FSM{ - internal class Program{ - private static void Main(string[] args){ - var Q = new List{"q0", "q1"}; - var Sigma = new List{'0', '1'}; - var Delta = new List{ +namespace CppSharp.Utils.FSM +{ + internal class Program + { + private static void Main(string[] args) + { + var Q = new List { "q0", "q1" }; + var Sigma = new List { '0', '1' }; + var Delta = new List{ new Transition("q0", '0', "q0"), new Transition("q0", '1', "q1"), new Transition("q1", '1', "q1"), new Transition("q1", '0', "q0") }; - var Q0 = new List{"q0"}; - var F = new List{"q0", "q1"}; - var DFSM = new DFSM(Q, Sigma, Delta, Q0, F); + var Q0 = new List { "q0" }; + var F = new List { "q0", "q1" }; + var DFSM = new DFSM(Q, Sigma, Delta, Q0, F); - var minimizedDFSM = Minimize.MinimizeDFSM(DFSM); - } - } + var minimizedDFSM = Minimize.MinimizeDFSM(DFSM); + } + } } \ No newline at end of file diff --git a/src/Generator/Utils/FSM/Transition.cs b/src/Generator/Utils/FSM/Transition.cs index 2c0f3b9b..46c7a826 100644 --- a/src/Generator/Utils/FSM/Transition.cs +++ b/src/Generator/Utils/FSM/Transition.cs @@ -1,18 +1,22 @@ -namespace CppSharp.Utils.FSM{ - public class Transition{ - public string StartState { get; private set; } - public char Symbol { get; private set; } - public string EndState { get; private set; } +namespace CppSharp.Utils.FSM +{ + public class Transition + { + public string StartState { get; private set; } + public char Symbol { get; private set; } + public string EndState { get; private set; } - public Transition(string startState, char symbol, string endState){ - StartState = startState; - Symbol = symbol; - EndState = endState; - } + public Transition(string startState, char symbol, string endState) + { + StartState = startState; + Symbol = symbol; + EndState = endState; + } - public override string ToString(){ - return string.Format("({0}, {1}) -> {2}\n", StartState, Symbol, EndState); - } - } + public override string ToString() + { + return string.Format("({0}, {1}) -> {2}\n", StartState, Symbol, EndState); + } + } } diff --git a/src/Generator/Utils/HtmlEncoder.cs b/src/Generator/Utils/HtmlEncoder.cs index 0b065d54..4c332101 100644 --- a/src/Generator/Utils/HtmlEncoder.cs +++ b/src/Generator/Utils/HtmlEncoder.cs @@ -38,483 +38,520 @@ using System.Text; namespace System.Web.Util { - public class HtmlEncoder - { - static SortedDictionary entities; + public class HtmlEncoder + { + static SortedDictionary entities; - static HtmlEncoder () - { - InitEntities(); - } + static HtmlEncoder() + { + InitEntities(); + } - public static string HtmlEncode (string s) - { - if (s == null) - return null; + public static string HtmlEncode(string s) + { + if (s == null) + return null; - if (s.Length == 0) - return String.Empty; - - bool needEncode = s.Any(c => c == '&' || c == '"' || c == '<' || c == '>' || c > 159); + if (s.Length == 0) + return String.Empty; - if (!needEncode) - return s; + bool needEncode = s.Any(c => c == '&' || c == '"' || c == '<' || c == '>' || c > 159); - StringBuilder output = new StringBuilder (); - int len = s.Length; - - for (int i = 0; i < len; i++) { - switch (s [i]) { - case '&' : - output.Append ("&"); - break; - case '>' : - output.Append (">"); - break; - case '<' : - output.Append ("<"); - break; - case '"' : - output.Append ("""); - break; - case '\uff1c': - output.Append ("<"); - break; + if (!needEncode) + return s; - case '\uff1e': - output.Append (">"); - break; - - default: - char ch = s [i]; - if (ch > 159 && ch < 256) { - output.Append ("&#"); - output.Append (((int) ch).ToString (CultureInfo.InvariantCulture)); - output.Append (";"); - } else - output.Append (ch); - break; - } - } - - return output.ToString (); - } - - internal static string HtmlAttributeEncode (string s) - { - if (s == null) - return null; - - if (s.Length == 0) - return String.Empty; - bool needEncode = s.Any(c => c == '&' || c == '"' || c == '<'); + StringBuilder output = new StringBuilder(); + int len = s.Length; - if (!needEncode) - return s; + for (int i = 0; i < len; i++) + { + switch (s[i]) + { + case '&': + output.Append("&"); + break; + case '>': + output.Append(">"); + break; + case '<': + output.Append("<"); + break; + case '"': + output.Append("""); + break; + case '\uff1c': + output.Append("<"); + break; - StringBuilder output = new StringBuilder (); - int len = s.Length; - for (int i = 0; i < len; i++) - switch (s [i]) { - case '&' : - output.Append ("&"); - break; - case '"' : - output.Append ("""); - break; - case '<': - output.Append ("<"); - break; - default: - output.Append (s [i]); - break; - } - - return output.ToString(); - } - - public static string HtmlDecode (string s) - { - if (s == null) - return null; + case '\uff1e': + output.Append(">"); + break; - if (s.Length == 0) - return String.Empty; - - if (s.IndexOf ('&') == -1) - return s; - StringBuilder rawEntity = new StringBuilder (); - StringBuilder entity = new StringBuilder (); - StringBuilder output = new StringBuilder (); - int len = s.Length; - // 0 -> nothing, - // 1 -> right after '&' - // 2 -> between '&' and ';' but no '#' - // 3 -> '#' found after '&' and getting numbers - int state = 0; - int number = 0; - bool is_hex_value = false; - bool have_trailing_digits = false; - - for (int i = 0; i < len; i++) { - char c = s [i]; - if (state == 0) { - if (c == '&') { - entity.Append (c); - rawEntity.Append (c); - state = 1; - } else { - output.Append (c); - } - continue; - } + default: + char ch = s[i]; + if (ch > 159 && ch < 256) + { + output.Append("&#"); + output.Append(((int)ch).ToString(CultureInfo.InvariantCulture)); + output.Append(";"); + } + else + output.Append(ch); + break; + } + } - if (c == '&') { - state = 1; - if (have_trailing_digits) { - entity.Append (number.ToString (CultureInfo.InvariantCulture)); - have_trailing_digits = false; - } + return output.ToString(); + } - output.Append (entity); - entity.Length = 0; - entity.Append ('&'); - continue; - } + internal static string HtmlAttributeEncode(string s) + { + if (s == null) + return null; - if (state == 1) { - if (c == ';') { - state = 0; - output.Append (entity); - output.Append (c); - entity.Length = 0; - } else { - number = 0; - is_hex_value = false; - state = c != '#' ? 2 : 3; - entity.Append (c); - rawEntity.Append (c); - } - } else if (state == 2) { - entity.Append (c); - if (c == ';') { - string key = entity.ToString (); - if (key.Length > 1 && entities.ContainsKey (key.Substring (1, key.Length - 2))) - key = entities [key.Substring (1, key.Length - 2)].ToString (); + if (s.Length == 0) + return String.Empty; + bool needEncode = s.Any(c => c == '&' || c == '"' || c == '<'); - output.Append (key); - state = 0; - entity.Length = 0; - rawEntity.Length = 0; - } - } else if (state == 3) { - if (c == ';') { - if (number == 0) - output.Append (rawEntity + ";"); - else if (number > 65535) { - output.Append ("&#"); - output.Append (number.ToString (CultureInfo.InvariantCulture)); - output.Append (";"); - } else { - output.Append ((char) number); - } - state = 0; - entity.Length = 0; - rawEntity.Length = 0; - have_trailing_digits = false; - } else if (is_hex_value && Uri.IsHexDigit(c)) { - number = number * 16 + Uri.FromHex(c); - have_trailing_digits = true; - rawEntity.Append (c); - } else if (Char.IsDigit (c)) { - number = number * 10 + (c - '0'); - have_trailing_digits = true; - rawEntity.Append (c); - } else if (number == 0 && (c == 'x' || c == 'X')) { - is_hex_value = true; - rawEntity.Append (c); - } else { - state = 2; - if (have_trailing_digits) { - entity.Append (number.ToString (CultureInfo.InvariantCulture)); - have_trailing_digits = false; - } - entity.Append (c); - } - } - } + if (!needEncode) + return s; - if (entity.Length > 0) { - output.Append (entity); - } else if (have_trailing_digits) { - output.Append (number.ToString (CultureInfo.InvariantCulture)); - } - return output.ToString (); - } + StringBuilder output = new StringBuilder(); + int len = s.Length; + for (int i = 0; i < len; i++) + switch (s[i]) + { + case '&': + output.Append("&"); + break; + case '"': + output.Append("""); + break; + case '<': + output.Append("<"); + break; + default: + output.Append(s[i]); + break; + } - internal static bool NotEncoded (char c) - { - return (c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_'); - } + return output.ToString(); + } - static void InitEntities () - { - // Build the hash table of HTML entity references. This list comes - // from the HTML 4.01 W3C recommendation. - entities = new SortedDictionary (StringComparer.Ordinal); - - entities.Add ("nbsp", '\u00A0'); - entities.Add ("iexcl", '\u00A1'); - entities.Add ("cent", '\u00A2'); - entities.Add ("pound", '\u00A3'); - entities.Add ("curren", '\u00A4'); - entities.Add ("yen", '\u00A5'); - entities.Add ("brvbar", '\u00A6'); - entities.Add ("sect", '\u00A7'); - entities.Add ("uml", '\u00A8'); - entities.Add ("copy", '\u00A9'); - entities.Add ("ordf", '\u00AA'); - entities.Add ("laquo", '\u00AB'); - entities.Add ("not", '\u00AC'); - entities.Add ("shy", '\u00AD'); - entities.Add ("reg", '\u00AE'); - entities.Add ("macr", '\u00AF'); - entities.Add ("deg", '\u00B0'); - entities.Add ("plusmn", '\u00B1'); - entities.Add ("sup2", '\u00B2'); - entities.Add ("sup3", '\u00B3'); - entities.Add ("acute", '\u00B4'); - entities.Add ("micro", '\u00B5'); - entities.Add ("para", '\u00B6'); - entities.Add ("middot", '\u00B7'); - entities.Add ("cedil", '\u00B8'); - entities.Add ("sup1", '\u00B9'); - entities.Add ("ordm", '\u00BA'); - entities.Add ("raquo", '\u00BB'); - entities.Add ("frac14", '\u00BC'); - entities.Add ("frac12", '\u00BD'); - entities.Add ("frac34", '\u00BE'); - entities.Add ("iquest", '\u00BF'); - entities.Add ("Agrave", '\u00C0'); - entities.Add ("Aacute", '\u00C1'); - entities.Add ("Acirc", '\u00C2'); - entities.Add ("Atilde", '\u00C3'); - entities.Add ("Auml", '\u00C4'); - entities.Add ("Aring", '\u00C5'); - entities.Add ("AElig", '\u00C6'); - entities.Add ("Ccedil", '\u00C7'); - entities.Add ("Egrave", '\u00C8'); - entities.Add ("Eacute", '\u00C9'); - entities.Add ("Ecirc", '\u00CA'); - entities.Add ("Euml", '\u00CB'); - entities.Add ("Igrave", '\u00CC'); - entities.Add ("Iacute", '\u00CD'); - entities.Add ("Icirc", '\u00CE'); - entities.Add ("Iuml", '\u00CF'); - entities.Add ("ETH", '\u00D0'); - entities.Add ("Ntilde", '\u00D1'); - entities.Add ("Ograve", '\u00D2'); - entities.Add ("Oacute", '\u00D3'); - entities.Add ("Ocirc", '\u00D4'); - entities.Add ("Otilde", '\u00D5'); - entities.Add ("Ouml", '\u00D6'); - entities.Add ("times", '\u00D7'); - entities.Add ("Oslash", '\u00D8'); - entities.Add ("Ugrave", '\u00D9'); - entities.Add ("Uacute", '\u00DA'); - entities.Add ("Ucirc", '\u00DB'); - entities.Add ("Uuml", '\u00DC'); - entities.Add ("Yacute", '\u00DD'); - entities.Add ("THORN", '\u00DE'); - entities.Add ("szlig", '\u00DF'); - entities.Add ("agrave", '\u00E0'); - entities.Add ("aacute", '\u00E1'); - entities.Add ("acirc", '\u00E2'); - entities.Add ("atilde", '\u00E3'); - entities.Add ("auml", '\u00E4'); - entities.Add ("aring", '\u00E5'); - entities.Add ("aelig", '\u00E6'); - entities.Add ("ccedil", '\u00E7'); - entities.Add ("egrave", '\u00E8'); - entities.Add ("eacute", '\u00E9'); - entities.Add ("ecirc", '\u00EA'); - entities.Add ("euml", '\u00EB'); - entities.Add ("igrave", '\u00EC'); - entities.Add ("iacute", '\u00ED'); - entities.Add ("icirc", '\u00EE'); - entities.Add ("iuml", '\u00EF'); - entities.Add ("eth", '\u00F0'); - entities.Add ("ntilde", '\u00F1'); - entities.Add ("ograve", '\u00F2'); - entities.Add ("oacute", '\u00F3'); - entities.Add ("ocirc", '\u00F4'); - entities.Add ("otilde", '\u00F5'); - entities.Add ("ouml", '\u00F6'); - entities.Add ("divide", '\u00F7'); - entities.Add ("oslash", '\u00F8'); - entities.Add ("ugrave", '\u00F9'); - entities.Add ("uacute", '\u00FA'); - entities.Add ("ucirc", '\u00FB'); - entities.Add ("uuml", '\u00FC'); - entities.Add ("yacute", '\u00FD'); - entities.Add ("thorn", '\u00FE'); - entities.Add ("yuml", '\u00FF'); - entities.Add ("fnof", '\u0192'); - entities.Add ("Alpha", '\u0391'); - entities.Add ("Beta", '\u0392'); - entities.Add ("Gamma", '\u0393'); - entities.Add ("Delta", '\u0394'); - entities.Add ("Epsilon", '\u0395'); - entities.Add ("Zeta", '\u0396'); - entities.Add ("Eta", '\u0397'); - entities.Add ("Theta", '\u0398'); - entities.Add ("Iota", '\u0399'); - entities.Add ("Kappa", '\u039A'); - entities.Add ("Lambda", '\u039B'); - entities.Add ("Mu", '\u039C'); - entities.Add ("Nu", '\u039D'); - entities.Add ("Xi", '\u039E'); - entities.Add ("Omicron", '\u039F'); - entities.Add ("Pi", '\u03A0'); - entities.Add ("Rho", '\u03A1'); - entities.Add ("Sigma", '\u03A3'); - entities.Add ("Tau", '\u03A4'); - entities.Add ("Upsilon", '\u03A5'); - entities.Add ("Phi", '\u03A6'); - entities.Add ("Chi", '\u03A7'); - entities.Add ("Psi", '\u03A8'); - entities.Add ("Omega", '\u03A9'); - entities.Add ("alpha", '\u03B1'); - entities.Add ("beta", '\u03B2'); - entities.Add ("gamma", '\u03B3'); - entities.Add ("delta", '\u03B4'); - entities.Add ("epsilon", '\u03B5'); - entities.Add ("zeta", '\u03B6'); - entities.Add ("eta", '\u03B7'); - entities.Add ("theta", '\u03B8'); - entities.Add ("iota", '\u03B9'); - entities.Add ("kappa", '\u03BA'); - entities.Add ("lambda", '\u03BB'); - entities.Add ("mu", '\u03BC'); - entities.Add ("nu", '\u03BD'); - entities.Add ("xi", '\u03BE'); - entities.Add ("omicron", '\u03BF'); - entities.Add ("pi", '\u03C0'); - entities.Add ("rho", '\u03C1'); - entities.Add ("sigmaf", '\u03C2'); - entities.Add ("sigma", '\u03C3'); - entities.Add ("tau", '\u03C4'); - entities.Add ("upsilon", '\u03C5'); - entities.Add ("phi", '\u03C6'); - entities.Add ("chi", '\u03C7'); - entities.Add ("psi", '\u03C8'); - entities.Add ("omega", '\u03C9'); - entities.Add ("thetasym", '\u03D1'); - entities.Add ("upsih", '\u03D2'); - entities.Add ("piv", '\u03D6'); - entities.Add ("bull", '\u2022'); - entities.Add ("hellip", '\u2026'); - entities.Add ("prime", '\u2032'); - entities.Add ("Prime", '\u2033'); - entities.Add ("oline", '\u203E'); - entities.Add ("frasl", '\u2044'); - entities.Add ("weierp", '\u2118'); - entities.Add ("image", '\u2111'); - entities.Add ("real", '\u211C'); - entities.Add ("trade", '\u2122'); - entities.Add ("alefsym", '\u2135'); - entities.Add ("larr", '\u2190'); - entities.Add ("uarr", '\u2191'); - entities.Add ("rarr", '\u2192'); - entities.Add ("darr", '\u2193'); - entities.Add ("harr", '\u2194'); - entities.Add ("crarr", '\u21B5'); - entities.Add ("lArr", '\u21D0'); - entities.Add ("uArr", '\u21D1'); - entities.Add ("rArr", '\u21D2'); - entities.Add ("dArr", '\u21D3'); - entities.Add ("hArr", '\u21D4'); - entities.Add ("forall", '\u2200'); - entities.Add ("part", '\u2202'); - entities.Add ("exist", '\u2203'); - entities.Add ("empty", '\u2205'); - entities.Add ("nabla", '\u2207'); - entities.Add ("isin", '\u2208'); - entities.Add ("notin", '\u2209'); - entities.Add ("ni", '\u220B'); - entities.Add ("prod", '\u220F'); - entities.Add ("sum", '\u2211'); - entities.Add ("minus", '\u2212'); - entities.Add ("lowast", '\u2217'); - entities.Add ("radic", '\u221A'); - entities.Add ("prop", '\u221D'); - entities.Add ("infin", '\u221E'); - entities.Add ("ang", '\u2220'); - entities.Add ("and", '\u2227'); - entities.Add ("or", '\u2228'); - entities.Add ("cap", '\u2229'); - entities.Add ("cup", '\u222A'); - entities.Add ("int", '\u222B'); - entities.Add ("there4", '\u2234'); - entities.Add ("sim", '\u223C'); - entities.Add ("cong", '\u2245'); - entities.Add ("asymp", '\u2248'); - entities.Add ("ne", '\u2260'); - entities.Add ("equiv", '\u2261'); - entities.Add ("le", '\u2264'); - entities.Add ("ge", '\u2265'); - entities.Add ("sub", '\u2282'); - entities.Add ("sup", '\u2283'); - entities.Add ("nsub", '\u2284'); - entities.Add ("sube", '\u2286'); - entities.Add ("supe", '\u2287'); - entities.Add ("oplus", '\u2295'); - entities.Add ("otimes", '\u2297'); - entities.Add ("perp", '\u22A5'); - entities.Add ("sdot", '\u22C5'); - entities.Add ("lceil", '\u2308'); - entities.Add ("rceil", '\u2309'); - entities.Add ("lfloor", '\u230A'); - entities.Add ("rfloor", '\u230B'); - entities.Add ("lang", '\u2329'); - entities.Add ("rang", '\u232A'); - entities.Add ("loz", '\u25CA'); - entities.Add ("spades", '\u2660'); - entities.Add ("clubs", '\u2663'); - entities.Add ("hearts", '\u2665'); - entities.Add ("diams", '\u2666'); - entities.Add ("quot", '\u0022'); - entities.Add ("amp", '\u0026'); - entities.Add ("lt", '\u003C'); - entities.Add ("gt", '\u003E'); - entities.Add ("OElig", '\u0152'); - entities.Add ("oelig", '\u0153'); - entities.Add ("Scaron", '\u0160'); - entities.Add ("scaron", '\u0161'); - entities.Add ("Yuml", '\u0178'); - entities.Add ("circ", '\u02C6'); - entities.Add ("tilde", '\u02DC'); - entities.Add ("ensp", '\u2002'); - entities.Add ("emsp", '\u2003'); - entities.Add ("thinsp", '\u2009'); - entities.Add ("zwnj", '\u200C'); - entities.Add ("zwj", '\u200D'); - entities.Add ("lrm", '\u200E'); - entities.Add ("rlm", '\u200F'); - entities.Add ("ndash", '\u2013'); - entities.Add ("mdash", '\u2014'); - entities.Add ("lsquo", '\u2018'); - entities.Add ("rsquo", '\u2019'); - entities.Add ("sbquo", '\u201A'); - entities.Add ("ldquo", '\u201C'); - entities.Add ("rdquo", '\u201D'); - entities.Add ("bdquo", '\u201E'); - entities.Add ("dagger", '\u2020'); - entities.Add ("Dagger", '\u2021'); - entities.Add ("permil", '\u2030'); - entities.Add ("lsaquo", '\u2039'); - entities.Add ("rsaquo", '\u203A'); - entities.Add ("euro", '\u20AC'); - } - } + public static string HtmlDecode(string s) + { + if (s == null) + return null; + + if (s.Length == 0) + return String.Empty; + + if (s.IndexOf('&') == -1) + return s; + StringBuilder rawEntity = new StringBuilder(); + StringBuilder entity = new StringBuilder(); + StringBuilder output = new StringBuilder(); + int len = s.Length; + // 0 -> nothing, + // 1 -> right after '&' + // 2 -> between '&' and ';' but no '#' + // 3 -> '#' found after '&' and getting numbers + int state = 0; + int number = 0; + bool is_hex_value = false; + bool have_trailing_digits = false; + + for (int i = 0; i < len; i++) + { + char c = s[i]; + if (state == 0) + { + if (c == '&') + { + entity.Append(c); + rawEntity.Append(c); + state = 1; + } + else + { + output.Append(c); + } + continue; + } + + if (c == '&') + { + state = 1; + if (have_trailing_digits) + { + entity.Append(number.ToString(CultureInfo.InvariantCulture)); + have_trailing_digits = false; + } + + output.Append(entity); + entity.Length = 0; + entity.Append('&'); + continue; + } + + if (state == 1) + { + if (c == ';') + { + state = 0; + output.Append(entity); + output.Append(c); + entity.Length = 0; + } + else + { + number = 0; + is_hex_value = false; + state = c != '#' ? 2 : 3; + entity.Append(c); + rawEntity.Append(c); + } + } + else if (state == 2) + { + entity.Append(c); + if (c == ';') + { + string key = entity.ToString(); + if (key.Length > 1 && entities.ContainsKey(key.Substring(1, key.Length - 2))) + key = entities[key.Substring(1, key.Length - 2)].ToString(); + + output.Append(key); + state = 0; + entity.Length = 0; + rawEntity.Length = 0; + } + } + else if (state == 3) + { + if (c == ';') + { + if (number == 0) + output.Append(rawEntity + ";"); + else if (number > 65535) + { + output.Append("&#"); + output.Append(number.ToString(CultureInfo.InvariantCulture)); + output.Append(";"); + } + else + { + output.Append((char)number); + } + state = 0; + entity.Length = 0; + rawEntity.Length = 0; + have_trailing_digits = false; + } + else if (is_hex_value && Uri.IsHexDigit(c)) + { + number = number * 16 + Uri.FromHex(c); + have_trailing_digits = true; + rawEntity.Append(c); + } + else if (Char.IsDigit(c)) + { + number = number * 10 + (c - '0'); + have_trailing_digits = true; + rawEntity.Append(c); + } + else if (number == 0 && (c == 'x' || c == 'X')) + { + is_hex_value = true; + rawEntity.Append(c); + } + else + { + state = 2; + if (have_trailing_digits) + { + entity.Append(number.ToString(CultureInfo.InvariantCulture)); + have_trailing_digits = false; + } + entity.Append(c); + } + } + } + + if (entity.Length > 0) + { + output.Append(entity); + } + else if (have_trailing_digits) + { + output.Append(number.ToString(CultureInfo.InvariantCulture)); + } + return output.ToString(); + } + + internal static bool NotEncoded(char c) + { + return (c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_'); + } + + static void InitEntities() + { + // Build the hash table of HTML entity references. This list comes + // from the HTML 4.01 W3C recommendation. + entities = new SortedDictionary(StringComparer.Ordinal); + + entities.Add("nbsp", '\u00A0'); + entities.Add("iexcl", '\u00A1'); + entities.Add("cent", '\u00A2'); + entities.Add("pound", '\u00A3'); + entities.Add("curren", '\u00A4'); + entities.Add("yen", '\u00A5'); + entities.Add("brvbar", '\u00A6'); + entities.Add("sect", '\u00A7'); + entities.Add("uml", '\u00A8'); + entities.Add("copy", '\u00A9'); + entities.Add("ordf", '\u00AA'); + entities.Add("laquo", '\u00AB'); + entities.Add("not", '\u00AC'); + entities.Add("shy", '\u00AD'); + entities.Add("reg", '\u00AE'); + entities.Add("macr", '\u00AF'); + entities.Add("deg", '\u00B0'); + entities.Add("plusmn", '\u00B1'); + entities.Add("sup2", '\u00B2'); + entities.Add("sup3", '\u00B3'); + entities.Add("acute", '\u00B4'); + entities.Add("micro", '\u00B5'); + entities.Add("para", '\u00B6'); + entities.Add("middot", '\u00B7'); + entities.Add("cedil", '\u00B8'); + entities.Add("sup1", '\u00B9'); + entities.Add("ordm", '\u00BA'); + entities.Add("raquo", '\u00BB'); + entities.Add("frac14", '\u00BC'); + entities.Add("frac12", '\u00BD'); + entities.Add("frac34", '\u00BE'); + entities.Add("iquest", '\u00BF'); + entities.Add("Agrave", '\u00C0'); + entities.Add("Aacute", '\u00C1'); + entities.Add("Acirc", '\u00C2'); + entities.Add("Atilde", '\u00C3'); + entities.Add("Auml", '\u00C4'); + entities.Add("Aring", '\u00C5'); + entities.Add("AElig", '\u00C6'); + entities.Add("Ccedil", '\u00C7'); + entities.Add("Egrave", '\u00C8'); + entities.Add("Eacute", '\u00C9'); + entities.Add("Ecirc", '\u00CA'); + entities.Add("Euml", '\u00CB'); + entities.Add("Igrave", '\u00CC'); + entities.Add("Iacute", '\u00CD'); + entities.Add("Icirc", '\u00CE'); + entities.Add("Iuml", '\u00CF'); + entities.Add("ETH", '\u00D0'); + entities.Add("Ntilde", '\u00D1'); + entities.Add("Ograve", '\u00D2'); + entities.Add("Oacute", '\u00D3'); + entities.Add("Ocirc", '\u00D4'); + entities.Add("Otilde", '\u00D5'); + entities.Add("Ouml", '\u00D6'); + entities.Add("times", '\u00D7'); + entities.Add("Oslash", '\u00D8'); + entities.Add("Ugrave", '\u00D9'); + entities.Add("Uacute", '\u00DA'); + entities.Add("Ucirc", '\u00DB'); + entities.Add("Uuml", '\u00DC'); + entities.Add("Yacute", '\u00DD'); + entities.Add("THORN", '\u00DE'); + entities.Add("szlig", '\u00DF'); + entities.Add("agrave", '\u00E0'); + entities.Add("aacute", '\u00E1'); + entities.Add("acirc", '\u00E2'); + entities.Add("atilde", '\u00E3'); + entities.Add("auml", '\u00E4'); + entities.Add("aring", '\u00E5'); + entities.Add("aelig", '\u00E6'); + entities.Add("ccedil", '\u00E7'); + entities.Add("egrave", '\u00E8'); + entities.Add("eacute", '\u00E9'); + entities.Add("ecirc", '\u00EA'); + entities.Add("euml", '\u00EB'); + entities.Add("igrave", '\u00EC'); + entities.Add("iacute", '\u00ED'); + entities.Add("icirc", '\u00EE'); + entities.Add("iuml", '\u00EF'); + entities.Add("eth", '\u00F0'); + entities.Add("ntilde", '\u00F1'); + entities.Add("ograve", '\u00F2'); + entities.Add("oacute", '\u00F3'); + entities.Add("ocirc", '\u00F4'); + entities.Add("otilde", '\u00F5'); + entities.Add("ouml", '\u00F6'); + entities.Add("divide", '\u00F7'); + entities.Add("oslash", '\u00F8'); + entities.Add("ugrave", '\u00F9'); + entities.Add("uacute", '\u00FA'); + entities.Add("ucirc", '\u00FB'); + entities.Add("uuml", '\u00FC'); + entities.Add("yacute", '\u00FD'); + entities.Add("thorn", '\u00FE'); + entities.Add("yuml", '\u00FF'); + entities.Add("fnof", '\u0192'); + entities.Add("Alpha", '\u0391'); + entities.Add("Beta", '\u0392'); + entities.Add("Gamma", '\u0393'); + entities.Add("Delta", '\u0394'); + entities.Add("Epsilon", '\u0395'); + entities.Add("Zeta", '\u0396'); + entities.Add("Eta", '\u0397'); + entities.Add("Theta", '\u0398'); + entities.Add("Iota", '\u0399'); + entities.Add("Kappa", '\u039A'); + entities.Add("Lambda", '\u039B'); + entities.Add("Mu", '\u039C'); + entities.Add("Nu", '\u039D'); + entities.Add("Xi", '\u039E'); + entities.Add("Omicron", '\u039F'); + entities.Add("Pi", '\u03A0'); + entities.Add("Rho", '\u03A1'); + entities.Add("Sigma", '\u03A3'); + entities.Add("Tau", '\u03A4'); + entities.Add("Upsilon", '\u03A5'); + entities.Add("Phi", '\u03A6'); + entities.Add("Chi", '\u03A7'); + entities.Add("Psi", '\u03A8'); + entities.Add("Omega", '\u03A9'); + entities.Add("alpha", '\u03B1'); + entities.Add("beta", '\u03B2'); + entities.Add("gamma", '\u03B3'); + entities.Add("delta", '\u03B4'); + entities.Add("epsilon", '\u03B5'); + entities.Add("zeta", '\u03B6'); + entities.Add("eta", '\u03B7'); + entities.Add("theta", '\u03B8'); + entities.Add("iota", '\u03B9'); + entities.Add("kappa", '\u03BA'); + entities.Add("lambda", '\u03BB'); + entities.Add("mu", '\u03BC'); + entities.Add("nu", '\u03BD'); + entities.Add("xi", '\u03BE'); + entities.Add("omicron", '\u03BF'); + entities.Add("pi", '\u03C0'); + entities.Add("rho", '\u03C1'); + entities.Add("sigmaf", '\u03C2'); + entities.Add("sigma", '\u03C3'); + entities.Add("tau", '\u03C4'); + entities.Add("upsilon", '\u03C5'); + entities.Add("phi", '\u03C6'); + entities.Add("chi", '\u03C7'); + entities.Add("psi", '\u03C8'); + entities.Add("omega", '\u03C9'); + entities.Add("thetasym", '\u03D1'); + entities.Add("upsih", '\u03D2'); + entities.Add("piv", '\u03D6'); + entities.Add("bull", '\u2022'); + entities.Add("hellip", '\u2026'); + entities.Add("prime", '\u2032'); + entities.Add("Prime", '\u2033'); + entities.Add("oline", '\u203E'); + entities.Add("frasl", '\u2044'); + entities.Add("weierp", '\u2118'); + entities.Add("image", '\u2111'); + entities.Add("real", '\u211C'); + entities.Add("trade", '\u2122'); + entities.Add("alefsym", '\u2135'); + entities.Add("larr", '\u2190'); + entities.Add("uarr", '\u2191'); + entities.Add("rarr", '\u2192'); + entities.Add("darr", '\u2193'); + entities.Add("harr", '\u2194'); + entities.Add("crarr", '\u21B5'); + entities.Add("lArr", '\u21D0'); + entities.Add("uArr", '\u21D1'); + entities.Add("rArr", '\u21D2'); + entities.Add("dArr", '\u21D3'); + entities.Add("hArr", '\u21D4'); + entities.Add("forall", '\u2200'); + entities.Add("part", '\u2202'); + entities.Add("exist", '\u2203'); + entities.Add("empty", '\u2205'); + entities.Add("nabla", '\u2207'); + entities.Add("isin", '\u2208'); + entities.Add("notin", '\u2209'); + entities.Add("ni", '\u220B'); + entities.Add("prod", '\u220F'); + entities.Add("sum", '\u2211'); + entities.Add("minus", '\u2212'); + entities.Add("lowast", '\u2217'); + entities.Add("radic", '\u221A'); + entities.Add("prop", '\u221D'); + entities.Add("infin", '\u221E'); + entities.Add("ang", '\u2220'); + entities.Add("and", '\u2227'); + entities.Add("or", '\u2228'); + entities.Add("cap", '\u2229'); + entities.Add("cup", '\u222A'); + entities.Add("int", '\u222B'); + entities.Add("there4", '\u2234'); + entities.Add("sim", '\u223C'); + entities.Add("cong", '\u2245'); + entities.Add("asymp", '\u2248'); + entities.Add("ne", '\u2260'); + entities.Add("equiv", '\u2261'); + entities.Add("le", '\u2264'); + entities.Add("ge", '\u2265'); + entities.Add("sub", '\u2282'); + entities.Add("sup", '\u2283'); + entities.Add("nsub", '\u2284'); + entities.Add("sube", '\u2286'); + entities.Add("supe", '\u2287'); + entities.Add("oplus", '\u2295'); + entities.Add("otimes", '\u2297'); + entities.Add("perp", '\u22A5'); + entities.Add("sdot", '\u22C5'); + entities.Add("lceil", '\u2308'); + entities.Add("rceil", '\u2309'); + entities.Add("lfloor", '\u230A'); + entities.Add("rfloor", '\u230B'); + entities.Add("lang", '\u2329'); + entities.Add("rang", '\u232A'); + entities.Add("loz", '\u25CA'); + entities.Add("spades", '\u2660'); + entities.Add("clubs", '\u2663'); + entities.Add("hearts", '\u2665'); + entities.Add("diams", '\u2666'); + entities.Add("quot", '\u0022'); + entities.Add("amp", '\u0026'); + entities.Add("lt", '\u003C'); + entities.Add("gt", '\u003E'); + entities.Add("OElig", '\u0152'); + entities.Add("oelig", '\u0153'); + entities.Add("Scaron", '\u0160'); + entities.Add("scaron", '\u0161'); + entities.Add("Yuml", '\u0178'); + entities.Add("circ", '\u02C6'); + entities.Add("tilde", '\u02DC'); + entities.Add("ensp", '\u2002'); + entities.Add("emsp", '\u2003'); + entities.Add("thinsp", '\u2009'); + entities.Add("zwnj", '\u200C'); + entities.Add("zwj", '\u200D'); + entities.Add("lrm", '\u200E'); + entities.Add("rlm", '\u200F'); + entities.Add("ndash", '\u2013'); + entities.Add("mdash", '\u2014'); + entities.Add("lsquo", '\u2018'); + entities.Add("rsquo", '\u2019'); + entities.Add("sbquo", '\u201A'); + entities.Add("ldquo", '\u201C'); + entities.Add("rdquo", '\u201D'); + entities.Add("bdquo", '\u201E'); + entities.Add("dagger", '\u2020'); + entities.Add("Dagger", '\u2021'); + entities.Add("permil", '\u2030'); + entities.Add("lsaquo", '\u2039'); + entities.Add("rsaquo", '\u203A'); + entities.Add("euro", '\u20AC'); + } + } } diff --git a/src/Generator/Utils/IEnumerableExtensions.cs b/src/Generator/Utils/IEnumerableExtensions.cs index 986209b3..95e786f9 100644 --- a/src/Generator/Utils/IEnumerableExtensions.cs +++ b/src/Generator/Utils/IEnumerableExtensions.cs @@ -27,7 +27,7 @@ namespace CppSharp.Utils if (source.Contains(item)) { - sorted.Add(item); + sorted.Add(item); } } else diff --git a/src/Generator/Utils/Options.cs b/src/Generator/Utils/Options.cs index d86de259..f5740700 100644 --- a/src/Generator/Utils/Options.cs +++ b/src/Generator/Utils/Options.cs @@ -151,1284 +151,1284 @@ namespace NDesk.Options namespace Mono.Options #endif { - static class StringCoda - { - - public static IEnumerable WrappedLines(string self, params int[] widths) - { - IEnumerable w = widths; - return WrappedLines(self, w); - } - - public static IEnumerable WrappedLines(string self, IEnumerable widths) - { - if (widths == null) - throw new ArgumentNullException("widths"); - return CreateWrappedLinesIterator(self, widths); - } - - private static IEnumerable CreateWrappedLinesIterator(string self, IEnumerable widths) - { - if (string.IsNullOrEmpty(self)) - { - yield return string.Empty; - yield break; - } - using (IEnumerator ewidths = widths.GetEnumerator()) - { - bool? hw = null; - int width = GetNextWidth(ewidths, int.MaxValue, ref hw); - int start = 0, end; - do - { - end = GetLineEnd(start, width, self); - char c = self[end - 1]; - if (char.IsWhiteSpace(c)) - --end; - bool needContinuation = end != self.Length && !IsEolChar(c); - string continuation = ""; - if (needContinuation) - { - --end; - continuation = "-"; - } - string line = self.Substring(start, end - start) + continuation; - yield return line; - start = end; - if (char.IsWhiteSpace(c)) - ++start; - width = GetNextWidth(ewidths, width, ref hw); - } while (start < self.Length); - } - } - - private static int GetNextWidth(IEnumerator ewidths, int curWidth, ref bool? eValid) - { - if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) - { - curWidth = (eValid = ewidths.MoveNext()).Value ? ewidths.Current : curWidth; - // '.' is any character, - is for a continuation - const string minWidth = ".-"; - if (curWidth < minWidth.Length) - throw new ArgumentOutOfRangeException("widths", - string.Format("Element must be >= {0}, was {1}.", minWidth.Length, curWidth)); - return curWidth; - } - // no more elements, use the last element. - return curWidth; - } - - private static bool IsEolChar(char c) - { - return !char.IsLetterOrDigit(c); - } - - private static int GetLineEnd(int start, int length, string description) - { - int end = System.Math.Min(start + length, description.Length); - int sep = -1; - for (int i = start; i < end; ++i) - { - if (description[i] == '\n') - return i + 1; - if (IsEolChar(description[i])) - sep = i + 1; - } - if (sep == -1 || end == description.Length) - return end; - return sep; - } - } - - public class OptionValueCollection : IList, IList - { - - List values = new List(); - OptionContext c; - - internal OptionValueCollection(OptionContext c) - { - this.c = c; - } - - #region ICollection - void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); } - bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } } - object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } } - #endregion - - #region ICollection - public void Add(string item) { values.Add(item); } - public void Clear() { values.Clear(); } - public bool Contains(string item) { return values.Contains(item); } - public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); } - public bool Remove(string item) { return values.Remove(item); } - public int Count { get { return values.Count; } } - public bool IsReadOnly { get { return false; } } - #endregion - - #region IEnumerable - IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } - #endregion - - #region IEnumerable - public IEnumerator GetEnumerator() { return values.GetEnumerator(); } - #endregion - - #region IList - int IList.Add(object value) { return (values as IList).Add(value); } - bool IList.Contains(object value) { return (values as IList).Contains(value); } - int IList.IndexOf(object value) { return (values as IList).IndexOf(value); } - void IList.Insert(int index, object value) { (values as IList).Insert(index, value); } - void IList.Remove(object value) { (values as IList).Remove(value); } - void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); } - bool IList.IsFixedSize { get { return false; } } - object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } } - #endregion - - #region IList - public int IndexOf(string item) { return values.IndexOf(item); } - public void Insert(int index, string item) { values.Insert(index, item); } - public void RemoveAt(int index) { values.RemoveAt(index); } - - private void AssertValid(int index) - { - if (c.Option == null) - throw new InvalidOperationException("OptionContext.Option is null."); - if (index >= c.Option.MaxValueCount) - throw new ArgumentOutOfRangeException("index"); - if (c.Option.OptionValueType == OptionValueType.Required && - index >= values.Count) - throw new OptionException(string.Format( - c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName), - c.OptionName); - } - - public string this[int index] - { - get - { - AssertValid(index); - return index >= values.Count ? null : values[index]; - } - set - { - values[index] = value; - } - } - #endregion - - public List ToList() - { - return new List(values); - } - - public string[] ToArray() - { - return values.ToArray(); - } - - public override string ToString() - { - return string.Join(", ", values.ToArray()); - } - } - - public class OptionContext - { - private Option option; - private string name; - private int index; - private OptionSet set; - private OptionValueCollection c; - - public OptionContext(OptionSet set) - { - this.set = set; - this.c = new OptionValueCollection(this); - } - - public Option Option - { - get { return option; } - set { option = value; } - } - - public string OptionName - { - get { return name; } - set { name = value; } - } - - public int OptionIndex - { - get { return index; } - set { index = value; } - } - - public OptionSet OptionSet - { - get { return set; } - } - - public OptionValueCollection OptionValues - { - get { return c; } - } - } - - public enum OptionValueType - { - None, - Optional, - Required, - } - - public abstract class Option - { - string prototype, description; - string[] names; - OptionValueType type; - int count; - string[] separators; - - protected Option(string prototype, string description) - : this(prototype, description, 1) - { - } - - protected Option(string prototype, string description, int maxValueCount) - { - if (prototype == null) - throw new ArgumentNullException("prototype"); - if (prototype.Length == 0) - throw new ArgumentException("Cannot be the empty string.", "prototype"); - if (maxValueCount < 0) - throw new ArgumentOutOfRangeException("maxValueCount"); - - this.prototype = prototype; - this.description = description; - this.count = maxValueCount; - this.names = (this is OptionSet.Category) - // append GetHashCode() so that "duplicate" categories have distinct - // names, e.g. adding multiple "" categories should be valid. - ? new[] { prototype + this.GetHashCode() } - : prototype.Split('|'); - - if (this is OptionSet.Category) - return; - - this.type = ParsePrototype(); - - if (this.count == 0 && type != OptionValueType.None) - throw new ArgumentException( - "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + - "OptionValueType.Optional.", - "maxValueCount"); - if (this.type == OptionValueType.None && maxValueCount > 1) - throw new ArgumentException( - string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), - "maxValueCount"); - if (Array.IndexOf(names, "<>") >= 0 && - ((names.Length == 1 && this.type != OptionValueType.None) || - (names.Length > 1 && this.MaxValueCount > 1))) - throw new ArgumentException( - "The default option handler '<>' cannot require values.", - "prototype"); - } - - public string Prototype { get { return prototype; } } - public string Description { get { return description; } } - public OptionValueType OptionValueType { get { return type; } } - public int MaxValueCount { get { return count; } } - - public string[] GetNames() - { - return (string[])names.Clone(); - } - - public string[] GetValueSeparators() - { - if (separators == null) - return new string[0]; - return (string[])separators.Clone(); - } - - protected static T Parse(string value, OptionContext c) - { - Type tt = typeof(T); - bool nullable = tt.IsValueType && tt.IsGenericType && - !tt.IsGenericTypeDefinition && - tt.GetGenericTypeDefinition() == typeof(Nullable<>); - Type targetType = nullable ? tt.GetGenericArguments()[0] : typeof(T); - TypeConverter conv = TypeDescriptor.GetConverter(targetType); - T t = default(T); - try - { - if (value != null) - t = (T)conv.ConvertFromString(value); - } - catch (Exception e) - { - throw new OptionException( - string.Format( - c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."), - value, targetType.Name, c.OptionName), - c.OptionName, e); - } - return t; - } - - internal string[] Names { get { return names; } } - internal string[] ValueSeparators { get { return separators; } } - - static readonly char[] NameTerminator = new char[] { '=', ':' }; - - private OptionValueType ParsePrototype() - { - char type = '\0'; - List seps = new List(); - for (int i = 0; i < names.Length; ++i) - { - string name = names[i]; - if (name.Length == 0) - throw new ArgumentException("Empty option names are not supported.", "prototype"); - - int end = name.IndexOfAny(NameTerminator); - if (end == -1) - continue; - names[i] = name.Substring(0, end); - if (type == '\0' || type == name[end]) - type = name[end]; - else - throw new ArgumentException( - string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]), - "prototype"); - AddSeparators(name, end, seps); - } - - if (type == '\0') - return OptionValueType.None; - - if (count <= 1 && seps.Count != 0) - throw new ArgumentException( - string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count), - "prototype"); - if (count > 1) - { - if (seps.Count == 0) - this.separators = new string[] { ":", "=" }; - else if (seps.Count == 1 && seps[0].Length == 0) - this.separators = null; - else - this.separators = seps.ToArray(); - } - - return type == '=' ? OptionValueType.Required : OptionValueType.Optional; - } - - private static void AddSeparators(string name, int end, ICollection seps) - { - int start = -1; - for (int i = end + 1; i < name.Length; ++i) - { - switch (name[i]) - { - case '{': - if (start != -1) - throw new ArgumentException( - string.Format("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - start = i + 1; - break; - case '}': - if (start == -1) - throw new ArgumentException( - string.Format("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - seps.Add(name.Substring(start, i - start)); - start = -1; - break; - default: - if (start == -1) - seps.Add(name[i].ToString()); - break; - } - } - if (start != -1) - throw new ArgumentException( - string.Format("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - } - - public void Invoke(OptionContext c) - { - OnParseComplete(c); - c.OptionName = null; - c.Option = null; - c.OptionValues.Clear(); - } - - protected abstract void OnParseComplete(OptionContext c); - - public override string ToString() - { - return Prototype; - } - } - - public abstract class ArgumentSource - { - - protected ArgumentSource() - { - } - - public abstract string[] GetNames(); - public abstract string Description { get; } - public abstract bool GetArguments(string value, out IEnumerable replacement); - - public static IEnumerable GetArgumentsFromFile(string file) - { - return GetArguments(File.OpenText(file), true); - } - - public static IEnumerable GetArguments(TextReader reader) - { - return GetArguments(reader, false); - } - - // Cribbed from mcs/driver.cs:LoadArgs(string) - static IEnumerable GetArguments(TextReader reader, bool close) - { - try - { - StringBuilder arg = new StringBuilder(); - - string line; - while ((line = reader.ReadLine()) != null) - { - int t = line.Length; - - for (int i = 0; i < t; i++) - { - char c = line[i]; - - if (c == '"' || c == '\'') - { - char end = c; - - for (i++; i < t; i++) - { - c = line[i]; - - if (c == end) - break; - arg.Append(c); - } - } - else if (c == ' ') - { - if (arg.Length > 0) - { - yield return arg.ToString(); - arg.Length = 0; - } - } - else - arg.Append(c); - } - if (arg.Length > 0) - { - yield return arg.ToString(); - arg.Length = 0; - } - } - } - finally - { - if (close) - reader.Close(); - } - } - } - - public class ResponseFileSource : ArgumentSource - { - - public override string[] GetNames() - { - return new string[] { "@file" }; - } - - public override string Description - { - get { return "Read response file for more options."; } - } - - public override bool GetArguments(string value, out IEnumerable replacement) - { - if (string.IsNullOrEmpty(value) || !value.StartsWith("@")) - { - replacement = null; - return false; - } - replacement = ArgumentSource.GetArgumentsFromFile(value.Substring(1)); - return true; - } - } - - [Serializable] - public class OptionException : Exception - { - private string option; - - public OptionException() - { - } - - public OptionException(string message, string optionName) - : base(message) - { - this.option = optionName; - } - - public OptionException(string message, string optionName, Exception innerException) - : base(message, innerException) - { - this.option = optionName; - } - - protected OptionException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - this.option = info.GetString("OptionName"); - } - - public string OptionName - { - get { return this.option; } - } - - [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("OptionName", option); - } - } - - public delegate void OptionAction(TKey key, TValue value); - - public class OptionSet : KeyedCollection - { - public OptionSet() - : this(delegate(string f) { return f; }) - { - } - - public OptionSet(Converter localizer) - { - this.localizer = localizer; - this.roSources = new ReadOnlyCollection(sources); - } - - Converter localizer; - - public Converter MessageLocalizer - { - get { return localizer; } - } - - List sources = new List(); - ReadOnlyCollection roSources; - - public ReadOnlyCollection ArgumentSources - { - get { return roSources; } - } - - - protected override string GetKeyForItem(Option item) - { - if (item == null) - throw new ArgumentNullException("option"); - if (item.Names != null && item.Names.Length > 0) - return item.Names[0]; - // This should never happen, as it's invalid for Option to be - // constructed w/o any names. - throw new InvalidOperationException("Option has no names!"); - } - - [Obsolete("Use KeyedCollection.this[string]")] - protected Option GetOptionForName(string option) - { - if (option == null) - throw new ArgumentNullException("option"); - try - { - return base[option]; - } - catch (KeyNotFoundException) - { - return null; - } - } - - protected override void InsertItem(int index, Option item) - { - base.InsertItem(index, item); - AddImpl(item); - } - - protected override void RemoveItem(int index) - { - Option p = Items[index]; - base.RemoveItem(index); - // KeyedCollection.RemoveItem() handles the 0th item - for (int i = 1; i < p.Names.Length; ++i) - { - Dictionary.Remove(p.Names[i]); - } - } - - protected override void SetItem(int index, Option item) - { - base.SetItem(index, item); - AddImpl(item); - } - - private void AddImpl(Option option) - { - if (option == null) - throw new ArgumentNullException("option"); - List added = new List(option.Names.Length); - try - { - // KeyedCollection.InsertItem/SetItem handle the 0th name. - for (int i = 1; i < option.Names.Length; ++i) - { - Dictionary.Add(option.Names[i], option); - added.Add(option.Names[i]); - } - } - catch (Exception) - { - foreach (string name in added) - Dictionary.Remove(name); - throw; - } - } - - public OptionSet Add(string header) - { - if (header == null) - throw new ArgumentNullException("header"); - Add(new Category(header)); - return this; - } - - internal sealed class Category : Option - { - - // Prototype starts with '=' because this is an invalid prototype - // (see Option.ParsePrototype(), and thus it'll prevent Category - // instances from being accidentally used as normal options. - public Category(string description) - : base("=:Category:= " + description, description) - { - } - - protected override void OnParseComplete(OptionContext c) - { - throw new NotSupportedException("Category.OnParseComplete should not be invoked."); - } - } - - - public new OptionSet Add(Option option) - { - base.Add(option); - return this; - } - - sealed class ActionOption : Option - { - Action action; - - public ActionOption(string prototype, string description, int count, Action action) - : base(prototype, description, count) - { - if (action == null) - throw new ArgumentNullException("action"); - this.action = action; - } - - protected override void OnParseComplete(OptionContext c) - { - action(c.OptionValues); - } - } - - public OptionSet Add(string prototype, Action action) - { - return Add(prototype, null, action); - } - - public OptionSet Add(string prototype, string description, Action action) - { - if (action == null) - throw new ArgumentNullException("action"); - Option p = new ActionOption(prototype, description, 1, - delegate(OptionValueCollection v) { action(v[0]); }); - base.Add(p); - return this; - } - - public OptionSet Add(string prototype, OptionAction action) - { - return Add(prototype, null, action); - } - - public OptionSet Add(string prototype, string description, OptionAction action) - { - if (action == null) - throw new ArgumentNullException("action"); - Option p = new ActionOption(prototype, description, 2, - delegate(OptionValueCollection v) { action(v[0], v[1]); }); - base.Add(p); - return this; - } - - sealed class ActionOption : Option - { - Action action; - - public ActionOption(string prototype, string description, Action action) - : base(prototype, description, 1) - { - if (action == null) - throw new ArgumentNullException("action"); - this.action = action; - } - - protected override void OnParseComplete(OptionContext c) - { - action(Parse(c.OptionValues[0], c)); - } - } - - sealed class ActionOption : Option - { - OptionAction action; - - public ActionOption(string prototype, string description, OptionAction action) - : base(prototype, description, 2) - { - if (action == null) - throw new ArgumentNullException("action"); - this.action = action; - } - - protected override void OnParseComplete(OptionContext c) - { - action( - Parse(c.OptionValues[0], c), - Parse(c.OptionValues[1], c)); - } - } - - public OptionSet Add(string prototype, Action action) - { - return Add(prototype, null, action); - } - - public OptionSet Add(string prototype, string description, Action action) - { - return Add(new ActionOption(prototype, description, action)); - } - - public OptionSet Add(string prototype, OptionAction action) - { - return Add(prototype, null, action); - } - - public OptionSet Add(string prototype, string description, OptionAction action) - { - return Add(new ActionOption(prototype, description, action)); - } - - public OptionSet Add(ArgumentSource source) - { - if (source == null) - throw new ArgumentNullException("source"); - sources.Add(source); - return this; - } - - protected virtual OptionContext CreateOptionContext() - { - return new OptionContext(this); - } - - public List Parse(IEnumerable arguments) - { - if (arguments == null) - throw new ArgumentNullException("arguments"); - OptionContext c = CreateOptionContext(); - c.OptionIndex = -1; - bool process = true; - List unprocessed = new List(); - Option def = Contains("<>") ? this["<>"] : null; - ArgumentEnumerator ae = new ArgumentEnumerator(arguments); - foreach (string argument in ae) - { - ++c.OptionIndex; - if (argument == "--") - { - process = false; - continue; - } - if (!process) - { - Unprocessed(unprocessed, def, c, argument); - continue; - } - if (AddSource(ae, argument)) - continue; - if (!Parse(argument, c)) - Unprocessed(unprocessed, def, c, argument); - } - if (c.Option != null) - c.Option.Invoke(c); - return unprocessed; - } - - class ArgumentEnumerator : IEnumerable - { - List> sources = new List>(); - - public ArgumentEnumerator(IEnumerable arguments) - { - sources.Add(arguments.GetEnumerator()); - } - - public void Add(IEnumerable arguments) - { - sources.Add(arguments.GetEnumerator()); - } - - public IEnumerator GetEnumerator() - { - do - { - IEnumerator c = sources[sources.Count - 1]; - if (c.MoveNext()) - yield return c.Current; - else - { - c.Dispose(); - sources.RemoveAt(sources.Count - 1); - } - } while (sources.Count > 0); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } - - bool AddSource(ArgumentEnumerator ae, string argument) - { - foreach (ArgumentSource source in sources) - { - IEnumerable replacement; - if (!source.GetArguments(argument, out replacement)) - continue; - ae.Add(replacement); - return true; - } - return false; - } - - private static bool Unprocessed(ICollection extra, Option def, OptionContext c, string argument) - { - if (def == null) - { - extra.Add(argument); - return false; - } - c.OptionValues.Add(argument); - c.Option = def; - c.Option.Invoke(c); - return false; - } - - private readonly Regex ValueOption = new Regex( - @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); - - protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) - { - if (argument == null) - throw new ArgumentNullException("argument"); - - flag = name = sep = value = null; - Match m = ValueOption.Match(argument); - if (!m.Success) - { - return false; - } - flag = m.Groups["flag"].Value; - name = m.Groups["name"].Value; - if (m.Groups["sep"].Success && m.Groups["value"].Success) - { - sep = m.Groups["sep"].Value; - value = m.Groups["value"].Value; - } - return true; - } - - protected virtual bool Parse(string argument, OptionContext c) - { - if (c.Option != null) - { - ParseValue(argument, c); - return true; - } - - string f, n, s, v; - if (!GetOptionParts(argument, out f, out n, out s, out v)) - return false; - - Option p; - if (Contains(n)) - { - p = this[n]; - c.OptionName = f + n; - c.Option = p; - switch (p.OptionValueType) - { - case OptionValueType.None: - c.OptionValues.Add(n); - c.Option.Invoke(c); - break; - case OptionValueType.Optional: - case OptionValueType.Required: - ParseValue(v, c); - break; - } - return true; - } - // no match; is it a bool option? - if (ParseBool(argument, n, c)) - return true; - // is it a bundled option? - if (ParseBundledValue(f, string.Concat(n + s + v), c)) - return true; - - return false; - } - - private void ParseValue(string option, OptionContext c) - { - if (option != null) - foreach (string o in c.Option.ValueSeparators != null - ? option.Split(c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None) - : new string[] { option }) - { - c.OptionValues.Add(o); - } - if (c.OptionValues.Count == c.Option.MaxValueCount || - c.Option.OptionValueType == OptionValueType.Optional) - c.Option.Invoke(c); - else if (c.OptionValues.Count > c.Option.MaxValueCount) - { - throw new OptionException(localizer(string.Format( - "Error: Found {0} option values when expecting {1}.", - c.OptionValues.Count, c.Option.MaxValueCount)), - c.OptionName); - } - } - - private bool ParseBool(string option, string n, OptionContext c) - { - Option p; - string rn; - if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') && - Contains((rn = n.Substring(0, n.Length - 1)))) - { - p = this[rn]; - string v = n[n.Length - 1] == '+' ? option : null; - c.OptionName = option; - c.Option = p; - c.OptionValues.Add(v); - p.Invoke(c); - return true; - } - return false; - } - - private bool ParseBundledValue(string f, string n, OptionContext c) - { - if (f != "-") - return false; - for (int i = 0; i < n.Length; ++i) - { - Option p; - string opt = f + n[i].ToString(); - string rn = n[i].ToString(); - if (!Contains(rn)) - { - if (i == 0) - return false; - throw new OptionException(string.Format(localizer( - "Cannot bundle unregistered option '{0}'."), opt), opt); - } - p = this[rn]; - switch (p.OptionValueType) - { - case OptionValueType.None: - Invoke(c, opt, n, p); - break; - case OptionValueType.Optional: - case OptionValueType.Required: - { - string v = n.Substring(i + 1); - c.Option = p; - c.OptionName = opt; - ParseValue(v.Length != 0 ? v : null, c); - return true; - } - default: - throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType); - } - } - return true; - } - - private static void Invoke(OptionContext c, string name, string value, Option option) - { - c.OptionName = name; - c.Option = option; - c.OptionValues.Add(value); - option.Invoke(c); - } - - private const int OptionWidth = 29; - private const int Description_FirstWidth = 80 - OptionWidth; - private const int Description_RemWidth = 80 - OptionWidth - 2; - - public void WriteOptionDescriptions(TextWriter o) - { - foreach (Option p in this) - { - int written = 0; - - Category c = p as Category; - if (c != null) - { - WriteDescription(o, p.Description, "", 80, 80); - continue; - } - - if (!WriteOptionPrototype(o, p, ref written)) - continue; - - if (written < OptionWidth) - o.Write(new string(' ', OptionWidth - written)); - else - { - o.WriteLine(); - o.Write(new string(' ', OptionWidth)); - } - - WriteDescription(o, p.Description, new string(' ', OptionWidth + 2), - Description_FirstWidth, Description_RemWidth); - } - - foreach (ArgumentSource s in sources) - { - string[] names = s.GetNames(); - if (names == null || names.Length == 0) - continue; - - int written = 0; - - Write(o, ref written, " "); - Write(o, ref written, names[0]); - for (int i = 1; i < names.Length; ++i) - { - Write(o, ref written, ", "); - Write(o, ref written, names[i]); - } - - if (written < OptionWidth) - o.Write(new string(' ', OptionWidth - written)); - else - { - o.WriteLine(); - o.Write(new string(' ', OptionWidth)); - } - - WriteDescription(o, s.Description, new string(' ', OptionWidth + 2), - Description_FirstWidth, Description_RemWidth); - } - } - - void WriteDescription(TextWriter o, string value, string prefix, int firstWidth, int remWidth) - { - bool indent = false; - foreach (string line in GetLines(localizer(GetDescription(value)), firstWidth, remWidth)) - { - if (indent) - o.Write(prefix); - o.WriteLine(line); - indent = true; - } - } - - bool WriteOptionPrototype(TextWriter o, Option p, ref int written) - { - string[] names = p.Names; - - int i = GetNextOptionIndex(names, 0); - if (i == names.Length) - return false; - - if (names[i].Length == 1) - { - Write(o, ref written, " -"); - Write(o, ref written, names[0]); - } - else - { - Write(o, ref written, " --"); - Write(o, ref written, names[0]); - } - - for (i = GetNextOptionIndex(names, i + 1); - i < names.Length; i = GetNextOptionIndex(names, i + 1)) - { - Write(o, ref written, ", "); - Write(o, ref written, names[i].Length == 1 ? "-" : "--"); - Write(o, ref written, names[i]); - } - - if (p.OptionValueType == OptionValueType.Optional || - p.OptionValueType == OptionValueType.Required) - { - if (p.OptionValueType == OptionValueType.Optional) - { - Write(o, ref written, localizer("[")); - } - Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description))); - string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 - ? p.ValueSeparators[0] - : " "; - for (int c = 1; c < p.MaxValueCount; ++c) - { - Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description))); - } - if (p.OptionValueType == OptionValueType.Optional) - { - Write(o, ref written, localizer("]")); - } - } - return true; - } - - static int GetNextOptionIndex(string[] names, int i) - { - while (i < names.Length && names[i] == "<>") - { - ++i; - } - return i; - } - - static void Write(TextWriter o, ref int n, string s) - { - n += s.Length; - o.Write(s); - } - - private static string GetArgumentName(int index, int maxIndex, string description) - { - if (description == null) - return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - string[] nameStart; - if (maxIndex == 1) - nameStart = new string[] { "{0:", "{" }; - else - nameStart = new string[] { "{" + index + ":" }; - for (int i = 0; i < nameStart.Length; ++i) - { - int start, j = 0; - do - { - start = description.IndexOf(nameStart[i], j); - } while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false); - if (start == -1) - continue; - int end = description.IndexOf("}", start); - if (end == -1) - continue; - return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length); - } - return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - } - - private static string GetDescription(string description) - { - if (description == null) - return string.Empty; - StringBuilder sb = new StringBuilder(description.Length); - int start = -1; - for (int i = 0; i < description.Length; ++i) - { - switch (description[i]) - { - case '{': - if (i == start) - { - sb.Append('{'); - start = -1; - } - else if (start < 0) - start = i + 1; - break; - case '}': - if (start < 0) - { - if ((i + 1) == description.Length || description[i + 1] != '}') - throw new InvalidOperationException("Invalid option description: " + description); - ++i; - sb.Append("}"); - } - else - { - sb.Append(description.Substring(start, i - start)); - start = -1; - } - break; - case ':': - if (start < 0) - goto default; - start = i + 1; - break; - default: - if (start < 0) - sb.Append(description[i]); - break; - } - } - return sb.ToString(); - } - - private static IEnumerable GetLines(string description, int firstWidth, int remWidth) - { - return StringCoda.WrappedLines(description, firstWidth, remWidth); - } - } + static class StringCoda + { + + public static IEnumerable WrappedLines(string self, params int[] widths) + { + IEnumerable w = widths; + return WrappedLines(self, w); + } + + public static IEnumerable WrappedLines(string self, IEnumerable widths) + { + if (widths == null) + throw new ArgumentNullException("widths"); + return CreateWrappedLinesIterator(self, widths); + } + + private static IEnumerable CreateWrappedLinesIterator(string self, IEnumerable widths) + { + if (string.IsNullOrEmpty(self)) + { + yield return string.Empty; + yield break; + } + using (IEnumerator ewidths = widths.GetEnumerator()) + { + bool? hw = null; + int width = GetNextWidth(ewidths, int.MaxValue, ref hw); + int start = 0, end; + do + { + end = GetLineEnd(start, width, self); + char c = self[end - 1]; + if (char.IsWhiteSpace(c)) + --end; + bool needContinuation = end != self.Length && !IsEolChar(c); + string continuation = ""; + if (needContinuation) + { + --end; + continuation = "-"; + } + string line = self.Substring(start, end - start) + continuation; + yield return line; + start = end; + if (char.IsWhiteSpace(c)) + ++start; + width = GetNextWidth(ewidths, width, ref hw); + } while (start < self.Length); + } + } + + private static int GetNextWidth(IEnumerator ewidths, int curWidth, ref bool? eValid) + { + if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) + { + curWidth = (eValid = ewidths.MoveNext()).Value ? ewidths.Current : curWidth; + // '.' is any character, - is for a continuation + const string minWidth = ".-"; + if (curWidth < minWidth.Length) + throw new ArgumentOutOfRangeException("widths", + string.Format("Element must be >= {0}, was {1}.", minWidth.Length, curWidth)); + return curWidth; + } + // no more elements, use the last element. + return curWidth; + } + + private static bool IsEolChar(char c) + { + return !char.IsLetterOrDigit(c); + } + + private static int GetLineEnd(int start, int length, string description) + { + int end = System.Math.Min(start + length, description.Length); + int sep = -1; + for (int i = start; i < end; ++i) + { + if (description[i] == '\n') + return i + 1; + if (IsEolChar(description[i])) + sep = i + 1; + } + if (sep == -1 || end == description.Length) + return end; + return sep; + } + } + + public class OptionValueCollection : IList, IList + { + + List values = new List(); + OptionContext c; + + internal OptionValueCollection(OptionContext c) + { + this.c = c; + } + + #region ICollection + void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); } + bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } } + object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } } + #endregion + + #region ICollection + public void Add(string item) { values.Add(item); } + public void Clear() { values.Clear(); } + public bool Contains(string item) { return values.Contains(item); } + public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); } + public bool Remove(string item) { return values.Remove(item); } + public int Count { get { return values.Count; } } + public bool IsReadOnly { get { return false; } } + #endregion + + #region IEnumerable + IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } + #endregion + + #region IEnumerable + public IEnumerator GetEnumerator() { return values.GetEnumerator(); } + #endregion + + #region IList + int IList.Add(object value) { return (values as IList).Add(value); } + bool IList.Contains(object value) { return (values as IList).Contains(value); } + int IList.IndexOf(object value) { return (values as IList).IndexOf(value); } + void IList.Insert(int index, object value) { (values as IList).Insert(index, value); } + void IList.Remove(object value) { (values as IList).Remove(value); } + void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); } + bool IList.IsFixedSize { get { return false; } } + object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } } + #endregion + + #region IList + public int IndexOf(string item) { return values.IndexOf(item); } + public void Insert(int index, string item) { values.Insert(index, item); } + public void RemoveAt(int index) { values.RemoveAt(index); } + + private void AssertValid(int index) + { + if (c.Option == null) + throw new InvalidOperationException("OptionContext.Option is null."); + if (index >= c.Option.MaxValueCount) + throw new ArgumentOutOfRangeException("index"); + if (c.Option.OptionValueType == OptionValueType.Required && + index >= values.Count) + throw new OptionException(string.Format( + c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName), + c.OptionName); + } + + public string this[int index] + { + get + { + AssertValid(index); + return index >= values.Count ? null : values[index]; + } + set + { + values[index] = value; + } + } + #endregion + + public List ToList() + { + return new List(values); + } + + public string[] ToArray() + { + return values.ToArray(); + } + + public override string ToString() + { + return string.Join(", ", values.ToArray()); + } + } + + public class OptionContext + { + private Option option; + private string name; + private int index; + private OptionSet set; + private OptionValueCollection c; + + public OptionContext(OptionSet set) + { + this.set = set; + this.c = new OptionValueCollection(this); + } + + public Option Option + { + get { return option; } + set { option = value; } + } + + public string OptionName + { + get { return name; } + set { name = value; } + } + + public int OptionIndex + { + get { return index; } + set { index = value; } + } + + public OptionSet OptionSet + { + get { return set; } + } + + public OptionValueCollection OptionValues + { + get { return c; } + } + } + + public enum OptionValueType + { + None, + Optional, + Required, + } + + public abstract class Option + { + string prototype, description; + string[] names; + OptionValueType type; + int count; + string[] separators; + + protected Option(string prototype, string description) + : this(prototype, description, 1) + { + } + + protected Option(string prototype, string description, int maxValueCount) + { + if (prototype == null) + throw new ArgumentNullException("prototype"); + if (prototype.Length == 0) + throw new ArgumentException("Cannot be the empty string.", "prototype"); + if (maxValueCount < 0) + throw new ArgumentOutOfRangeException("maxValueCount"); + + this.prototype = prototype; + this.description = description; + this.count = maxValueCount; + this.names = (this is OptionSet.Category) + // append GetHashCode() so that "duplicate" categories have distinct + // names, e.g. adding multiple "" categories should be valid. + ? new[] { prototype + this.GetHashCode() } + : prototype.Split('|'); + + if (this is OptionSet.Category) + return; + + this.type = ParsePrototype(); + + if (this.count == 0 && type != OptionValueType.None) + throw new ArgumentException( + "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + + "OptionValueType.Optional.", + "maxValueCount"); + if (this.type == OptionValueType.None && maxValueCount > 1) + throw new ArgumentException( + string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), + "maxValueCount"); + if (Array.IndexOf(names, "<>") >= 0 && + ((names.Length == 1 && this.type != OptionValueType.None) || + (names.Length > 1 && this.MaxValueCount > 1))) + throw new ArgumentException( + "The default option handler '<>' cannot require values.", + "prototype"); + } + + public string Prototype { get { return prototype; } } + public string Description { get { return description; } } + public OptionValueType OptionValueType { get { return type; } } + public int MaxValueCount { get { return count; } } + + public string[] GetNames() + { + return (string[])names.Clone(); + } + + public string[] GetValueSeparators() + { + if (separators == null) + return new string[0]; + return (string[])separators.Clone(); + } + + protected static T Parse(string value, OptionContext c) + { + Type tt = typeof(T); + bool nullable = tt.IsValueType && tt.IsGenericType && + !tt.IsGenericTypeDefinition && + tt.GetGenericTypeDefinition() == typeof(Nullable<>); + Type targetType = nullable ? tt.GetGenericArguments()[0] : typeof(T); + TypeConverter conv = TypeDescriptor.GetConverter(targetType); + T t = default(T); + try + { + if (value != null) + t = (T)conv.ConvertFromString(value); + } + catch (Exception e) + { + throw new OptionException( + string.Format( + c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."), + value, targetType.Name, c.OptionName), + c.OptionName, e); + } + return t; + } + + internal string[] Names { get { return names; } } + internal string[] ValueSeparators { get { return separators; } } + + static readonly char[] NameTerminator = new char[] { '=', ':' }; + + private OptionValueType ParsePrototype() + { + char type = '\0'; + List seps = new List(); + for (int i = 0; i < names.Length; ++i) + { + string name = names[i]; + if (name.Length == 0) + throw new ArgumentException("Empty option names are not supported.", "prototype"); + + int end = name.IndexOfAny(NameTerminator); + if (end == -1) + continue; + names[i] = name.Substring(0, end); + if (type == '\0' || type == name[end]) + type = name[end]; + else + throw new ArgumentException( + string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]), + "prototype"); + AddSeparators(name, end, seps); + } + + if (type == '\0') + return OptionValueType.None; + + if (count <= 1 && seps.Count != 0) + throw new ArgumentException( + string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count), + "prototype"); + if (count > 1) + { + if (seps.Count == 0) + this.separators = new string[] { ":", "=" }; + else if (seps.Count == 1 && seps[0].Length == 0) + this.separators = null; + else + this.separators = seps.ToArray(); + } + + return type == '=' ? OptionValueType.Required : OptionValueType.Optional; + } + + private static void AddSeparators(string name, int end, ICollection seps) + { + int start = -1; + for (int i = end + 1; i < name.Length; ++i) + { + switch (name[i]) + { + case '{': + if (start != -1) + throw new ArgumentException( + string.Format("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + start = i + 1; + break; + case '}': + if (start == -1) + throw new ArgumentException( + string.Format("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + seps.Add(name.Substring(start, i - start)); + start = -1; + break; + default: + if (start == -1) + seps.Add(name[i].ToString()); + break; + } + } + if (start != -1) + throw new ArgumentException( + string.Format("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + } + + public void Invoke(OptionContext c) + { + OnParseComplete(c); + c.OptionName = null; + c.Option = null; + c.OptionValues.Clear(); + } + + protected abstract void OnParseComplete(OptionContext c); + + public override string ToString() + { + return Prototype; + } + } + + public abstract class ArgumentSource + { + + protected ArgumentSource() + { + } + + public abstract string[] GetNames(); + public abstract string Description { get; } + public abstract bool GetArguments(string value, out IEnumerable replacement); + + public static IEnumerable GetArgumentsFromFile(string file) + { + return GetArguments(File.OpenText(file), true); + } + + public static IEnumerable GetArguments(TextReader reader) + { + return GetArguments(reader, false); + } + + // Cribbed from mcs/driver.cs:LoadArgs(string) + static IEnumerable GetArguments(TextReader reader, bool close) + { + try + { + StringBuilder arg = new StringBuilder(); + + string line; + while ((line = reader.ReadLine()) != null) + { + int t = line.Length; + + for (int i = 0; i < t; i++) + { + char c = line[i]; + + if (c == '"' || c == '\'') + { + char end = c; + + for (i++; i < t; i++) + { + c = line[i]; + + if (c == end) + break; + arg.Append(c); + } + } + else if (c == ' ') + { + if (arg.Length > 0) + { + yield return arg.ToString(); + arg.Length = 0; + } + } + else + arg.Append(c); + } + if (arg.Length > 0) + { + yield return arg.ToString(); + arg.Length = 0; + } + } + } + finally + { + if (close) + reader.Close(); + } + } + } + + public class ResponseFileSource : ArgumentSource + { + + public override string[] GetNames() + { + return new string[] { "@file" }; + } + + public override string Description + { + get { return "Read response file for more options."; } + } + + public override bool GetArguments(string value, out IEnumerable replacement) + { + if (string.IsNullOrEmpty(value) || !value.StartsWith("@")) + { + replacement = null; + return false; + } + replacement = ArgumentSource.GetArgumentsFromFile(value.Substring(1)); + return true; + } + } + + [Serializable] + public class OptionException : Exception + { + private string option; + + public OptionException() + { + } + + public OptionException(string message, string optionName) + : base(message) + { + this.option = optionName; + } + + public OptionException(string message, string optionName, Exception innerException) + : base(message, innerException) + { + this.option = optionName; + } + + protected OptionException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + this.option = info.GetString("OptionName"); + } + + public string OptionName + { + get { return this.option; } + } + + [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("OptionName", option); + } + } + + public delegate void OptionAction(TKey key, TValue value); + + public class OptionSet : KeyedCollection + { + public OptionSet() + : this(delegate (string f) { return f; }) + { + } + + public OptionSet(Converter localizer) + { + this.localizer = localizer; + this.roSources = new ReadOnlyCollection(sources); + } + + Converter localizer; + + public Converter MessageLocalizer + { + get { return localizer; } + } + + List sources = new List(); + ReadOnlyCollection roSources; + + public ReadOnlyCollection ArgumentSources + { + get { return roSources; } + } + + + protected override string GetKeyForItem(Option item) + { + if (item == null) + throw new ArgumentNullException("option"); + if (item.Names != null && item.Names.Length > 0) + return item.Names[0]; + // This should never happen, as it's invalid for Option to be + // constructed w/o any names. + throw new InvalidOperationException("Option has no names!"); + } + + [Obsolete("Use KeyedCollection.this[string]")] + protected Option GetOptionForName(string option) + { + if (option == null) + throw new ArgumentNullException("option"); + try + { + return base[option]; + } + catch (KeyNotFoundException) + { + return null; + } + } + + protected override void InsertItem(int index, Option item) + { + base.InsertItem(index, item); + AddImpl(item); + } + + protected override void RemoveItem(int index) + { + Option p = Items[index]; + base.RemoveItem(index); + // KeyedCollection.RemoveItem() handles the 0th item + for (int i = 1; i < p.Names.Length; ++i) + { + Dictionary.Remove(p.Names[i]); + } + } + + protected override void SetItem(int index, Option item) + { + base.SetItem(index, item); + AddImpl(item); + } + + private void AddImpl(Option option) + { + if (option == null) + throw new ArgumentNullException("option"); + List added = new List(option.Names.Length); + try + { + // KeyedCollection.InsertItem/SetItem handle the 0th name. + for (int i = 1; i < option.Names.Length; ++i) + { + Dictionary.Add(option.Names[i], option); + added.Add(option.Names[i]); + } + } + catch (Exception) + { + foreach (string name in added) + Dictionary.Remove(name); + throw; + } + } + + public OptionSet Add(string header) + { + if (header == null) + throw new ArgumentNullException("header"); + Add(new Category(header)); + return this; + } + + internal sealed class Category : Option + { + + // Prototype starts with '=' because this is an invalid prototype + // (see Option.ParsePrototype(), and thus it'll prevent Category + // instances from being accidentally used as normal options. + public Category(string description) + : base("=:Category:= " + description, description) + { + } + + protected override void OnParseComplete(OptionContext c) + { + throw new NotSupportedException("Category.OnParseComplete should not be invoked."); + } + } + + + public new OptionSet Add(Option option) + { + base.Add(option); + return this; + } + + sealed class ActionOption : Option + { + Action action; + + public ActionOption(string prototype, string description, int count, Action action) + : base(prototype, description, count) + { + if (action == null) + throw new ArgumentNullException("action"); + this.action = action; + } + + protected override void OnParseComplete(OptionContext c) + { + action(c.OptionValues); + } + } + + public OptionSet Add(string prototype, Action action) + { + return Add(prototype, null, action); + } + + public OptionSet Add(string prototype, string description, Action action) + { + if (action == null) + throw new ArgumentNullException("action"); + Option p = new ActionOption(prototype, description, 1, + delegate (OptionValueCollection v) { action(v[0]); }); + base.Add(p); + return this; + } + + public OptionSet Add(string prototype, OptionAction action) + { + return Add(prototype, null, action); + } + + public OptionSet Add(string prototype, string description, OptionAction action) + { + if (action == null) + throw new ArgumentNullException("action"); + Option p = new ActionOption(prototype, description, 2, + delegate (OptionValueCollection v) { action(v[0], v[1]); }); + base.Add(p); + return this; + } + + sealed class ActionOption : Option + { + Action action; + + public ActionOption(string prototype, string description, Action action) + : base(prototype, description, 1) + { + if (action == null) + throw new ArgumentNullException("action"); + this.action = action; + } + + protected override void OnParseComplete(OptionContext c) + { + action(Parse(c.OptionValues[0], c)); + } + } + + sealed class ActionOption : Option + { + OptionAction action; + + public ActionOption(string prototype, string description, OptionAction action) + : base(prototype, description, 2) + { + if (action == null) + throw new ArgumentNullException("action"); + this.action = action; + } + + protected override void OnParseComplete(OptionContext c) + { + action( + Parse(c.OptionValues[0], c), + Parse(c.OptionValues[1], c)); + } + } + + public OptionSet Add(string prototype, Action action) + { + return Add(prototype, null, action); + } + + public OptionSet Add(string prototype, string description, Action action) + { + return Add(new ActionOption(prototype, description, action)); + } + + public OptionSet Add(string prototype, OptionAction action) + { + return Add(prototype, null, action); + } + + public OptionSet Add(string prototype, string description, OptionAction action) + { + return Add(new ActionOption(prototype, description, action)); + } + + public OptionSet Add(ArgumentSource source) + { + if (source == null) + throw new ArgumentNullException("source"); + sources.Add(source); + return this; + } + + protected virtual OptionContext CreateOptionContext() + { + return new OptionContext(this); + } + + public List Parse(IEnumerable arguments) + { + if (arguments == null) + throw new ArgumentNullException("arguments"); + OptionContext c = CreateOptionContext(); + c.OptionIndex = -1; + bool process = true; + List unprocessed = new List(); + Option def = Contains("<>") ? this["<>"] : null; + ArgumentEnumerator ae = new ArgumentEnumerator(arguments); + foreach (string argument in ae) + { + ++c.OptionIndex; + if (argument == "--") + { + process = false; + continue; + } + if (!process) + { + Unprocessed(unprocessed, def, c, argument); + continue; + } + if (AddSource(ae, argument)) + continue; + if (!Parse(argument, c)) + Unprocessed(unprocessed, def, c, argument); + } + if (c.Option != null) + c.Option.Invoke(c); + return unprocessed; + } + + class ArgumentEnumerator : IEnumerable + { + List> sources = new List>(); + + public ArgumentEnumerator(IEnumerable arguments) + { + sources.Add(arguments.GetEnumerator()); + } + + public void Add(IEnumerable arguments) + { + sources.Add(arguments.GetEnumerator()); + } + + public IEnumerator GetEnumerator() + { + do + { + IEnumerator c = sources[sources.Count - 1]; + if (c.MoveNext()) + yield return c.Current; + else + { + c.Dispose(); + sources.RemoveAt(sources.Count - 1); + } + } while (sources.Count > 0); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + bool AddSource(ArgumentEnumerator ae, string argument) + { + foreach (ArgumentSource source in sources) + { + IEnumerable replacement; + if (!source.GetArguments(argument, out replacement)) + continue; + ae.Add(replacement); + return true; + } + return false; + } + + private static bool Unprocessed(ICollection extra, Option def, OptionContext c, string argument) + { + if (def == null) + { + extra.Add(argument); + return false; + } + c.OptionValues.Add(argument); + c.Option = def; + c.Option.Invoke(c); + return false; + } + + private readonly Regex ValueOption = new Regex( + @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); + + protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) + { + if (argument == null) + throw new ArgumentNullException("argument"); + + flag = name = sep = value = null; + Match m = ValueOption.Match(argument); + if (!m.Success) + { + return false; + } + flag = m.Groups["flag"].Value; + name = m.Groups["name"].Value; + if (m.Groups["sep"].Success && m.Groups["value"].Success) + { + sep = m.Groups["sep"].Value; + value = m.Groups["value"].Value; + } + return true; + } + + protected virtual bool Parse(string argument, OptionContext c) + { + if (c.Option != null) + { + ParseValue(argument, c); + return true; + } + + string f, n, s, v; + if (!GetOptionParts(argument, out f, out n, out s, out v)) + return false; + + Option p; + if (Contains(n)) + { + p = this[n]; + c.OptionName = f + n; + c.Option = p; + switch (p.OptionValueType) + { + case OptionValueType.None: + c.OptionValues.Add(n); + c.Option.Invoke(c); + break; + case OptionValueType.Optional: + case OptionValueType.Required: + ParseValue(v, c); + break; + } + return true; + } + // no match; is it a bool option? + if (ParseBool(argument, n, c)) + return true; + // is it a bundled option? + if (ParseBundledValue(f, string.Concat(n + s + v), c)) + return true; + + return false; + } + + private void ParseValue(string option, OptionContext c) + { + if (option != null) + foreach (string o in c.Option.ValueSeparators != null + ? option.Split(c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None) + : new string[] { option }) + { + c.OptionValues.Add(o); + } + if (c.OptionValues.Count == c.Option.MaxValueCount || + c.Option.OptionValueType == OptionValueType.Optional) + c.Option.Invoke(c); + else if (c.OptionValues.Count > c.Option.MaxValueCount) + { + throw new OptionException(localizer(string.Format( + "Error: Found {0} option values when expecting {1}.", + c.OptionValues.Count, c.Option.MaxValueCount)), + c.OptionName); + } + } + + private bool ParseBool(string option, string n, OptionContext c) + { + Option p; + string rn; + if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') && + Contains((rn = n.Substring(0, n.Length - 1)))) + { + p = this[rn]; + string v = n[n.Length - 1] == '+' ? option : null; + c.OptionName = option; + c.Option = p; + c.OptionValues.Add(v); + p.Invoke(c); + return true; + } + return false; + } + + private bool ParseBundledValue(string f, string n, OptionContext c) + { + if (f != "-") + return false; + for (int i = 0; i < n.Length; ++i) + { + Option p; + string opt = f + n[i].ToString(); + string rn = n[i].ToString(); + if (!Contains(rn)) + { + if (i == 0) + return false; + throw new OptionException(string.Format(localizer( + "Cannot bundle unregistered option '{0}'."), opt), opt); + } + p = this[rn]; + switch (p.OptionValueType) + { + case OptionValueType.None: + Invoke(c, opt, n, p); + break; + case OptionValueType.Optional: + case OptionValueType.Required: + { + string v = n.Substring(i + 1); + c.Option = p; + c.OptionName = opt; + ParseValue(v.Length != 0 ? v : null, c); + return true; + } + default: + throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType); + } + } + return true; + } + + private static void Invoke(OptionContext c, string name, string value, Option option) + { + c.OptionName = name; + c.Option = option; + c.OptionValues.Add(value); + option.Invoke(c); + } + + private const int OptionWidth = 29; + private const int Description_FirstWidth = 80 - OptionWidth; + private const int Description_RemWidth = 80 - OptionWidth - 2; + + public void WriteOptionDescriptions(TextWriter o) + { + foreach (Option p in this) + { + int written = 0; + + Category c = p as Category; + if (c != null) + { + WriteDescription(o, p.Description, "", 80, 80); + continue; + } + + if (!WriteOptionPrototype(o, p, ref written)) + continue; + + if (written < OptionWidth) + o.Write(new string(' ', OptionWidth - written)); + else + { + o.WriteLine(); + o.Write(new string(' ', OptionWidth)); + } + + WriteDescription(o, p.Description, new string(' ', OptionWidth + 2), + Description_FirstWidth, Description_RemWidth); + } + + foreach (ArgumentSource s in sources) + { + string[] names = s.GetNames(); + if (names == null || names.Length == 0) + continue; + + int written = 0; + + Write(o, ref written, " "); + Write(o, ref written, names[0]); + for (int i = 1; i < names.Length; ++i) + { + Write(o, ref written, ", "); + Write(o, ref written, names[i]); + } + + if (written < OptionWidth) + o.Write(new string(' ', OptionWidth - written)); + else + { + o.WriteLine(); + o.Write(new string(' ', OptionWidth)); + } + + WriteDescription(o, s.Description, new string(' ', OptionWidth + 2), + Description_FirstWidth, Description_RemWidth); + } + } + + void WriteDescription(TextWriter o, string value, string prefix, int firstWidth, int remWidth) + { + bool indent = false; + foreach (string line in GetLines(localizer(GetDescription(value)), firstWidth, remWidth)) + { + if (indent) + o.Write(prefix); + o.WriteLine(line); + indent = true; + } + } + + bool WriteOptionPrototype(TextWriter o, Option p, ref int written) + { + string[] names = p.Names; + + int i = GetNextOptionIndex(names, 0); + if (i == names.Length) + return false; + + if (names[i].Length == 1) + { + Write(o, ref written, " -"); + Write(o, ref written, names[0]); + } + else + { + Write(o, ref written, " --"); + Write(o, ref written, names[0]); + } + + for (i = GetNextOptionIndex(names, i + 1); + i < names.Length; i = GetNextOptionIndex(names, i + 1)) + { + Write(o, ref written, ", "); + Write(o, ref written, names[i].Length == 1 ? "-" : "--"); + Write(o, ref written, names[i]); + } + + if (p.OptionValueType == OptionValueType.Optional || + p.OptionValueType == OptionValueType.Required) + { + if (p.OptionValueType == OptionValueType.Optional) + { + Write(o, ref written, localizer("[")); + } + Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description))); + string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 + ? p.ValueSeparators[0] + : " "; + for (int c = 1; c < p.MaxValueCount; ++c) + { + Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description))); + } + if (p.OptionValueType == OptionValueType.Optional) + { + Write(o, ref written, localizer("]")); + } + } + return true; + } + + static int GetNextOptionIndex(string[] names, int i) + { + while (i < names.Length && names[i] == "<>") + { + ++i; + } + return i; + } + + static void Write(TextWriter o, ref int n, string s) + { + n += s.Length; + o.Write(s); + } + + private static string GetArgumentName(int index, int maxIndex, string description) + { + if (description == null) + return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); + string[] nameStart; + if (maxIndex == 1) + nameStart = new string[] { "{0:", "{" }; + else + nameStart = new string[] { "{" + index + ":" }; + for (int i = 0; i < nameStart.Length; ++i) + { + int start, j = 0; + do + { + start = description.IndexOf(nameStart[i], j); + } while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false); + if (start == -1) + continue; + int end = description.IndexOf("}", start); + if (end == -1) + continue; + return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length); + } + return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); + } + + private static string GetDescription(string description) + { + if (description == null) + return string.Empty; + StringBuilder sb = new StringBuilder(description.Length); + int start = -1; + for (int i = 0; i < description.Length; ++i) + { + switch (description[i]) + { + case '{': + if (i == start) + { + sb.Append('{'); + start = -1; + } + else if (start < 0) + start = i + 1; + break; + case '}': + if (start < 0) + { + if ((i + 1) == description.Length || description[i + 1] != '}') + throw new InvalidOperationException("Invalid option description: " + description); + ++i; + sb.Append("}"); + } + else + { + sb.Append(description.Substring(start, i - start)); + start = -1; + } + break; + case ':': + if (start < 0) + goto default; + start = i + 1; + break; + default: + if (start < 0) + sb.Append(description[i]); + break; + } + } + return sb.ToString(); + } + + private static IEnumerable GetLines(string description, int firstWidth, int remWidth) + { + return StringCoda.WrappedLines(description, firstWidth, remWidth); + } + } } diff --git a/src/Generator/Utils/TextGenerator.cs b/src/Generator/Utils/TextGenerator.cs index 7edbf9f0..ed68d7a0 100644 --- a/src/Generator/Utils/TextGenerator.cs +++ b/src/Generator/Utils/TextGenerator.cs @@ -55,7 +55,7 @@ namespace CppSharp if (IsStartOfLine && !string.IsNullOrWhiteSpace(msg)) StringBuilder.Append(new string(' ', - (int) (CurrentIndentation * DefaultIndentation))); + (int)(CurrentIndentation * DefaultIndentation))); if (msg.Length > 0) IsStartOfLine = msg.EndsWith(Environment.NewLine); diff --git a/src/Parser/ASTConverter.cs b/src/Parser/ASTConverter.cs index 4d95df4c..5e682d49 100644 --- a/src/Parser/ASTConverter.cs +++ b/src/Parser/ASTConverter.cs @@ -41,100 +41,100 @@ namespace CppSharp switch (type.Kind) { case TypeKind.Tag: - { - var _type = TagType.__CreateInstance(type.__Instance); - return VisitTag(_type); - } + { + var _type = TagType.__CreateInstance(type.__Instance); + return VisitTag(_type); + } case TypeKind.Array: - { - var _type = ArrayType.__CreateInstance(type.__Instance); - return VisitArray(_type); - } + { + var _type = ArrayType.__CreateInstance(type.__Instance); + return VisitArray(_type); + } case TypeKind.Function: - { - var _type = FunctionType.__CreateInstance(type.__Instance); - return VisitFunction(_type); - } + { + var _type = FunctionType.__CreateInstance(type.__Instance); + return VisitFunction(_type); + } case TypeKind.Pointer: - { - var _type = PointerType.__CreateInstance(type.__Instance); - return VisitPointer(_type); - } + { + var _type = PointerType.__CreateInstance(type.__Instance); + return VisitPointer(_type); + } case TypeKind.MemberPointer: - { - var _type = MemberPointerType.__CreateInstance(type.__Instance); - return VisitMemberPointer(_type); - } + { + var _type = MemberPointerType.__CreateInstance(type.__Instance); + return VisitMemberPointer(_type); + } case TypeKind.Typedef: - { - var _type = TypedefType.__CreateInstance(type.__Instance); - return VisitTypedef(_type); - } + { + var _type = TypedefType.__CreateInstance(type.__Instance); + return VisitTypedef(_type); + } case TypeKind.Attributed: - { - var _type = AttributedType.__CreateInstance(type.__Instance); - return VisitAttributed(_type); - } + { + var _type = AttributedType.__CreateInstance(type.__Instance); + return VisitAttributed(_type); + } case TypeKind.Decayed: - { - var _type = DecayedType.__CreateInstance(type.__Instance); - return VisitDecayed(_type); - } + { + var _type = DecayedType.__CreateInstance(type.__Instance); + return VisitDecayed(_type); + } case TypeKind.TemplateSpecialization: - { - var _type = TemplateSpecializationType.__CreateInstance(type.__Instance); - return VisitTemplateSpecialization(_type); - } + { + var _type = TemplateSpecializationType.__CreateInstance(type.__Instance); + return VisitTemplateSpecialization(_type); + } case TypeKind.DependentTemplateSpecialization: - { - var _type = DependentTemplateSpecializationType.__CreateInstance(type.__Instance); - return VisitDependentTemplateSpecialization(_type); - } + { + var _type = DependentTemplateSpecializationType.__CreateInstance(type.__Instance); + return VisitDependentTemplateSpecialization(_type); + } case TypeKind.TemplateParameter: - { - var _type = TemplateParameterType.__CreateInstance(type.__Instance); - return VisitTemplateParameter(_type); - } + { + var _type = TemplateParameterType.__CreateInstance(type.__Instance); + return VisitTemplateParameter(_type); + } case TypeKind.TemplateParameterSubstitution: - { - var _type = TemplateParameterSubstitutionType.__CreateInstance(type.__Instance); - return VisitTemplateParameterSubstitution(_type); - } + { + var _type = TemplateParameterSubstitutionType.__CreateInstance(type.__Instance); + return VisitTemplateParameterSubstitution(_type); + } case TypeKind.InjectedClassName: - { - var _type = InjectedClassNameType.__CreateInstance(type.__Instance); - return VisitInjectedClassName(_type); - } + { + var _type = InjectedClassNameType.__CreateInstance(type.__Instance); + return VisitInjectedClassName(_type); + } case TypeKind.DependentName: - { - var _type = DependentNameType.__CreateInstance(type.__Instance); - return VisitDependentName(_type); - } + { + var _type = DependentNameType.__CreateInstance(type.__Instance); + return VisitDependentName(_type); + } case TypeKind.Builtin: - { - var _type = BuiltinType.__CreateInstance(type.__Instance); - return VisitBuiltin(_type); - } + { + var _type = BuiltinType.__CreateInstance(type.__Instance); + return VisitBuiltin(_type); + } case TypeKind.PackExpansion: - { - var _type = PackExpansionType.__CreateInstance(type.__Instance); - return VisitPackExpansion(_type); - } + { + var _type = PackExpansionType.__CreateInstance(type.__Instance); + return VisitPackExpansion(_type); + } case TypeKind.UnaryTransform: - { - var _type = UnaryTransformType.__CreateInstance(type.__Instance); - return VisitUnaryTransform(_type); - } + { + var _type = UnaryTransformType.__CreateInstance(type.__Instance); + return VisitUnaryTransform(_type); + } case TypeKind.UnresolvedUsing: - { - var _type = UnresolvedUsingType.__CreateInstance(type.__Instance); - return VisitUnresolvedUsing(_type); - } + { + var _type = UnresolvedUsingType.__CreateInstance(type.__Instance); + return VisitUnresolvedUsing(_type); + } case TypeKind.Vector: - { - var _type = VectorType.__CreateInstance(type.__Instance); - return VisitVector(_type); - } + { + var _type = VectorType.__CreateInstance(type.__Instance); + return VisitVector(_type); + } } throw new ArgumentOutOfRangeException(); @@ -176,7 +176,7 @@ namespace CppSharp public abstract TRet VisitTypeTemplateParameter(TypeTemplateParameter decl); public abstract TRet VisitNonTypeTemplateParameter(NonTypeTemplateParameter decl); public abstract TRet VisitUnresolvedUsingTypename(UnresolvedUsingTypename decl); - + public virtual TRet Visit(Parser.AST.Declaration decl) { switch (decl.Kind) @@ -421,14 +421,14 @@ namespace CppSharp for (uint i = 0; i < Context.TranslationUnitsCount; ++i) { var unit = Context.GetTranslationUnits(i); - var _unit = (AST.TranslationUnit) declConverter.Visit(unit); + var _unit = (AST.TranslationUnit)declConverter.Visit(unit); _ctx.TranslationUnits.Add(_unit); } for (uint i = 0; i < Context.TranslationUnitsCount; i++) { var unit = Context.GetTranslationUnits(i); - var _unit = (AST.TranslationUnit) declConverter.Visit(unit); + var _unit = (AST.TranslationUnit)declConverter.Visit(unit); declConverter.VisitDeclContext(unit, _unit); } @@ -604,7 +604,7 @@ namespace CppSharp { var _type = new AST.TypedefType(); VisitType(type, _type); - _type.Declaration = (AST.TypedefNameDecl) declConverter.Visit(type.Declaration); + _type.Declaration = (AST.TypedefNameDecl)declConverter.Visit(type.Declaration); return _type; } @@ -705,7 +705,7 @@ namespace CppSharp { var _type = new AST.TemplateParameterType(); if (type.Parameter != null) - _type.Parameter = (AST.TypeTemplateParameter) declConverter.Visit(type.Parameter); + _type.Parameter = (AST.TypeTemplateParameter)declConverter.Visit(type.Parameter); _type.Depth = type.Depth; _type.Index = type.Index; _type.IsParameterPack = type.IsParameterPack; @@ -717,7 +717,7 @@ namespace CppSharp { var _type = new AST.TemplateParameterSubstitutionType(); _type.Replacement = VisitQualified(type.Replacement); - _type.ReplacedParameter = (AST.TemplateParameterType) Visit(type.ReplacedParameter); + _type.ReplacedParameter = (AST.TemplateParameterType)Visit(type.ReplacedParameter); VisitType(type, _type); return _type; } @@ -976,7 +976,7 @@ namespace CppSharp bool CheckForDuplicates(Declaration decl) { - return decl.OriginalPtr.ToPointer() != (void*) (0x1); + return decl.OriginalPtr.ToPointer() != (void*)(0x1); } void VisitDeclaration(Declaration decl, AST.Declaration _decl) @@ -1105,14 +1105,14 @@ namespace CppSharp for (uint i = 0; i < ctx.NamespacesCount; ++i) { var decl = ctx.GetNamespaces(i); - var _decl = (AST.Namespace) Visit(decl); + var _decl = (AST.Namespace)Visit(decl); VisitDeclContext(decl, _decl); } for (uint i = 0; i < ctx.ClassesCount; ++i) { var decl = ctx.GetClasses(i); - var _decl = (AST.Class) Visit(decl); + var _decl = (AST.Class)Visit(decl); if (!_decl.IsIncomplete || _decl.IsOpaque) VisitClass(decl, _decl); } @@ -1161,7 +1161,7 @@ namespace CppSharp VisitDeclaration(decl, _typeAlias); _typeAlias.QualifiedType = typeConverter.VisitQualified(decl.QualifiedType); if (decl.DescribedAliasTemplate != null) - _typeAlias.DescribedAliasTemplate = (AST.TypeAliasTemplate) Visit(decl.DescribedAliasTemplate); + _typeAlias.DescribedAliasTemplate = (AST.TypeAliasTemplate)Visit(decl.DescribedAliasTemplate); return _typeAlias; } @@ -1267,7 +1267,7 @@ namespace CppSharp _function.Body = function.Body; _function.CallingConvention = VisitCallingConvention(function.CallingConvention); if (function.InstantiatedFrom != null) - _function.InstantiatedFrom = (AST.Function) Visit(function.InstantiatedFrom); + _function.InstantiatedFrom = (AST.Function)Visit(function.InstantiatedFrom); for (uint i = 0; i < function.ParametersCount; ++i) { @@ -1331,7 +1331,7 @@ namespace CppSharp for (uint i = 0; i < decl.OverriddenMethodsCount; i++) { var @override = decl.GetOverriddenMethods(i); - _method.OverriddenMethods.Add((AST.Method) Visit(@override)); + _method.OverriddenMethods.Add((AST.Method)Visit(@override)); } return _method; @@ -1517,7 +1517,7 @@ namespace CppSharp private AST.Enumeration.EnumModifiers VisitEnumModifiers( Enumeration.EnumModifiers modifiers) { - return (AST.Enumeration.EnumModifiers) modifiers; + return (AST.Enumeration.EnumModifiers)modifiers; } public override AST.Declaration VisitEnumerationItem(Enumeration.Item decl) @@ -1650,12 +1650,12 @@ namespace CppSharp { switch (argAbi) { - case RecordArgABI.Default: - return AST.RecordArgABI.Default; - case RecordArgABI.DirectInMemory: - return AST.RecordArgABI.DirectInMemory; - case RecordArgABI.Indirect: - return AST.RecordArgABI.Indirect; + case RecordArgABI.Default: + return AST.RecordArgABI.Default; + case RecordArgABI.DirectInMemory: + return AST.RecordArgABI.DirectInMemory; + case RecordArgABI.Indirect: + return AST.RecordArgABI.Indirect; } throw new NotImplementedException(); @@ -1698,7 +1698,7 @@ namespace CppSharp var @base = layout.GetBases(i); var _base = new AST.LayoutBase(); _base.Offset = @base.Offset; - _base.Class = (AST.Class) Visit(@base.Class); + _base.Class = (AST.Class)Visit(@base.Class); _layout.Bases.Add(_base); } @@ -1821,7 +1821,7 @@ namespace CppSharp for (uint i = 0; i < decl.SpecializationsCount; ++i) { var spec = decl.GetSpecializations(i); - var _spec = (AST.ClassTemplateSpecialization) Visit(spec); + var _spec = (AST.ClassTemplateSpecialization)Visit(spec); _decl.Specializations.Add(_spec); } return _decl; @@ -1841,7 +1841,7 @@ namespace CppSharp VisitDeclaration(decl, _decl); VisitClass(decl, _decl); _decl.SpecializationKind = VisitSpecializationKind(decl.SpecializationKind); - _decl.TemplatedDecl = (AST.ClassTemplate) Visit(decl.TemplatedDecl); + _decl.TemplatedDecl = (AST.ClassTemplate)Visit(decl.TemplatedDecl); for (uint i = 0; i < decl.ArgumentsCount; ++i) { var arg = decl.GetArguments(i); @@ -1935,8 +1935,8 @@ namespace CppSharp var _spec = new AST.FunctionTemplateSpecialization(); FunctionTemplateSpecializations.Add(spec.__Instance, _spec); - _spec.Template = (AST.FunctionTemplate) Visit(spec.Template); - _spec.SpecializedFunction = (AST.Function) Visit(spec.SpecializedFunction); + _spec.Template = (AST.FunctionTemplate)Visit(spec.Template); + _spec.SpecializedFunction = (AST.Function)Visit(spec.SpecializedFunction); _spec.SpecializationKind = VisitSpecializationKind(spec.SpecializationKind); for (uint i = 0; i < spec.ArgumentsCount; ++i) { @@ -1954,7 +1954,7 @@ namespace CppSharp for (uint i = 0; i < decl.SpecializationsCount; ++i) { var spec = decl.GetSpecializations(i); - var _spec = (AST.VarTemplateSpecialization) Visit(spec); + var _spec = (AST.VarTemplateSpecialization)Visit(spec); _decl.Specializations.Add(_spec); } return _decl; @@ -1973,7 +1973,7 @@ namespace CppSharp { VisitVariable(decl, _decl); _decl.SpecializationKind = VisitSpecializationKind(decl.SpecializationKind); - _decl.TemplatedDecl = (AST.VarTemplate) Visit(decl.TemplatedDecl); + _decl.TemplatedDecl = (AST.VarTemplate)Visit(decl.TemplatedDecl); for (uint i = 0; i < decl.ArgumentsCount; ++i) { var arg = decl.GetArguments(i); @@ -2108,7 +2108,7 @@ namespace CppSharp { var fullComment = new AST.FullComment(); for (uint i = 0; i < comment.BlocksCount; i++) - fullComment.Blocks.Add((AST.BlockContentComment) Visit(comment.GetBlocks(i))); + fullComment.Blocks.Add((AST.BlockContentComment)Visit(comment.GetBlocks(i))); return fullComment; } @@ -2152,7 +2152,7 @@ namespace CppSharp { var verbatimBlockComment = new AST.VerbatimBlockComment(); for (uint i = 0; i < comment.LinesCount; i++) - verbatimBlockComment.Lines.Add((AST.VerbatimBlockLineComment) Visit(comment.GetLines(i))); + verbatimBlockComment.Lines.Add((AST.VerbatimBlockLineComment)Visit(comment.GetLines(i))); VisitBlockCommandComment(verbatimBlockComment, comment); return verbatimBlockComment; } @@ -2168,7 +2168,7 @@ namespace CppSharp { var paragraphComment = new AST.ParagraphComment(); for (uint i = 0; i < comment.ContentCount; i++) - paragraphComment.Content.Add((AST.InlineContentComment) Visit(comment.GetContent(i))); + paragraphComment.Content.Add((AST.InlineContentComment)Visit(comment.GetContent(i))); paragraphComment.IsWhitespace = comment.IsWhitespace; return paragraphComment; } @@ -2249,7 +2249,7 @@ namespace CppSharp { blockCommandComment.CommandId = comment.CommandId; if (comment.ParagraphComment != null) - blockCommandComment.ParagraphComment = (AST.ParagraphComment) Visit(comment.ParagraphComment); + blockCommandComment.ParagraphComment = (AST.ParagraphComment)Visit(comment.ParagraphComment); for (uint i = 0; i < comment.ArgumentsCount; i++) { var argument = new AST.BlockCommandComment.Argument { Text = comment.GetArguments(i).Text }; diff --git a/src/Parser/Parser.cs b/src/Parser/Parser.cs index 5c1c891e..fa1a889b 100644 --- a/src/Parser/Parser.cs +++ b/src/Parser/Parser.cs @@ -13,19 +13,19 @@ namespace CppSharp /// /// Fired when source files are parsed. /// - public static Action, ParserResult> SourcesParsed = delegate {}; + public static Action, ParserResult> SourcesParsed = delegate { }; /// /// Fired when library files are parsed. /// - public static Action LibraryParsed = delegate {}; + public static Action LibraryParsed = delegate { }; /// /// Parses a C++ source file as a translation unit. /// public static ParserResult ParseSourceFile(string file, ParserOptions options) { - return ParseSourceFiles(new [] { file }, options); + return ParseSourceFiles(new[] { file }, options); } /// @@ -70,7 +70,7 @@ namespace CppSharp var newLibrary = new AST.NativeLibrary { FileName = library.FileName, - ArchType = (ArchType) library.ArchType + ArchType = (ArchType)library.ArchType }; for (uint i = 0; i < library.SymbolsCount; ++i) diff --git a/src/Parser/ParserOptions.cs b/src/Parser/ParserOptions.cs index 7e064e3a..41dffa66 100644 --- a/src/Parser/ParserOptions.cs +++ b/src/Parser/ParserOptions.cs @@ -11,391 +11,391 @@ using LanguageVersion = CppSharp.Parser.LanguageVersion; namespace CppSharp.Parser { - public enum LanguageVersion - { - /// - /// C programming language (year 1999). - /// - C99, - /// - /// C programming language (year 1999, GNU variant). - /// - C99_GNU, - /// - /// C++ programming language (year 1998). - /// - CPP98, - /// - /// C++ programming language (year 1998, GNU variant). - /// - CPP98_GNU, - /// - /// C++ programming language (year 2011). - /// - CPP11, - /// - /// C++ programming language (year 2011, GNU variant). - /// - CPP11_GNU, - /// - /// C++ programming language (year 2014). - /// - CPP14, - /// - /// C++ programming language (year 2014, GNU variant). - /// - CPP14_GNU, - /// - /// C++ programming language (year 2017). - /// - CPP17, - /// - /// C++ programming language (year 2017, GNU variant). - /// - CPP17_GNU, - /// - /// C++ programming language (year 2020). - /// - CPP20, - /// - /// C++ programming language (year 2020, GNU variant). - /// - CPP20_GNU, - /// - /// C++ programming language (year 2023). - /// - CPP23, - /// - /// C++ programming language (year 2023, GNU variant). - /// - CPP23_GNU, - } - - public class ParserOptions : CppParserOptions - { - public ParserOptions() - { - MicrosoftMode = !Platform.IsUnixPlatform; - AddCompilationOptions("-flto"); - AddCompilationOptions("-O3"); - AddCompilationOptions("-fno-use-cxa-atexit"); - } - - public bool IsItaniumLikeAbi => !IsMicrosoftAbi; - public bool IsMicrosoftAbi => TargetTriple.Contains("win32") || - TargetTriple.Contains("windows") || TargetTriple.Contains("msvc"); - - public bool EnableRTTI { get; set; } - public LanguageVersion? LanguageVersion { get; set; } - - public void BuildForSourceFile( - IEnumerable modules, string file = null) - { - // This eventually gets passed to Clang's MSCompatibilityVersion, which - // is in turn used to derive the value of the built-in define _MSC_VER. - // It used to receive a 4-digit based identifier but now expects a full - // version MSVC digit, so check if we still have the old version and - // convert to the right format. - - if (ToolSetToUse.ToString(CultureInfo.InvariantCulture).Length == 4) - ToolSetToUse *= 100000; - - foreach (var module in modules.Where( - m => file == null || m.Headers.Contains(file))) - { - foreach (var include in module.IncludeDirs) - AddIncludeDirs(include); - - foreach (var define in module.Defines) - AddDefines(define); - - foreach (var undefine in module.Undefines) - AddUndefines(undefine); - } - } - - public void SetupMSVC() - { - var vsVersion = VisualStudioVersion.Latest; - - // Silence "warning CS0162: Unreachable code detected" + public enum LanguageVersion + { + /// + /// C programming language (year 1999). + /// + C99, + /// + /// C programming language (year 1999, GNU variant). + /// + C99_GNU, + /// + /// C++ programming language (year 1998). + /// + CPP98, + /// + /// C++ programming language (year 1998, GNU variant). + /// + CPP98_GNU, + /// + /// C++ programming language (year 2011). + /// + CPP11, + /// + /// C++ programming language (year 2011, GNU variant). + /// + CPP11_GNU, + /// + /// C++ programming language (year 2014). + /// + CPP14, + /// + /// C++ programming language (year 2014, GNU variant). + /// + CPP14_GNU, + /// + /// C++ programming language (year 2017). + /// + CPP17, + /// + /// C++ programming language (year 2017, GNU variant). + /// + CPP17_GNU, + /// + /// C++ programming language (year 2020). + /// + CPP20, + /// + /// C++ programming language (year 2020, GNU variant). + /// + CPP20_GNU, + /// + /// C++ programming language (year 2023). + /// + CPP23, + /// + /// C++ programming language (year 2023, GNU variant). + /// + CPP23_GNU, + } + + public class ParserOptions : CppParserOptions + { + public ParserOptions() + { + MicrosoftMode = !Platform.IsUnixPlatform; + AddCompilationOptions("-flto"); + AddCompilationOptions("-O3"); + AddCompilationOptions("-fno-use-cxa-atexit"); + } + + public bool IsItaniumLikeAbi => !IsMicrosoftAbi; + public bool IsMicrosoftAbi => TargetTriple.Contains("win32") || + TargetTriple.Contains("windows") || TargetTriple.Contains("msvc"); + + public bool EnableRTTI { get; set; } + public LanguageVersion? LanguageVersion { get; set; } + + public void BuildForSourceFile( + IEnumerable modules, string file = null) + { + // This eventually gets passed to Clang's MSCompatibilityVersion, which + // is in turn used to derive the value of the built-in define _MSC_VER. + // It used to receive a 4-digit based identifier but now expects a full + // version MSVC digit, so check if we still have the old version and + // convert to the right format. + + if (ToolSetToUse.ToString(CultureInfo.InvariantCulture).Length == 4) + ToolSetToUse *= 100000; + + foreach (var module in modules.Where( + m => file == null || m.Headers.Contains(file))) + { + foreach (var include in module.IncludeDirs) + AddIncludeDirs(include); + + foreach (var define in module.Defines) + AddDefines(define); + + foreach (var undefine in module.Undefines) + AddUndefines(undefine); + } + } + + public void SetupMSVC() + { + var vsVersion = VisualStudioVersion.Latest; + + // Silence "warning CS0162: Unreachable code detected" #pragma warning disable 162 - switch (BuildConfig.Choice) - { - case "vs2012": - vsVersion = VisualStudioVersion.VS2012; - break; - case "vs2013": - vsVersion = VisualStudioVersion.VS2013; - break; - case "vs2015": - vsVersion = VisualStudioVersion.VS2015; - break; - case "vs2017": - vsVersion = VisualStudioVersion.VS2017; - break; - case "vs2019": - vsVersion = VisualStudioVersion.VS2019; - break; + switch (BuildConfig.Choice) + { + case "vs2012": + vsVersion = VisualStudioVersion.VS2012; + break; + case "vs2013": + vsVersion = VisualStudioVersion.VS2013; + break; + case "vs2015": + vsVersion = VisualStudioVersion.VS2015; + break; + case "vs2017": + vsVersion = VisualStudioVersion.VS2017; + break; + case "vs2019": + vsVersion = VisualStudioVersion.VS2019; + break; #pragma warning restore 162 - } + } - SetupMSVC(vsVersion); - } + SetupMSVC(vsVersion); + } - /// - /// Sets up the parser options to work with the given Visual Studio toolchain. - /// - /// The version of Visual Studio to look for. - public void SetupMSVC(VisualStudioVersion vsVersion) - { - MicrosoftMode = true; - - var clVersion = MSVCToolchain.GetCLVersion(vsVersion); - ToolSetToUse = clVersion.Major * 10000000 + clVersion.Minor * 100000; - - // do not remove the CppSharp prefix becase the Mono C# compiler breaks - if (!LanguageVersion.HasValue) - LanguageVersion = CppSharp.Parser.LanguageVersion.CPP14_GNU; - - AddArguments("-fms-extensions"); - AddArguments("-fms-compatibility"); - AddArguments("-fdelayed-template-parsing"); - } - - /// - /// Set to true to opt for Xcode Clang builtin headers - /// - public bool UseXcodeBuiltins; - - public void SetupXcode() - { - var cppIncPath = XcodeToolchain.GetXcodeCppIncludesFolder(); - AddSystemIncludeDirs(cppIncPath); - - var builtinsPath = XcodeToolchain.GetXcodeBuiltinIncludesFolder(); - AddSystemIncludeDirs(UseXcodeBuiltins ? builtinsPath : BuiltinsDir); - - var includePath = XcodeToolchain.GetXcodeIncludesFolder(); - AddSystemIncludeDirs(includePath); - - NoBuiltinIncludes = true; - NoStandardIncludes = true; - - AddArguments("-fgnuc-version=4.2.1"); - AddArguments("-stdlib=libc++"); - } - - private void GetUnixCompilerInfo(string headersPath, out string compiler, - out string longVersion, out string shortVersion) - { - if (!Platform.IsLinux) - { - compiler = "gcc"; - - // Search for the available GCC versions on the provided headers. - var versions = Directory.EnumerateDirectories(Path.Combine(headersPath, - "usr", "include", "c++")); - - if (versions.Count() == 0) - throw new Exception("No valid GCC version found on system include paths"); - - string gccVersionPath = versions.First(); - longVersion = shortVersion = gccVersionPath.Substring( - gccVersionPath.LastIndexOf(Path.DirectorySeparatorChar) + 1); - - return; - } - - var info = new ProcessStartInfo(Environment.GetEnvironmentVariable("CXX") ?? "gcc", "-v"); - info.RedirectStandardError = true; - info.CreateNoWindow = true; - info.UseShellExecute = false; - - var process = Process.Start(info); - if (process == null) - throw new SystemException("GCC compiler was not found."); - - process.WaitForExit(); - - var output = process.StandardError.ReadToEnd(); - var match = Regex.Match(output, "(gcc|clang) version (([0-9]+\\.[0-9]+)\\.[0-9]+)"); - if (!match.Success) - throw new SystemException("GCC compiler was not found."); - - compiler = match.Groups[1].ToString(); - longVersion = match.Groups[2].ToString(); - shortVersion = match.Groups[3].ToString(); - } - - public void SetupLinux(string headersPath = "") - { - MicrosoftMode = false; - NoBuiltinIncludes = true; - NoStandardIncludes = true; - - string compiler, longVersion, shortVersion; - GetUnixCompilerInfo(headersPath, out compiler, out longVersion, out shortVersion); - - AddSystemIncludeDirs(BuiltinsDir); - AddArguments($"-fgnuc-version={longVersion}"); - - string majorVersion = shortVersion.Split('.')[0]; - string[] versions = { longVersion, shortVersion, majorVersion }; - string[] triples = { "x86_64-linux-gnu", "x86_64-pc-linux-gnu" }; - if (compiler == "gcc") - { - foreach (var version in versions) - { - AddSystemIncludeDirs($"{headersPath}/usr/include/c++/{version}"); - AddSystemIncludeDirs($"{headersPath}/usr/include/c++/{version}/backward"); - - foreach (var triple in triples) - { - AddSystemIncludeDirs($"{headersPath}/usr/include/{triple}/c++/{version}"); - AddSystemIncludeDirs($"{headersPath}/usr/include/c++/{version}/{triple}"); - } - } - } - - foreach (var triple in triples) - { - foreach (var version in versions) - { - AddSystemIncludeDirs($"{headersPath}/usr/lib/{compiler}/{triple}/{version}/include"); - AddSystemIncludeDirs($"{headersPath}/usr/lib/{compiler}/{triple}/{version}/include/c++"); - AddSystemIncludeDirs($"{headersPath}/usr/lib/{compiler}/{triple}/{version}/include/c++/{triple}"); - } - - AddSystemIncludeDirs($"{headersPath}/usr/include/{triple}"); - } - - AddSystemIncludeDirs($"{headersPath}/usr/include"); - AddSystemIncludeDirs($"{headersPath}/usr/include/linux"); - } - - public void Setup() - { - SetupArguments(); - - if (!NoBuiltinIncludes) - SetupIncludes(); - } - - private void SetupArguments() - { - // do not remove the CppSharp prefix becase the Mono C# compiler breaks - if (!LanguageVersion.HasValue) - LanguageVersion = CppSharp.Parser.LanguageVersion.CPP14_GNU; - - // As of Clang revision 5e866e411caa we are required to pass "-fgnuc-version=" - // to get the __GNUC__ symbol defined. macOS and Linux system headers require - // this define, so we need explicitly pass it to Clang. - - // Note that this setup is more accurately done in the platform-specific - // setup methods, below is generic fallback in case that logic was disabled. - if (NoBuiltinIncludes) - { - switch (Platform.Host) - { - case TargetPlatform.MacOS: - case TargetPlatform.Linux: - AddArguments("-fgnuc-version=4.2.1"); - break; - } - } - - switch (LanguageVersion) - { - case CppSharp.Parser.LanguageVersion.C99: - case CppSharp.Parser.LanguageVersion.C99_GNU: - AddArguments("-xc"); - break; - default: - AddArguments("-xc++"); - break; - } - - switch (LanguageVersion) - { - case CppSharp.Parser.LanguageVersion.C99: - AddArguments("-std=c99"); - break; - case CppSharp.Parser.LanguageVersion.C99_GNU: - AddArguments("-std=gnu99"); - break; - case CppSharp.Parser.LanguageVersion.CPP98: - AddArguments("-std=c++98"); - break; - case CppSharp.Parser.LanguageVersion.CPP98_GNU: - AddArguments("-std=gnu++98"); - break; - case CppSharp.Parser.LanguageVersion.CPP11: - AddArguments("-std=c++11"); - break; - case CppSharp.Parser.LanguageVersion.CPP11_GNU: - AddArguments("-std=gnu++11"); - break; - case CppSharp.Parser.LanguageVersion.CPP14: - AddArguments("-std=c++14"); - break; - case CppSharp.Parser.LanguageVersion.CPP14_GNU: - AddArguments("-std=gnu++14"); - break; - case CppSharp.Parser.LanguageVersion.CPP17: - AddArguments("-std=c++17"); - break; - case CppSharp.Parser.LanguageVersion.CPP17_GNU: - AddArguments("-std=gnu++17"); - break; - case CppSharp.Parser.LanguageVersion.CPP20: - AddArguments("-std=c++20"); - break; - case CppSharp.Parser.LanguageVersion.CPP20_GNU: - AddArguments("-std=gnu++20"); - break; - case CppSharp.Parser.LanguageVersion.CPP23: - AddArguments("-std=c++2b"); - break; - case CppSharp.Parser.LanguageVersion.CPP23_GNU: - AddArguments("-std=gnu++2b"); - break; - } - - if (!EnableRTTI) - AddArguments("-fno-rtti"); - } - - public string BuiltinsDir - { - get - { - var assemblyDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); - return Path.Combine(assemblyDir, "lib", "clang", ClangVersion, "include"); - } - } - - private void SetupIncludes() - { - // Check that the builtin includes folder exists. - if (!Directory.Exists(BuiltinsDir)) - throw new Exception($"Clang resource folder 'lib/clang/{ClangVersion}/include' was not found."); - - switch (Platform.Host) - { - case TargetPlatform.Windows: - SetupMSVC(); - break; - case TargetPlatform.MacOS: - SetupXcode(); - break; - case TargetPlatform.Linux: - SetupLinux(); - break; - } - } - } + /// + /// Sets up the parser options to work with the given Visual Studio toolchain. + /// + /// The version of Visual Studio to look for. + public void SetupMSVC(VisualStudioVersion vsVersion) + { + MicrosoftMode = true; + + var clVersion = MSVCToolchain.GetCLVersion(vsVersion); + ToolSetToUse = clVersion.Major * 10000000 + clVersion.Minor * 100000; + + // do not remove the CppSharp prefix becase the Mono C# compiler breaks + if (!LanguageVersion.HasValue) + LanguageVersion = CppSharp.Parser.LanguageVersion.CPP14_GNU; + + AddArguments("-fms-extensions"); + AddArguments("-fms-compatibility"); + AddArguments("-fdelayed-template-parsing"); + } + + /// + /// Set to true to opt for Xcode Clang builtin headers + /// + public bool UseXcodeBuiltins; + + public void SetupXcode() + { + var cppIncPath = XcodeToolchain.GetXcodeCppIncludesFolder(); + AddSystemIncludeDirs(cppIncPath); + + var builtinsPath = XcodeToolchain.GetXcodeBuiltinIncludesFolder(); + AddSystemIncludeDirs(UseXcodeBuiltins ? builtinsPath : BuiltinsDir); + + var includePath = XcodeToolchain.GetXcodeIncludesFolder(); + AddSystemIncludeDirs(includePath); + + NoBuiltinIncludes = true; + NoStandardIncludes = true; + + AddArguments("-fgnuc-version=4.2.1"); + AddArguments("-stdlib=libc++"); + } + + private void GetUnixCompilerInfo(string headersPath, out string compiler, + out string longVersion, out string shortVersion) + { + if (!Platform.IsLinux) + { + compiler = "gcc"; + + // Search for the available GCC versions on the provided headers. + var versions = Directory.EnumerateDirectories(Path.Combine(headersPath, + "usr", "include", "c++")); + + if (versions.Count() == 0) + throw new Exception("No valid GCC version found on system include paths"); + + string gccVersionPath = versions.First(); + longVersion = shortVersion = gccVersionPath.Substring( + gccVersionPath.LastIndexOf(Path.DirectorySeparatorChar) + 1); + + return; + } + + var info = new ProcessStartInfo(Environment.GetEnvironmentVariable("CXX") ?? "gcc", "-v"); + info.RedirectStandardError = true; + info.CreateNoWindow = true; + info.UseShellExecute = false; + + var process = Process.Start(info); + if (process == null) + throw new SystemException("GCC compiler was not found."); + + process.WaitForExit(); + + var output = process.StandardError.ReadToEnd(); + var match = Regex.Match(output, "(gcc|clang) version (([0-9]+\\.[0-9]+)\\.[0-9]+)"); + if (!match.Success) + throw new SystemException("GCC compiler was not found."); + + compiler = match.Groups[1].ToString(); + longVersion = match.Groups[2].ToString(); + shortVersion = match.Groups[3].ToString(); + } + + public void SetupLinux(string headersPath = "") + { + MicrosoftMode = false; + NoBuiltinIncludes = true; + NoStandardIncludes = true; + + string compiler, longVersion, shortVersion; + GetUnixCompilerInfo(headersPath, out compiler, out longVersion, out shortVersion); + + AddSystemIncludeDirs(BuiltinsDir); + AddArguments($"-fgnuc-version={longVersion}"); + + string majorVersion = shortVersion.Split('.')[0]; + string[] versions = { longVersion, shortVersion, majorVersion }; + string[] triples = { "x86_64-linux-gnu", "x86_64-pc-linux-gnu" }; + if (compiler == "gcc") + { + foreach (var version in versions) + { + AddSystemIncludeDirs($"{headersPath}/usr/include/c++/{version}"); + AddSystemIncludeDirs($"{headersPath}/usr/include/c++/{version}/backward"); + + foreach (var triple in triples) + { + AddSystemIncludeDirs($"{headersPath}/usr/include/{triple}/c++/{version}"); + AddSystemIncludeDirs($"{headersPath}/usr/include/c++/{version}/{triple}"); + } + } + } + + foreach (var triple in triples) + { + foreach (var version in versions) + { + AddSystemIncludeDirs($"{headersPath}/usr/lib/{compiler}/{triple}/{version}/include"); + AddSystemIncludeDirs($"{headersPath}/usr/lib/{compiler}/{triple}/{version}/include/c++"); + AddSystemIncludeDirs($"{headersPath}/usr/lib/{compiler}/{triple}/{version}/include/c++/{triple}"); + } + + AddSystemIncludeDirs($"{headersPath}/usr/include/{triple}"); + } + + AddSystemIncludeDirs($"{headersPath}/usr/include"); + AddSystemIncludeDirs($"{headersPath}/usr/include/linux"); + } + + public void Setup() + { + SetupArguments(); + + if (!NoBuiltinIncludes) + SetupIncludes(); + } + + private void SetupArguments() + { + // do not remove the CppSharp prefix becase the Mono C# compiler breaks + if (!LanguageVersion.HasValue) + LanguageVersion = CppSharp.Parser.LanguageVersion.CPP14_GNU; + + // As of Clang revision 5e866e411caa we are required to pass "-fgnuc-version=" + // to get the __GNUC__ symbol defined. macOS and Linux system headers require + // this define, so we need explicitly pass it to Clang. + + // Note that this setup is more accurately done in the platform-specific + // setup methods, below is generic fallback in case that logic was disabled. + if (NoBuiltinIncludes) + { + switch (Platform.Host) + { + case TargetPlatform.MacOS: + case TargetPlatform.Linux: + AddArguments("-fgnuc-version=4.2.1"); + break; + } + } + + switch (LanguageVersion) + { + case CppSharp.Parser.LanguageVersion.C99: + case CppSharp.Parser.LanguageVersion.C99_GNU: + AddArguments("-xc"); + break; + default: + AddArguments("-xc++"); + break; + } + + switch (LanguageVersion) + { + case CppSharp.Parser.LanguageVersion.C99: + AddArguments("-std=c99"); + break; + case CppSharp.Parser.LanguageVersion.C99_GNU: + AddArguments("-std=gnu99"); + break; + case CppSharp.Parser.LanguageVersion.CPP98: + AddArguments("-std=c++98"); + break; + case CppSharp.Parser.LanguageVersion.CPP98_GNU: + AddArguments("-std=gnu++98"); + break; + case CppSharp.Parser.LanguageVersion.CPP11: + AddArguments("-std=c++11"); + break; + case CppSharp.Parser.LanguageVersion.CPP11_GNU: + AddArguments("-std=gnu++11"); + break; + case CppSharp.Parser.LanguageVersion.CPP14: + AddArguments("-std=c++14"); + break; + case CppSharp.Parser.LanguageVersion.CPP14_GNU: + AddArguments("-std=gnu++14"); + break; + case CppSharp.Parser.LanguageVersion.CPP17: + AddArguments("-std=c++17"); + break; + case CppSharp.Parser.LanguageVersion.CPP17_GNU: + AddArguments("-std=gnu++17"); + break; + case CppSharp.Parser.LanguageVersion.CPP20: + AddArguments("-std=c++20"); + break; + case CppSharp.Parser.LanguageVersion.CPP20_GNU: + AddArguments("-std=gnu++20"); + break; + case CppSharp.Parser.LanguageVersion.CPP23: + AddArguments("-std=c++2b"); + break; + case CppSharp.Parser.LanguageVersion.CPP23_GNU: + AddArguments("-std=gnu++2b"); + break; + } + + if (!EnableRTTI) + AddArguments("-fno-rtti"); + } + + public string BuiltinsDir + { + get + { + var assemblyDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + return Path.Combine(assemblyDir, "lib", "clang", ClangVersion, "include"); + } + } + + private void SetupIncludes() + { + // Check that the builtin includes folder exists. + if (!Directory.Exists(BuiltinsDir)) + throw new Exception($"Clang resource folder 'lib/clang/{ClangVersion}/include' was not found."); + + switch (Platform.Host) + { + case TargetPlatform.Windows: + SetupMSVC(); + break; + case TargetPlatform.MacOS: + SetupXcode(); + break; + case TargetPlatform.Linux: + SetupLinux(); + break; + } + } + } } diff --git a/src/Runtime/SymbolResolver.cs b/src/Runtime/SymbolResolver.cs index 28e0e745..cc2c3680 100644 --- a/src/Runtime/SymbolResolver.cs +++ b/src/Runtime/SymbolResolver.cs @@ -33,15 +33,15 @@ namespace CppSharp static readonly Func loadImage; static readonly Func resolveSymbol; - static SymbolResolver () + static SymbolResolver() { switch (Environment.OSVersion.Platform) { - case PlatformID.Unix: - case PlatformID.MacOSX: - loadImage = dlopen; - resolveSymbol = dlsym; - formats = new[] { + case PlatformID.Unix: + case PlatformID.MacOSX: + loadImage = dlopen; + resolveSymbol = dlsym; + formats = new[] { "{0}", "{0}.so", "{0}.dylib", @@ -49,16 +49,16 @@ namespace CppSharp "lib{0}.dylib", "{0}.bundle" }; - break; - default: - loadImage = LoadLibrary; - resolveSymbol = GetProcAddress; - formats = new[] { "{0}", "{0}.dll" }; - break; + break; + default: + loadImage = LoadLibrary; + resolveSymbol = GetProcAddress; + formats = new[] { "{0}", "{0}.dll" }; + break; } } - public static IntPtr LoadImage (ref string name) + public static IntPtr LoadImage(ref string name) { var pathValues = Environment.GetEnvironmentVariable("PATH"); var paths = new List(pathValues == null ? new string[0] : @@ -83,7 +83,7 @@ namespace CppSharp if (!File.Exists(attempted)) continue; - var ptr = loadImage (attempted); + var ptr = loadImage(attempted); if (ptr == IntPtr.Zero) continue; @@ -95,44 +95,44 @@ namespace CppSharp return IntPtr.Zero; } - public static IntPtr ResolveSymbol (string name, string symbol) + public static IntPtr ResolveSymbol(string name, string symbol) { var image = LoadImage(ref name); return ResolveSymbol(image, symbol); } - public static IntPtr ResolveSymbol (IntPtr image, string symbol) + public static IntPtr ResolveSymbol(IntPtr image, string symbol) { if (image != IntPtr.Zero) - return resolveSymbol (image, symbol); + return resolveSymbol(image, symbol); return IntPtr.Zero; } #region POSIX - + private const int RTLD_LAZY = 0x1; - static IntPtr dlopen (string path) + static IntPtr dlopen(string path) { - return dlopen (path, RTLD_LAZY); + return dlopen(path, RTLD_LAZY); } - [DllImport ("dl", CharSet=CharSet.Ansi)] - static extern IntPtr dlopen (string path, int flags); + [DllImport("dl", CharSet = CharSet.Ansi)] + static extern IntPtr dlopen(string path, int flags); - [DllImport ("dl", CharSet=CharSet.Ansi)] - static extern IntPtr dlsym (IntPtr handle, string symbol); + [DllImport("dl", CharSet = CharSet.Ansi)] + static extern IntPtr dlsym(IntPtr handle, string symbol); #endregion #region Win32 - [DllImport("kernel32", SetLastError=true)] - static extern IntPtr LoadLibrary (string lpFileName); + [DllImport("kernel32", SetLastError = true)] + static extern IntPtr LoadLibrary(string lpFileName); - [DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)] - static extern IntPtr GetProcAddress (IntPtr hModule, string procName); + [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] + static extern IntPtr GetProcAddress(IntPtr hModule, string procName); #endregion diff --git a/src/Runtime/UTF8Marshaller.cs b/src/Runtime/UTF8Marshaller.cs index 6ac831ed..cc9fa50c 100644 --- a/src/Runtime/UTF8Marshaller.cs +++ b/src/Runtime/UTF8Marshaller.cs @@ -25,7 +25,7 @@ namespace CppSharp.Runtime "UTF8Marshaler must be used on a string."); // not null terminated - byte[] strbuf = Encoding.UTF8.GetBytes((string) managedObj); + byte[] strbuf = Encoding.UTF8.GetBytes((string)managedObj); IntPtr buffer = Marshal.AllocHGlobal(strbuf.Length + 1); Marshal.Copy(strbuf, 0, buffer, strbuf.Length); @@ -40,10 +40,10 @@ namespace CppSharp.Runtime return null; int byteCount = 0; - var str8 = (byte*) str; + var str8 = (byte*)str; while (*(str8++) != 0) byteCount += sizeof(byte); - return Encoding.UTF8.GetString((byte*) str, byteCount); + return Encoding.UTF8.GetString((byte*)str, byteCount); } public static ICustomMarshaler GetInstance(string pstrCookie) diff --git a/tests/CSharp/CSharp.Gen.cs b/tests/CSharp/CSharp.Gen.cs index d44d791e..f6fe8dd0 100644 --- a/tests/CSharp/CSharp.Gen.cs +++ b/tests/CSharp/CSharp.Gen.cs @@ -61,10 +61,10 @@ namespace CppSharp.Tests ctx.GenerateEnumFromMacros("TestBoolValuedEnums", "TEST_BOOL_VALUED_ENUMS_.*"); enumTest.Namespace = new Namespace() - { - Name = "MacroTest", - Namespace = ctx.TranslationUnits.First(u => u.IsValid && !u.IsSystemHeader) - }; + { + Name = "MacroTest", + Namespace = ctx.TranslationUnits.First(u => u.IsValid && !u.IsSystemHeader) + }; // Generate a finalizer for just the one test case. driver.Options.GenerateFinalizers = true; @@ -167,10 +167,10 @@ namespace CppSharp.Tests var templateSpecializationType = type as TemplateSpecializationType; if (templateSpecializationType != null) return templateSpecializationType.Arguments[0].Type.Type; - var declaration = ((TagType) type).Declaration; + var declaration = ((TagType)type).Declaration; if (declaration.IsDependent) - return new TagType(((Class) declaration).TemplateParameters[0]); - classTemplateSpecialization = (ClassTemplateSpecialization) declaration; + return new TagType(((Class)declaration).TemplateParameters[0]); + classTemplateSpecialization = (ClassTemplateSpecialization)declaration; return classTemplateSpecialization.Arguments[0].Type.Type; } } @@ -208,7 +208,7 @@ namespace CppSharp.Tests { get { - var type = (TemplateSpecializationType) Type; + var type = (TemplateSpecializationType)Type; var pointeeType = type.Arguments[0].Type; var checker = new TypeIgnoreChecker(TypeMapDatabase); pointeeType.Visit(checker); @@ -220,7 +220,7 @@ namespace CppSharp.Tests { if (ctx.Kind == TypePrinterContextKind.Native) { - var type = (TemplateSpecializationType) ctx.Type.Desugar(); + var type = (TemplateSpecializationType)ctx.Type.Desugar(); var specialization = type.GetClassTemplateSpecialization(); var typePrinter = new CSharpTypePrinter(null); typePrinter.PushContext(TypePrinterContextKind.Native); @@ -239,7 +239,7 @@ namespace CppSharp.Tests public override void CSharpMarshalToNative(CSharpMarshalContext ctx) { // pointless, put just so that the generated code compiles - var type = (TemplateSpecializationType) ctx.Parameter.Type.Desugar(); + var type = (TemplateSpecializationType)ctx.Parameter.Type.Desugar(); var specialization = type.GetClassTemplateSpecialization(); var typePrinter = new CSharpTypePrinter(null); typePrinter.PushContext(TypePrinterContextKind.Native); diff --git a/tests/CSharp/CSharp.Tests.cs b/tests/CSharp/CSharp.Tests.cs index aedb1479..5aa39e73 100644 --- a/tests/CSharp/CSharp.Tests.cs +++ b/tests/CSharp/CSharp.Tests.cs @@ -149,7 +149,7 @@ public unsafe class CSharpTests foo[0] = 250; Assert.That(foo[0], Is.EqualTo(250)); - Assert.That(foo[(uint) 0], Is.EqualTo(15)); + Assert.That(foo[(uint)0], Is.EqualTo(15)); } using (var bar = new Bar()) @@ -168,7 +168,7 @@ public unsafe class CSharpTests { using (var f = new Foo()) { - foreach(var pod in new[] { f.SmallPodCdecl, f.SmallPodStdcall, f.SmallPodThiscall }) + foreach (var pod in new[] { f.SmallPodCdecl, f.SmallPodStdcall, f.SmallPodThiscall }) { Assert.That(pod.A, Is.EqualTo(10000)); Assert.That(pod.B, Is.EqualTo(40000)); @@ -189,7 +189,7 @@ public unsafe class CSharpTests using (var baz = new Baz()) { Assert.That(baz.Method, Is.EqualTo(1)); - var bar = (IBar) baz; + var bar = (IBar)baz; Assert.That(bar.Method, Is.EqualTo(2)); Assert.That(baz[0], Is.EqualTo(50)); using (Foo foo = new Foo { A = 1000 }) @@ -222,7 +222,7 @@ public unsafe class CSharpTests } using (var qux = new Qux()) { - using (var p = new P((IQux) qux) { Value = 20 }) + using (var p = new P((IQux)qux) { Value = 20 }) { Assert.That(p.Value, Is.EqualTo(30)); p.Prop = 50; @@ -271,7 +271,7 @@ public unsafe class CSharpTests int i = 5; array[0] = new IntPtr(&i); bar.ArrayOfPrimitivePointers = array; - Assert.That(i, Is.EqualTo(*(int*) bar.ArrayOfPrimitivePointers[0])); + Assert.That(i, Is.EqualTo(*(int*)bar.ArrayOfPrimitivePointers[0])); } } @@ -287,7 +287,7 @@ public unsafe class CSharpTests [Test] public void TestPropertiesConflictingWithMethod() { - using (var p = new P((IQux) new Qux()) { Test = true }) + using (var p = new P((IQux)new Qux()) { Test = true }) { Assert.That(p.Test, Is.True); p.GetTest(); @@ -463,10 +463,10 @@ public unsafe class CSharpTests { IntPtr native1; IntPtr native2; - var hasVirtualDtor1Map = (IDictionary) typeof( + var hasVirtualDtor1Map = (IDictionary)typeof( HasVirtualDtor1).GetField("NativeToManagedMap", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); - var hasVirtualDtor2Map = (IDictionary) typeof( + var hasVirtualDtor2Map = (IDictionary)typeof( HasVirtualDtor2).GetField("NativeToManagedMap", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); using (var testNativeToManagedMap = new TestNativeToManagedMap()) @@ -487,7 +487,7 @@ public unsafe class CSharpTests { using (var testNativeToManagedMap = new TestNativeToManagedMap()) { - var quxMap = (IDictionary) typeof( + var quxMap = (IDictionary)typeof( Qux).GetField("NativeToManagedMap", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); var bar = new Bar(); @@ -811,7 +811,7 @@ public unsafe class CSharpTests }) { var independentFields = internalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); - var fieldOffset = (FieldOffsetAttribute) independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute)); + var fieldOffset = (FieldOffsetAttribute)independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute)); if (fieldOffset != null) Assert.That(fieldOffset.Value, Is.EqualTo(0)); Assert.That((int)Marshal.OffsetOf(internalType, independentFields[0].Name), Is.EqualTo(0)); @@ -827,11 +827,11 @@ public unsafe class CSharpTests { var independentFields = internalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); Assert.That(independentFields.Length, Is.EqualTo(2)); - var fieldOffsetKey = (FieldOffsetAttribute) independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute)); + var fieldOffsetKey = (FieldOffsetAttribute)independentFields[0].GetCustomAttribute(typeof(FieldOffsetAttribute)); if (fieldOffsetKey != null) - Assert.That(fieldOffsetKey.Value, Is.EqualTo(0)); + Assert.That(fieldOffsetKey.Value, Is.EqualTo(0)); Assert.That((int)Marshal.OffsetOf(internalType, independentFields[0].Name), Is.EqualTo(0)); - var fieldOffsetValue = (FieldOffsetAttribute) independentFields[1].GetCustomAttribute(typeof(FieldOffsetAttribute)); + var fieldOffsetValue = (FieldOffsetAttribute)independentFields[1].GetCustomAttribute(typeof(FieldOffsetAttribute)); if (fieldOffsetValue != null) Assert.That(fieldOffsetValue.Value, Is.EqualTo(Marshal.SizeOf(IntPtr.Zero))); Assert.That((int)Marshal.OffsetOf(internalType, independentFields[1].Name), Is.EqualTo(Marshal.SizeOf(IntPtr.Zero))); @@ -860,7 +860,7 @@ public unsafe class CSharpTests [Test] public void TestEmbeddedArrayOfStructAccessor() { - const ulong firstLong = 0xC92EEDE87AAB4FECul; + const ulong firstLong = 0xC92EEDE87AAB4FECul; const ulong secondLong = 0xAD5FB16491935522ul; var testStruct = new StructWithEmbeddedArrayOfStructObjectAlignment(); @@ -896,8 +896,8 @@ public unsafe class CSharpTests Assert.That(StaticVariables.Int, Is.EqualTo(1020304050)); Assert.That(StaticVariables.Float, Is.EqualTo(0.5020f)); Assert.That(StaticVariables.String, Is.EqualTo("Str")); - Assert.That(StaticVariables.ChrArray, Is.EqualTo(new[] { 'A', 'B'})); - Assert.That(StaticVariables.IntArray, Is.EqualTo(new[] { 1020304050 , 1526374850 })); + Assert.That(StaticVariables.ChrArray, Is.EqualTo(new[] { 'A', 'B' })); + Assert.That(StaticVariables.IntArray, Is.EqualTo(new[] { 1020304050, 1526374850 })); Assert.That(StaticVariables.FloatArray, Is.EqualTo(new[] { 0.5020f, 0.6020f })); Assert.That(StaticVariables.BoolArray, Is.EqualTo(new[] { false, true })); Assert.That(StaticVariables.VoidPtrArray, Is.EqualTo(new IntPtr[] { new IntPtr(0x10203040), new IntPtr(0x40302010) })); @@ -921,7 +921,7 @@ public unsafe class CSharpTests Assert.That(VariablesWithInitializer.WideString, Is.EqualTo("Str")); Assert.That(VariablesWithInitializer.StringArray1, Is.EqualTo(new[] { "StrF,\"or" })); Assert.That(VariablesWithInitializer.StringArray3, Is.EqualTo(new[] { "StrF,\"or", "C#", VariablesWithInitializer.String })); - Assert.That(VariablesWithInitializer.StringArray30, Is.EqualTo(new[] { + Assert.That(VariablesWithInitializer.StringArray30, Is.EqualTo(new[] { "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str", "Str"})); @@ -985,7 +985,7 @@ public unsafe class CSharpTests GC.Collect(); - for (var i = 0; i < instanceCount; i++) + for (var i = 0; i < instanceCount; i++) { if (batch[i].UnicodeConst != otherString) { @@ -1036,7 +1036,7 @@ public unsafe class CSharpTests Assert.That(ts.ThirtyTwoBitConst, Is.EqualTo(str)); Assert.That(OwnsNativeMemory(ts, "__thirtyTwoBitConst_OwnsNativeMemory"), Is.EqualTo(false)); - var x = (uint *)ts.ThirtyTwoBitNonConst; + var x = (uint*)ts.ThirtyTwoBitNonConst; for (int i = 0; i < otherStr.Length; i++) { Assert.That(*x++, Is.EqualTo(otherStr[i])); @@ -1333,8 +1333,8 @@ public unsafe class CSharpTests using (var dependentValueFields = new DependentValueFields()) { int i = 10; - dependentValueFields.DependentValue = (IntPtr) (&i); - Assert.That(*(int*) dependentValueFields.DependentValue, Is.EqualTo(10)); + dependentValueFields.DependentValue = (IntPtr)(&i); + Assert.That(*(int*)dependentValueFields.DependentValue, Is.EqualTo(10)); } } @@ -1673,7 +1673,7 @@ public unsafe class CSharpTests using (var indexproperty = new TestIndexedProperties()) { uint n = 21; - Assert.That(*((int*) indexproperty[n]), Is.EqualTo(21)); + Assert.That(*((int*)indexproperty[n]), Is.EqualTo(21)); } } @@ -1773,14 +1773,14 @@ public unsafe class CSharpTests public void TestRValueReferenceToPointer() { int value = 5; - IntPtr intPtr = CSharp.CSharp.RValueReferenceToPointer((IntPtr*) &value); - Assert.That((int) intPtr, Is.EqualTo(value)); + IntPtr intPtr = CSharp.CSharp.RValueReferenceToPointer((IntPtr*)&value); + Assert.That((int)intPtr, Is.EqualTo(value)); } [Test] public void TakeRefToPointerToObject() { - using (Foo foo = new Foo { A = 25 }) + using (Foo foo = new Foo { A = 25 }) { Foo returnedFoo = CSharp.CSharp.TakeReturnReferenceToPointer(foo); Assert.That(returnedFoo.A, Is.EqualTo(foo.A)); diff --git a/tests/Common/Common.Tests.cs b/tests/Common/Common.Tests.cs index 21a26241..eb088354 100644 --- a/tests/Common/Common.Tests.cs +++ b/tests/Common/Common.Tests.cs @@ -66,7 +66,7 @@ public class CommonTests new AmbiguousParamNames(0, 0).Dispose(); Common.SMallFollowedByCapital(); Common.IntegerOverload(0); - Common.IntegerOverload((uint) 0); + Common.IntegerOverload((uint)0); Common.TakeVoidStarStar(null); Common.OverloadPointer(IntPtr.Zero, 1); using (new DerivedFromSecondaryBaseWithIgnoredVirtualMethod()) { } @@ -198,7 +198,7 @@ public class CommonTests { using (var hello = new Hello()) { - hello.EnumOut((int) Enum.C, out Enum e); + hello.EnumOut((int)Enum.C, out Enum e); Assert.That(e, Is.EqualTo(Enum.C)); } } @@ -208,7 +208,7 @@ public class CommonTests { using (var hello = new Hello()) { - hello.EnumOutRef((int) Enum.C, out Enum e); + hello.EnumOutRef((int)Enum.C, out Enum e); Assert.That(e, Is.EqualTo(Enum.C)); } } @@ -485,16 +485,16 @@ public class CommonTests Assert.AreEqual(2, indexedProperties[0]); indexedProperties[0f] = 3; Assert.AreEqual(3, indexedProperties[0f]); - var properties = indexedProperties[(byte) 0]; + var properties = indexedProperties[(byte)0]; Assert.AreEqual(0, properties.Field); var newProperties = new TestProperties(); newProperties.Field = 4; - indexedProperties[(byte) 0] = newProperties; - Assert.AreEqual(4, indexedProperties[(byte) 0].Field); - newProperties = indexedProperties[(short) 0]; + indexedProperties[(byte)0] = newProperties; + Assert.AreEqual(4, indexedProperties[(byte)0].Field); + newProperties = indexedProperties[(short)0]; Assert.AreEqual(4, newProperties.Field); newProperties.Field = 5; - Assert.AreEqual(5, indexedProperties[(byte) 0].Field); + Assert.AreEqual(5, indexedProperties[(byte)0].Field); newProperties.get(); newProperties.set(0); newProperties.Get(); @@ -503,8 +503,8 @@ public class CommonTests var bar = new Bar { A = 5 }; indexedProperties[0u] = bar; Assert.That(bar.A, Is.EqualTo(indexedProperties[0u].A)); - indexedProperties[(ushort) 0] = bar; - Assert.That(bar.A, Is.EqualTo(indexedProperties[(ushort) 0].A)); + indexedProperties[(ushort)0] = bar; + Assert.That(bar.A, Is.EqualTo(indexedProperties[(ushort)0].A)); using (var foo = new Foo()) { @@ -649,7 +649,7 @@ public class CommonTests { ClassB classB = classA; Assert.AreEqual(classA.Value, classB.Value); - ClassC classC = (ClassC) classB; + ClassC classC = (ClassC)classB; Assert.AreEqual(classB.Value, classC.Value); } } @@ -889,7 +889,7 @@ public class CommonTests [Test] public void TestPassingNullToValue() { - Assert.Catch(() => new Bar((Foo) null)); + Assert.Catch(() => new Bar((Foo)null)); } [Test] diff --git a/tests/NamespacesDerived/NamespacesDerived.Tests.cs b/tests/NamespacesDerived/NamespacesDerived.Tests.cs index b2a3d4c8..6c486bc5 100644 --- a/tests/NamespacesDerived/NamespacesDerived.Tests.cs +++ b/tests/NamespacesDerived/NamespacesDerived.Tests.cs @@ -129,7 +129,7 @@ public class NamespaceDerivedTests Is.EqualTo(@params[0].Name)); Assert.That(path.Value, Is.EqualTo("A full or partial name for the process to attach to.")); - XElement wait_for = (XElement) path.NextNode; + XElement wait_for = (XElement)path.NextNode; Assert.That(wait_for.Attribute("name").Value, Is.EqualTo(@params[1].Name)); Assert.That(wait_for.Elements("para").Select(p => string.Concat(p.Nodes())), Is.EquivalentTo( @@ -137,7 +137,7 @@ public class NamespaceDerivedTests { "If false, attach to an existing process whose name matches.", "If true, then wait for the next process whose name matches." - })); + })); } private static void TestGlfwDestroyWindow(Type testCommentsType, XElement members) diff --git a/tests/StandardLib/StandardLib.Tests.cs b/tests/StandardLib/StandardLib.Tests.cs index 63f3f988..6f8ca883 100644 --- a/tests/StandardLib/StandardLib.Tests.cs +++ b/tests/StandardLib/StandardLib.Tests.cs @@ -57,4 +57,3 @@ public class StandardLibTests Assert.AreEqual(testString, stringWriter.ToString()); } } - \ No newline at end of file