private CodeRoot GetPrevGenOrNewGenRoot()
        {
            Class cl = new Class(controller, "Class1");

            cl.IsPartial = true;
            cl.GenericTypes.Add("T");
            AttributeSection attrs = new AttributeSection(controller);
            Attribute        attr  = new Attribute(controller);

            attr.PositionalArguments.Add("true");
            attr.Name = "Serializable";
            attrs.AddAttribute(attr);
            cl.AddAttributeSection(attrs);

            // Create another class to match to the user one.
            Class c3 = new Class(controller, "Class3");

            Namespace ns = new Namespace(controller);

            ns.Name = "ArchAngel.Tests";
            ns.AddChild(cl);
            ns.AddChild(c3);
            CodeRoot root = new CodeRoot(controller);

            root.AddChild(ns);
            return(root);
        }
Exemplo n.º 2
0
        protected CodeRoot CreateClassAndNamespace(IEnumerable <IBaseConstruct> children)
        {
            Class cl = new Class(controller, "Class1");

            foreach (IBaseConstruct child in children)
            {
                cl.AddChild(child);
            }
            cl.Index = 10;
            AttributeSection attrs = new AttributeSection(controller);

            attrs.Index = 5;
            Attribute attr = new Attribute(controller);

            attr.Index = 6;
            attr.PositionalArguments.Add("true");
            attr.Name = "Serializable";
            attrs.AddAttribute(attr);
            cl.AddAttributeSection(attrs);
            Namespace ns = new Namespace(controller);

            ns.Index = 0;
            ns.Name  = "ArchAngel.Tests";
            ns.AddChild(cl);
            CodeRoot userRoot = new CodeRoot(controller);

            userRoot.AddChild(ns);
            return(userRoot);
        }
        public static T                 add_Attribute <T>(this T attributedNode, Attribute attribute) where T : AttributedNode
        {
            var attributeSection = new AttributeSection();

            attributeSection.Attributes.Add(attribute);
            return(attributedNode.add_Attribute(attributeSection));
        }
        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"));
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Makes sure that the PHP-visible type is serializable.
        /// </summary>
        private void AddSerializibility(TypeDeclaration type, TypeDeclaration outType)
        {
            // make the type serializable
            if (!Utility.IsDecoratedByAttribute(type, "System.SerializableAttribute"))
            {
                AttributeSection section = new AttributeSection();
                section.Attributes.Add(new ICSharpCode.NRefactory.Parser.AST.Attribute("Serializable", null, null));
                outType.Attributes.Add(section);

                ConstructorDeclaration ctor = new ConstructorDeclaration(type.Name,
                                                                         ((type.Modifier & Modifier.Sealed) == Modifier.Sealed ? Modifier.Private : Modifier.Protected),
                                                                         new List <ParameterDeclarationExpression>(), null);

                ctor.Parameters.Add(
                    new ParameterDeclarationExpression(new TypeReference("System.Runtime.Serialization.SerializationInfo"), "info"));
                ctor.Parameters.Add(
                    new ParameterDeclarationExpression(new TypeReference("System.Runtime.Serialization.StreamingContext"), "context"));

                ctor.ConstructorInitializer = new ConstructorInitializer();
                ctor.ConstructorInitializer.ConstructorInitializerType = ConstructorInitializerType.Base;

                ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("info"));
                ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("context"));

                ctor.Body = new BlockStatement();

                outType.AddChild(ctor);
            }
        }
            IEnumerable <CodeAction> GetActions(Attribute attribute, AttributeSection attributeSection, FieldDeclaration fieldDeclaration)
            {
                string removeAttributeMessage = ctx.TranslateString("Remove attribute");

                yield return(new CodeAction(removeAttributeMessage, script =>
                {
                    if (attributeSection.Attributes.Count > 1)
                    {
                        var newSection = new AttributeSection();
                        newSection.AttributeTarget = attributeSection.AttributeTarget;
                        foreach (var attr in attributeSection.Attributes)
                        {
                            if (attr != attribute)
                            {
                                newSection.Attributes.Add((Attribute)attr.Clone());
                            }
                        }
                        script.Replace(attributeSection, newSection);
                    }
                    else
                    {
                        script.Remove(attributeSection);
                    }
                }));

                var makeStaticMessage = ctx.TranslateString("Make the field static");

                yield return(new CodeAction(makeStaticMessage, script =>
                {
                    var newDeclaration = (FieldDeclaration)fieldDeclaration.Clone();
                    newDeclaration.Modifiers |= Modifiers.Static;
                    script.Replace(fieldDeclaration, newDeclaration);
                }));
            }
Exemplo n.º 7
0
		/// <summary>
		/// Makes sure that the PHP-visible type is serializable.
		/// </summary>
		private void AddSerializibility(TypeDeclaration type, TypeDeclaration outType)
		{
			// make the type serializable
			if (!Utility.IsDecoratedByAttribute(type, "System.SerializableAttribute"))
			{
				AttributeSection section = new AttributeSection();
				section.Attributes.Add(new ICSharpCode.NRefactory.Parser.AST.Attribute("Serializable", null, null));
				outType.Attributes.Add(section);

				ConstructorDeclaration ctor = new ConstructorDeclaration(type.Name, 
					((type.Modifier & Modifier.Sealed) == Modifier.Sealed ? Modifier.Private : Modifier.Protected),
					new List<ParameterDeclarationExpression>(), null);

				ctor.Parameters.Add(
					new ParameterDeclarationExpression(new TypeReference("System.Runtime.Serialization.SerializationInfo"), "info"));
				ctor.Parameters.Add(
					new ParameterDeclarationExpression(new TypeReference("System.Runtime.Serialization.StreamingContext"), "context"));

				ctor.ConstructorInitializer = new ConstructorInitializer();
				ctor.ConstructorInitializer.ConstructorInitializerType = ConstructorInitializerType.Base;
					
				ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("info"));
				ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("context"));

				ctor.Body = new BlockStatement();

				outType.AddChild(ctor);
			}
		}
        public override object VisitDeclareDeclaration(DeclareDeclaration declareDeclaration, object data)
        {
            if (usings != null && !usings.ContainsKey("System.Runtime.InteropServices"))
            {
                UsingDeclaration @using = new UsingDeclaration("System.Runtime.InteropServices");
                addedUsings.Add(@using);
                base.VisitUsingDeclaration(@using, data);
            }

            MethodDeclaration method = new MethodDeclaration(declareDeclaration.Name, declareDeclaration.Modifier,
                                                             declareDeclaration.TypeReference, declareDeclaration.Parameters,
                                                             declareDeclaration.Attributes);

            if ((method.Modifier & Modifiers.Visibility) == 0)
            {
                method.Modifier |= Modifiers.Public;
            }
            method.Modifier |= Modifiers.Extern | Modifiers.Static;

            if (method.TypeReference.IsNull)
            {
                method.TypeReference = new TypeReference("System.Void");
            }

            Attribute att = new Attribute("DllImport", null, null);

            att.PositionalArguments.Add(CreateStringLiteral(declareDeclaration.Library));
            if (declareDeclaration.Alias.Length > 0)
            {
                att.NamedArguments.Add(new NamedArgumentExpression("EntryPoint", CreateStringLiteral(declareDeclaration.Alias)));
            }
            switch (declareDeclaration.Charset)
            {
            case CharsetModifier.Auto:
                att.NamedArguments.Add(new NamedArgumentExpression("CharSet",
                                                                   new FieldReferenceExpression(new IdentifierExpression("CharSet"),
                                                                                                "Auto")));
                break;

            case CharsetModifier.Unicode:
                att.NamedArguments.Add(new NamedArgumentExpression("CharSet",
                                                                   new FieldReferenceExpression(new IdentifierExpression("CharSet"),
                                                                                                "Unicode")));
                break;

            default:
                att.NamedArguments.Add(new NamedArgumentExpression("CharSet",
                                                                   new FieldReferenceExpression(new IdentifierExpression("CharSet"),
                                                                                                "Ansi")));
                break;
            }
            att.NamedArguments.Add(new NamedArgumentExpression("SetLastError", new PrimitiveExpression(true, true.ToString())));
            att.NamedArguments.Add(new NamedArgumentExpression("ExactSpelling", new PrimitiveExpression(true, true.ToString())));
            AttributeSection sec = new AttributeSection(null, null);

            sec.Attributes.Add(att);
            method.Attributes.Add(sec);
            ReplaceCurrentNode(method);
            return(base.VisitMethodDeclaration(method, data));
        }
