Esempio n. 1
0
        public override bool VisitFunctionDecl(Function function)
        {
            if (!VisitDeclaration(function))
                return false;

            if (function.IsReturnIndirect)
            {
                var indirectParam = new Parameter()
                    {
                        Kind = ParameterKind.IndirectReturnType,
                        QualifiedType = function.ReturnType,
                        Name = "return",
                    };

                function.Parameters.Insert(0, indirectParam);
                function.ReturnType = new QualifiedType(new BuiltinType(
                    PrimitiveType.Void));
            }

            if (function.HasThisReturn)
            {
                // This flag should only be true on methods.
                var method = (Method) function;
                var classType = new QualifiedType(new TagType(method.Namespace),
                    new TypeQualifiers {IsConst = true});
                function.ReturnType = new QualifiedType(new PointerType(classType));
            }

            // TODO: Handle indirect parameters

            return true;
        }
Esempio n. 2
0
        private bool IsStdType(QualifiedType type)
        {
            var typePrinter = new CppTypePrinter(Driver.TypeDatabase);
            var typeName = type.Visit(typePrinter);

            return typeName.Contains("std::");
        }
 private static void ChangeToInterfaceType(QualifiedType type)
 {
     var tagType = type.Type.SkipPointerRefs() as TagType;
     if (tagType != null)
     {
         var @class = tagType.Declaration as Class;
         if (@class != null)
         {
             var @interface = @class.Namespace.Classes.Find(c => c.OriginalClass == @class);
             if (@interface != null)
                 tagType.Declaration = @interface;
         }
     }
 }
        public override bool VisitMethodDecl(Method method)
        {
            if (!method.IsConstructor)
                return false;
            if (method.IsCopyConstructor)
                return false;
            if (method.Parameters.Count != 1)
                return false;
            var parameter = method.Parameters[0];
            // TODO: disable implicit operators for C++/CLI because they seem not to be support parameters
            if (!Driver.Options.IsCSharpGenerator)
            {
                var pointerType = parameter.Type as PointerType;
                if (pointerType != null && !pointerType.IsReference)
                    return false;
            }
            var qualifiedPointee = parameter.Type.SkipPointerRefs();
            Class castFromClass;
            if (qualifiedPointee.TryGetClass(out castFromClass))
            {
                var castToClass = method.OriginalNamespace as Class;
                if (castToClass == null)
                    return false;
                if (castFromClass == castToClass)
                    return false;
            }

            var operatorKind = method.IsExplicit
                ? CXXOperatorKind.ExplicitConversion
                : CXXOperatorKind.Conversion;
            var qualifiedCastToType = new QualifiedType(new TagType(method.Namespace));
            var conversionOperator = new Method
            {
                Name = Operators.GetOperatorIdentifier(operatorKind),
                Namespace = method.Namespace,
                Kind = CXXMethodKind.Conversion,
                SynthKind = FunctionSynthKind.ComplementOperator,
                ConversionType = qualifiedCastToType,
                ReturnType = qualifiedCastToType,
                OperatorKind = operatorKind
            };
            var p = new Parameter(parameter);
            Class @class;
            if (p.Type.SkipPointerRefs().TryGetClass(out @class))
                p.QualifiedType = new QualifiedType(new TagType(@class), parameter.QualifiedType.Qualifiers);
            p.DefaultArgument = null;
            conversionOperator.Parameters.Add(p);
            ((Class) method.Namespace).Methods.Add(conversionOperator);
            return true;
        }
        /// <summary>
        /// Generates a new typedef for the given type if necessary and returns the new type.
        /// </summary>
        /// <param name="namespace">The namespace the typedef will be added to.</param>
        /// <param name="type">The type to check.</param>
        /// <returns>The new type.</returns>
        private QualifiedType CheckType(DeclarationContext @namespace, QualifiedType type)
        {
            if (type.Type.IsDependent)
                return type;

            var pointerType = type.Type as PointerType;
            if (pointerType == null)
                return type;

            var functionType = pointerType.Pointee as FunctionType;
            if (functionType == null)
                return type;

            List<Typedef> typedefs;
            if (!allTypedefs.TryGetValue(@namespace.QualifiedName, out typedefs))
            {
                typedefs = new List<Typedef>();
                allTypedefs.Add(@namespace.QualifiedName, typedefs);
            }

            var typedef = FindMatchingTypedef(typedefs, functionType);
            if (typedef == null)
            {
                for (int i = 0; i < functionType.Parameters.Count; i++)
                {
                    functionType.Parameters[i].Name = string.Format("_{0}", i);
                }

                typedef = new TypedefDecl
                {
                    Access = AccessSpecifier.Public,
                    Name = string.Format("__AnonymousDelegate{0}", typedefs.Count),
                    Namespace = @namespace,
                    QualifiedType = type,
                    IsSynthetized = true
                };
                typedefs.Add(new Typedef
                {
                    Context = @namespace,
                    Declaration = typedef
                });
            }

            var typedefType = new TypedefType
            {
                Declaration = typedef
            };
            return new QualifiedType(typedefType);
        }
 private static void ChangeToInterfaceType(ref QualifiedType type)
 {
     var tagType = (type.Type.GetFinalPointee() ?? type.Type) as TagType;
     if (tagType != null)
     {
         var @class = tagType.Declaration as Class;
         if (@class != null)
         {
             var @interface = @class.Namespace.Classes.Find(c => c.OriginalClass == @class);
             if (@interface != null)
             {
                 type.Type = (Type) type.Type.Clone();
                 ((TagType) (type.Type.GetFinalPointee() ?? type.Type)).Declaration = @interface;
             }
         }
     }
 }
