Exemple #1
0
        public void FindClass_BaseDerived_Base()
        {
            var foo1 = new DerivedClass1 {
                Foo = "bar"
            };
            var foo2 = new DerivedClass2 {
                Foo = "baz"
            };

            var expression1 = (Expression <Func <object> >)(() => foo1.Foo);
            var expression2 = (Expression <Func <object> >)(() => foo2.Foo);

            var(type, instance) = ClassFinder.FindClass(expression2);

            Assert.AreEqual(typeof(DerivedClass2), type);
            Assert.AreSame(foo2, instance);
        }
Exemple #2
0
        public void Complete(CompletionContext context)
        {
            ITextEditor editor      = context.Editor;
            ClassFinder classFinder = new ClassFinder(ParserService.GetParseInformation(editor.FileName),
                                                      editor.Caret.Line, editor.Caret.Column);
            int           caretPosition = editor.Caret.Offset;
            IDocumentLine line          = editor.Document.GetLine(editor.Caret.Line);
            string        lineText      = editor.Document.GetText(line.Offset, caretPosition - line.Offset);

            foreach (char c in lineText)
            {
                if (!char.IsWhiteSpace(c) && !char.IsLetterOrDigit(c))
                {
                    editor.Document.Replace(context.StartOffset, context.Length, this.Text);
                    context.EndOffset = context.StartOffset + this.Text.Length;
                    return;
                }
            }

            string indentation = lineText.Substring(0, lineText.Length - lineText.TrimStart().Length);

            editor.Document.Remove(line.Offset, caretPosition - line.Offset);

            foreach (ICompletionItemHandler handler in handlers)
            {
                if (handler.Handles(this))
                {
                    editor.Document.Insert(line.Offset, indentation);
                    handler.Insert(context, this);
                    return;
                }
            }

            CodeGenerator codeGen = ParserService.CurrentProjectContent.Language.CodeGenerator;

            string text = codeGen.GenerateCode(codeGen.GetOverridingMethod(member, classFinder), indentation);

            text = text.TrimEnd(); // remove newline from end

            editor.Document.Insert(line.Offset, text);

            int endPos = line.Offset + text.Length;

            line = editor.Document.GetLineForOffset(endPos);
            editor.JumpTo(line.LineNumber, endPos - line.Offset + 1);
        }