Exemplo n.º 9
0
        public void Class()
        {
            Class cl = new Class(controller, "Class1");

            cl.IsPartial = true;
            cl.GenericTypes.Add("T");
            AttributeSection attrs = new AttributeSection(controller);
            Attribute        attr  = new Attribute(controller);

            attr.PositionalArguments.Add("true");
            attr.Name = "Serializable";
            attrs.AddAttribute(attr);
            cl.AddAttributeSection(attrs);
            Namespace ns = new Namespace(controller);

            ns.Name = "ArchAngel.Tests";
            ns.AddChild(cl);
            CodeRoot root = new CodeRoot(controller);

            root.AddChild(ns);
            CodeRootMap map = new CodeRootMap();

            map.AddCodeRoot(root, Version.User);
            map.AddCodeRoot(root, Version.NewGen);
            map.AddCodeRoot(root, Version.PrevGen);

            string result = map.GetMergedCodeRoot().ToString();

            Assert.That(result, Is.EqualTo(root.ToString()));
            Assertions.StringContains(result, "class Class1");
            Assertions.StringContains(result, "[Serializable(true)]");
            Assertions.StringContains(result, "namespace ArchAngel.Tests");
        }
        public override ActionResult ApplyActionTo(StringBuilder sb)
        {
            int startSearch = FieldToAddTo.TextRange.StartOffset;
            string text = sb.ToString();

            // Put the new Attribute just in front of the property declaration.
            int insertionPoint = text.LastIndexOf("\n", startSearch) + 1;

            AttributeSection section = new AttributeSection(AttributeToAdd.Controller);
            section.AddAttribute(AttributeToAdd);
            section.PreceedingBlankLines = -1;
            var indentLevel = InsertionHelpers.GetIndentationInFrontOf(text, startSearch);
            section.Controller.IndentLevel = indentLevel;

            string newText = Helper.StandardizeLineBreaks(section.ToString(), "\n") + "\n";

            // Calculate the Attribute's Text Range
            // The start index is the insertion point + the number of tabs in front of the attribute, +1 for the \n
            AttributeToAdd.TextRange.StartOffset = insertionPoint + indentLevel + 1;
            AttributeToAdd.TextRange.EndOffset = AttributeToAdd.TextRange.StartOffset + (newText.Trim()).Length;

            sb.Insert(insertionPoint, newText);

            FieldToAddTo.AttributeSections.Add(section);

            //return new ActionResult(insertionPoint, newText.Length, new[] { AttributeToAdd });
            return new ActionResult(AttributeToAdd.TextRange.StartOffset, newText.Length, new[] { AttributeToAdd });
        }
Exemplo n.º 11
0
        public override ActionResult ApplyActionTo(StringBuilder sb)
        {
            int    startSearch = PropertyToAddTo.TextRange.StartOffset;
            string text        = sb.ToString();

            // Put the new Attribute just in front of the property declaration.
            int insertionPoint = text.LastIndexOf("\n", startSearch) + 1;

            AttributeSection section = new AttributeSection(AttributeToAdd.Controller);

            section.AddAttribute(AttributeToAdd);
            section.PreceedingBlankLines = -1;
            var indentLevel = InsertionHelpers.GetIndentationInFrontOf(text, startSearch);

            section.Controller.IndentLevel = indentLevel;

            string newText = Helper.StandardizeLineBreaks(section.ToString(), "\n") + "\n";

            // Calculate the Attribute's Text Range
            // The start index is the insertion point + the number of tabs in front of the attribute, +1 for the \n
            AttributeToAdd.TextRange.StartOffset = insertionPoint + indentLevel + 1;
            AttributeToAdd.TextRange.EndOffset   = AttributeToAdd.TextRange.StartOffset + (newText.Trim()).Length;

            sb.Insert(insertionPoint, newText);

            PropertyToAddTo.AttributeSections.Add(section);

            //return new ActionResult(insertionPoint, newText.Length, new[] { AttributeToAdd });
            return(new ActionResult(AttributeToAdd.TextRange.StartOffset, newText.Length, new[] { AttributeToAdd }));
        }
Exemplo n.º 12
0
        public static void AddAttribute(this AttributedNode typeDeclaration, string name, Expression[] positionalArguments, params NamedArgumentExpression[] namedArguments)
        {
            var section = new AttributeSection();

            section.Attributes.Add(new ICSharpCode.NRefactory.Ast.Attribute(name, positionalArguments.ToList(), namedArguments.ToList()));

            typeDeclaration.Attributes.Add(section);
        }
Exemplo n.º 13
0
 public override void VisitAttributeSection(AttributeSection attributeSection)
 {
     base.VisitAttributeSection(attributeSection);
     if (attributeSection.Attributes.Count == 0)
     {
         attributeSection.Remove();
     }
 }
Exemplo n.º 14
0
        public void AssemblyAttributeCSharp()
        {
            string           program = @"[assembly: System.Attribute()]";
            AttributeSection decl    = ParseUtilCSharp.ParseGlobal <AttributeSection>(program);

            Assert.AreEqual(new AstLocation(1, 1), decl.StartLocation);
            Assert.AreEqual("assembly", decl.AttributeTarget);
        }
Exemplo n.º 15
0
        public void AssemblyAttributeVBNet()
        {
            string           program = @"<assembly: System.Attribute()>";
            AttributeSection decl    = ParseUtilVBNet.ParseGlobal <AttributeSection>(program);

            Assert.AreEqual(new Location(1, 1), decl.StartLocation);
            Assert.AreEqual("assembly", decl.AttributeTarget);
        }