Esempio n. 7
0
        public override bool VisitFunctionDecl(Function function)
        {
            if (!VisitDeclaration(function))
                return false;

            if (function.IsReturnIndirect)
            {
                var indirectParam = new Parameter()
                    {
                        Kind = ParameterKind.IndirectReturnType,
                        QualifiedType = function.ReturnType,
                        Name = "return",
                    };

                function.Parameters.Insert(0, indirectParam);
                function.ReturnType = new QualifiedType(new BuiltinType(
                    PrimitiveType.Void));
            }

            var method = function as Method;

            if (function.HasThisReturn)
            {
                // This flag should only be true on methods.
                var classType = new QualifiedType(new TagType(method.Namespace),
                    new TypeQualifiers {IsConst = true});
                function.ReturnType = new QualifiedType(new PointerType(classType));
            }

            // Deleting destructors (default in v-table) accept an i32 bitfield as a
            // second parameter.in MS ABI.
            if (method != null && method.IsDestructor && Driver.Options.IsMicrosoftAbi)
            {
                method.Parameters.Add(new Parameter
                {
                    Kind = ParameterKind.ImplicitDestructorParameter,
                    QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.Int)),
                    Name = "delete"
                });
            }

            // TODO: Handle indirect parameters

            return true;
        }
        public override bool VisitMethodDecl(Method method)
        {
            if (AlreadyVisited(method) || !method.IsGenerated || !method.IsConstructor ||
                method.IsCopyConstructor || method.Parameters.Count != 1)
                return false;

            var parameter = method.Parameters[0];
            // TODO: disable implicit operators for C++/CLI because they seem not to be support parameters
            if (!Driver.Options.IsCSharpGenerator)
            {
                var pointerType = parameter.Type as PointerType;
                if (pointerType != null && !pointerType.IsReference)
                    return false;
            }
            var qualifiedPointee = parameter.Type.GetFinalPointee() ?? parameter.Type;
            Class castFromClass;
            var castToClass = method.OriginalNamespace as Class;
            if (qualifiedPointee.TryGetClass(out castFromClass))
            {
                if (castToClass == null || castToClass.IsAbstract)
                    return false;
                if (ConvertsBetweenDerivedTypes(castToClass, castFromClass))
                    return false;
            }
            if (castToClass != null && castToClass.IsAbstract)
                return false;
            var operatorKind = method.IsExplicit
                ? CXXOperatorKind.ExplicitConversion
                : CXXOperatorKind.Conversion;
            var qualifiedCastToType = new QualifiedType(new TagType(method.Namespace));
            var conversionOperator = new Method
            {
                Name = Operators.GetOperatorIdentifier(operatorKind),
                Namespace = method.Namespace,
                Kind = CXXMethodKind.Conversion,
                SynthKind = FunctionSynthKind.ComplementOperator,
                ConversionType = qualifiedCastToType,
                ReturnType = qualifiedCastToType,
                OperatorKind = operatorKind,
                IsExplicit = method.IsExplicit
            };
            conversionOperator.Parameters.Add(new Parameter(parameter) { DefaultArgument = null });
            ((Class) method.Namespace).Methods.Add(conversionOperator);
            return true;
        }
        public override bool VisitMethodDecl(Method method)
        {
            if (!method.IsConstructor)
                return false;
            if (method.IsCopyConstructor)
                return false;
            if (method.Parameters.Count != 1)
                return false;
            var parameter = method.Parameters[0];
            var parameterType = parameter.Type as PointerType;
            if (parameterType == null)
                return false;
            if (!parameterType.IsReference)
                return false;
            var qualifiedPointee = parameterType.QualifiedPointee;
            Class castFromClass;
            if (!qualifiedPointee.Type.TryGetClass(out castFromClass))
                return false;
            var castToClass = method.OriginalNamespace as Class;
            if (castToClass == null)
                return false;
            if (castFromClass == castToClass)
                return false;

            var operatorKind = method.IsExplicit
                ? CXXOperatorKind.ExplicitConversion
                : CXXOperatorKind.Conversion;
            var castToType = new TagType(castToClass);
            var qualifiedCastToType = new QualifiedType(castToType);
            var conversionOperator = new Method()
            {
                Name = Operators.GetOperatorIdentifier(operatorKind),
                Namespace = castFromClass,
                Kind = CXXMethodKind.Conversion,
                IsSynthetized = true,
                ConversionType = qualifiedCastToType,
                ReturnType = qualifiedCastToType
            };
            conversionOperator.OperatorKind = operatorKind;

            castFromClass.Methods.Add(conversionOperator);
            return true;
        }
Esempio n. 10
0
 private static QualifiedType GetInterfaceType(QualifiedType type)
 {
     var tagType = type.Type as TagType;
     if (tagType == null)
     {
         var pointerType = type.Type as PointerType;
         if (pointerType != null)
             tagType = pointerType.Pointee as TagType;
     }
     if (tagType != null)
     {
         var @class = tagType.Declaration as Class;
         if (@class != null)
         {
             var @interface = @class.Namespace.Classes.Find(c => c.OriginalClass == @class);
             if (@interface != null)
                 return new QualifiedType(new TagType(@interface));
         }
     }
     return type;
 }
        Property GetOrCreateProperty(Class @class, string name, QualifiedType type)
        {
            var prop = @class.Properties.FirstOrDefault(property => property.Name == name
                && property.QualifiedType.Equals(type));

            var prop2 = @class.Properties.FirstOrDefault(property => property.Name == name);

            if (prop == null && prop2 != null)
                Driver.Diagnostics.Debug("Property {0}::{1} already exists (type: {2})",
                    @class.Name, name, type.Type.ToString());

            if (prop != null)
                return prop;

            prop = new Property
            {
                Name = name,
                Namespace = @class,
                QualifiedType = type
            };

            @class.Properties.Add(prop);
            return prop;
        }