Exemple #3
0
        public virtual AttributedNode GetOverridingMethod(IMember baseMember, ClassFinder targetContext)
        {
            AbstractMember newMember = (AbstractMember)baseMember.Clone();

            newMember.Modifiers &= ~(ModifierEnum.Virtual | ModifierEnum.Abstract);
            newMember.Modifiers |= ModifierEnum.Override;
            // set modifiers be before calling convert so that a body is generated
            AttributedNode node = ConvertMember(newMember, targetContext);

            node.Attributes.Clear();             // don't copy over attributes

            if (!baseMember.IsAbstract)
            {
                // replace the method/property body with a call to the base method/property
                MethodDeclaration method = node as MethodDeclaration;
                if (method != null)
                {
                    method.Body.Children.Clear();
                    if (method.TypeReference.Type == "System.Void")
                    {
                        method.Body.AddChild(new ExpressionStatement(CreateForwardingMethodCall(method)));
                    }
                    else
                    {
                        method.Body.AddChild(new ReturnStatement(CreateForwardingMethodCall(method)));
                    }
                }
                PropertyDeclaration property = node as PropertyDeclaration;
                if (property != null)
                {
                    Expression field = new BaseReferenceExpression().Member(property.Name);
                    if (!property.GetRegion.Block.IsNull)
                    {
                        property.GetRegion.Block.Children.Clear();
                        property.GetRegion.Block.Return(field);
                    }
                    if (!property.SetRegion.Block.IsNull)
                    {
                        property.SetRegion.Block.Children.Clear();
                        property.SetRegion.Block.Assign(field, new IdentifierExpression("value"));
                    }
                }
            }
            return(node);
        }
        private bool TryDeclarationTypeInference(CodeEditorControl editor, string curLine)
        {
            string lineText  = curLine;
            ILexer lexer     = ParserFactory.CreateLexer(SupportedLanguage.CSharp, new System.IO.StringReader(lineText));
            Token  typeToken = lexer.NextToken();

            if (typeToken.kind == CSTokens.Question)
            {
                if (lexer.NextToken().kind == CSTokens.Identifier)
                {
                    Token t = lexer.NextToken();
                    if (t.kind == CSTokens.Assign)
                    {
                        string expr = lineText.Substring(t.col);
                        //LoggingService.Debug("DeclarationTypeInference: >" + expr + "<");
                        ResolveResult rr = ScriptControl.Parser.ProjectParser.GetResolver().Resolve(new ExpressionResult(expr),
                                                                                                    editor.ActiveViewControl.Caret.Position.Y + 1,
                                                                                                    t.col, editor.ActiveViewControl.FileName,
                                                                                                    ScriptControl.Parser.ProjectParser.GetFileContents(editor.FileName));

                        if (rr != null && rr.ResolvedType != null)
                        {
                            ClassFinder context = new ClassFinder(editor.ActiveViewControl.FileName, editor.ActiveViewControl.Caret.Position.Y, t.col);
                            if (CodeGenerator.CanUseShortTypeName(rr.ResolvedType, context))
                            {
                                CSharpAmbience.Instance.ConversionFlags = ConversionFlags.None;
                            }
                            else
                            {
                                CSharpAmbience.Instance.ConversionFlags = ConversionFlags.UseFullyQualifiedNames;
                            }
                            string typeName = CSharpAmbience.Instance.Convert(rr.ResolvedType);

                            //editor.Document.Replace(curLine.Offset + typeToken.col - 1, 1, typeName);
                            int offset = editor.ActiveViewControl.Document.GetRange(new TextRange(0, 0, 0, editor.ActiveViewControl.Caret.Position.Y)).Length;

                            editor.ActiveViewControl.Document.InsertText(typeName, offset + typeToken.col - 1, editor.ActiveViewControl.Caret.Position.Y);
                            editor.ActiveViewControl.Caret.SetPos(new TextPoint(editor.ActiveViewControl.Caret.Position.X + typeName.Length - 1, editor.ActiveViewControl.Caret.Position.Y));
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemple #5
0
        public virtual AttributedNode GetOverridingMethod(IMember baseMember, ClassFinder targetContext)
        {
            AttributedNode node = ConvertMember(baseMember, targetContext);

            node.Modifier &= ~(Modifiers.Virtual | Modifiers.Abstract);
            node.Modifier |= Modifiers.Override;

            MethodDeclaration method = node as MethodDeclaration;

            if (method != null)
            {
                method.Body.Children.Clear();
                if (method.TypeReference.SystemType == "System.Void")
                {
                    method.Body.AddChild(new ExpressionStatement(CreateForwardingMethodCall(method)));
                }
                else
                {
                    method.Body.AddChild(new ReturnStatement(CreateForwardingMethodCall(method)));
                }
            }
            PropertyDeclaration property = node as PropertyDeclaration;

            if (property != null)
            {
                Expression field = new FieldReferenceExpression(new BaseReferenceExpression(),
                                                                property.Name);
                if (!property.GetRegion.Block.IsNull)
                {
                    property.GetRegion.Block.Children.Clear();
                    property.GetRegion.Block.AddChild(new ReturnStatement(field));
                }
                if (!property.SetRegion.Block.IsNull)
                {
                    property.SetRegion.Block.Children.Clear();
                    Expression expr = new AssignmentExpression(field,
                                                               AssignmentOperatorType.Assign,
                                                               new IdentifierExpression("value"));
                    property.SetRegion.Block.AddChild(new ExpressionStatement(expr));
                }
            }
            return(node);
        }
Exemple #6
0
        public static TypeReference ConvertType(IReturnType returnType, ClassFinder context)
        {
            if (returnType == null)
            {
                return(TypeReference.Null);
            }
            if (returnType is NullReturnType)
            {
                return(TypeReference.Null);
            }

            TypeReference typeRef;

            if (IsPrimitiveType(returnType))
            {
                typeRef = new TypeReference(returnType.FullyQualifiedName, true);
            }
            else if (context != null && CanUseShortTypeName(returnType, context))
            {
                typeRef = new TypeReference(returnType.Name);
            }
            else
            {
                typeRef = new TypeReference(returnType.FullyQualifiedName);
            }
            while (returnType.IsArrayReturnType)
            {
                int[] rank = typeRef.RankSpecifier ?? new int[0];
                Array.Resize(ref rank, rank.Length + 1);
                rank[rank.Length - 1] = returnType.CastToArrayReturnType().ArrayDimensions - 1;
                typeRef.RankSpecifier = rank;
                returnType            = returnType.CastToArrayReturnType().ArrayElementType;
            }
            if (returnType.IsConstructedReturnType)
            {
                foreach (IReturnType typeArgument in returnType.CastToConstructedReturnType().TypeArguments)
                {
                    typeRef.GenericTypes.Add(ConvertType(typeArgument, context));
                }
            }
            return(typeRef);
        }
 public static AttributedNode ConvertMember(IProperty p, ClassFinder targetContext)
 {
     if (p.IsIndexer)
     {
         IndexerDeclaration md;
         md = new IndexerDeclaration(ConvertType(p.ReturnType, targetContext),
                                     ConvertParameters(p.Parameters, targetContext),
                                     ConvertModifier(p.Modifiers, targetContext),
                                     ConvertAttributes(p.Attributes, targetContext));
         md.Parameters = ConvertParameters(p.Parameters, targetContext);
         if (p.CanGet)
         {
             md.GetRegion = new PropertyGetRegion(CreateNotImplementedBlock(), null);
         }
         if (p.CanSet)
         {
             md.SetRegion = new PropertySetRegion(CreateNotImplementedBlock(), null);
         }
         return(md);
     }
     else
     {
         PropertyDeclaration md;
         md = new PropertyDeclaration(ConvertModifier(p.Modifiers, targetContext),
                                      ConvertAttributes(p.Attributes, targetContext),
                                      p.Name,
                                      ConvertParameters(p.Parameters, targetContext));
         md.TypeReference = ConvertType(p.ReturnType, targetContext);
         if (p.CanGet)
         {
             md.GetRegion          = new PropertyGetRegion(CreateNotImplementedBlock(), null);
             md.GetRegion.Modifier = ConvertModifier(p.GetterModifiers, null);
         }
         if (p.CanSet)
         {
             md.SetRegion          = new PropertySetRegion(CreateNotImplementedBlock(), null);
             md.SetRegion.Modifier = ConvertModifier(p.SetterModifiers, null);
         }
         return(md);
     }
 }
Exemple #8
0
 void ConvertAttributes(AST.AttributedNode from, AbstractEntity to)
 {
     if (from.Attributes.Count == 0)
     {
         to.Attributes = DefaultAttribute.EmptyAttributeList;
     }
     else
     {
         ICSharpCode.NRefactory.Location location = from.Attributes[0].StartLocation;
         ClassFinder context;
         if (to is IClass)
         {
             context = new ClassFinder((IClass)to, location.Line, location.Column);
         }
         else
         {
             context = new ClassFinder(to.DeclaringType, location.Line, location.Column);
         }
         to.Attributes = VisitAttributes(from.Attributes, context);
     }
 }
Exemple #9
0
        public static PropertyDeclaration ConvertMember(IProperty p, ClassFinder targetContext)
        {
            PropertyDeclaration md = new PropertyDeclaration(ConvertModifier(p.Modifiers, targetContext),
                                                             ConvertAttributes(p.Attributes, targetContext),
                                                             p.Name,
                                                             ConvertParameters(p.Parameters, targetContext));

            md.TypeReference            = ConvertType(p.ReturnType, targetContext);
            md.InterfaceImplementations = ConvertInterfaceImplementations(p.InterfaceImplementations, targetContext);
            if (p.CanGet)
            {
                md.GetRegion          = new PropertyGetRegion(p.Modifiers.HasFlag(ModifierEnum.Extern) ? null : CreateNotImplementedBlock(), null);
                md.GetRegion.Modifier = ConvertModifier(p.GetterModifiers, null);
            }
            if (p.CanSet)
            {
                md.SetRegion          = new PropertySetRegion(p.Modifiers.HasFlag(ModifierEnum.Extern) ? null : CreateNotImplementedBlock(), null);
                md.SetRegion.Modifier = ConvertModifier(p.SetterModifiers, null);
            }
            return(md);
        }
Exemple #10
0
        bool TryDeclarationTypeInference(SharpDevelopTextAreaControl editor, LineSegment curLine)
        {
            string lineText  = editor.Document.GetText(curLine.Offset, curLine.Length);
            ILexer lexer     = ParserFactory.CreateLexer(SupportedLanguage.CSharp, new System.IO.StringReader(lineText));
            Token  typeToken = lexer.NextToken();

            if (typeToken.kind == CSTokens.Question)
            {
                if (lexer.NextToken().kind == CSTokens.Identifier)
                {
                    Token t = lexer.NextToken();
                    if (t.kind == CSTokens.Assign)
                    {
                        string expr = lineText.Substring(t.col);
                        LoggingService.Debug("DeclarationTypeInference: >" + expr + "<");
                        ResolveResult rr = ParserService.Resolve(new ExpressionResult(expr),
                                                                 editor.ActiveTextAreaControl.Caret.Line + 1,
                                                                 t.col, editor.FileName,
                                                                 editor.Document.TextContent);
                        if (rr != null && rr.ResolvedType != null)
                        {
                            ClassFinder context = new ClassFinder(editor.FileName, editor.ActiveTextAreaControl.Caret.Line, t.col);
                            if (CodeGenerator.CanUseShortTypeName(rr.ResolvedType, context))
                            {
                                CSharpAmbience.Instance.ConversionFlags = ConversionFlags.None;
                            }
                            else
                            {
                                CSharpAmbience.Instance.ConversionFlags = ConversionFlags.UseFullyQualifiedNames;
                            }
                            string typeName = CSharpAmbience.Instance.Convert(rr.ResolvedType);
                            editor.Document.Replace(curLine.Offset + typeToken.col - 1, 1, typeName);
                            editor.ActiveTextAreaControl.Caret.Column += typeName.Length - 1;
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
 public static ParametrizedNode ConvertMember(IMethod m, ClassFinder targetContext)
 {
     if (m.IsConstructor)
     {
         return(new ConstructorDeclaration(m.Name,
                                           ConvertModifier(m.Modifiers, targetContext),
                                           ConvertParameters(m.Parameters, targetContext),
                                           ConvertAttributes(m.Attributes, targetContext)));
     }
     else
     {
         var methodDeclaration = new MethodDeclaration();
         methodDeclaration.Body          = CreateNotImplementedBlock();
         methodDeclaration.Templates     = ConvertTemplates(m.TypeParameters, targetContext);
         methodDeclaration.Attributes    = ConvertAttributes(m.Attributes, targetContext);
         methodDeclaration.Parameters    = ConvertParameters(m.Parameters, targetContext);
         methodDeclaration.TypeReference = ConvertType(m.ReturnType, targetContext);
         methodDeclaration.Modifier      = ConvertModifier(m.Modifiers, targetContext);
         methodDeclaration.Name          = m.Name;
         return(methodDeclaration);
     }
 }
Exemple #12
0
 public static AttributedNode ConvertMember(IMethod m, ClassFinder targetContext)
 {
     if (m.IsConstructor)
     {
         return(new ConstructorDeclaration(m.Name,
                                           ConvertModifier(m.Modifiers, targetContext),
                                           ConvertParameters(m.Parameters, targetContext),
                                           ConvertAttributes(m.Attributes, targetContext))
         {
             Body = CreateNotImplementedBlock()
         });
     }
     else if (m.Name == "#dtor")                 // TODO : maybe add IsDestructor property?
     {
         return(new DestructorDeclaration(m.Name,
                                          ConvertModifier(m.Modifiers, targetContext),
                                          ConvertAttributes(m.Attributes, targetContext))
         {
             Body = CreateNotImplementedBlock()
         });
     }
     else
     {
         return(new MethodDeclaration {
             Name = m.Name,
             Modifier = ConvertModifier(m.Modifiers, targetContext),
             TypeReference = ConvertType(m.ReturnType, targetContext),
             Parameters = ConvertParameters(m.Parameters, targetContext),
             Attributes = ConvertAttributes(m.Attributes, targetContext),
             Templates = ConvertTemplates(m.TypeParameters, targetContext),
             Body = m.Modifiers.HasFlag(ModifierEnum.Extern) ? null : CreateNotImplementedBlock(),
             IsExtensionMethod = m.IsExtensionMethod,
             InterfaceImplementations = ConvertInterfaceImplementations(m.InterfaceImplementations, targetContext)
         });
     }
 }
Exemple #13
0
        public virtual void CreateChangedEvent(IProperty property, IDocument document)
        {
            ClassFinder      targetContext = new ClassFinder(property);
            string           name          = property.Name + "Changed";
            EventDeclaration ed            = new EventDeclaration(new TypeReference("EventHandler"), name,
                                                                  ConvertModifier(property.Modifiers & (ModifierEnum.VisibilityMask | ModifierEnum.Static), targetContext)
                                                                  , null, null);

            InsertCodeAfter(property, document, ed);

            List <Expression> arguments = new List <Expression>(2);

            if (property.IsStatic)
            {
                arguments.Add(new PrimitiveExpression(null, "null"));
            }
            else
            {
                arguments.Add(new ThisReferenceExpression());
            }
            arguments.Add(new FieldReferenceExpression(new IdentifierExpression("EventArgs"), "Empty"));
            InsertCodeAtEnd(property.SetterRegion, document,
                            new RaiseEventStatement(name, arguments));
        }
        private static void RegisterDomainEntityHooks(this IServiceCollection services)
        {
            var interfaces = new[]
            {
                typeof(IBeforeCreate <>),
                typeof(IBeforeUpdate <>),
                typeof(IBeforeDelete <>),
                typeof(IAfterCreate <>),
                typeof(IAfterUpdate <>),
                typeof(IAfterDelete <>),
                typeof(IValidator <>),
                typeof(IDefaultValuesSetter <>)
            };

            foreach (var @interface in interfaces)
            {
                ClassFinder
                .SearchInAssembly(Assembly.GetExecutingAssembly())
                .ClassesThatImplementInterface(@interface)
                .ForEach(type =>
                {
                    if (type.IsGenericTypeDefinition)     // like LoggingHook<T>
                    {
                        services.AddTransient(@interface, type);
                    }
                    else
                    {
                        var interfaceType = type.GetInterfaces()
                                            .Where(i => i.GetTypeInfo().IsGenericType)
                                            .Where(i => i.GetGenericTypeDefinition() == @interface)
                                            .FirstOrDefault();
                        services.AddTransient(interfaceType, type);
                    }
                });
            }
        }
Exemple #15
0
        List <IAttribute> VisitAttributes(IList <AST.AttributeSection> attributes, ClassFinder context)
        {
            // TODO Expressions???
            List <IAttribute> result = new List <IAttribute>();

            foreach (AST.AttributeSection section in attributes)
            {
                AttributeTarget target = AttributeTarget.None;
                if (section.AttributeTarget != null && section.AttributeTarget != "")
                {
                    switch (section.AttributeTarget.ToUpperInvariant())
                    {
                    case "ASSEMBLY":
                        target = AttributeTarget.Assembly;
                        break;

                    case "FIELD":
                        target = AttributeTarget.Field;
                        break;

                    case "EVENT":
                        target = AttributeTarget.Event;
                        break;

                    case "METHOD":
                        target = AttributeTarget.Method;
                        break;

                    case "MODULE":
                        target = AttributeTarget.Module;
                        break;

                    case "PARAM":
                        target = AttributeTarget.Param;
                        break;

                    case "PROPERTY":
                        target = AttributeTarget.Property;
                        break;

                    case "RETURN":
                        target = AttributeTarget.Return;
                        break;

                    case "TYPE":
                        target = AttributeTarget.Type;
                        break;

                    default:
                        target = AttributeTarget.None;
                        break;
                    }
                }

                foreach (AST.Attribute attribute in section.Attributes)
                {
                    List <object> positionalArguments = new List <object>();
                    foreach (AST.Expression positionalArgument in attribute.PositionalArguments)
                    {
                        positionalArguments.Add(ConvertAttributeArgument(positionalArgument));
                    }
                    Dictionary <string, object> namedArguments = new Dictionary <string, object>();
                    foreach (AST.NamedArgumentExpression namedArgumentExpression in attribute.NamedArguments)
                    {
                        namedArguments.Add(namedArgumentExpression.Name, ConvertAttributeArgument(namedArgumentExpression.Expression));
                    }
                    result.Add(new DefaultAttribute(new AttributeReturnType(context, attribute.Name),
                                                    target, positionalArguments, namedArguments)
                    {
                        CompilationUnit = cu,
                        Region          = GetRegion(attribute.StartLocation, attribute.EndLocation)
                    });
                }
            }
            return(result);
        }
        /// <summary>
        /// Adds the methods implementing the <paramref name="interf"/> to the list
        /// <paramref name="nodes"/>.
        /// </summary>
        public virtual void ImplementInterface(IList <AbstractNode> nodes, IReturnType interf, bool explicitImpl, IClass targetClass)
        {
            ClassFinder   context = new ClassFinder(targetClass, targetClass.Region.BeginLine + 1, 0);
            Modifiers     implicitImplModifier = ConvertModifier(ModifierEnum.Public, context);
            Modifiers     explicitImplModifier = ConvertModifier(context.Language.ExplicitInterfaceImplementationIsPrivateScope ? ModifierEnum.None : ModifierEnum.Public, context);
            List <IEvent> targetClassEvents    = targetClass.DefaultReturnType.GetEvents();
            bool          requireAlternativeImplementation;

            foreach (IEvent e in interf.GetEvents())
            {
                if (!InterfaceMemberAlreadyImplemented(targetClassEvents, e, out requireAlternativeImplementation))
                {
                    EventDeclaration ed = ConvertMember(e, context);
                    ed.Attributes.Clear();
                    if (explicitImpl || requireAlternativeImplementation)
                    {
                        ed.InterfaceImplementations.Add(CreateInterfaceImplementation(e, context));

                        if (context.Language.RequiresAddRemoveRegionInExplicitInterfaceImplementation)
                        {
                            ed.AddRegion          = new EventAddRegion(null);
                            ed.AddRegion.Block    = CreateNotImplementedBlock();
                            ed.RemoveRegion       = new EventRemoveRegion(null);
                            ed.RemoveRegion.Block = CreateNotImplementedBlock();
                        }

                        targetClassEvents.Add(CloneAndAddExplicitImpl(e, targetClass));
                        ed.Modifier = explicitImplModifier;
                    }
                    else
                    {
                        targetClassEvents.Add(e);
                        ed.Modifier = implicitImplModifier;
                    }
                    nodes.Add(ed);
                }
            }
            List <IProperty> targetClassProperties = targetClass.DefaultReturnType.GetProperties();

            foreach (IProperty p in interf.GetProperties())
            {
                if (!InterfaceMemberAlreadyImplemented(targetClassProperties, p, out requireAlternativeImplementation))
                {
                    AttributedNode pd = ConvertMember(p, context);
                    pd.Attributes.Clear();
                    if (explicitImpl || requireAlternativeImplementation)
                    {
                        InterfaceImplementation impl = CreateInterfaceImplementation(p, context);
                        if (pd is IndexerDeclaration)
                        {
                            ((IndexerDeclaration)pd).InterfaceImplementations.Add(impl);
                        }
                        else
                        {
                            ((PropertyDeclaration)pd).InterfaceImplementations.Add(impl);
                        }
                        targetClassProperties.Add(CloneAndAddExplicitImpl(p, targetClass));
                        pd.Modifier = explicitImplModifier;
                    }
                    else
                    {
                        targetClassProperties.Add(p);
                        pd.Modifier = implicitImplModifier;
                    }
                    nodes.Add(pd);
                }
            }
            List <IMethod> targetClassMethods = targetClass.DefaultReturnType.GetMethods();

            foreach (IMethod m in interf.GetMethods())
            {
                if (!InterfaceMemberAlreadyImplemented(targetClassMethods, m, out requireAlternativeImplementation))
                {
                    MethodDeclaration md = ConvertMember(m, context) as MethodDeclaration;
                    md.Attributes.Clear();
                    if (md != null)
                    {
                        if (explicitImpl || requireAlternativeImplementation)
                        {
                            md.InterfaceImplementations.Add(CreateInterfaceImplementation(m, context));
                            targetClassMethods.Add(CloneAndAddExplicitImpl(m, targetClass));
                            md.Modifier = explicitImplModifier;
                        }
                        else
                        {
                            targetClassMethods.Add(m);
                            md.Modifier = implicitImplModifier;
                        }
                        nodes.Add(md);
                    }
                }
            }
        }
 ExpressionContext GetCreationContext()
 {
     UnGetToken();
     if (GetNextNonWhiteSpace() == '=') { // was: "= new"
         ReadNextToken();
         if (curTokenType == Ident) {     // was: "ident = new"
             int typeEnd = offset;
             ReadNextToken();
             int typeStart = -1;
             while (curTokenType == Ident) {
                 typeStart = offset + 1;
                 ReadNextToken();
                 if (curTokenType == Dot) {
                     ReadNextToken();
                 } else {
                     break;
                 }
             }
             if (typeStart >= 0) {
                 string className = text.Substring(typeStart, typeEnd - typeStart);
                 int pos = className.IndexOf('<');
                 string nonGenericClassName, genericPart;
                 int typeParameterCount = 0;
                 if (pos > 0) {
                     nonGenericClassName = className.Substring(0, pos);
                     genericPart = className.Substring(pos);
                     pos = 0;
                     do {
                         typeParameterCount += 1;
                         pos = genericPart.IndexOf(',', pos + 1);
                     } while (pos > 0);
                 } else {
                     nonGenericClassName = className;
                     genericPart = null;
                 }
                 ClassFinder finder = new ClassFinder(fileName, text, typeStart);
                 IReturnType t = finder.SearchType(nonGenericClassName, typeParameterCount);
                 IClass c = (t != null) ? t.GetUnderlyingClass() : null;
                 if (c != null) {
                     ExpressionContext context = ExpressionContext.TypeDerivingFrom(c.BaseType, true);
                     if (context.ShowEntry(c)) {
                         if (genericPart != null) {
                             DefaultClass genericClass = new DefaultClass(c.CompilationUnit, c.ClassType, c.Modifiers, c.Region, c.DeclaringType);
                             genericClass.FullyQualifiedName = c.FullyQualifiedName + genericPart;
                             genericClass.Documentation = c.Documentation;
                             context.SuggestedItem = genericClass;
                         } else {
                             context.SuggestedItem = c;
                         }
                     }
                     return context;
                 }
             }
         }
     } else {
         UnGet();
         if (ReadIdentifier(GetNextNonWhiteSpace()) == "throw") {
             return ExpressionContext.TypeDerivingFrom(HostCallback.GetCurrentProjectContent().GetClass("System.Exception", 1).BaseType, true);
         }
     }
     return ExpressionContext.ObjectCreation;
 }
        public virtual MethodDeclaration CreateOnEventMethod(IEvent e)
        {
            ClassFinder context = new ClassFinder(e);
            List <ParameterDeclarationExpression> parameters = new List <ParameterDeclarationExpression>();
            bool sender = false;

            if (e.ReturnType != null)
            {
                IMethod invoke = e.ReturnType.GetMethods().Find(delegate(IMethod m) { return(m.Name == "Invoke"); });
                if (invoke != null)
                {
                    foreach (IParameter param in invoke.Parameters)
                    {
                        parameters.Add(new ParameterDeclarationExpression(ConvertType(param.ReturnType, context), param.Name));
                    }
                    if (parameters.Count > 0 && string.Equals(parameters[0].ParameterName, "sender", StringComparison.InvariantCultureIgnoreCase))
                    {
                        sender = true;
                        parameters.RemoveAt(0);
                    }
                }
            }

            ModifierEnum modifier;

            if (e.IsStatic)
            {
                modifier = ModifierEnum.Private | ModifierEnum.Static;
            }
            else if (e.DeclaringType.IsSealed)
            {
                modifier = ModifierEnum.Protected;
            }
            else
            {
                modifier = ModifierEnum.Protected | ModifierEnum.Virtual;
            }

            MethodDeclaration method = new MethodDeclaration();

            method.Parameters    = parameters;
            method.TypeReference = new TypeReference("System.Void", true);
            method.Modifier      = ConvertModifier(modifier, context);
            method.Name          = "On" + e.Name;

            List <Expression> arguments = new List <Expression>();

            if (sender)
            {
                if (e.IsStatic)
                {
                    arguments.Add(new PrimitiveExpression(null, "null"));
                }
                else
                {
                    arguments.Add(new ThisReferenceExpression());
                }
            }
            foreach (ParameterDeclarationExpression param in parameters)
            {
                arguments.Add(new IdentifierExpression(param.ParameterName));
            }
            method.Body = new BlockStatement();
            method.Body.AddChild(new RaiseEventStatement(e.Name, arguments));

            return(method);
        }
 static InterfaceImplementation CreateInterfaceImplementation(IMember interfaceMember, ClassFinder context)
 {
     return(new InterfaceImplementation(ConvertType(interfaceMember.DeclaringTypeReference, context), interfaceMember.Name));
 }
		public override object VisitAttributeSection(ICSharpCode.NRefactory.Ast.AttributeSection attributeSection, object data)
		{
			if (GetCurrentClass() == null) {
				ClassFinder cf = new ClassFinder(new DefaultClass(cu, "DummyClass"), attributeSection.StartLocation.Line, attributeSection.StartLocation.Column);
				cu.Attributes.AddRange(VisitAttributes(new[] { attributeSection }, cf));
			}
			return null;
		}
Exemple #21
0
        public static List <AttributeSection> ConvertAttributes(IList <IAttribute> attributes, ClassFinder targetContext)
        {
            AttributeSection sec = new AttributeSection();

            foreach (IAttribute att in attributes)
            {
                sec.Attributes.Add(new ICSharpCode.NRefactory.Ast.Attribute(
                                       ConvertType(att.AttributeType, targetContext).Type,
                                       att.PositionalArguments.Select(o => (Expression) new PrimitiveExpression(o)).ToList(),
                                       att.NamedArguments.Select(p => new NamedArgumentExpression(p.Key, new PrimitiveExpression(p.Value))).ToList()
                                       ));
            }
            List <AttributeSection> resultList = new List <AttributeSection>(1);

            if (sec.Attributes.Count > 0)
            {
                resultList.Add(sec);
            }
            return(resultList);
        }
        public static List <TemplateDefinition> ConvertTemplates(IList <ITypeParameter> l, ClassFinder targetContext)
        {
            List <TemplateDefinition> o = new List <TemplateDefinition>(l.Count);

            foreach (ITypeParameter p in l)
            {
                TemplateDefinition td = new TemplateDefinition(p.Name, ConvertAttributes(p.Attributes, targetContext));
                foreach (IReturnType rt in p.Constraints)
                {
                    td.Bases.Add(ConvertType(rt, targetContext));
                }
                o.Add(td);
            }
            return(o);
        }
        internal void ExecuteIntroduceMethod(UnknownMethodResolveResult rr, Ast.Expression invocationExpr, ITextEditor editor, bool isNew, object result)
        {
            IClass targetClass = IsEqualClass(rr.CallingClass, rr.Target.GetUnderlyingClass()) ? rr.CallingClass
                                : rr.Target.GetUnderlyingClass();

            CodeGenerator gen      = targetClass.ProjectContent.Language.CodeGenerator;
            IAmbience     ambience = targetClass.ProjectContent.Language.GetAmbience();

            ClassFinder finder = new ClassFinder(rr.CallingMember);

            ModifierEnum modifiers = ModifierEnum.None;

            bool isExtension = !targetClass.IsUserCode();

            if (IsEqualClass(rr.CallingClass, targetClass))
            {
                if (rr.CallingMember != null)
                {
                    modifiers |= (rr.CallingMember.Modifiers & ModifierEnum.Static);
                }
            }
            else
            {
                if (isExtension)
                {
                    if (isNew)
                    {
                        targetClass = rr.CallingClass;
                    }
                    else
                    {
                        targetClass = result as IClass;
                    }
                }
                // exclude in Unit Test mode
                if (WorkbenchSingleton.Workbench != null)
                {
                    editor = (FileService.OpenFile(targetClass.CompilationUnit.FileName) as ITextEditorProvider).TextEditor;
                }
                if (targetClass.ClassType != ClassType.Interface)
                {
                    modifiers |= ModifierEnum.Public;
                }
                if (rr.IsStaticContext)
                {
                    modifiers |= ModifierEnum.Static;
                }
            }

            NRefactoryResolver resolver = Extensions.CreateResolverForContext(targetClass.ProjectContent.Language, editor);

            IReturnType type = resolver.GetExpectedTypeFromContext(invocationExpr);

            Ast.TypeReference typeRef = CodeGenerator.ConvertType(type, finder);

            if (typeRef.IsNull)
            {
                if (invocationExpr.Parent is Ast.ExpressionStatement)
                {
                    typeRef = new Ast.TypeReference("void", true);
                }
                else
                {
                    typeRef = new Ast.TypeReference("object", true);
                }
            }

            Ast.MethodDeclaration method = new Ast.MethodDeclaration {
                Name          = rr.CallName,
                Modifier      = CodeGenerator.ConvertModifier(modifiers, finder),
                TypeReference = typeRef,
                Parameters    = CreateParameters(rr, finder, invocationExpr as Ast.InvocationExpression).ToList(),
            };

            if (targetClass.ClassType != ClassType.Interface)
            {
                method.Body = CodeGenerator.CreateNotImplementedBlock();
            }

            RefactoringDocumentAdapter documentWrapper = new RefactoringDocumentAdapter(editor.Document);

            if (isExtension)
            {
                method.Parameters.Insert(0, new Ast.ParameterDeclarationExpression(CodeGenerator.ConvertType(rr.Target, finder), "thisInstance"));
                method.IsExtensionMethod = true;
                method.Modifier         |= Ast.Modifiers.Static;
            }

            if (isNew)
            {
                Ast.TypeDeclaration newType = new Ast.TypeDeclaration(isExtension ? Ast.Modifiers.Static : Ast.Modifiers.None, null);
                newType.Name = result as string;
                newType.AddChild(method);
                gen.InsertCodeAfter(targetClass, documentWrapper, newType);
            }
            else
            {
                if (IsEqualClass(rr.CallingClass, targetClass))
                {
                    gen.InsertCodeAfter(rr.CallingMember, documentWrapper, method);
                }
                else
                {
                    gen.InsertCodeAtEnd(targetClass.BodyRegion, documentWrapper, method);
                }
            }

            if (targetClass.ClassType == ClassType.Interface)
            {
                return;
            }

            ParseInformation info = ParserService.ParseFile(targetClass.CompilationUnit.FileName);

            if (info != null)
            {
                IMember newMember;

                if (isNew)
                {
                    targetClass = info.CompilationUnit.Classes.FirstOrDefault(c => c.DotNetName == c.Namespace + "." + (result as string));
                }
                else
                {
                    targetClass = info.CompilationUnit.Classes.Flatten(c => c.InnerClasses).FirstOrDefault(c => c.DotNetName == targetClass.DotNetName);
                }

                if (targetClass == null)
                {
                    return;
                }

                if (IsEqualClass(rr.CallingClass, targetClass))
                {
                    newMember = targetClass.GetInnermostMember(editor.Caret.Line, editor.Caret.Column);
                    newMember = targetClass.AllMembers
                                .OrderBy(m => m.BodyRegion.BeginLine)
                                .ThenBy(m2 => m2.BodyRegion.BeginColumn)
                                .First(m3 => m3.BodyRegion.BeginLine > newMember.BodyRegion.BeginLine);
                }
                else
                {
                    newMember = targetClass.Methods.Last();
                }

                IDocumentLine line         = editor.Document.GetLine(newMember.BodyRegion.BeginLine + 2);
                int           indentLength = DocumentUtilitites.GetWhitespaceAfter(editor.Document, line.Offset).Length;
                editor.Select(line.Offset + indentLength, "throw new NotImplementedException();".Length);
            }
        }
        public static List <ParameterDeclarationExpression> ConvertParameters(IList <IParameter> parameters, ClassFinder targetContext)
        {
            List <ParameterDeclarationExpression> l = new List <ParameterDeclarationExpression>(parameters.Count);

            foreach (IParameter p in parameters)
            {
                ParameterDeclarationExpression pd = new ParameterDeclarationExpression(ConvertType(p.ReturnType, targetContext),
                                                                                       p.Name,
                                                                                       ConvertModifier(p.Modifiers));
                pd.Attributes = ConvertAttributes(p.Attributes, targetContext);
                l.Add(pd);
            }
            return(l);
        }
        public static List <AttributeSection> ConvertAttributes(IList <IAttribute> attributes, ClassFinder targetContext)
        {
            AttributeSection sec = new AttributeSection();

            foreach (IAttribute att in attributes)
            {
                sec.Attributes.Add(new ICSharpCode.NRefactory.Ast.Attribute(ConvertType(att.AttributeType, targetContext).Type, null, null));
            }
            List <AttributeSection> resultList = new List <AttributeSection>(1);

            if (sec.Attributes.Count > 0)
            {
                resultList.Add(sec);
            }
            return(resultList);
        }
 static TypeReference CreateTypeReference(IClass c, IList <IReturnType> typeArguments, ClassFinder context)
 {
     if (c.DeclaringType != null)
     {
         TypeReference        outerClass = CreateTypeReference(c.DeclaringType, typeArguments, context);
         List <TypeReference> args       = new List <TypeReference>();
         for (int i = c.DeclaringType.TypeParameters.Count; i < Math.Min(c.TypeParameters.Count, typeArguments.Count); i++)
         {
             args.Add(ConvertType(typeArguments[i], context));
         }
         return(new InnerClassTypeReference(outerClass, c.Name, args));
     }
     else
     {
         TypeReference typeRef;
         if (IsPrimitiveType(c.DefaultReturnType))
         {
             typeRef = new TypeReference(c.FullyQualifiedName, true);
         }
         else if (context != null && CanUseShortTypeName(c.DefaultReturnType, context))
         {
             typeRef = new TypeReference(c.Name);
         }
         else
         {
             typeRef = new TypeReference(c.FullyQualifiedName);
         }
         for (int i = 0; i < Math.Min(c.TypeParameters.Count, typeArguments.Count); i++)
         {
             typeRef.GenericTypes.Add(ConvertType(typeArguments[i], context));
         }
         return(typeRef);
     }
 }
        IEnumerable <Ast.ParameterDeclarationExpression> CreateParameters(UnknownMethodResolveResult rr, ClassFinder context, Ast.InvocationExpression invocation)
        {
            List <string> usedNames = new List <string>();

            for (int i = 0; i < rr.Arguments.Count; i++)
            {
                IReturnType type = rr.Arguments[i];

                if (type is LambdaReturnType)
                {
                    type = (type as LambdaReturnType).ToDefaultDelegate();
                }

                Ast.TypeReference typeRef = CodeGenerator.ConvertType(type, context);
                typeRef = typeRef.IsNull ? new Ast.TypeReference("object", true) : typeRef;

                Ast.Expression ex        = invocation.Arguments[i];
                string         paramName = IsNumericType(type) ? "num" + i : type.Name + i.ToString();

                if (ex is Ast.IdentifierExpression)
                {
                    paramName = (ex as Ast.IdentifierExpression).Identifier;
                }

                if (ex is Ast.MemberReferenceExpression)
                {
                    paramName = (ex as Ast.MemberReferenceExpression).MemberName;
                }

                Ast.ParameterModifiers mod = Ast.ParameterModifiers.None;

                if (ex is Ast.DirectionExpression)
                {
                    var dex = ex as Ast.DirectionExpression;

                    if (dex.Expression is Ast.IdentifierExpression)
                    {
                        paramName = (dex.Expression as Ast.IdentifierExpression).Identifier;
                    }

                    if (dex.Expression is Ast.MemberReferenceExpression)
                    {
                        paramName = (dex.Expression as Ast.MemberReferenceExpression).MemberName;
                    }

                    mod = dex.FieldDirection == Ast.FieldDirection.Out ? Ast.ParameterModifiers.Out : (dex.FieldDirection == Ast.FieldDirection.Ref ? Ast.ParameterModifiers.Ref : Ast.ParameterModifiers.None);
                }

                paramName = rr.CallingClass.ProjectContent.Language.CodeGenerator.GetParameterName(paramName);

                if (usedNames.Contains(paramName))
                {
                    paramName += i.ToString();
                }

                usedNames.Add(paramName);

                yield return(new Ast.ParameterDeclarationExpression(typeRef, paramName)
                {
                    ParamModifier = mod
                });
            }
        }
Exemple #28
0
        public void Insert(CompletionContext context, ICompletionItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (!(item is OverrideCompletionItem))
            {
                throw new ArgumentException("item is not an OverrideCompletionItem");
            }

            OverrideCompletionItem completionItem = item as OverrideCompletionItem;

            ITextEditor textEditor = context.Editor;

            IEditorUIService uiService = textEditor.GetService(typeof(IEditorUIService)) as IEditorUIService;

            if (uiService == null)
            {
                return;
            }

            ParseInformation parseInfo = ParserService.GetParseInformation(textEditor.FileName);

            if (parseInfo == null)
            {
                return;
            }

            CodeGenerator generator = parseInfo.CompilationUnit.Language.CodeGenerator;
            IClass        current   = parseInfo.CompilationUnit.GetInnermostClass(textEditor.Caret.Line, textEditor.Caret.Column);
            ClassFinder   finder    = new ClassFinder(current, textEditor.Caret.Line, textEditor.Caret.Column);

            if (current == null)
            {
                return;
            }

            using (textEditor.Document.OpenUndoGroup()) {
                ITextAnchor startAnchor = textEditor.Document.CreateAnchor(textEditor.Caret.Offset);
                startAnchor.MovementType = AnchorMovementType.BeforeInsertion;

                ITextAnchor endAnchor = textEditor.Document.CreateAnchor(textEditor.Caret.Offset);
                endAnchor.MovementType = AnchorMovementType.AfterInsertion;

                MethodDeclaration member = (MethodDeclaration)generator.GetOverridingMethod(completionItem.Member, finder);

                string indent          = DocumentUtilitites.GetWhitespaceBefore(textEditor.Document, textEditor.Caret.Offset);
                string codeForBaseCall = generator.GenerateCode(member.Body.Children.OfType <AbstractNode>().First(), "");
                string code            = generator.GenerateCode(member, indent);
                int    marker          = code.IndexOf(codeForBaseCall);

                textEditor.Document.Insert(startAnchor.Offset, code.Substring(0, marker).TrimStart());

                ITextAnchor insertionPos = textEditor.Document.CreateAnchor(endAnchor.Offset);
                insertionPos.MovementType = AnchorMovementType.BeforeInsertion;

                InsertionContext insertionContext = new InsertionContext(textEditor.GetService(typeof(TextArea)) as TextArea, startAnchor.Offset);

                AbstractInlineRefactorDialog dialog = new OverrideEqualsGetHashCodeMethodsDialog(insertionContext, textEditor, startAnchor, endAnchor, insertionPos, current, completionItem.Member as IMethod, codeForBaseCall.Trim());
                dialog.Element = uiService.CreateInlineUIElement(insertionPos, dialog);

                textEditor.Document.InsertNormalized(endAnchor.Offset, Environment.NewLine + code.Substring(marker + codeForBaseCall.Length));

                insertionContext.RegisterActiveElement(new InlineRefactorSnippetElement(cxt => null, ""), dialog);
                insertionContext.RaiseInsertionCompleted(EventArgs.Empty);
            }
        }
		void ConvertAttributes(AST.AttributedNode from, AbstractEntity to)
		{
			if (from.Attributes.Count == 0) {
				to.Attributes = DefaultAttribute.EmptyAttributeList;
			} else {
				ICSharpCode.NRefactory.Location location = from.Attributes[0].StartLocation;
				ClassFinder context;
				if (to is IClass) {
					context = new ClassFinder((IClass)to, location.Line, location.Column);
				} else {
					context = new ClassFinder(to.DeclaringType, location.Line, location.Column);
				}
				to.Attributes = VisitAttributes(from.Attributes, context);
			}
		}
Exemple #30
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private Object invokeInternal() throws Exception
        private Object InvokeInternal()
        {
            Object target     = Target;
            String methodName = MethodName;

            if (target == null || methodName == null)
            {
                throw new NullPointerException((target == null ? "target" : "methodName") + " should not be null");
            }

            Object[] arguments = Arguments;
            if (arguments == null)
            {
                arguments = EmptyArray;
            }
            // Class.forName() won't load classes outside
            // of core from a class inside core. Special
            // case this method.
            if (target == typeof(Class) && methodName.Equals("forName"))
            {
                return(ClassFinder.resolveClass((String)arguments[0], this.Loader));
            }
            Class[] argClasses = new Class[arguments.Length];
            for (int i = 0; i < arguments.Length; i++)
            {
                argClasses[i] = (arguments[i] == null) ? null : arguments[i].GetType();
            }

            AccessibleObject m = null;

            if (target is Class)
            {
                /*
                 * For class methods, simluate the effect of a meta class
                 * by taking the union of the static methods of the
                 * actual class, with the instance methods of "Class.class"
                 * and the overloaded "newInstance" methods defined by the
                 * constructors.
                 * This way "System.class", for example, will perform both
                 * the static method getProperties() and the instance method
                 * getSuperclass() defined in "Class.class".
                 */
                if (methodName.Equals("new"))
                {
                    methodName = "newInstance";
                }
                // Provide a short form for array instantiation by faking an nary-constructor.
                if (methodName.Equals("newInstance") && ((Class)target).Array)
                {
                    Object result = Array.newInstance(((Class)target).ComponentType, arguments.Length);
                    for (int i = 0; i < arguments.Length; i++)
                    {
                        Array.set(result, i, arguments[i]);
                    }
                    return(result);
                }
                if (methodName.Equals("newInstance") && arguments.Length != 0)
                {
                    // The Character class, as of 1.4, does not have a constructor
                    // which takes a String. All of the other "wrapper" classes
                    // for Java's primitive types have a String constructor so we
                    // fake such a constructor here so that this special case can be
                    // ignored elsewhere.
                    if (target == typeof(Character) && arguments.Length == 1 && argClasses[0] == typeof(String))
                    {
                        return(new Character(((String)arguments[0]).CharAt(0)));
                    }
                    try
                    {
                        m = ConstructorFinder.findConstructor((Class)target, argClasses);
                    }
                    catch (NoSuchMethodException)
                    {
                        m = null;
                    }
                }
                if (m == null && target != typeof(Class))
                {
                    m = GetMethod((Class)target, methodName, argClasses);
                }
                if (m == null)
                {
                    m = GetMethod(typeof(Class), methodName, argClasses);
                }
            }
            else
            {
                /*
                 * This special casing of arrays is not necessary, but makes files
                 * involving arrays much shorter and simplifies the archiving infrastrcure.
                 * The Array.set() method introduces an unusual idea - that of a static method
                 * changing the state of an instance. Normally statements with side
                 * effects on objects are instance methods of the objects themselves
                 * and we reinstate this rule (perhaps temporarily) by special-casing arrays.
                 */
                if (target.GetType().IsArray&& (methodName.Equals("set") || methodName.Equals("get")))
                {
                    int index = ((Integer)arguments[0]).IntValue();
                    if (methodName.Equals("get"))
                    {
                        return(Array.get(target, index));
                    }
                    else
                    {
                        Array.set(target, index, arguments[1]);
                        return(null);
                    }
                }
                m = GetMethod(target.GetType(), methodName, argClasses);
            }
            if (m != null)
            {
                try
                {
                    if (m is Method)
                    {
                        return(MethodUtil.invoke((Method)m, target, arguments));
                    }
                    else
                    {
                        return(((Constructor)m).newInstance(arguments));
                    }
                }
                catch (IllegalAccessException iae)
                {
                    throw new Exception("Statement cannot invoke: " + methodName + " on " + target.GetType(), iae);
                }
                catch (InvocationTargetException ite)
                {
                    Throwable te = ite.TargetException;
                    if (te is Exception)
                    {
                        throw (Exception)te;
                    }
                    else
                    {
                        throw ite;
                    }
                }
            }
            throw new NoSuchMethodException(ToString());
        }
		List<IAttribute> VisitAttributes(IList<AST.AttributeSection> attributes, ClassFinder context)
		{
			// TODO Expressions???
			List<IAttribute> result = new List<IAttribute>();
			foreach (AST.AttributeSection section in attributes) {
				
				AttributeTarget target = AttributeTarget.None;
				if (section.AttributeTarget != null && section.AttributeTarget != "") {
					switch (section.AttributeTarget.ToUpperInvariant()) {
						case "ASSEMBLY":
							target = AttributeTarget.Assembly;
							break;
						case "FIELD":
							target = AttributeTarget.Field;
							break;
						case "EVENT":
							target = AttributeTarget.Event;
							break;
						case "METHOD":
							target = AttributeTarget.Method;
							break;
						case "MODULE":
							target = AttributeTarget.Module;
							break;
						case "PARAM":
							target = AttributeTarget.Param;
							break;
						case "PROPERTY":
							target = AttributeTarget.Property;
							break;
						case "RETURN":
							target = AttributeTarget.Return;
							break;
						case "TYPE":
							target = AttributeTarget.Type;
							break;
						default:
							target = AttributeTarget.None;
							break;
							
					}
				}
				
				foreach (AST.Attribute attribute in section.Attributes) {
					List<object> positionalArguments = new List<object>();
					foreach (AST.Expression positionalArgument in attribute.PositionalArguments) {
						positionalArguments.Add(ConvertAttributeArgument(positionalArgument));
					}
					Dictionary<string, object> namedArguments = new Dictionary<string, object>();
					foreach (AST.NamedArgumentExpression namedArgumentExpression in attribute.NamedArguments) {
						namedArguments.Add(namedArgumentExpression.Name, ConvertAttributeArgument(namedArgumentExpression.Expression));
					}
					result.Add(new DefaultAttribute(new AttributeReturnType(context, attribute.Name),
					                                target, positionalArguments, namedArguments)
					           {
					           	CompilationUnit = cu,
					           	Region = GetRegion(attribute.StartLocation, attribute.EndLocation)
					           });
				}
			}
			return result;
		}
        public static TypeReference ConvertType(IReturnType returnType, ClassFinder context)
        {
            if (returnType == null)
            {
                return(TypeReference.Null);
            }
            if (returnType is NullReturnType)
            {
                return(TypeReference.Null);
            }

            ArrayReturnType arrayReturnType = returnType.CastToArrayReturnType();

            if (arrayReturnType != null)
            {
                TypeReference typeRef = ConvertType(arrayReturnType.ArrayElementType, context);
                int[]         rank    = typeRef.RankSpecifier ?? new int[0];
                Array.Resize(ref rank, rank.Length + 1);
                rank[rank.Length - 1] = arrayReturnType.ArrayDimensions - 1;
                typeRef.RankSpecifier = rank;
                return(typeRef);
            }
            PointerReturnType pointerReturnType = returnType.CastToDecoratingReturnType <PointerReturnType>();

            if (pointerReturnType != null)
            {
                TypeReference typeRef = ConvertType(pointerReturnType.BaseType, context);
                typeRef.PointerNestingLevel++;
                return(typeRef);
            }

            IList <IReturnType> typeArguments = EmptyList <IReturnType> .Instance;

            if (returnType.IsConstructedReturnType)
            {
                typeArguments = returnType.CastToConstructedReturnType().TypeArguments;
            }
            IClass c = returnType.GetUnderlyingClass();

            if (c != null)
            {
                return(CreateTypeReference(c, typeArguments, context));
            }
            else
            {
                TypeReference typeRef;
                if (IsPrimitiveType(returnType))
                {
                    typeRef = new TypeReference(returnType.FullyQualifiedName, true);
                }
                else if (context != null && CanUseShortTypeName(returnType, context))
                {
                    typeRef = new TypeReference(returnType.Name);
                }
                else
                {
                    string fullName = returnType.FullyQualifiedName;
                    if (string.IsNullOrEmpty(fullName))
                    {
                        fullName = returnType.Name;
                    }
                    typeRef = new TypeReference(fullName);
                }
                foreach (IReturnType typeArgument in typeArguments)
                {
                    typeRef.GenericTypes.Add(ConvertType(typeArgument, context));
                }
                return(typeRef);
            }
        }
 ExpressionContext GetCreationContext()
 {
     UnGetToken();
     if (GetNextNonWhiteSpace() == '=')               // was: "= new"
     {
         ReadNextToken();
         if (curTokenType == Ident)                       // was: "ident = new"
         {
             int typeEnd = offset;
             ReadNextToken();
             int typeStart = -1;
             while (curTokenType == Ident)
             {
                 typeStart = offset + 1;
                 ReadNextToken();
                 if (curTokenType == Dot)
                 {
                     ReadNextToken();
                 }
                 else
                 {
                     break;
                 }
             }
             if (typeStart >= 0)
             {
                 string className = text.Substring(typeStart, typeEnd - typeStart);
                 int    pos = className.IndexOf('<');
                 string nonGenericClassName, genericPart;
                 int    typeParameterCount = 0;
                 if (pos > 0)
                 {
                     nonGenericClassName = className.Substring(0, pos);
                     genericPart         = className.Substring(pos);
                     pos = 0;
                     do
                     {
                         typeParameterCount += 1;
                         pos = genericPart.IndexOf(',', pos + 1);
                     } while (pos > 0);
                 }
                 else
                 {
                     nonGenericClassName = className;
                     genericPart         = null;
                 }
                 ClassFinder finder = new ClassFinder(fileName, text, typeStart);
                 IReturnType t      = finder.SearchType(nonGenericClassName, typeParameterCount);
                 IClass      c      = (t != null) ? t.GetUnderlyingClass() : null;
                 if (c != null)
                 {
                     ExpressionContext context = ExpressionContext.TypeDerivingFrom(c.BaseType, true);
                     if (context.ShowEntry(c))
                     {
                         if (genericPart != null)
                         {
                             DefaultClass genericClass = new DefaultClass(c.CompilationUnit, c.ClassType, c.Modifiers, c.Region, c.DeclaringType);
                             genericClass.FullyQualifiedName = c.FullyQualifiedName + genericPart;
                             genericClass.Documentation      = c.Documentation;
                             context.SuggestedItem           = genericClass;
                         }
                         else
                         {
                             context.SuggestedItem = c;
                         }
                     }
                     return(context);
                 }
             }
         }
     }
     else
     {
         UnGet();
         if (ReadIdentifier(GetNextNonWhiteSpace()) == "throw")
         {
             return(ExpressionContext.TypeDerivingFrom(HostCallback.GetCurrentProjectContent().GetClass("System.Exception", 1).BaseType, true));
         }
     }
     return(ExpressionContext.ObjectCreation);
 }
Exemple #34
0
 public static List <InterfaceImplementation> ConvertInterfaceImplementations(IEnumerable <ExplicitInterfaceImplementation> items, ClassFinder targetContext)
 {
     return(items
            .Select(i => new InterfaceImplementation(ConvertType(i.InterfaceReference, targetContext), i.MemberName))
            .ToList());
 }