Exemplo n.º 16
0
        public void ModuleAttributeCSharp()
        {
            string           program = @"[module: System.Attribute()]";
            AttributeSection decl    = ParseUtilCSharp.ParseGlobal <AttributeSection>(program);

            Assert.AreEqual(new AstLocation(1, 1), decl.StartLocation);
            Assert.AreEqual(AttributeTarget.Module, decl.AttributeTarget);
        }
Exemplo n.º 17
0
 public override object VisitAttributeSection(AttributeSection attributeSection, object data)
 {
     foreach (Attribute attribute in attributeSection.Attributes)
     {
         attribute.Parent = attributeSection;
     }
     return(base.VisitAttributeSection(attributeSection, data));
 }
        public void AttributeSection()
        {
            AttributeSection inter = new AttributeSection(controller);

            inter.Target = "";

            Assert.That(inter.IsTheSame(inter.Clone(), ComparisonDepth.Outer), Is.True);
        }
Exemplo n.º 19
0
 public override void VisitAttributeSection(AttributeSection attributeSection)
 {
     VisitChildrenToFormat(attributeSection, child => {
         child.AcceptVisitor(this);
         if (child.NextSibling != null && child.NextSibling.Role == Roles.RBracket) {
             ForceSpacesAfter(child, false);
         }
     });
 }
Exemplo n.º 20
0
 public void AddAttributeSection(AttributeSection sec)
 {
     sec.ParentObject = this;
     _AttributeSections.Add(sec);
     foreach (Attribute attr in sec.SingleAttributes)
     {
         _Attributes.Add(attr);
     }
 }
        public void Matching_Successful()
        {
            controller.Reorder = true;
            Class cl = new Class(controller, "Class1");

            cl.IsPartial = true;
            cl.GenericTypes.Add("T");
            Class            c2    = new Class(controller, "Class2"); // Extra class in user
            AttributeSection attrs = new AttributeSection(controller);
            Attribute        attr  = new Attribute(controller);

            attr.PositionalArguments.Add("true");
            attr.Name = "Serializable";
            attrs.AddAttribute(attr);
            cl.AddAttributeSection(attrs);
            Namespace ns = new Namespace(controller);

            ns.Name = "ArchAngel.Tests";
            ns.AddChild(cl);
            ns.AddChild(c2);
            CodeRoot root = new CodeRoot(controller);

            root.AddChild(ns);

            CodeRootMap map = new CodeRootMap();

            map.AddCodeRoot(root, Version.User);

            root = GetPrevGenOrNewGenRoot();
            map.AddCodeRoot(root, Version.PrevGen);

            root = GetPrevGenOrNewGenRoot();
            map.AddCodeRoot(root, Version.NewGen);

            bool matchResult = map.MatchConstructs("ArchAngel.Tests|Class2", "ArchAngel.Tests|Class3", "ArchAngel.Tests|Class3");

            Assert.That(matchResult, Is.True);

            string result = map.GetMergedCodeRoot().ToString();

            Assert.That(map.Diff(), Is.EqualTo(TypeOfDiff.UserChangeOnly));
            Assertions.StringContains(result, "class Class1");
            Assertions.StringContains(result, "[Serializable(true)]");
            Assertions.StringContains(result, "namespace ArchAngel.Tests");
            Assertions.StringContains(result, "Class2");
            Assertions.StringContains(result, "Class3", 0);
            int count = 0;

            foreach (CodeRootMapNode node in map.AllNodes)
            {
                if (node.IsTheSameReference(c2))
                {
                    count++;
                }
            }
            Assert.That(count, Is.EqualTo(1));
        }
Exemplo n.º 22
0
        public void ModuleAttribute()
        {
            string           program = @"[module: System.Attribute()]";
            AttributeSection decl    = ParseUtilCSharp.ParseGlobal <AttributeSection>(program);

            Assert.AreEqual(new TextLocation(1, 1), decl.StartLocation);
            Assert.AreEqual("module", decl.AttributeTarget);
            Assert.AreEqual(SyntaxTree.MemberRole, decl.Role);
        }
Exemplo n.º 23
0
		public virtual object VisitAttributeSection(AttributeSection attributeSection, object data) {
			Debug.Assert((attributeSection != null));
			Debug.Assert((attributeSection.Attributes != null));
			foreach (ICSharpCode.NRefactory.Ast.Attribute o in attributeSection.Attributes) {
				Debug.Assert(o != null);
				o.AcceptVisitor(this, data);
			}
			return null;
		}
Exemplo n.º 24
0
        public void TypeAttribute()
        {
            string           program = @"[type: System.Attribute()] class Test {}";
            TypeDeclaration  type    = ParseUtilCSharp.ParseGlobal <TypeDeclaration>(program);
            AttributeSection decl    = type.Attributes.Single();

            Assert.AreEqual(new TextLocation(1, 1), decl.StartLocation);
            Assert.AreEqual("type", decl.AttributeTarget);
        }