Esempio n. 12
0
        public static IEnumerable<Parameter> GatherInternalParams(this Function function,
            bool isItaniumLikeAbi, bool universalDelegate = false)
        {
            var @params = new List<Parameter>();

            var method = function as Method;
            var isInstanceMethod = method != null && !method.IsStatic;

            var pointer = new QualifiedType(new PointerType(new QualifiedType(new BuiltinType(PrimitiveType.Void))));

            if (isInstanceMethod && !isItaniumLikeAbi)
            {
                @params.Add(new Parameter
                    {
                        QualifiedType = pointer,
                        Name = "instance"
                    });
            }

            if (!function.HasIndirectReturnTypeParameter &&
                isInstanceMethod && isItaniumLikeAbi)
            {
                @params.Add(new Parameter
                    {
                        QualifiedType = pointer,
                        Name = "instance"
                    });
            }

            var i = 0;
            foreach (var param in function.Parameters.Where(p => p.Kind != ParameterKind.OperatorParameter))
            {
                @params.Add(new Parameter
                    {
                        QualifiedType = universalDelegate && param.Kind == ParameterKind.IndirectReturnType ?
                            pointer : param.QualifiedType,
                        Kind = param.Kind,
                        Usage = param.Usage,
                        Name = universalDelegate ? "arg" + ++i : param.Name
                    });

                if (param.Kind == ParameterKind.IndirectReturnType &&
                    isInstanceMethod && isItaniumLikeAbi)
                {
                    @params.Add(new Parameter
                        {
                            QualifiedType = pointer,
                            Name = "instance"
                        });
                }
            }

            if (method != null && method.IsConstructor)
            {
                var @class = (Class) method.Namespace;
                if (!isItaniumLikeAbi && @class.Layout.HasVirtualBases)
                {
                    @params.Add(new Parameter
                        {
                            QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.Int)),
                            Name = "__forBases"
                        });
                }
            }

            return @params;
        }
Esempio n. 13
0
        private string GenerateDelegateSignature(IEnumerable<Parameter> @params, QualifiedType returnType)
        {
            TypePrinter.PushContext(CSharpTypePrinterContextKind.Native);
            CSharpTypePrinter.AppendGlobal = false;
            var typesBuilder = new StringBuilder();
            if (!returnType.Type.IsPrimitiveType(PrimitiveType.Void))
            {
                typesBuilder.Insert(0, returnType.Type.CSharpType(TypePrinter));
                typesBuilder.Append('_');
            }
            foreach (var parameter in @params)
            {
                typesBuilder.Append(parameter.CSharpType(TypePrinter));
                typesBuilder.Append('_');
            }
            if (typesBuilder.Length > 0)
                typesBuilder.Remove(typesBuilder.Length - 1, 1);
            var delegateName = Helpers.FormatTypesStringForIdentifier(typesBuilder);
            if (returnType.Type.IsPrimitiveType(PrimitiveType.Void))
                delegateName = "Action_" + delegateName;
            else
                delegateName = "Func_" + delegateName;

            TypePrinter.PopContext();
            CSharpTypePrinter.AppendGlobal = true;
            return delegateName;
        }
 public override QualifiedType TransformType(QualifiedType type)
 {
     return(new QualifiedType(new BuiltinType(Kind), type.Qualifiers));
 }
Esempio n. 15
0
        private string GenerateDelegateSignature(IEnumerable<Parameter> @params, QualifiedType returnType)
        {
            var typePrinter = new CSharpTypePrinter(Driver);
            typePrinter.PushContext(CSharpTypePrinterContextKind.Native);

            var typesBuilder = new StringBuilder();
            if (!returnType.Type.IsPrimitiveType(PrimitiveType.Void))
            {
                typesBuilder.Insert(0, returnType.Type.CSharpType(typePrinter));
                typesBuilder.Append('_');
            }
            foreach (var parameter in @params)
            {
                typesBuilder.Append(parameter.CSharpType(typePrinter));
                typesBuilder.Append('_');
            }
            if (typesBuilder.Length > 0)
                typesBuilder.Remove(typesBuilder.Length - 1, 1);
            var delegateName = typesBuilder.Replace("global::System.", string.Empty).Replace(
                "*", "Ptr").Replace('.', '_').ToString();
            if (returnType.Type.IsPrimitiveType(PrimitiveType.Void))
                delegateName = "Action_" + delegateName;
            else
                delegateName = "Func_" + delegateName;

            typePrinter.PopContext();
            return delegateName;
        }
Esempio n. 16
0
 public virtual TypePrinterResult VisitQualifiedType(QualifiedType type)
 {
     return(type.Type.Visit(this, type.Qualifiers));
 }
Esempio n. 17
0
 public static void CSharpMarshalToManaged(this QualifiedType type,
                                           CSharpMarshalNativeToManagedPrinter printer)
 {
     printer.Context.FullType = type;
     type.Visit(printer);
 }
Esempio n. 18
0
 public QualifiedMember(QualifiedType containingType, string methodName)
 {
     this.ContainingType = containingType;
     this.Name           = methodName;
 }
Esempio n. 19
0
 public static QualifiedType __CreateInstance(QualifiedType.Internal native)
 {
     return new QualifiedType(native);
 }
Esempio n. 20
0
 public object VisitQualifiedType(QualifiedType qualifiedType, object data)
 {
     throw new NotImplementedException();
 }
