protected virtual IEnumerable <string> GetScriptArguments(ICSharpCode.NRefactory.CSharp.Attribute attr) { if (attr == null) { return(null); } var result = new List <string>(); foreach (var arg in attr.Arguments) { string value = ""; if (arg is PrimitiveExpression expr) { value = (string)expr.Value; } else { if (Resolver.ResolveNode(arg) is ConstantResolveResult rr && rr.ConstantValue != null) { value = rr.ConstantValue.ToString(); } } result.Add(value); } return(result); }
private void SetAttributeValueOrAddAttributeIfNotDefault( SyntaxTree syntaxTree, string attributeName, object value, object defaultValue, Expression valueExpression) { if (value == null) { return; } var attribute = syntaxTree.Children.OfType <AttributeSection>().SelectMany(x => x.Attributes) .FirstOrDefault(x => x.Type is SimpleType && ((SimpleType)x.Type).Identifier == attributeName); if (attribute != null) { attribute.Arguments.Clear(); attribute.Arguments.Add(valueExpression); } else if (!value.Equals(defaultValue)) { attribute = new Attribute { Type = new SimpleType(attributeName) }; attribute.Arguments.Add(valueExpression); var attributeSection = new AttributeSection(attribute) { AttributeTarget = "assembly" }; syntaxTree.AddChild(attributeSection, new NRefactory.Role <AttributeSection>("Member")); } }
/// <summary> /// 创建字段列表 /// </summary> /// <param name="classNode"></param> /// <param name="components"></param> private static void CreateMemberFields(TypeDeclaration classNode, ComponentItem[] components) { foreach (var item in components) { var fieldName = string.Format("m_" + item.name); var field = classNode.Descendants.OfType <FieldDeclaration>().Where(x => x.Variables.Where(y => y.Name == fieldName).Count() > 0).FirstOrDefault(); if (field != null && (field.ReturnType).ToString() != item.componentType.Name) { classNode.Members.Remove(field); field = null; } if (field == null) { field = new FieldDeclaration(); field.Modifiers = Modifiers.Private; field.ReturnType = new ICSharpCode.NRefactory.CSharp.PrimitiveType(item.componentType.FullName); field.Variables.Add(new VariableInitializer(fieldName)); var att = new ICSharpCode.NRefactory.CSharp.Attribute(); att.Type = new SimpleType("SerializeField"); field.Attributes.Add(new AttributeSection(att)); classNode.AddChild(field, Roles.TypeMemberRole); } } }
protected virtual bool ReadFileHierarchyInfo(ICSharpCode.NRefactory.CSharp.Attribute attr, string name, ResolveResult resolveResult) { if ((name == (Translator.Bridge_ASSEMBLY + ".FilesHierarchy")) || (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == (Translator.Bridge_ASSEMBLY + ".FilesHierarchyAttribute"))) { if (attr.Arguments.Count > 0) { object nameObj = this.GetAttributeArgumentValue(attr, resolveResult, 0); if (nameObj != null) { this.AssemblyInfo.OutputBy = (OutputBy)Enum.ToObject(typeof(OutputBy), nameObj); } if (attr.Arguments.Count > 1) { nameObj = this.GetAttributeArgumentValue(attr, resolveResult, 1); if (nameObj is int) { this.AssemblyInfo.StartIndexInName = (int)nameObj; } } } return(true); } return(false); }
protected virtual bool ReadModuleDependency(ICSharpCode.NRefactory.CSharp.Attribute attr, string name, ResolveResult resolveResult) { if ((name == (Translator.Bridge_ASSEMBLY + ".ModuleDependency")) || (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == (Translator.Bridge_ASSEMBLY + ".ModuleDependencyAttribute"))) { if (attr.Arguments.Count > 0) { ModuleDependency dependency = new ModuleDependency(); object nameObj = this.GetAttributeArgumentValue(attr, resolveResult, 0); if (nameObj is string) { dependency.DependencyName = nameObj.ToString(); } nameObj = this.GetAttributeArgumentValue(attr, resolveResult, 1); if (nameObj is string) { dependency.VariableName = nameObj.ToString(); } this.AssemblyInfo.Dependencies.Add(dependency); } return(true); } return(false); }
private static NamedExpression FindAttributeArgument(Attribute attribute, string argumentName) { if (attribute == null) { return(null); } return(attribute.Arguments.OfType <NamedExpression>().FirstOrDefault(expr => expr.Name == argumentName)); }
public override void VisitAttribute(ICSharpCode.NRefactory.CSharp.Attribute attribute) { base.VisitAttribute(attribute); if (stripMarshalAtts && string.Equals(attribute.Type.ToString(), "global::System.Runtime.InteropServices.MarshalAsAttribute", StringComparison.Ordinal)) { attribute.Remove(); } }
private AssemblyNameFlags GetAssemblyFlagsFromAttribute(Attribute attribute) { if (attribute.Arguments.Count == 1) { return(GetAssemblyFlagsFromExpression(attribute.Arguments.ElementAt(0))); } return(AssemblyNameFlags.PublicKey); }
protected ICSharpCode.NRefactory.CSharp.Attribute GetAttribute(String attributeType, String parameter) { var attribute = new ICSharpCode.NRefactory.CSharp.Attribute(); attribute.Type = new SimpleType(attributeType); if (parameter != null) { attribute.Arguments.Add(new PrimitiveExpression(parameter)); } return attribute; }
private T GetAttributeValue <T>(Attribute attribute, T defaultValue = default(T)) { var attributeArguments = attribute.Arguments.OfType <PrimitiveExpression>().ToArray(); if (attributeArguments.Length == 1 && attributeArguments[0].Value is T) { return((T)attributeArguments[0].Value); } return(defaultValue); }
public UnifiedElement VisitAttribute(Attribute attribute, object data) { var type = LookupType(attribute.Type); if (attribute.HasArgumentList == false) { return(UnifiedAnnotation.Create(type)); } var uArgs = attribute.Arguments.AcceptVisitorAsArgs(this, data); return(UnifiedAnnotation.Create(type, uArgs)); }
private AttributeSection BuildCodeGeneratedAttributeSection() { var attribute = new Attribute { Type = new SimpleType("global::System.CodeDom.Compiler.GeneratedCodeAttribute"), }; attribute.Arguments.Add(new PrimitiveExpression("pMixin")); attribute.Arguments.Add(new PrimitiveExpression(ToolVersion)); return(new AttributeSection(attribute)); }
protected virtual bool ReadReflectionInfo(ICSharpCode.NRefactory.CSharp.Attribute attr, string name, ResolveResult resolveResult) { if (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == Translator.Bridge_ASSEMBLY + ".ReflectableAttribute") { var config = ((AssemblyInfo)this.AssemblyInfo).ReflectionInternal; if (attr.Arguments.Count > 0) { object v = this.GetAttributeArgumentValue(attr, resolveResult, 0); if (v is bool) { config.Enabled = (bool)v; } else if (v is string) { if (string.IsNullOrEmpty(config.Filter)) { config.Filter = v.ToString(); } else { config.Filter += ";" + v.ToString(); } } else if (v is int) { IType t = this.GetAttributeArgumentType(attr, resolveResult, 0); if (t.FullName == "Bridge.TypeAccessibility") { config.TypeAccessibility = (TypeAccessibility)(int)v; } else { config.MemberAccessibility = (MemberAccessibility)(int)v; } } } else { config.Enabled = true; } return(true); } return(false); }
protected static IEnumerable <string> TypeArrayValue(Attribute attribute, string argumentName) { var argument = FindAttributeArgument(attribute, argumentName); if (argument == null) { return(new string[0]); } var array = argument.Expression as ArrayCreateExpression; if (array != null) { return(TypeArrayInitializerToArray(array)); } return(new string[0]); }
protected virtual IEnumerable <string> GetScriptArguments(ICSharpCode.NRefactory.CSharp.Attribute attr) { if (attr == null) { return(null); } var result = new List <string>(); foreach (var arg in attr.Arguments) { PrimitiveExpression expr = (PrimitiveExpression)arg; result.Add((string)expr.Value); } return(result); }
public override object VisitAttribute(ICSharpCode.NRefactory.CSharp.Attribute attribute, object data) { possibleTypeReferences.Add(attribute.Type); var t = attribute.Type.Clone(); if (t is SimpleType) { ((SimpleType)t).IdentifierToken.Name += "Attribute"; possibleTypeReferences.Add(t); } else if (t is ICSharpCode.NRefactory.CSharp.MemberType) { ((ICSharpCode.NRefactory.CSharp.MemberType)t).MemberNameToken.Name += "Attribute"; possibleTypeReferences.Add(t); } return(base.VisitAttribute(attribute, data)); }
protected virtual IType GetAttributeArgumentType(ICSharpCode.NRefactory.CSharp.Attribute attr, ResolveResult resolveResult, int index) { if (!(resolveResult is ErrorResolveResult) && (resolveResult is InvocationResolveResult result)) { var arg = result.Arguments.Skip(index).Take(1).First(); return(arg.Type); } else { var arg = attr.Arguments.Skip(index).Take(1).First(); if (arg is PrimitiveExpression primitive) { return(Resolver.ResolveNode(primitive).Type); } } return(null); }
private Guid?GetAttributeValueAsGuid(Attribute attribute) { var attributeArguments = attribute.Arguments.OfType <PrimitiveExpression>().ToArray(); if (attributeArguments.Length == 1) { var guidString = attributeArguments[0].Value as string; if (!string.IsNullOrEmpty(guidString)) { Guid guid; if (System.Guid.TryParse(guidString, out guid)) { return(guid); } } } return(null); }
private Version GetAttributeValueAsVersion(Attribute attribute) { var attributeArguments = attribute.Arguments.OfType <PrimitiveExpression>().ToArray(); if (attributeArguments.Length == 1) { var versionString = attributeArguments[0].Value as string; if (!string.IsNullOrEmpty(versionString)) { Version version; if (Version.TryParse(versionString, out version)) { return(version); } } } return(null); }
protected virtual object GetAttributeArgumentValue(ICSharpCode.NRefactory.CSharp.Attribute attr, ResolveResult resolveResult, int index) { object nameObj = null; if (!(resolveResult is ErrorResolveResult) && (resolveResult is InvocationResolveResult result)) { nameObj = result.Arguments.Skip(index).Take(1).First().ConstantValue; } else { var arg = attr.Arguments.Skip(index).Take(1).First(); if (arg is PrimitiveExpression primitive) { nameObj = primitive.Value; } } return(nameObj); }
protected virtual bool TryGetAttribute(EntityDeclaration type, string attributeName, out NRAttribute attribute) { foreach (var i in type.Attributes) { foreach (var j in i.Attributes) { if (j.Type.ToString() == attributeName) { attribute = j; return true; } // FIXME: Will not try to get the attribute via Resolver.ResolveNode() (see above): it returns a // different type, without minimum information needed to make a full NRAttribute -fzm } } attribute = default(NRAttribute); return false; }
protected virtual bool ReadModuleInfo(ICSharpCode.NRefactory.CSharp.Attribute attr, string name, ResolveResult resolveResult) { if ((name == (Translator.Bridge_ASSEMBLY + ".Module")) || (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == (Translator.Bridge_ASSEMBLY + ".ModuleAttribute"))) { if (attr.Arguments.Count > 0) { object nameObj = this.GetAttributeArgumentValue(attr, resolveResult, 0); this.AssemblyInfo.Module = nameObj != null?nameObj.ToString() : ""; } else { this.AssemblyInfo.Module = ""; } return(true); } return(false); }
protected virtual bool ReadOutputPathInfo(ICSharpCode.NRefactory.CSharp.Attribute attr, string name, ResolveResult resolveResult) { if ((name == (Translator.Bridge_ASSEMBLY + ".Output")) || (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == (Translator.Bridge_ASSEMBLY + ".OutputPathAttribute"))) { if (attr.Arguments.Count > 0) { object nameObj = this.GetAttributeArgumentValue(attr, resolveResult, 0); if (nameObj is string) { this.AssemblyInfo.Output = nameObj.ToString(); } } return(true); } return(false); }
public static ICSharpCode.NRefactory.CSharp.Attribute GenerateExportAttribute (RefactoringContext ctx, IMember member) { if (member == null) return null; var astType = ctx.CreateShortType ("MonoTouch.Foundation", "ExportAttribute"); if (astType is SimpleType) { astType = new SimpleType ("Export"); } else { astType = new MemberType (new MemberType (new SimpleType ("MonoTouch"), "Foundation"), "Export"); } var attr = new ICSharpCode.NRefactory.CSharp.Attribute { Type = astType, }; var exportAttribute = member.GetAttribute (new FullTypeName (new TopLevelTypeName ("MonoTouch.Foundation", "ExportAttribute"))); if (exportAttribute == null || exportAttribute.PositionalArguments.Count == 0) return null; attr.Arguments.Add (new PrimitiveExpression (exportAttribute.PositionalArguments.First ().ConstantValue)); return attr; }
public void VisitAttribute(Attribute attribute) { StartNode(attribute); attribute.Type.AcceptVisitor(this); if (attribute.Arguments.Count != 0 || !attribute.GetChildByRole(Roles.LPar).IsNull) { Space(policy.SpaceBeforeMethodCallParentheses); WriteCommaSeparatedListInParenthesis(attribute.Arguments, policy.SpaceWithinMethodCallParentheses); } EndNode(attribute); }
protected override IEnumerable<string> GenerateCode (List<object> includedMembers) { var generator = Options.CreateCodeGenerator (); generator.AutoIndent = false; var ctx = MDRefactoringContext.Create (Options.Document, Options.Document.Editor.Caret.Location); if (ctx == null) yield break; var builder = ctx.CreateTypeSystemAstBuilder (); foreach (IMember member in includedMembers) { var method = builder.ConvertEntity (member) as MethodDeclaration; method.Body = new BlockStatement () { new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException"))) }; var astType = ctx.CreateShortType ("MonoTouch.Foundation", "ExportAttribute"); if (astType is SimpleType) { astType = new SimpleType ("Export"); } else { astType = new MemberType (new MemberType (new SimpleType ("MonoTouch"), "Foundation"), "Export"); } var attr = new ICSharpCode.NRefactory.CSharp.Attribute { Type = astType, }; method.Modifiers &= ~Modifiers.Virtual; var exportAttribute = member.GetAttribute (new FullTypeName (new TopLevelTypeName ("MonoTouch.Foundation", "ExportAttribute"))); attr.Arguments.Add (new PrimitiveExpression (exportAttribute.PositionalArguments.First ().ConstantValue)); method.Attributes.Add (new AttributeSection { Attributes = { attr } }); yield return method.ToString (); } }
protected virtual bool ReadModuleInfo(ICSharpCode.NRefactory.CSharp.Attribute attr, string name, ResolveResult resolveResult) { if ((name == (Translator.Bridge_ASSEMBLY + ".Module")) || (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == (Translator.Bridge_ASSEMBLY + ".ModuleAttribute"))) { Module module = null; var args = ((InvocationResolveResult)resolveResult).Arguments.Select(a => a.ConstantValue).ToList(); var positionArgs = ((InvocationResolveResult)resolveResult).InitializerStatements.Select(s => new { Name = ((MemberResolveResult)((OperatorResolveResult)s).Operands[0]).Member.Name, Value = ((OperatorResolveResult)s).Operands[1].ConstantValue }).ToList(); if (args.Count == 1) { var obj = args[0]; if (obj is bool) { module = new Module((bool)obj, null); } else if (obj is string) { module = new Module(obj.ToString(), null); } else if (obj is int) { module = new Module("", (ModuleType)(int)obj, null); } else { module = new Module(null); } } else if (args.Count == 2) { var first = args[0]; var second = args[1]; if (first is string) { var mname = first; var preventName = second; module = new Module(mname != null ? mname.ToString() : "", null, (bool)preventName); } else if (second is bool) { var mtype = first; var preventName = second; module = new Module("", (ModuleType)(int)mtype, null, (bool)preventName); } else { var mtype = first; var mname = second; module = new Module(mname != null ? mname.ToString() : "", (ModuleType)(int)mtype, null); } } else if (args.Count == 3) { var mtype = args[0]; var mname = args[1]; var preventName = args[2]; module = new Module(mname != null ? mname.ToString() : "", (ModuleType)(int)mtype, null, (bool)preventName); } else { module = new Module(null); } if (positionArgs.Count > 0) { foreach (var arg in positionArgs) { if (arg.Name == "Name") { module.Name = arg.Value != null ? (string)arg.Value : ""; } else if (arg.Name == "ExportAsNamespace") { module.ExportAsNamespace = arg.Value != null ? (string)arg.Value : ""; } } } this.AssemblyInfo.Module = module; return(true); } return(false); }
protected virtual bool ReadReflectionInfo(ICSharpCode.NRefactory.CSharp.Attribute attr, string name, ResolveResult resolveResult) { if (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == Translator.Bridge_ASSEMBLY + ".ReflectableAttribute") { var config = ((AssemblyInfo)this.AssemblyInfo).ReflectionInternal; if (attr.Arguments.Count > 0) { if (attr.Arguments.Count > 1) { var list = new List <MemberAccessibility>(); for (int i = 0; i < attr.Arguments.Count; i++) { object v = this.GetAttributeArgumentValue(attr, resolveResult, i); list.Add((MemberAccessibility)(int)v); } config.MemberAccessibility = list.ToArray(); } else { object v = this.GetAttributeArgumentValue(attr, resolveResult, 0); if (v is bool) { config.Disabled = !(bool)v; } else if (v is string) { if (string.IsNullOrEmpty(config.Filter)) { config.Filter = v.ToString(); } else { config.Filter += ";" + v.ToString(); } } else if (v is int) { IType t = this.GetAttributeArgumentType(attr, resolveResult, 0); if (t.FullName == "Bridge.TypeAccessibility") { config.TypeAccessibility = (TypeAccessibility)(int)v; } else { config.MemberAccessibility = new[] { (MemberAccessibility)(int)v }; } } else if (v is int[]) { config.MemberAccessibility = ((int[])v).Cast <MemberAccessibility>().ToArray(); } } } else { config.Disabled = false; } return(true); } return(false); }
protected virtual bool ReadModuleInfo(ICSharpCode.NRefactory.CSharp.Attribute attr, string name, ResolveResult resolveResult) { if ((name == (Translator.Bridge_ASSEMBLY + ".Module")) || (resolveResult != null && resolveResult.Type != null && resolveResult.Type.FullName == (Translator.Bridge_ASSEMBLY + ".ModuleAttribute"))) { Module module = null; if (attr.Arguments.Count == 1) { var obj = this.GetAttributeArgumentValue(attr, resolveResult, 0); if (obj is bool) { module = new Module((bool)obj); } else if (obj is string) { module = new Module(obj.ToString()); } else if (obj is int) { module = new Module("", (ModuleType)(int)obj); } else { module = new Module(); } } else if (attr.Arguments.Count == 2) { var first = this.GetAttributeArgumentValue(attr, resolveResult, 0); var second = this.GetAttributeArgumentValue(attr, resolveResult, 1); if (first is string) { var mname = first; var preventName = second; module = new Module(mname != null ? mname.ToString() : "", (bool)preventName); } else if (second is bool) { var mtype = first; var preventName = second; module = new Module("", (ModuleType)(int)mtype, (bool)preventName); } else { var mtype = first; var mname = second; module = new Module(mname != null ? mname.ToString() : "", (ModuleType)(int)mtype); } } else if (attr.Arguments.Count == 3) { var mtype = this.GetAttributeArgumentValue(attr, resolveResult, 0); var mname = this.GetAttributeArgumentValue(attr, resolveResult, 1); var preventName = this.GetAttributeArgumentValue(attr, resolveResult, 2); module = new Module(mname != null ? mname.ToString() : "", (ModuleType)(int)mtype, (bool)preventName); } else { module = new Module(); } this.AssemblyInfo.Module = module; return(true); } return(false); }
void Bind(CXXRecordDecl baseDecl, CXXRecordDecl decl) { var name = decl.Name; //Console.WriteLine(name); bool isStruct = IsStructure (decl); PushType(new TypeDeclaration { Name = RemapTypeName (decl.Name), ClassType = isStruct ? ClassType.Struct : ClassType.Class, Modifiers = Modifiers.Partial | Modifiers.Public | Modifiers.Unsafe }, StringUtil.GetTypeComments(decl)); if (baseDecl != null) { foreach (var baseType in decl.Bases) { var baseName = baseType.Decl?.Name; if (baseName == null) continue; // WorkItem is a structure, with a RefCount base class, avoid that if (IsStructure(decl)) continue; // // Only a (File, MemoryBuffer, VectorBuffer) // implement that, and the Serializer class is never // surfaced as an API entry point, so we should just inline the methods // from those classes into the generated class // if (baseName == "GPUObject" || baseName == "Thread" || baseName == "Octant" || baseName == "b2Draw" || baseName == "b2ContactListener" || baseName == "btIDebugDraw" || baseName == "btMotionState") continue; if (currentType.BaseTypes.Count > 0) baseName = "I" + baseName; currentType.BaseTypes.Add(new SimpleType(RemapTypeName(baseName))); } } // Determines if this is a subclass of RefCounted (but not RefCounted itself) bool refCountedSubclass = decl.TagKind == TagDeclKind.Class && decl.QualifiedName != "Urho3D::RefCounted" && decl.IsDerivedFrom(ScanBaseTypes.UrhoRefCounted); // Same for Urho3D::Object bool objectSubclass = decl.TagKind == TagDeclKind.Class && decl.QualifiedName != "Urho3D::Object" && decl.IsDerivedFrom(ScanBaseTypes.UrhoObjectType); if (refCountedSubclass) { var nativeCtor = new ConstructorDeclaration { Modifiers = Modifiers.Public, Body = new BlockStatement(), Initializer = new ConstructorInitializer() }; nativeCtor.Parameters.Add(new ParameterDeclaration(new SimpleType("IntPtr"), "handle")); nativeCtor.Initializer.Arguments.Add(new IdentifierExpression("handle")); currentType.Members.Add(nativeCtor); // The construtor with the emtpy chain flag nativeCtor = new ConstructorDeclaration { Modifiers = Modifiers.Protected, Body = new BlockStatement(), Initializer = new ConstructorInitializer() }; nativeCtor.Parameters.Add(new ParameterDeclaration(new SimpleType("UrhoObjectFlag"), "emptyFlag")); nativeCtor.Initializer.Arguments.Add(new IdentifierExpression("emptyFlag")); currentType.Members.Add(nativeCtor); } else if (IsStructure(decl)) { var serializable = new Attribute() { Type = new SimpleType("StructLayout") }; serializable.Arguments.Add(new TypeReferenceExpression(new MemberType(new SimpleType("LayoutKind"), "Sequential"))); var attrs = new AttributeSection(); attrs.Attributes.Add(serializable); currentType.Attributes.Add(attrs); } }
public override void VisitCXXMethodDecl(CXXMethodDecl decl, VisitKind visitKind) { if (!MethodIsBindable (decl, visitKind)) return; var cmethodBuilder = new StringBuilder(); AstType pinvokeReturn, methodReturn; WrapKind returnIsWrapped; ICSharpCode.NRefactory.CSharp.ParameterModifier pinvokeMod, methodMod; LookupMarshalTypes(decl.ReturnQualType, out pinvokeReturn, out pinvokeMod, out methodReturn, out methodMod, out returnIsWrapped, isReturn: true); var methodReturn2 = methodReturn.Clone(); var propertyInfo = ScanBaseTypes.GetPropertyInfo(decl); if (propertyInfo != null) { propertyInfo.HostType = currentType; if (decl.Name.StartsWith("Get") || decl.Name.StartsWith("Is")) propertyInfo.MethodReturn = methodReturn.Clone(); } var methodName = decl.Name; if (currentTypeNames.Contains(methodName)) methodName += (uniqueMethodName++).ToString(); currentTypeNames.Add(methodName); // // PInvoke declaration + C counterpart declaration // string pinvoke_name = currentType.Name + "_" + methodName; var isConstructor = decl is CXXConstructorDecl; if (isConstructor) { pinvokeReturn = new SimpleType ("IntPtr"); // Do not bind a default constructor for Skeleton if (currentType.Name == "Skeleton") return; } var pinvoke = new MethodDeclaration { Name = pinvoke_name, ReturnType = pinvokeReturn, Modifiers = Modifiers.Extern | Modifiers.Static | Modifiers.Internal }; if (!decl.IsStatic && !isConstructor) pinvoke.Parameters.Add(new ParameterDeclaration(new SimpleType("IntPtr"), "handle")); var dllImport = new Attribute { Type = new SimpleType("DllImport") }; dllImport.Arguments.Add (new PrimitiveExpression ("mono-urho")); dllImport.Arguments.Add (new AssignmentExpression (new IdentifierExpression ("CallingConvention"), csParser.ParseExpression ("CallingConvention.Cdecl"))); pinvoke.Attributes.Add(new AttributeSection(dllImport)); // The C counterpart var cinvoke = new StringBuilder(); string marshalReturn = "{0}"; string creturnType = CleanTypeCplusplus(decl.ReturnQualType); switch (creturnType) { case "bool": creturnType = "int"; break; case "Urho3D::StringHash": creturnType = "int"; marshalReturn = "({0}).Value ()"; break; case "Urho3D::String": case "const Urho3D::String &": case "const class Urho3D::String &": creturnType = "const char *"; marshalReturn = "strdup(({0}).CString ())"; break; case "const struct Urho3D::TileMapInfo2D &": creturnType = "Urho3D::TileMapInfo2D"; break; case "const struct Urho3D::CrowdObstacleAvoidanceParams &": creturnType = "Urho3D::CrowdObstacleAvoidanceParams"; break; case "const class Urho3D::Vector3 &": case "const class Urho3D::Vector2 &": case "const class Urho3D::Vector4 &": case "const class Urho3D::IntVector2 &": case "const class Urho3D::Quaternion &": case "const class Urho3D::Plane &": case "const class Urho3D::BoundingBox &": case "const class Urho3D::Color &": case "Urho3D::Vector3": case "Urho3D::Vector2": case "Urho3D::Vector4": case "Urho3D::IntVector2": case "Urho3D::Quaternion": case "Urho3D::Plane": case "Urho3D::BoundingBox": case "Urho3D::Color": var nsIndex = creturnType.IndexOf ("Urho3D::") + "Urho3D".Length; creturnType = "Interop" + creturnType.Remove (0, nsIndex).Trim ('&', ' ') + " "; marshalReturn = "*((" + creturnType + " *) &({0}))"; break; } if (creturnType.StartsWith("SharedPtr<")) { creturnType = creturnType.ExtractGenericParameter().DropClassOrStructPrefix() + " *"; marshalReturn = "auto copy = {0};\n" + "\tauto plain = copy.Get();\n" + "\tcopy.Detach();\n" + "\tdelete copy;\n" + "\treturn plain;"; } const string methodNameSuffix = "%MethodSuffix%"; const string variantConverterMask = "%VariantConvertor%"; if (isConstructor) cmethodBuilder.Append($"DllExport void *\n{pinvoke_name}{methodNameSuffix} ("); else cmethodBuilder.Append($"DllExport {creturnType}\n{pinvoke_name}{methodNameSuffix} ("); if (decl.IsStatic) { cinvoke.Append($"{decl.Parent.Name}::{decl.Name} ("); } else if (isConstructor) { cinvoke.Append($"new {decl.Name}("); } else { cmethodBuilder.Append($"Urho3D::{decl.Parent.Name} *_target"); if (decl.Parameters.Any()) cmethodBuilder.Append(", "); cinvoke.Append($"_target->{decl.Name} ("); } // // Method declaration // MethodDeclaration method = null; ConstructorDeclaration constructor = null; if (isConstructor) { constructor = new ConstructorDeclaration { Name = RemapMemberName(decl.Parent.Name, decl.Name), Modifiers = (decl.IsStatic ? Modifiers.Static : 0) | (propertyInfo != null ? Modifiers.Private : Modifiers.Public) | (decl.Name == "ToString" ? Modifiers.Override : 0) }; constructor.Body = new BlockStatement(); } else { method = new MethodDeclaration { Name = RemapMemberName(decl.Parent.Name, decl.Name), ReturnType = methodReturn, Modifiers = (decl.IsStatic ? Modifiers.Static : 0) | (propertyInfo != null ? Modifiers.Private : Modifiers.Public) }; method.Body = new BlockStatement(); } // // Marshal from C# to C and the C support to call into C++ // var invoke = new InvocationExpression(new IdentifierExpression(pinvoke_name)); if (!decl.IsStatic && !isConstructor) invoke.Arguments.Add(new IdentifierExpression("handle")); bool first = true; int anonymousParameterNameCount = 1; int currentParamCount = -1; foreach (var param in decl.Parameters) { currentParamCount++; AstType pinvokeParameter, parameter; WrapKind wrapKind; if (!first) { cinvoke.Append(", "); cmethodBuilder.Append(", "); } else first = false; LookupMarshalTypes(param.QualType, out pinvokeParameter, out pinvokeMod, out parameter, out methodMod, out wrapKind); string paramName = param.Name; if (string.IsNullOrEmpty(paramName)) paramName = "param" + (anonymousParameterNameCount++); Expression parameterReference = new IdentifierExpression (paramName); switch (currentType.Name) { case "Input": switch (decl.Name) { case "GetMouseButtonDown": case "GetMouseButtonPress": parameter = new SimpleType ("MouseButton"); parameterReference = new CastExpression (new PrimitiveType ("int"), parameterReference); break; case "GetKeyPress": case "GetKeyDown": case "GetScancodeFromKey": case "GetKeyName": if (currentParamCount == 0 && paramName == "key") { parameter = new SimpleType ("Key"); parameterReference = new CastExpression (new PrimitiveType ("int"), parameterReference); } break; } break; case "VertexBuffer": switch (decl.Name) { case "SetSize": if (currentParamCount == 1 && paramName == "elementMask") { parameter = new SimpleType ("ElementMask"); parameterReference = new CastExpression (new PrimitiveType ("uint"), parameterReference); } break; case "GetVertexSize": if (currentParamCount == 0 && paramName == "elementMask") { parameter = new SimpleType ("ElementMask"); parameterReference = new CastExpression (new PrimitiveType ("uint"), parameterReference); } break; case "GetElementOffset": if (currentParamCount == 0 && paramName == "elementMask") { parameter = new SimpleType ("ElementMask"); parameterReference = new CastExpression (new PrimitiveType ("uint"), parameterReference); } break; } break; case "Log": switch (decl.Name) { case "Write": if (currentParamCount == 0 && paramName == "level") { parameter = new SimpleType ("LogLevel"); parameterReference = new CastExpression (new PrimitiveType ("int"), parameterReference); } break; } break; } if (constructor == null) method.Parameters.Add(new ParameterDeclaration(parameter, paramName, methodMod)); else constructor.Parameters.Add(new ParameterDeclaration(parameter, paramName, methodMod)); pinvoke.Parameters.Add(new ParameterDeclaration(pinvokeParameter, paramName, pinvokeMod)); switch (wrapKind) { case WrapKind.None: invoke.Arguments.Add(parameterReference); break; case WrapKind.HandleMember: case WrapKind.UrhoObject: var cond = new ConditionalExpression (new BinaryOperatorExpression (new CastExpression (new PrimitiveType ("object"), parameterReference), BinaryOperatorType.Equality, new PrimitiveExpression (null)), csParser.ParseExpression ("IntPtr.Zero"), csParser.ParseExpression (paramName + ".Handle")); invoke.Arguments.Add (cond); break; case WrapKind.EventHandler: invoke.Arguments.Add(parameterReference); break; case WrapKind.StringHash: invoke.Arguments.Add (csParser.ParseExpression (paramName + ".Code")); break; case WrapKind.RefBlittable: invoke.Arguments.Add (new DirectionExpression (FieldDirection.Ref, parameterReference)); break; case WrapKind.VectorSharedPtr: throw new NotImplementedException ("Vector marshaling not supported for parameters yet"); } var ctype = CleanTypeCplusplus (param.QualType); string paramInvoke = paramName; switch (ctype) { case "bool": ctype = "int"; break; case "Urho3D::Deserializer &": case "Urho3D::Serializer &": ctype = "File *"; paramInvoke = $"*{paramInvoke}"; break; case "const class Urho3D::String &": ctype = "const char *"; paramInvoke = $"Urho3D::String({paramInvoke})"; break; case "Urho3D::StringHash": ctype = "int"; paramInvoke = $"Urho3D::StringHash({paramInvoke})"; break; case "const class Urho3D::Variant &": paramInvoke = $"{variantConverterMask}({paramInvoke})"; break; } cmethodBuilder.Append($"{ctype} {paramName}"); cinvoke.Append($"{paramInvoke}"); } cinvoke.Append(")"); cmethodBuilder.Append(")\n{\n\t"); // if the type has a ctor accepting Context - add a parameterless one that will use "this(Application.CurrentContext)" if (isConstructor && decl.Parameters.Count() == 1 && decl.Parameters.ElementAt(0).QualType.ToString() == "class Urho3D::Context *") { var ctor = new ConstructorDeclaration { Modifiers = Modifiers.Public, Body = new BlockStatement(), Initializer = new ConstructorInitializer { ConstructorInitializerType = ConstructorInitializerType.This } }; ctor.Initializer.Arguments.Add(csParser.ParseExpression("Application.CurrentContext")); currentType.Members.Add(ctor); } if (method != null && methodReturn is Sharpie.Bind.Types.VoidType) { method.Body.Add(invoke); // pn ($"fprintf (stderr,\"DEBUG {creturnType} {pinvoke_name} (...)\\n\");"); cmethodBuilder.AppendLine($"{cinvoke.ToString()};"); } else { ReturnStatement ret = null; Expression returnExpression; if (!isConstructor) ret = new ReturnStatement(); switch (returnIsWrapped) { case WrapKind.HandleMember: returnExpression = new InvocationExpression (new MemberReferenceExpression (new IdentifierExpression ("Runtime"), "LookupRefCounted", methodReturn2), invoke); break; case WrapKind.UrhoObject: returnExpression = new InvocationExpression (new MemberReferenceExpression (new IdentifierExpression ("Runtime"), "LookupObject", methodReturn2), invoke); break; case WrapKind.EventHandler: returnExpression = invoke; break; case WrapKind.StringHash: returnExpression = new ObjectCreateExpression (new SimpleType ("StringHash"), invoke); break; case WrapKind.MarshalPtrToString: returnExpression = new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression("Marshal"), "PtrToStringAnsi"), invoke); break; case WrapKind.MarshalPtrToStruct: returnExpression = new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression("Marshal"), "PtrToStructure"), invoke, new TypeOfExpression(methodReturn2)); returnExpression = new CastExpression(methodReturn2.Clone(), returnExpression); break; case WrapKind.VectorSharedPtr: var cacheName = "_" + method.Name + "_cache"; var f = new FieldDeclaration () { ReturnType = method.ReturnType.Clone (), Modifiers = Modifiers.Private | (method.Modifiers & Modifiers.Static) }; f.Variables.Add (new VariableInitializer (cacheName, null)); currentType.Members.Add (f); var sharedPtrType = (methodReturn as SimpleType).TypeArguments.First ().Clone (); //TODO: check if UrhoObject var create = (sharedPtrType.ToString() == "AnimationState") ? "CreateVectorSharedPtrRefcountedProxy" : "CreateVectorSharedPtrProxy"; returnExpression = new ConditionalExpression ( new BinaryOperatorExpression (new IdentifierExpression (cacheName), BinaryOperatorType.InEquality, new PrimitiveExpression (null)), new IdentifierExpression (cacheName), new AssignmentExpression ( new IdentifierExpression (cacheName), new InvocationExpression ( new MemberReferenceExpression ( new IdentifierExpression ("Runtime"), create, sharedPtrType), invoke))); break; default: returnExpression = invoke; break; } if (ret != null) { ret.Expression = returnExpression; method.Body.Add(ret); } else { if (currentType.ClassType == ClassType.Class){ //usually, the Context is the first object user creates so let's add additional check if engine is inited if (currentType.Name == "Context") { constructor.Body.Add (new InvocationExpression (new IdentifierExpression ("CheckEngine"), null)); } bool hasBaseTypes = currentType.BaseTypes.Count != 0; if (hasBaseTypes) { constructor.Initializer = new ConstructorInitializer { ConstructorInitializerType = ConstructorInitializerType.Base, }; constructor.Initializer.Arguments.Add(csParser.ParseExpression("UrhoObjectFlag.Empty")); } var ctorAssign = new AssignmentExpression(new IdentifierExpression("handle"), returnExpression); constructor.Body.Add(new ExpressionStatement(ctorAssign)); if (hasBaseTypes) { constructor.Body.Add (new InvocationExpression (new MemberReferenceExpression (new IdentifierExpression ("Runtime"), "RegisterObject"), new ThisReferenceExpression ())); } } } var rstr = String.Format(marshalReturn, cinvoke.ToString()); CXXRecordDecl returnType; //Wrap with WeakPtr all RefCounted subclasses constructors if (isConstructor) { if (ScanBaseTypes.nameToDecl.TryGetValue(decl.Parent.QualifiedName, out returnType) && returnType.IsDerivedFrom(ScanBaseTypes.UrhoRefCounted)) rstr = $"WeakPtr<{decl.Name}>({rstr})"; } cmethodBuilder.AppendLine(!rstr.Contains("\treturn ") ? $"return {rstr};" : rstr); } cmethodBuilder.AppendLine("}\n"); var code = cmethodBuilder.ToString(); const string variantArgDef = "const class Urho3D::Variant &"; //if methods contains Variant argument -- replace it with overloads if (code.Contains(variantArgDef)) { var variantSupportedTypes = new Dictionary<string, string> { //C++ - C# types map {"const class Urho3D::Vector3 &", "Vector3"}, {"const class Urho3D::IntRect &", "IntRect"}, {"const class Urho3D::Color &", "Color"}, {"const class Urho3D::Vector2 &", "Vector2"}, {"const class Urho3D::Vector4 &", "Vector4"}, {"const class Urho3D::IntVector2 &", "IntVector2"}, {"const class Urho3D::Quaternion &", "Quaternion"}, {"int", "int"}, {"float", "float"}, {"const char *", "string"}, //TODO: Matrix, StringHash? }; var primitiveTypes = new[] { "int", "float", "string" }; pn("// Urho3D::Variant overloads begin:"); int index = 0; foreach (var item in variantSupportedTypes) { //C: p(code .Replace(variantArgDef, item.Key) .Replace(methodNameSuffix, index.ToString()) .Replace(variantConverterMask, item.Key == "const char *" ? "Urho3D::String" : string.Empty)); //methodNameSuffix to avoid error: // error C2733: second C linkage of overloaded function 'function name' not allowed. //C#: var isPrimitive = primitiveTypes.Contains(item.Value); AstType argumentType; var argumentModifier = ICSharpCode.NRefactory.CSharp.ParameterModifier.None; if (!isPrimitive) { argumentType = new SimpleType(item.Value); argumentModifier = ICSharpCode.NRefactory.CSharp.ParameterModifier.Ref; } else { argumentType = new PrimitiveType(item.Value); } var dllImportItem = (MethodDeclaration)pinvoke.Clone(); var originalEntryPointName = dllImportItem.Name; dllImportItem.Name += index; var variantParam = dllImportItem.Parameters.First(p => p.ToString().Contains(variantArgDef)); variantParam.Type = argumentType.Clone(); variantParam.ParameterModifier = argumentModifier; currentType.Members.Add(dllImportItem); var clonedMethod = (MethodDeclaration)method.Clone(); variantParam = clonedMethod.Parameters.First(p => p.ToString().Contains(variantArgDef)); variantParam.Type = argumentType.Clone(); //add 'index' to all EntryPoint invocations inside the method (no mater how complex method body is): //and 'ref' keyword for the argument clonedMethod.Body.Descendants .OfType<InvocationExpression>() .Where(ie => ie.Target is IdentifierExpression && ((IdentifierExpression)ie.Target).Identifier == originalEntryPointName) .ToList() .ForEach(ie => { if (!isPrimitive) { //non-primitive types should be marked with 'ref' keyword var argument = ie.Arguments.OfType<IdentifierExpression>().First(arg => arg.Identifier == variantParam.Name); ie.Arguments.Remove(argument); ie.Arguments.Add(new DirectionExpression(FieldDirection.Ref, argument)); } var exp = (IdentifierExpression)ie.Target; exp.Identifier += index; }); currentType.Members.Add(clonedMethod); InsertSummaryComments(clonedMethod, StringUtil.GetMethodComments(decl)); index++; } pn("// Urho3D::Variant overloads end."); } //method does not have "Variant" arguments else { //C: pn(code .Replace(methodNameSuffix, string.Empty) .Replace(variantConverterMask, string.Empty)); //C#: currentType.Members.Add(pinvoke); if (method == null) currentType.Members.Add(constructor); else { currentType.Members.Add(method); InsertSummaryComments(method, StringUtil.GetMethodComments(decl)); } } }
static void ConvertCustomAttributes(AstNode attributedNode, ICustomAttributeProvider customAttributeProvider, AttributeTarget target = AttributeTarget.None) { if (customAttributeProvider.HasCustomAttributes) { var attributes = new List<ICSharpCode.NRefactory.CSharp.Attribute>(); foreach (var customAttribute in customAttributeProvider.CustomAttributes) { var attribute = new ICSharpCode.NRefactory.CSharp.Attribute(); attribute.AddAnnotation(customAttribute); attribute.Type = ConvertType(customAttribute.AttributeType); attributes.Add(attribute); SimpleType st = attribute.Type as SimpleType; if (st != null && st.Identifier.EndsWith("Attribute", StringComparison.Ordinal)) { st.Identifier = st.Identifier.Substring(0, st.Identifier.Length - "Attribute".Length); } if(customAttribute.HasConstructorArguments) { foreach (var parameter in customAttribute.ConstructorArguments) { Expression parameterValue = ConvertArgumentValue(parameter); attribute.Arguments.Add(parameterValue); } } if (customAttribute.HasProperties) { TypeDefinition resolvedAttributeType = customAttribute.AttributeType.Resolve(); foreach (var propertyNamedArg in customAttribute.Properties) { var propertyReference = resolvedAttributeType != null ? resolvedAttributeType.Properties.FirstOrDefault(pr => pr.Name == propertyNamedArg.Name) : null; var propertyName = new IdentifierExpression(propertyNamedArg.Name).WithAnnotation(propertyReference); var argumentValue = ConvertArgumentValue(propertyNamedArg.Argument); attribute.Arguments.Add(new AssignmentExpression(propertyName, argumentValue)); } } if (customAttribute.HasFields) { TypeDefinition resolvedAttributeType = customAttribute.AttributeType.Resolve(); foreach (var fieldNamedArg in customAttribute.Fields) { var fieldReference = resolvedAttributeType != null ? resolvedAttributeType.Fields.FirstOrDefault(f => f.Name == fieldNamedArg.Name) : null; var fieldName = new IdentifierExpression(fieldNamedArg.Name).WithAnnotation(fieldReference); var argumentValue = ConvertArgumentValue(fieldNamedArg.Argument); attribute.Arguments.Add(new AssignmentExpression(fieldName, argumentValue)); } } } if (target == AttributeTarget.Module || target == AttributeTarget.Assembly) { // use separate section for each attribute foreach (var attribute in attributes) { var section = new AttributeSection(); section.AttributeTarget = target; section.Attributes.Add(attribute); attributedNode.AddChild(section, AttributedNode.AttributeRole); } } else { // use single section for all attributes var section = new AttributeSection(); section.AttributeTarget = target; section.Attributes.AddRange(attributes); attributedNode.AddChild(section, AttributedNode.AttributeRole); } } }
public JNode VisitAttribute(ICSharpCode.NRefactory.CSharp.Attribute node) { throw new NotImplementedException(); }
public static void AddNamedArgument(this ICSharpCode.NRefactory.CSharp.Attribute attribute, string name, Expression argument) { attribute.Arguments.Add(new AssignmentExpression(new IdentifierExpression(name), argument)); }
public virtual void VisitAttribute(ICSharpCode.NRefactory.CSharp.Attribute attribute) { throw new NotImplementedException(); }
public override void VisitAttribute(ICSharpCode.NRefactory.CSharp.Attribute attribute) { throw NotSupportedToConsistency(); }
public StringBuilder VisitAttribute(Attribute attribute) { throw new NotImplementedException(); }
protected virtual bool TryGetAttribute(EntityDeclaration type, string attributeName, out NRAttribute attribute) { foreach (var i in type.Attributes) { foreach (var j in i.Attributes) { if (j.Type.ToString() == attributeName) { attribute = j; return(true); } // FIXME: Will not try to get the attribute via Resolver.ResolveNode() (see above): it returns a // different type, without minimum information needed to make a full NRAttribute -fzm } } attribute = default(NRAttribute); return(false); }
static void ConvertCustomAttributes(AstNode attributedNode, ICustomAttributeProvider customAttributeProvider, string attributeTarget = null) { if (customAttributeProvider.HasCustomAttributes) { var attributes = new List<ICSharpCode.NRefactory.CSharp.Attribute>(); foreach (var customAttribute in customAttributeProvider.CustomAttributes) { if (customAttribute.AttributeType.Name == "ExtensionAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices") { // don't show the ExtensionAttribute (it's converted to the 'this' modifier) continue; } if (customAttribute.AttributeType.Name == "ParamArrayAttribute" && customAttribute.AttributeType.Namespace == "System") { // don't show the ParamArrayAttribute (it's converted to the 'params' modifier) continue; } var attribute = new ICSharpCode.NRefactory.CSharp.Attribute(); attribute.AddAnnotation(customAttribute); attribute.Type = ConvertType(customAttribute.AttributeType); attributes.Add(attribute); SimpleType st = attribute.Type as SimpleType; if (st != null && st.Identifier.EndsWith("Attribute", StringComparison.Ordinal)) { st.Identifier = st.Identifier.Substring(0, st.Identifier.Length - "Attribute".Length); } if(customAttribute.HasConstructorArguments) { foreach (var parameter in customAttribute.ConstructorArguments) { Expression parameterValue = ConvertArgumentValue(parameter); attribute.Arguments.Add(parameterValue); } } if (customAttribute.HasProperties) { TypeDefinition resolvedAttributeType = customAttribute.AttributeType.Resolve(); foreach (var propertyNamedArg in customAttribute.Properties) { var propertyReference = resolvedAttributeType != null ? resolvedAttributeType.Properties.FirstOrDefault(pr => pr.Name == propertyNamedArg.Name) : null; var propertyName = new IdentifierExpression(propertyNamedArg.Name).WithAnnotation(propertyReference); var argumentValue = ConvertArgumentValue(propertyNamedArg.Argument); attribute.Arguments.Add(new AssignmentExpression(propertyName, argumentValue)); } } if (customAttribute.HasFields) { TypeDefinition resolvedAttributeType = customAttribute.AttributeType.Resolve(); foreach (var fieldNamedArg in customAttribute.Fields) { var fieldReference = resolvedAttributeType != null ? resolvedAttributeType.Fields.FirstOrDefault(f => f.Name == fieldNamedArg.Name) : null; var fieldName = new IdentifierExpression(fieldNamedArg.Name).WithAnnotation(fieldReference); var argumentValue = ConvertArgumentValue(fieldNamedArg.Argument); attribute.Arguments.Add(new AssignmentExpression(fieldName, argumentValue)); } } } if (attributeTarget == "module" || attributeTarget == "assembly") { // use separate section for each attribute foreach (var attribute in attributes) { var section = new AttributeSection(); section.AttributeTarget = attributeTarget; section.Attributes.Add(attribute); attributedNode.AddChild(section, AttributedNode.AttributeRole); } } else if (attributes.Count > 0) { // use single section for all attributes var section = new AttributeSection(); section.AttributeTarget = attributeTarget; section.Attributes.AddRange(attributes); attributedNode.AddChild(section, AttributedNode.AttributeRole); } } }