Exemplo n.º 25
0
        PropertyDeclaration TransformAutomaticProperties(PropertyDeclaration property)
        {
            PropertyDefinition cecilProperty = context.TypeSystem.GetCecil(property.GetSymbol() as IProperty) as PropertyDefinition;

            if (cecilProperty == null || cecilProperty.GetMethod == null)
            {
                return(null);
            }
            if (!cecilProperty.GetMethod.IsCompilerGenerated() && (cecilProperty.SetMethod?.IsCompilerGenerated() == false))
            {
                return(null);
            }
            IField fieldInfo = null;
            Match  m         = automaticPropertyPattern.Match(property);

            if (m.Success)
            {
                fieldInfo = m.Get <AstNode>("fieldReference").Single().GetSymbol() as IField;
            }
            else
            {
                Match m2 = automaticReadonlyPropertyPattern.Match(property);
                if (m2.Success)
                {
                    fieldInfo = m2.Get <AstNode>("fieldReference").Single().GetSymbol() as IField;
                }
            }
            if (fieldInfo == null)
            {
                return(null);
            }
            FieldDefinition field = context.TypeSystem.GetCecil(fieldInfo) as FieldDefinition;

            if (field.IsCompilerGenerated() && field.DeclaringType == cecilProperty.DeclaringType)
            {
                RemoveCompilerGeneratedAttribute(property.Getter.Attributes);
                RemoveCompilerGeneratedAttribute(property.Setter.Attributes);
                property.Getter.Body = null;
                property.Setter.Body = null;
            }
            // Add C# 7.3 attributes on backing field:
            var attributes = fieldInfo.Attributes
                             .Where(a => !attributeTypesToRemoveFromAutoProperties.Any(t => t == a.AttributeType.FullName))
                             .Select(context.TypeSystemAstBuilder.ConvertAttribute).ToArray();

            if (attributes.Length > 0)
            {
                var section = new AttributeSection {
                    AttributeTarget = "field"
                };
                section.Attributes.AddRange(attributes);
                property.Attributes.Add(section);
            }
            // Since the property instance is not changed, we can continue in the visitor as usual, so return null
            return(null);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Adds an attribute section to a given entity.
        /// </summary>
        /// <param name="entity">The entity to add the attribute to.</param>
        /// <param name="attr">The attribute to add.</param>
        public void AddAttribute(EntityDeclaration entity, AttributeSection attr)
        {
            var node = entity.FirstChild;

            while (node.NodeType == NodeType.Whitespace || node.Role == Roles.Attribute)
            {
                node = node.NextSibling;
            }
            InsertBefore(node, attr);
        }
Exemplo n.º 27
0
		public override IUnresolvedEntity VisitAttributeSection(AttributeSection attributeSection, object data)
		{
			// non-assembly attributes are handled by their parent entity
			if (attributeSection.AttributeTarget == "assembly") {
				ConvertAttributes(parsedFile.AssemblyAttributes, attributeSection);
			} else if (attributeSection.AttributeTarget == "module") {
				ConvertAttributes(parsedFile.ModuleAttributes, attributeSection);
			}
			return null;
		}
Exemplo n.º 28
0
 protected virtual IEnumerable <Syntax> TranslateAttributeSection(AttributeSection attributeSection, ILTranslationContext data)
 {
     foreach (var c in attributeSection.Children)
     {
         foreach (var cr in c.AcceptVisitor(this, data))
         {
             yield return(cr);
         }
     }
 }
Exemplo n.º 29
0
        public override object TrackedVisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
        {
            TypeDeclaration typeDeclaration = (TypeDeclaration)methodDeclaration.Parent;
            string          testcase        = "junit.framework.TestCase";

            if (typeDeclaration != null && ((IsDerivedFrom(typeDeclaration, testcase) &&
                                             !(typeDeclaration.Name.StartsWith("Abstract"))) || IsAllTestRunner(typeDeclaration.Name)))
            {
                if (methodDeclaration.Name == "main" || methodDeclaration.Name == "suite")
                {
                    RemoveCurrentNode();
                }

                else if (methodDeclaration.Name.StartsWith("test"))
                {
                    MethodDeclaration replaced   = methodDeclaration;
                    Attribute         attr       = new Attribute("NUnit.Framework.Test", null, null);
                    List <Attribute>  attributes = new List <Attribute>();
                    attributes.Add(attr);
                    AttributeSection testAttribute = new AttributeSection(null, attributes);
                    replaced.Attributes.Add(testAttribute);
                    AstUtil.RemoveModifierFrom(replaced, Modifiers.Static);

                    ReplaceCurrentNode(replaced);
                }
                else if (methodDeclaration.Name == "setUp" || methodDeclaration.Name == "tearDown")
                {
                    if (Mode == "DotNet")
                    {
                        MethodDeclaration replaced = methodDeclaration;
                        replaced.Modifier = Modifiers.Public;

                        string attributeName = "NUnit.Framework.SetUp";
                        if (methodDeclaration.Name == "tearDown")
                        {
                            attributeName = "NUnit.Framework.TearDown";
                        }

                        Attribute        attribute  = new Attribute(attributeName, null, null);
                        List <Attribute> attributes = new List <Attribute>();
                        attributes.Add(attribute);
                        AttributeSection attributeSection = new AttributeSection(null, attributes);
                        replaced.Attributes.Add(attributeSection);

                        ReplaceCurrentNode(replaced);
                    }
                    else if (Mode == "IKVM")
                    {
                        methodDeclaration.Modifier = Modifiers.Protected | Modifiers.Override;
                    }
                }
            }
            return(null);
        }
Exemplo n.º 30
0
        public void PrevGen_Is_Skipped_Where_No_Template_Or_User_Exist()
        {
            Class cl = new Class(controller, "Class1");

            cl.IsPartial = true;
            cl.GenericTypes.Add("T");
            Class            c2    = new Class(controller, "Class2"); // Extra class in prevgen
            AttributeSection attrs = new AttributeSection(controller);
            Attribute        attr  = new Attribute(controller);

            attr.PositionalArguments.Add("true");
            attr.Name = "Serializable";
            attrs.AddAttribute(attr);
            cl.AddAttributeSection(attrs);
            Namespace ns = new Namespace(controller);

            ns.Name = "ArchAngel.Tests";
            ns.AddChild(cl);
            ns.AddChild(c2);
            CodeRoot root = new CodeRoot(controller);

            root.AddChild(ns);

            CodeRootMap map = new CodeRootMap();

            map.AddCodeRoot(root, Version.PrevGen);

            cl           = new Class(controller, "Class1");
            cl.IsPartial = true;
            cl.GenericTypes.Add("T");
            attrs = new AttributeSection(controller);
            attr  = new Attribute(controller);
            attr.PositionalArguments.Add("true");
            attr.Name = "Serializable";
            attrs.AddAttribute(attr);
            cl.AddAttributeSection(attrs);
            ns      = new Namespace(controller);
            ns.Name = "ArchAngel.Tests";
            ns.AddChild(cl);
            root = new CodeRoot(controller);
            root.AddChild(ns);

            map.AddCodeRoot(root, Version.User);
            map.AddCodeRoot(root, Version.NewGen);

            string result = map.GetMergedCodeRoot().ToString();

            Assert.That(result, Is.EqualTo(root.ToString()));
            Assertions.StringContains(result, "class Class1");
            Assertions.StringContains(result, "[Serializable(true)]");
            Assertions.StringContains(result, "namespace ArchAngel.Tests");
            // make sure that the deleted class Class2 was not included int he merged code root.
            Assertions.StringContains(result, "Class2", 0);
        }
Exemplo n.º 31
0
        private static AttributeSection CreateAreaAttributeCode(string attributeName, string argumentName, Expression valueExpression)
        {
            NamedArgumentExpression argument = new NamedArgumentExpression(argumentName, valueExpression);
            Attribute attribute = new Attribute(attributeName, new List <Expression>(), new List <NamedArgumentExpression>());

            attribute.NamedArguments.Add(argument);
            AttributeSection attributeSection = new AttributeSection("IDontKnow", new List <Attribute>());

            attributeSection.Attributes.Add(attribute);
            return(attributeSection);
        }
Exemplo n.º 32
0
 public virtual object Visit(AttributeSection attributeSection, object data)
 {
     Debug.Assert(attributeSection != null);
     Debug.Assert(attributeSection.Attributes != null);
     foreach (ICSharpCode.NRefactory.Parser.AST.Attribute attribute in attributeSection.Attributes)
     {
         Debug.Assert(attribute != null);
         attribute.AcceptVisitor(this, data);
     }
     return(data);
 }
Exemplo n.º 33
0
        private AttributeSection CreateAttributeSection(string attributeName, List <Expression> args)
        {
            Attribute        attribute  = new Attribute(attributeName, args, null);
            List <Attribute> attributes = new List <Attribute>();

            attributes.Add(attribute);
            AttributeSection attributeSection = new AttributeSection("", attributes);

            attribute.Parent = attributeSection;
            return(attributeSection);
        }
Exemplo n.º 34
0
 public override object TrackedVisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data)
 {
     if (AstUtil.ContainsModifier(fieldDeclaration, Modifiers.Transient))
     {
         AttributeSection ats           = CreateAttributeSection("System.NonSerializedAttribute", null);
         FieldDeclaration replacedField = fieldDeclaration;
         replacedField.Attributes.Add(ats);
         ReplaceCurrentNode(replacedField);
     }
     return(base.TrackedVisitFieldDeclaration(fieldDeclaration, data));
 }