Esempio n. 21
0
 internal TypeMatchSpec(QualifiedType type, bool inverted)
 {
     this.InvertedLogic = inverted;
     this.Type          = type;
 }
Esempio n. 22
0
 public static bool IsConst(this QualifiedType type)
 {
     return(type.Type != null && (type.Qualifiers.IsConst ||
                                  type.Type.GetQualifiedPointee().IsConst()));
 }
 private static bool IsTemplateParameter(QualifiedType type)
 {
     return((type.Type.Desugar().GetFinalPointee() ?? type.Type).Desugar() is TemplateParameterType);
 }
Esempio n. 24
0
        private Class GetNewInterface(string name, Class @base)
        {
            var @interface = new Class
                {
                    Name = name,
                    Namespace = @base.Namespace,
                    Access = @base.Access,
                    Type = ClassType.Interface,
                    OriginalClass = @base
                };

            @interface.Bases.AddRange(
                from b in @base.Bases
                where b.Class != null
                let i = GetInterface(b.Class)
                select new BaseClassSpecifier(b) { Type = new TagType(i) });

            @interface.Methods.AddRange(
                from m in @base.Methods
                where !m.IsConstructor && !m.IsDestructor && !m.IsStatic && m.IsDeclared && !m.IsOperator
                select new Method(m) { Namespace = @interface, OriginalFunction = m });

            @interface.Properties.AddRange(
                from property in @base.Properties
                where property.IsDeclared
                select CreateInterfaceProperty(property, @interface));

            @interface.Fields.AddRange(@base.Fields);
            // avoid conflicts when potentially renaming later
            @interface.Declarations.AddRange(@base.Declarations);

            if (@interface.Bases.Count == 0)
            {
                var instance = new Property
                {
                    Namespace = @interface,
                    Name = Helpers.InstanceIdentifier,
                    QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.IntPtr)),
                    GetMethod = new Method
                    {
                        SynthKind = FunctionSynthKind.InterfaceInstance,
                        Namespace = @interface
                    }
                };

                @interface.Properties.Add(instance);
            }

            @interface.Events.AddRange(@base.Events);

            var type = new QualifiedType(new BuiltinType(PrimitiveType.IntPtr));
            var adjustmentTo = new Property
            {
                Namespace = @interface,
                Name = "__PointerTo" + @base.Name,
                QualifiedType = type,
                GetMethod = new Method
                {
                    SynthKind = FunctionSynthKind.InterfaceInstance,
                    Namespace = @interface,
                    ReturnType = type
                }
            };
            @interface.Properties.Add(adjustmentTo);
            @base.Properties.Add(adjustmentTo);

            @base.Bases.Add(new BaseClassSpecifier { Type = new TagType(@interface) });

            interfaces.Add(@base, @interface);
            return @interface;
        }
Esempio n. 25
0
 public virtual bool VisitQualifiedType(QualifiedType type)
 {
     return(type.Type.Visit(this, type.Qualifiers));
 }