Exemplo n.º 35
0
		/// <summary>
		/// Makes the given node [EditorBrowsable(Never)].
		/// </summary>
		public static void MakeNonBrowsable(AttributedNode node)
		{
			AttributeSection section = new AttributeSection();
			ICSharpCode.NRefactory.Parser.AST.Attribute attribute =
				new ICSharpCode.NRefactory.Parser.AST.Attribute("System.ComponentModel.EditorBrowsable",
				new List<Expression>(), null);

			attribute.PositionalArguments.Add(new FieldReferenceExpression(new TypeReferenceExpression(
				"System.ComponentModel.EditorBrowsableState"), "Never"));

			section.Attributes.Add(attribute);
			node.Attributes.Add(section);
		}
Exemplo n.º 36
0
        public override void VisitAttributeSection(AttributeSection attributeSection)
        {
            if (attributeSection.AttributeTarget != "assembly")
            {
                return;
            }

            foreach (var attr in attributeSection.Attributes)
            {
                var name = attr.Type.ToString();
                var resolveResult = this.Resolver.ResolveNode(attr, null);

                var handled = //this.ReadAspect(attr, name, resolveResult, AttributeTargets.Assembly, null) ||
                              this.ReadModuleInfo(attr, name, resolveResult) ||
                              this.ReadFileNameInfo(attr, name, resolveResult) ||
                              this.ReadOutputPathInfo(attr, name, resolveResult) ||
                              this.ReadFileHierarchyInfo(attr, name, resolveResult) ||
                              this.ReadModuleDependency(attr, name, resolveResult);
            }
        }
			IEnumerable<CodeAction> GetActions(Attribute attribute, AttributeSection attributeSection, FieldDeclaration fieldDeclaration)
			{
				string removeAttributeMessage = ctx.TranslateString("Remove attribute");
				yield return new CodeAction(removeAttributeMessage, script => {
					if (attributeSection.Attributes.Count > 1) {
						var newSection = new AttributeSection();
						newSection.AttributeTarget = attributeSection.AttributeTarget;
						foreach (var attr in attributeSection.Attributes) {
							if (attr != attribute)
								newSection.Attributes.Add((Attribute)attr.Clone());
						}
						script.Replace(attributeSection, newSection);
					} else {
						script.Remove(attributeSection);
					}
				});

				var makeStaticMessage = ctx.TranslateString("Make the field static");
				yield return new CodeAction(makeStaticMessage, script => {
					var newDeclaration = (FieldDeclaration)fieldDeclaration.Clone();
					newDeclaration.Modifiers |= Modifiers.Static;
					script.Replace(fieldDeclaration, newDeclaration);
				});
			}
Exemplo n.º 38
0
        private string Generate(String propertyName, String propertyTypeName, string indent)
        {
            // Create the attribute
            AttributeSection attributeSection = new AttributeSection ();
            var attribute = GetAttribute(Constants.OBJECTIVE_C_IVAR_SHORTFORM, propertyName);
            attributeSection.Attributes.Add (attribute);

            // Create the property declaration
            PropertyDeclaration propertyDeclaration = GetPropertyDeclaration(propertyName, new SimpleType (propertyTypeName), attributeSection);

            {
                // Create the member this.GetInstanceVariable<T>
                MemberReferenceExpression memberReferenceExpression = new MemberReferenceExpression (new ThisReferenceExpression (), "GetInstanceVariable");
                memberReferenceExpression.TypeArguments.Add (new SimpleType (propertyTypeName));

                // Create the invocation with arguments
                InvocationExpression invocationExpression = new InvocationExpression (memberReferenceExpression, new List<Expression> { new PrimitiveExpression (propertyName) });

                // Wrap the invocation with a return
                ReturnStatement returnStatement = new ReturnStatement (invocationExpression);

                // Create the "get" region
                propertyDeclaration.Getter = new Accessor();
                propertyDeclaration.Getter.Body = new BlockStatement ();
                propertyDeclaration.Getter.Body.Add(returnStatement);
            }

            {
                // Create the member this.SetInstanceVariable<T>
                MemberReferenceExpression memberReferenceExpression = new MemberReferenceExpression (new ThisReferenceExpression (), "SetInstanceVariable");
                memberReferenceExpression.TypeArguments.Add (new SimpleType (propertyTypeName));

                // Create the invocation with arguments
                InvocationExpression invocationExpression = new InvocationExpression (memberReferenceExpression, new List<Expression> { new PrimitiveExpression (propertyName), new IdentifierExpression ("value") });

                // Wrap the invocation with an expression
                ExpressionStatement expressionStatement = new ExpressionStatement (invocationExpression);

                // Create the "set" region
                propertyDeclaration.Setter = new Accessor();
                propertyDeclaration.Setter.Body = new BlockStatement ();
                propertyDeclaration.Setter.Body.Add(expressionStatement);
            }

            // Return the result of the AST generation
            String generated = this.Options.OutputNode(propertyDeclaration);

            // Add ident space
            return Indent(generated, indent);
        }
Exemplo n.º 39
0
	void GlobalAttributeSection() {
		Expect(18);

#line  213 "cs.ATG" 
		Location startPos = t.Location; 
		Identifier();

#line  214 "cs.ATG" 
		if (t.val != "assembly" && t.val != "module") Error("global attribute target specifier (assembly or module) expected");
		string attributeTarget = t.val;
		List<ASTAttribute> attributes = new List<ASTAttribute>();
		ASTAttribute attribute;
		
		Expect(9);
		Attribute(
#line  219 "cs.ATG" 
out attribute);

#line  219 "cs.ATG" 
		attributes.Add(attribute); 
		while (
#line  220 "cs.ATG" 
NotFinalComma()) {
			Expect(14);
			Attribute(
#line  220 "cs.ATG" 
out attribute);

#line  220 "cs.ATG" 
			attributes.Add(attribute); 
		}
		if (la.kind == 14) {
			lexer.NextToken();
		}
		Expect(19);

#line  222 "cs.ATG" 
		AttributeSection section = new AttributeSection {
		   AttributeTarget = attributeTarget,
		   Attributes = attributes,
		   StartLocation = startPos,
		   EndLocation = t.EndLocation
		};
		compilationUnit.AddChild(section);
		
	}
Exemplo n.º 40
0
        public void VisitAttributeSection(AttributeSection attributeSection)
        {
            JsonObject visit = new JsonObject();
            visit.Comment = "VisitAttributeSection";
            if (!string.IsNullOrEmpty(attributeSection.AttributeTarget))
            {
                visit.AddJsonValue("target", new JsonElement(attributeSection.AttributeTarget));
            }
            visit.AddJsonValue("attributes", GetCommaSeparatedList(attributeSection.Attributes));

            Push(visit);
        }
Exemplo n.º 41
0
		public void VisitAttributeSection(AttributeSection attributeSection)
		{
			StartNode(attributeSection);
			WriteToken(Roles.LBracket);
			if (!string.IsNullOrEmpty(attributeSection.AttributeTarget)) {
				WriteToken(attributeSection.AttributeTarget, Roles.AttributeTargetRole);
				WriteToken(Roles.Colon);
				Space();
			}
			WriteCommaSeparatedList(attributeSection.Attributes);
			WriteToken(Roles.RBracket);
			if (attributeSection.Parent is ParameterDeclaration || attributeSection.Parent is TypeParameterDeclaration) {
				Space();
			} else {
				NewLine();
			}
			EndNode(attributeSection);
		}
Exemplo n.º 42
0
			AttributeSection ConvertAttributeSection(IEnumerable<Mono.CSharp.Attribute> optAttributes)
			{
				if (optAttributes == null)
					return null;
				var result = new AttributeSection();
				var loc = LocationsBag.GetLocations(optAttributes);
				int pos = 0;
				if (loc != null)
					result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.LBracket), Roles.LBracket);
				var first = optAttributes.FirstOrDefault();
				string target = first != null ? first.ExplicitTarget : null;
				
				if (!string.IsNullOrEmpty(target)) {
					if (loc != null && pos < loc.Count - 1) {
						result.AddChild(Identifier.Create(target, Convert(loc [pos++])), Roles.Identifier);
					} else {
						result.AddChild(Identifier.Create(target), Roles.Identifier);
					}
					if (loc != null && pos < loc.Count)
						result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Colon), Roles.Colon);
				}

				int attributeCount = 0;
				foreach (var attr in GetAttributes (optAttributes)) {
					result.AddChild(attr, Roles.Attribute);
					if (loc != null && pos + 1 < loc.Count)
						result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Comma), Roles.Comma);

					attributeCount++;
				}
				if (attributeCount == 0)
					return null;
				// Left and right bracket + commas between the attributes
				int locCount = 2 + attributeCount - 1;
				// optional comma
				if (loc != null && pos < loc.Count - 1 && loc.Count == locCount + 1)
					result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Comma), Roles.Comma);
				if (loc != null && pos < loc.Count)
					result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.RBracket), Roles.RBracket);
				return result;
			}
Exemplo n.º 43
0
		void AddAttribute(DomRegion region, IAttribute attribute, string target = "")
		{
			var view = SD.FileService.OpenFile(new FileName(region.FileName), false);
			var editor = view.GetRequiredService<ITextEditor>();
			var context = SDRefactoringContext.Create(editor.FileName, editor.Document, region.Begin, CancellationToken.None);
			var node = context.RootNode.GetNodeAt<EntityDeclaration>(region.Begin);
			var resolver = context.GetResolverStateBefore(node);
			var builder = new TypeSystemAstBuilder(resolver);
			
			using (Script script = context.StartScript()) {
				var attr = new AttributeSection();
				attr.AttributeTarget = target;
				attr.Attributes.Add(builder.ConvertAttribute(attribute));
				script.InsertBefore(node, attr);
			}
		}
Exemplo n.º 44
0
			AttributeSection ConvertAttributeSection (List<Mono.CSharp.Attribute> optAttributes)
			{
				if (optAttributes == null)
					return null;
				
				AttributeSection result = new AttributeSection ();
				var loc = LocationsBag.GetLocations (optAttributes);
				if (loc != null)
					result.AddChild (new CSharpTokenNode (Convert (loc [0]), 1), AttributeSection.Roles.LBracket);
				
				result.AttributeTarget = optAttributes.First ().ExplicitTarget;
				foreach (var attr in GetAttributes (optAttributes)) {
					result.AddChild (attr, AttributeSection.AttributeRole);
				}
				
				if (loc != null)
					result.AddChild (new CSharpTokenNode (Convert (loc [1]), 1), AttributeSection.Roles.RBracket);
				return result;
			}
Exemplo n.º 45
0
		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);
			}
		}
Exemplo n.º 46
0
	void AttributeSection(
#line  2596 "VBNET.ATG" 
out AttributeSection section) {

#line  2598 "VBNET.ATG" 
		string attributeTarget = "";List<ASTAttribute> attributes = new List<ASTAttribute>();
		ASTAttribute attribute;
		
		
		Expect(28);

#line  2602 "VBNET.ATG" 
		Location startPos = t.Location; 
		if (
#line  2603 "VBNET.ATG" 
IsLocalAttrTarget()) {
			if (la.kind == 106) {
				lexer.NextToken();

#line  2604 "VBNET.ATG" 
				attributeTarget = "event";
			} else if (la.kind == 180) {
				lexer.NextToken();

#line  2605 "VBNET.ATG" 
				attributeTarget = "return";
			} else {
				Identifier();

#line  2608 "VBNET.ATG" 
				string val = t.val.ToLower(System.Globalization.CultureInfo.InvariantCulture);
				if (val != "field"	|| val != "method" ||
					val != "module" || val != "param"  ||
					val != "property" || val != "type")
				Error("attribute target specifier (event, return, field," +
						"method, module, param, property, or type) expected");
				attributeTarget = t.val;
				
			}
			Expect(11);
		}
		Attribute(
#line  2618 "VBNET.ATG" 
out attribute);

#line  2618 "VBNET.ATG" 
		attributes.Add(attribute); 
		while (
#line  2619 "VBNET.ATG" 
NotFinalComma()) {
			Expect(12);
			Attribute(
#line  2619 "VBNET.ATG" 
out attribute);

#line  2619 "VBNET.ATG" 
			attributes.Add(attribute); 
		}
		if (la.kind == 12) {
			lexer.NextToken();
		}
		Expect(27);

#line  2623 "VBNET.ATG" 
		section = new AttributeSection {
		AttributeTarget = attributeTarget,
		Attributes = attributes,
		StartLocation = startPos,
		EndLocation = t.EndLocation
		};
		
	}