Esempio n. 26
0
        public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
        {
            if (!VisitType(pointer, quals))
            {
                return(false);
            }

            var qualifiedPointer = new QualifiedType(pointer, quals);

            var         templateSubstitution = pointer.Pointee as TemplateParameterSubstitutionType;
            PointerType realPointer          = null;

            if (templateSubstitution != null)
            {
                realPointer = templateSubstitution.Replacement.Type.Desugar() as PointerType;
            }
            realPointer = realPointer ?? pointer;
            var pointee = pointer.Pointee.Desugar();

            if (Context.Function != null &&
                (realPointer.IsPrimitiveTypeConvertibleToRef() ||
                 (templateSubstitution != null && realPointer.Pointee.IsEnumType())) &&
                Context.MarshalKind != MarshalKind.VTableReturnValue)
            {
                var refParamPtr = $"__refParamPtr{Context.ParameterIndex}";
                if (templateSubstitution != null)
                {
                    var castParam = $"__{Context.Parameter.Name}{Context.ParameterIndex}";
                    Context.Before.Write($"var {castParam} = ({templateSubstitution}) ");
                    if (realPointer != pointer)
                    {
                        Context.Before.Write($"({CSharpTypePrinter.IntPtrType}) ");
                    }
                    Context.Before.WriteLine($"(object) {Context.Parameter.Name};");
                    Context.Before.Write($"var {refParamPtr} = ");
                    if (realPointer == pointer)
                    {
                        Context.Before.Write("&");
                    }
                    Context.Before.WriteLine($"{castParam};");
                    Context.Return.Write(refParamPtr);
                    return(true);
                }
                if (Context.Function.OperatorKind != CXXOperatorKind.Subscript)
                {
                    if (Context.Parameter.Kind == ParameterKind.PropertyValue ||
                        qualifiedPointer.IsConstRefToPrimitive())
                    {
                        Context.Return.Write($"&{Context.Parameter.Name}");
                    }
                    else
                    {
                        Context.Before.WriteLine(
                            $"fixed ({realPointer} {refParamPtr} = &{Context.Parameter.Name})");
                        Context.HasCodeBlock = true;
                        Context.Before.WriteOpenBraceAndIndent();
                        Context.Return.Write(refParamPtr);
                    }
                    return(true);
                }
            }

            var param      = Context.Parameter;
            var isRefParam = param != null && (param.IsInOut || param.IsOut);

            if (pointee.IsConstCharString() && isRefParam)
            {
                if (param.IsOut)
                {
                    Context.Return.Write("IntPtr.Zero");
                    Context.ArgumentPrefix.Write("&");
                }
                else if (param.IsInOut)
                {
                    Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
                    Context.ArgumentPrefix.Write("&");
                }
                else
                {
                    Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
                    Context.Cleanup.WriteLine("Marshal.FreeHGlobal({0});", Context.ArgName);
                }
                return(true);
            }

            if (pointee is FunctionType)
            {
                return(VisitDelegateType());
            }

            Class @class;

            if (pointee.TryGetClass(out @class) && @class.IsValueType)
            {
                if (Context.Parameter.Usage == ParameterUsage.Out)
                {
                    var qualifiedIdentifier = (@class.OriginalClass ?? @class).Visit(typePrinter);
                    Context.Before.WriteLine("var {0} = new {1}.{2}();",
                                             Generator.GeneratedIdentifier(Context.ArgName), qualifiedIdentifier,
                                             Helpers.InternalStruct);
                }
                else
                {
                    Context.Before.WriteLine("var {0} = {1}.{2};",
                                             Generator.GeneratedIdentifier(Context.ArgName),
                                             Context.Parameter.Name,
                                             Helpers.InstanceIdentifier);
                }

                Context.Return.Write("new global::System.IntPtr(&{0})",
                                     Generator.GeneratedIdentifier(Context.ArgName));
                return(true);
            }

            var           marshalAsString = pointer.IsConstCharString();
            var           finalPointee    = pointer.GetFinalPointee();
            PrimitiveType primitive;

            if (finalPointee.IsPrimitiveType(out primitive) || finalPointee.IsEnumType() ||
                marshalAsString)
            {
                // From MSDN: "note that a ref or out parameter is classified as a moveable
                // variable". This means we must create a local variable to hold the result
                // and then assign this value to the parameter.

                if (isRefParam)
                {
                    var typeName = Type.TypePrinterDelegate(finalPointee);
                    if (Context.Function.OperatorKind == CXXOperatorKind.Subscript)
                    {
                        Context.Return.Write(param.Name);
                    }
                    else
                    {
                        if (param.IsInOut)
                        {
                            Context.Before.WriteLine($"{typeName} _{param.Name} = {param.Name};");
                        }
                        else
                        {
                            Context.Before.WriteLine($"{typeName} _{param.Name};");
                        }

                        Context.Return.Write($"&_{param.Name}");
                    }
                }
                else
                {
                    if (!marshalAsString &&
                        Context.Context.Options.MarshalCharAsManagedChar &&
                        primitive == PrimitiveType.Char)
                    {
                        Context.Return.Write($"({typePrinter.PrintNative(pointer)}) ");
                    }

                    if (marshalAsString && (Context.MarshalKind == MarshalKind.NativeField ||
                                            Context.MarshalKind == MarshalKind.VTableReturnValue ||
                                            Context.MarshalKind == MarshalKind.Variable))
                    {
                        Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
                    }
                    else
                    {
                        if (qualifiedPointer.IsConstRefToPrimitive())
                        {
                            Context.Return.Write("&");
                        }
                        Context.Return.Write(Context.Parameter.Name);
                    }
                }

                return(true);
            }

            return(pointer.QualifiedPointee.Visit(this));
        }
Esempio n. 27
0
 protected QualifiedType(QualifiedType.Internal* native, bool skipVTables = false)
 {
     if (native == null)
         return;
     __Instance = new global::System.IntPtr(native);
 }
        public override bool VisitMethodDecl(Method method)
        {
            if (AlreadyVisited(method) || !method.IsGenerated || !method.IsConstructor ||
                method.IsCopyConstructor
                // conversion operators can only be public
                || method.Access != AccessSpecifier.Public)
            {
                return(false);
            }

            var @params = method.Parameters.Where(p => p.Kind == ParameterKind.Regular).ToList();

            if (@params.Count == 0)
            {
                return(false);
            }

            if (Options.GenerateDefaultValuesForArguments)
            {
                var nonDefaultParams = @params.Count(p => p.DefaultArgument == null ||
                                                     (p.DefaultArgument.Class == StatementClass.Call &&
                                                      (p.DefaultArgument.Declaration == null ||
                                                       p.DefaultArgument.Declaration.Ignore)));
                if (nonDefaultParams > 1)
                {
                    return(false);
                }
            }
            else
            {
                if (@params.Count != 1)
                {
                    return(false);
                }
            }

            if (method.Parameters[0].Type.IsDependentPointer())
            {
                return(false);
            }

            var   parameter = method.Parameters[0];
            Class @class;
            var   paramType = (parameter.Type.GetFinalPointee() ?? parameter.Type).Desugar();

            if (paramType.TryGetClass(out @class) && @class == method.Namespace)
            {
                return(false);
            }

            // TODO: disable implicit operators for C++/CLI because they seem not to be support parameters
            if (!Options.IsCSharpGenerator)
            {
                var pointerType = parameter.Type as PointerType;
                if (pointerType != null && !pointerType.IsReference)
                {
                    return(false);
                }
            }
            var   qualifiedPointee = parameter.Type.GetFinalPointee() ?? parameter.Type;
            Class castFromClass;
            var   castToClass = method.OriginalNamespace as Class;

            if (qualifiedPointee.TryGetClass(out castFromClass))
            {
                if (castToClass == null || castToClass.IsAbstract)
                {
                    return(false);
                }
                if (ConvertsBetweenDerivedTypes(castToClass, castFromClass))
                {
                    return(false);
                }
            }
            if (castToClass != null && castToClass.IsAbstract)
            {
                return(false);
            }
            var operatorKind = method.IsExplicit
                ? CXXOperatorKind.ExplicitConversion
                : CXXOperatorKind.Conversion;
            var qualifiedCastToType = new QualifiedType(new TagType(method.Namespace));
            var conversionOperator  = new Method
            {
                Name           = Operators.GetOperatorIdentifier(operatorKind),
                Namespace      = method.Namespace,
                Kind           = CXXMethodKind.Conversion,
                SynthKind      = FunctionSynthKind.ComplementOperator,
                ConversionType = qualifiedCastToType,
                ReturnType     = qualifiedCastToType,
                OperatorKind   = operatorKind,
                IsExplicit     = method.IsExplicit,
                FunctionType   = method.FunctionType
            };

            conversionOperator.Parameters.Add(new Parameter(parameter)
            {
                Namespace               = conversionOperator,
                DefaultArgument         = null,
                OriginalDefaultArgument = null
            });
            ((Class)method.Namespace).Methods.Add(conversionOperator);
            return(true);
        }