Exemplo n.º 47
0
		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);
				}
			}
		}
    /// <summary>
    /// Adds the linking attribute.
    /// </summary>
    /// <param name="contractClass">The contract class.</param>
    private void AddLinkingAttribute(Class contractClass)
    {
      Contract.Requires(contractClass != null, "contractClass must not be null.");

      var typeOfExp = new TypeOfExpression(new TypeReferenceExpression(this.InterfaceName));
      var attribute = new CustomAttribute() { Name = ContractClassFor };
      if (attribute.Arguments != null)
      {
        attribute.Arguments.Add(typeOfExp);
      }

      var section = new AttributeSection();
      if (section.AttributeCollection != null)
      {
        section.AttributeCollection.Add(attribute);
      }

      contractClass.AddAttributeSection(section);
    }
        private String GenerateProperty(IProperty property, IMethod getterMethod, IMethod setterMethod)
        {
            // Create the property declaration
            var propertyType = this.Options.CreateShortType (property.ReturnType);
            PropertyDeclaration propertyDeclaration = this.GetPropertyDeclaration (property.Name, propertyType, null);

            if (property.CanGet && getterMethod != null) {
                // Retrieve the Objective-C message in the attribute
                String message = AttributeHelper.GetAttributeValue (getterMethod, Constants.OBJECTIVE_C_MESSAGE);
                AttributeSection attributeSection = new AttributeSection ();
                if (!String.IsNullOrEmpty (message)) {
                    var attribute = this.GetAttribute (Constants.OBJECTIVE_C_MESSAGE_SHORTFORM, message);
                    attributeSection.Attributes.Add (attribute);
                }

                // Create the "get" region
                ThrowStatement throwStatement = this.GetThrowStatement (Constants.NOT_IMPLEMENTED_EXCEPTION);
                propertyDeclaration.Getter = new Accessor ();
                propertyDeclaration.Getter.Attributes.Add (attributeSection);
                propertyDeclaration.Getter.Body = new BlockStatement ();
                propertyDeclaration.Getter.Body.Add (throwStatement);
            }

            if (property.CanSet && setterMethod != null) {
                // Retrieve the Objective-C message in the attribute
                String message = AttributeHelper.GetAttributeValue (setterMethod, Constants.OBJECTIVE_C_MESSAGE);
                AttributeSection attributeSection = new AttributeSection ();
                if (!String.IsNullOrEmpty (message)) {
                    var attribute = this.GetAttribute (Constants.OBJECTIVE_C_MESSAGE_SHORTFORM, message);
                    attributeSection.Attributes.Add (attribute);
                }

                // Create the "set" region
                ThrowStatement throwStatement = this.GetThrowStatement (Constants.NOT_IMPLEMENTED_EXCEPTION);
                propertyDeclaration.Setter = new Accessor ();
                propertyDeclaration.Setter.Attributes.Add (attributeSection);
                propertyDeclaration.Setter.Body = new BlockStatement ();
                propertyDeclaration.Setter.Body.Add (throwStatement);
            }

            // Return the result of the AST generation
            return this.Options.OutputNode (propertyDeclaration);
        }
Exemplo n.º 50
0
	void GlobalAttributeSection() {
		Expect(28);

#line  2521 "VBNET.ATG" 
		Location startPos = t.Location; 
		if (la.kind == 52) {
			lexer.NextToken();
		} else if (la.kind == 141) {
			lexer.NextToken();
		} else SynErr(226);

#line  2523 "VBNET.ATG" 
		string attributeTarget = t.val != null ? t.val.ToLower(System.Globalization.CultureInfo.InvariantCulture) : null;
		List<ASTAttribute> attributes = new List<ASTAttribute>();
		ASTAttribute attribute;
		
		Expect(11);
		Attribute(
#line  2527 "VBNET.ATG" 
out attribute);

#line  2527 "VBNET.ATG" 
		attributes.Add(attribute); 
		while (
#line  2528 "VBNET.ATG" 
NotFinalComma()) {
			if (la.kind == 12) {
				lexer.NextToken();
				if (la.kind == 52) {
					lexer.NextToken();
				} else if (la.kind == 141) {
					lexer.NextToken();
				} else SynErr(227);
				Expect(11);
			}
			Attribute(
#line  2528 "VBNET.ATG" 
out attribute);

#line  2528 "VBNET.ATG" 
			attributes.Add(attribute); 
		}
		if (la.kind == 12) {
			lexer.NextToken();
		}
		Expect(27);
		EndOfStmt();

#line  2533 "VBNET.ATG" 
		AttributeSection section = new AttributeSection {
		AttributeTarget = attributeTarget,
		Attributes = attributes,
		StartLocation = startPos,
		EndLocation = t.EndLocation
		};
		compilationUnit.AddChild(section);
		
	}
        private String GenerateMethod(IMethod method)
        {
            // Retrieve the Objective-C message in the attribute
            String message = AttributeHelper.GetAttributeValue (method, Constants.OBJECTIVE_C_MESSAGE);
            AttributeSection attributeSection = new AttributeSection ();
            if (!String.IsNullOrEmpty (message)) {
                var attribute = this.GetAttribute (Constants.OBJECTIVE_C_MESSAGE_SHORTFORM, message);
                attributeSection.Attributes.Add (attribute);
            }

            // Create the method declaration
            MethodDeclaration methodDeclaration = new MethodDeclaration ();
            methodDeclaration.Name = method.Name;
            methodDeclaration.Attributes.Add (attributeSection);
            methodDeclaration.Modifiers = Modifiers.Public | Modifiers.Virtual;
            methodDeclaration.ReturnType = this.Options.CreateShortType (method.ReturnType);

            foreach (var parameter in method.Parameters) {
                ParameterDeclaration parameterDeclaration = new ParameterDeclaration (this.Options.CreateShortType (parameter.Type), parameter.Name);
                if (parameter.IsOut) {
                    parameterDeclaration.ParameterModifier |= ParameterModifier.Out;
                }
                if (parameter.IsRef) {
                    parameterDeclaration.ParameterModifier |= ParameterModifier.Ref;
                }
                methodDeclaration.Parameters.Add (parameterDeclaration);
            }

            // Create the method body
            methodDeclaration.Body = new BlockStatement ();
            ThrowStatement throwStatement = this.GetThrowStatement (Constants.NOT_IMPLEMENTED_EXCEPTION);
            methodDeclaration.Body.Add (throwStatement);

            // Return the result of the AST generation
            return this.Options.OutputNode (methodDeclaration);
        }
        protected PropertyDeclaration GetPropertyDeclaration(String name, AstType propertyType, AttributeSection attributeSection = null)
        {
            var declaration = new PropertyDeclaration();
            declaration.Name = name;
            declaration.Modifiers = Modifiers.Public | Modifiers.Virtual;
            declaration.ReturnType = propertyType;
            if (attributeSection != null) {
                declaration.Attributes.Add(attributeSection);
            }

            IDELogger.Log("BaseRefactoringDialog::GetPropertyDeclaration -- {0}", declaration.Name);

            return declaration;
        }
Exemplo n.º 53
0
		/// <summary>
		/// Creates an argfull stub for the specified implementation method.
		/// </summary>
		private MethodDeclaration CreateArgfull(MethodDeclaration template, bool skipThisParams, out bool hasThisParams)
		{
			hasThisParams = false;

			MethodDeclaration method = new MethodDeclaration(template.Name, template.Modifier,
				new TypeReference("Object"), new List<ParameterDeclarationExpression>(), new List<AttributeSection>());

			method.Body = new BlockStatement();

			Expression[] arguments = new Expression[template.Parameters.Count];

			// prepend a ScriptContext parameter and make all parameters Objects
			// (TODO: PhpReferences for ref parameters)
			method.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("ScriptContext"), "__context"));

			int arg_counter = 0;
			foreach (ParameterDeclarationExpression param in template.Parameters)
			{
				ParameterDeclarationExpression new_param =
					new ParameterDeclarationExpression(new TypeReference("Object"), param.ParameterName);

				bool optional = false;

				if (Utility.IsDecoratedByAttribute(param.Attributes, Utility.OptionalAttrType))
				{
					AttributeSection section = new AttributeSection();
					new_param.Attributes.Add(section);
					section.Attributes.Add(new ICSharpCode.NRefactory.Parser.AST.Attribute(Utility.OptionalAttrType, null, null));

					optional = true;
				}

				bool this_param = Utility.IsDecoratedByAttribute(param.Attributes, "PHP.Core.ThisAttribute");
				if (this_param) hasThisParams = true;

				if (this_param && skipThisParams)
				{
					arguments[arg_counter++] = new PrimitiveExpression(null, String.Empty);
				}
				else
				{
					// generate conversion
					arguments[arg_counter++] = Convertor.ConvertTo(
						template.Name,
						new IdentifierExpression(param.ParameterName),
						param.TypeReference,
						method.Body,
						new ReturnStatement(new PrimitiveExpression(null, String.Empty)),
						Utility.IsDecoratedByAttribute(param.Attributes, "PHP.Core.NullableAttribute") || this_param,
						optional,
						arg_counter);

					method.Parameters.Add(new_param);
				}
			}

			// invoke the template method
			InvocationExpression invocation = new InvocationExpression(new IdentifierExpression(template.Name),
				new ArrayList(arguments));

			if (template.TypeReference.SystemType == "System.Void")
			{
				method.Body.AddChild(new StatementExpression(invocation));
				method.Body.AddChild(new ReturnStatement(new PrimitiveExpression(null, String.Empty)));
			}
			else method.Body.AddChild(new ReturnStatement(invocation));

			if (!hasThisParams || skipThisParams) Utility.MakeNonBrowsable(method);
			return method;
		}
 public VBAttributeSectionPrinter(AttributeSection obj)
 {
     this.obj = obj;
 }
Exemplo n.º 55
0
			AttributeSection ConvertAttributeSection (List<Mono.CSharp.Attribute> optAttributes)
			{
				if (optAttributes == null)
					return null;
				AttributeSection result = new AttributeSection ();
				var loc = LocationsBag.GetLocations (optAttributes);
				int pos = 0;
				if (loc != null)
					result.AddChild (new CSharpTokenNode (Convert (loc [pos++]), 1), AttributeSection.Roles.LBracket);
				
				string target = optAttributes.First ().ExplicitTarget;
				
				if (!string.IsNullOrEmpty (target)) {
					if (loc != null && pos < loc.Count - 1) {
						result.AddChild (Identifier.Create (target, Convert (loc [pos++])), AttributeSection.Roles.Identifier);
					} else {
						result.AddChild (Identifier.Create (target), AttributeSection.Roles.Identifier);
					}
					if (loc != null && pos < loc.Count)
						result.AddChild (new CSharpTokenNode (Convert (loc [pos++]), 1), AttributeSection.Roles.Colon);
				}
				
				foreach (var attr in GetAttributes (optAttributes)) {
					result.AddChild (attr, AttributeSection.AttributeRole);
				}
				// optional comma
				if (loc != null && pos < loc.Count - 1 && !loc [pos].Equals (loc [pos + 1]))
					result.AddChild (new CSharpTokenNode (Convert (loc [pos++]), 1), AttributeSection.Roles.Comma);
				if (loc != null && pos < loc.Count)
					result.AddChild (new CSharpTokenNode (Convert (loc [pos++]), 1), AttributeSection.Roles.RBracket);
				return result;
			}
Exemplo n.º 56
0
		public virtual void VisitAttributeSection(AttributeSection attributeSection)
		{
			StartNode(attributeSection);
			var braceHelper = BraceHelper.LeftBracket(this, CodeBracesRangeFlags.SquareBrackets);
			if (!string.IsNullOrEmpty(attributeSection.AttributeTarget)) {
				WriteKeyword(attributeSection.AttributeTarget, Roles.Identifier);
				WriteToken(Roles.Colon, BoxedTextColor.Punctuation);
				Space();
			}
			WriteCommaSeparatedList(attributeSection.Attributes);
			braceHelper.RightBracket();
			if (attributeSection.Parent is ParameterDeclaration || attributeSection.Parent is TypeParameterDeclaration) {
				Space();
			} else {
				NewLine();
			}
			EndNode(attributeSection);
		}
		public virtual void VisitAttributeSection (AttributeSection attributeSection)
		{
			VisitChildren (attributeSection);
		}
Exemplo n.º 58
0
	void AttributeSection(
#line  288 "cs.ATG" 
out AttributeSection section) {

#line  290 "cs.ATG" 
		string attributeTarget = "";
		List<ASTAttribute> attributes = new List<ASTAttribute>();
		ASTAttribute attribute;
		
		
		Expect(18);

#line  296 "cs.ATG" 
		Location startPos = t.Location; 
		if (
#line  297 "cs.ATG" 
IsLocalAttrTarget()) {
			if (la.kind == 69) {
				lexer.NextToken();

#line  298 "cs.ATG" 
				attributeTarget = "event";
			} else if (la.kind == 101) {
				lexer.NextToken();

#line  299 "cs.ATG" 
				attributeTarget = "return";
			} else {
				Identifier();

#line  300 "cs.ATG" 
				if (t.val != "field"   && t.val != "method" &&
				  t.val != "param" &&
				  t.val != "property" && t.val != "type")
				Error("attribute target specifier (field, event, method, param, property, return or type) expected");
				attributeTarget = t.val;
				
			}
			Expect(9);
		}
		Attribute(
#line  309 "cs.ATG" 
out attribute);

#line  309 "cs.ATG" 
		attributes.Add(attribute); 
		while (
#line  310 "cs.ATG" 
NotFinalComma()) {
			Expect(14);
			Attribute(
#line  310 "cs.ATG" 
out attribute);

#line  310 "cs.ATG" 
			attributes.Add(attribute); 
		}
		if (la.kind == 14) {
			lexer.NextToken();
		}
		Expect(19);

#line  312 "cs.ATG" 
		section = new AttributeSection {
		   AttributeTarget = attributeTarget,
		   Attributes = attributes,
		   StartLocation = startPos,
		   EndLocation = t.EndLocation
		};
		
	}
Exemplo n.º 59
0
		/// <summary>
		/// Adds an attribute section to a given entity.
		/// </summary>
		/// <param name="entity">The entity to add the attribute to.</param>
		/// <param name="attr">The attribute to add.</param>
		public void AddAttribute(EntityDeclaration entity, AttributeSection attr)
		{
			var node = entity.FirstChild;
			while (node.NodeType == NodeType.Whitespace || node.Role == Roles.Attribute) {
				node = node.NextSibling;
			}
			InsertBefore(node, attr);
		}
Exemplo n.º 60
0
 public StringBuilder VisitAttributeSection(AttributeSection attributeSection, int data)
 {
     throw new SLSharpException("HLSL does not have attributes.");
 }