Esempio n. 29
0
 private QualifiedType(QualifiedType.Internal native)
     : this(__CopyValue(native))
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
Esempio n. 30
0
 public IEnumerable <WorkItem> VisitQualifiedType(QualifiedType qt)
 {
     return(qt.DataType.Accept(this));
 }
Esempio n. 31
0
 public static TypePrinterResult CSharpType(this QualifiedType type,
                                            CSharpTypePrinter printer)
 {
     printer.FullType = type;
     return(type.Visit(printer));
 }
Esempio n. 32
0
 public CodeFormatter VisitQualifiedType(QualifiedType qt)
 {
     return(qt.DataType.Accept(this));
 }
Esempio n. 33
0
 internal static IEnumerable <AttributeSyntax> FindAttributes(CompilationUnitSyntax assemblyInfo, QualifiedType typeName, SemanticModel semanticModel, CancellationToken cancellationToken)
 {
     foreach (var attributeList in assemblyInfo.AttributeLists)
     {
         foreach (var candidate in attributeList.Attributes)
         {
             AttributeSyntax attribute;
             if (TryGetAttribute(candidate, typeName, semanticModel, cancellationToken, out attribute))
             {
                 yield return(attribute);
             }
         }
     }
 }
Esempio n. 34
0
        public void TryGetTargetAssemblyGetTypeWithParameterByType()
        {
            var testCode      = @"
namespace RoslynSandbox
{
    using System.Reflection;

    public class Foo
    {
        public Foo(Assembly assembly)
        {
            assembly.GetType(""System.Int32"");
        }
    }
}";
            var syntaxTree    = CSharpSyntaxTree.ParseText(testCode);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var invocation    = syntaxTree.FindInvocation("GetType");
            var method        = new QualifiedMethod(new QualifiedType(typeof(Assembly).FullName), "GetType");

            Assert.AreEqual(true, invocation.TryGetTarget(method, QualifiedParameter.Create(QualifiedType.FromType(typeof(string))), semanticModel, CancellationToken.None, out var target, out var arg));
            Assert.AreEqual("System.Reflection.Assembly.GetType(string)", target.ToString());
            Assert.AreEqual("\"System.Int32\"", arg.ToString());
        }
Esempio n. 35
0
        private static void HandleDeclaration(SyntaxNodeAnalysisContext context)
        {
            var attributeSyntax = context.Node as AttributeSyntax;

            if (attributeSyntax == null ||
                attributeSyntax.IsMissing)
            {
                return;
            }

            QualifiedType   correspondingType = null;
            AttributeSyntax xmlnsAttribute;

            if (Attribute.TryGetAttribute(attributeSyntax, KnownSymbol.XmlnsPrefixAttribute, context.SemanticModel, context.CancellationToken, out xmlnsAttribute))
            {
                correspondingType = KnownSymbol.XmlnsDefinitionAttribute;
            }

            if (xmlnsAttribute == null && Attribute.TryGetAttribute(attributeSyntax, KnownSymbol.XmlnsDefinitionAttribute, context.SemanticModel, context.CancellationToken, out xmlnsAttribute))
            {
                correspondingType = KnownSymbol.XmlnsPrefixAttribute;
            }

            if (correspondingType == null || xmlnsAttribute == null)
            {
                return;
            }

            string xmlNamespace;
            AttributeArgumentSyntax arg;

            if (!Attribute.TryGetArgumentStringValue(xmlnsAttribute, 0, context.SemanticModel, context.CancellationToken, out arg, out xmlNamespace))
            {
                return;
            }

            var compilation = xmlnsAttribute.FirstAncestorOrSelf <CompilationUnitSyntax>();

            if (compilation == null)
            {
                return;
            }

            foreach (var correspondingAttribute in Attribute.FindAttributes(compilation, correspondingType, context.SemanticModel, context.CancellationToken))
            {
                string mappedNameSpace;
                AttributeArgumentSyntax correspondingArg;
                if (Attribute.TryGetArgumentStringValue(correspondingAttribute, 0, context.SemanticModel, context.CancellationToken, out correspondingArg, out mappedNameSpace))
                {
                    if (mappedNameSpace == xmlNamespace)
                    {
                        return;
                    }
                }
            }

            var attributeName = ReferenceEquals(correspondingType, KnownSymbol.XmlnsPrefixAttribute)
                                    ? XmlnsPrefix
                                    : XmlnsDefinition;

            context.ReportDiagnostic(Diagnostic.Create(Descriptor, arg.GetLocation(), attributeName, xmlNamespace));
        }
Esempio n. 36
0
 internal QualifiedType(QualifiedType.Internal native)
     : this(__CopyValue(native))
 {
 }
Esempio n. 37
0
        private Class GetNewInterface(string name, Class @base)
        {
            var @interface = new Class
            {
                Name          = name,
                Namespace     = @base.Namespace,
                Access        = @base.Access,
                Type          = ClassType.Interface,
                OriginalClass = @base
            };

            @interface.Bases.AddRange(
                from b in @base.Bases
                where b.Class != null
                let i = GetInterface(b.Class)
                        select new BaseClassSpecifier(b)
            {
                Type = new TagType(i)
            });

            @interface.Methods.AddRange(
                from m in @base.Methods
                where !m.IsConstructor && !m.IsDestructor && !m.IsStatic && m.IsDeclared && !m.IsOperator
                select new Method(m)
            {
                Namespace = @interface, OriginalFunction = m
            });

            @interface.Properties.AddRange(
                from property in @base.Properties
                where property.IsDeclared
                select CreateInterfaceProperty(property, @interface));

            @interface.Fields.AddRange(@base.Fields);
            // avoid conflicts when potentially renaming later
            @interface.Declarations.AddRange(@base.Declarations);

            if (@interface.Bases.Count == 0)
            {
                var instance = new Property
                {
                    Namespace     = @interface,
                    Name          = Helpers.InstanceIdentifier,
                    QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.IntPtr)),
                    GetMethod     = new Method
                    {
                        SynthKind = FunctionSynthKind.InterfaceInstance,
                        Namespace = @interface
                    }
                };

                @interface.Properties.Add(instance);
            }

            @interface.Events.AddRange(@base.Events);

            var type         = new QualifiedType(new BuiltinType(PrimitiveType.IntPtr));
            var adjustmentTo = new Property
            {
                Namespace     = @interface,
                Name          = "__PointerTo" + @base.Name,
                QualifiedType = type,
                GetMethod     = new Method
                {
                    SynthKind  = FunctionSynthKind.InterfaceInstance,
                    Namespace  = @interface,
                    ReturnType = type
                }
            };

            @interface.Properties.Add(adjustmentTo);
            @base.Properties.Add(adjustmentTo);

            @base.Bases.Add(new BaseClassSpecifier {
                Type = new TagType(@interface)
            });

            interfaces.Add(@base, @interface);
            return(@interface);
        }
Esempio n. 38
0
 internal QualifiedType(QualifiedType.Internal* native)
     : this(new global::System.IntPtr(native))
 {
 }
Esempio n. 39
0
 public Expression VisitQualifiedType(QualifiedType qt)
 {
     return(qt.DataType.Accept(this));
 }
 private static Type GetUnderlyingType(QualifiedType type)
 {
     TagType tagType = type.Type as TagType;
     if (tagType != null)
         return type.Type;
     // TODO: we should normally check pointer types for const;
     // however, there's some bug, probably in the parser, that returns IsConst = false for "const Type& arg"
     // so skip the check for the time being
     PointerType pointerType = type.Type as PointerType;
     return pointerType != null ? pointerType.Pointee : type.Type;
 }
        private static (ParameterUsage, CppSharp.AST.Type) TryAddImplicitMarahalingAttributesForType(QualifiedType type, IList <CppSharp.AST.Attribute> attributes)
        {
            // currently only handle strings and arrays of strings by default
            switch (type.Type)
            {
            case PointerType pt when pt.Pointee is BuiltinType bt && bt.Type == PrimitiveType.Char:
                attributes.Add(MarshalAsLPStrAttrib);
                return(ParameterUsage.In, StringType);

            case PointerType pt when pt.Pointee is PointerType pt2 && pt2.Pointee is BuiltinType bt && bt.Type == PrimitiveType.Char:
                attributes.Add(MarshalAsLPStrArrayAttrib);
                return(ParameterUsage.In, StringArrayType);

            default:
                return(ParameterUsage.Unknown, null);
            }
        }
Esempio n. 42
0
 public static QualifiedType __CreateInstance(QualifiedType.Internal native, bool skipVTables = false)
 {
     return new QualifiedType(native, skipVTables);
 }
 public ControlTemplateCastDataContextBindingSourceNode(XElement xElement, string elementName, string controlTemplateKey, XElement contentElement, QualifiedType castType, IReadOnlyList <IBinding> bindings)
     : base(xElement, elementName, null, castType, bindings)
 {
     this.ControlTemplateKey = controlTemplateKey;
     this.ContentElement     = contentElement;
 }
Esempio n. 44
0
 public int VisitQualifiedType(QualifiedType ptr)
 {
     throw new NotImplementedException();
 }
Esempio n. 45
0
 private static global::System.IntPtr __CopyValue(QualifiedType.Internal native)
 {
     global::System.IntPtr ret = Marshal.AllocHGlobal(8);
     *(QualifiedType.Internal*) ret = native;
     return ret;
 }
Esempio n. 46
0
        private Class GetNewInterface(string name, Class @base)
        {
            var   specialization = @base as ClassTemplateSpecialization;
            Class @interface;

            if (specialization == null)
            {
                @interface = new Class();
            }
            else
            {
                Class template           = specialization.TemplatedDecl.TemplatedClass;
                Class templatedInterface = GetInterface(template);
                @interface = interfaces.FirstOrDefault(i => i.OriginalClass == @base);
                if (@interface != null)
                {
                    return(@interface);
                }
                var specializedInterface = new ClassTemplateSpecialization();
                specializedInterface.Arguments.AddRange(specialization.Arguments);
                specializedInterface.TemplatedDecl = new ClassTemplate {
                    TemplatedDecl = templatedInterface
                };
                @interface = specializedInterface;
            }
            @interface.Name          = name;
            @interface.USR           = @base.USR;
            @interface.Namespace     = @base.Namespace;
            @interface.Access        = @base.Access;
            @interface.Type          = ClassType.Interface;
            @interface.OriginalClass = @base;

            @interface.Bases.AddRange(
                from b in @base.Bases
                where b.Class != null
                let i = GetInterface(b.Class)
                        select new BaseClassSpecifier(b)
            {
                Type = new TagType(i)
            });

            @interface.Methods.AddRange(
                from m in @base.Methods
                where !m.IsConstructor && !m.IsDestructor && !m.IsStatic &&
                (m.IsGenerated || (m.IsInvalid && specialization != null)) && !m.IsOperator
                select new Method(m)
            {
                Namespace = @interface, OriginalFunction = m
            });

            @interface.Properties.AddRange(
                from property in @base.Properties
                where property.IsDeclared
                select CreateInterfaceProperty(property, @interface));

            @interface.Fields.AddRange(@base.Fields);
            // avoid conflicts when potentially renaming later
            @interface.Declarations.AddRange(@base.Declarations);

            if (@interface.Bases.Count == 0)
            {
                var instance = new Property
                {
                    Namespace     = @interface,
                    Name          = Helpers.InstanceIdentifier,
                    QualifiedType = new QualifiedType(new BuiltinType(PrimitiveType.IntPtr)),
                    GetMethod     = new Method
                    {
                        SynthKind = FunctionSynthKind.InterfaceInstance,
                        Namespace = @interface
                    }
                };

                @interface.Properties.Add(instance);

                var dispose = new Method
                {
                    Namespace  = @interface,
                    Name       = "Dispose",
                    ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Void)),
                    SynthKind  = FunctionSynthKind.InterfaceDispose,
                    Mangled    = string.Empty
                };

                @interface.Methods.Add(dispose);
            }

            @interface.Events.AddRange(@base.Events);

            var type         = new QualifiedType(new BuiltinType(PrimitiveType.IntPtr));
            var adjustmentTo = new Property
            {
                Namespace     = @interface,
                Name          = "__PointerTo" + @base.Name,
                QualifiedType = type,
                GetMethod     = new Method
                {
                    SynthKind  = FunctionSynthKind.InterfaceInstance,
                    Namespace  = @interface,
                    ReturnType = type
                }
            };

            @interface.Properties.Add(adjustmentTo);
            @base.Properties.Add(adjustmentTo);

            @base.Bases.Add(new BaseClassSpecifier {
                Type = new TagType(@interface)
            });

            interfaces.Add(@interface);
            if (@base.IsTemplate)
            {
                @interface.IsDependent = true;
                @interface.TemplateParameters.AddRange(@base.TemplateParameters);
                templatedInterfaces[@base] = @interface;
                foreach (var spec in @base.Specializations)
                {
                    @interface.Specializations.Add(
                        (ClassTemplateSpecialization)GetNewInterface(name, spec));
                }
            }
            return(@interface);
        }
Esempio n. 47
0
 private QualifiedType(QualifiedType.Internal native)
     : this(__CopyValue(native))
 {
     __ownsNativeInstance = true;
 }
Esempio n. 48
0
 public void VisitQualifiedType(QualifiedType qt)
 {
     qt.DataType.Accept(this);
 }
Esempio n. 49
0
 internal QualifiedType(QualifiedType.Internal native)
     : this(&native)
 {
 }
Esempio n. 50
0
 public ManagedArrayType(ArrayType array, TypedefType typedef)
 {
     Decayed  = new QualifiedType(array);
     Original = new QualifiedType(typedef);
 }
Esempio n. 51
0
 private static void* __CopyValue(QualifiedType.__Internal native)
 {
     var ret = Marshal.AllocHGlobal(8);
     *(QualifiedType.__Internal*) ret = native;
     return ret.ToPointer();
 }
Esempio n. 52
0
 public DataType VisitQualifiedType(QualifiedType qt)
 {
     qt.DataType = qt.DataType.Accept(this);
     return(qt);
 }
Esempio n. 53
0
 private QualifiedType(QualifiedType.Internal native, bool skipVTables = false)
     : this(__CopyValue(native), skipVTables)
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
Esempio n. 54
0
 public static void CSharpMarshalToNative(this QualifiedType type,
                                          CSharpMarshalManagedToNativePrinter printer)
 {
     (printer.Context as CSharpMarshalContext).FullType = type;
     type.Visit(printer);
 }
Esempio n. 55
0
 void QualifiedTypeName(out AstType type)
 {
     if (la.kind == 130) {
     Get();
     } else if (StartOf(4)) {
     Identifier();
     } else SynErr(246);
     type = new SimpleType(TextTokenType.Text, t.val, t.Location);
     while (la.kind == 26) {
     Get();
     Identifier();
     type = new QualifiedType(type, new Identifier (TextTokenType.Text, t.val, t.Location));
     }
 }
        public static bool IsCovariantType(QualifiedType t1, QualifiedType t2)
        {
            var comparer = new CovariantTypeComparer(t1);

            return(t2.Visit(comparer));
        }
Esempio n. 57
0
 private static QualifiedType.Internal* __CopyValue(QualifiedType.Internal native)
 {
     var ret = (QualifiedType.Internal*) Marshal.AllocHGlobal(16);
     *ret = native;
     return ret;
 }
 public CovariantTypeComparer(QualifiedType type)
 {
     currentType = type;
 }
Esempio n. 59
0
 protected QualifiedType(QualifiedType.Internal* native, bool isInternalImpl = false)
 {
     __Instance = new global::System.IntPtr(native);
 }
Esempio n. 60
0
 public static bool IsConstCharString(QualifiedType qualType)
 {
     return(IsConstCharString(qualType.Type));
 }