Пример #1
0
        private void EnterTypeDefinition(AST.TypeDefinition node, ClassType classType)
        {
            //LoggingService.Debug("Enter " + node.GetType().Name + " (" + node.FullName + ")");
            foreach (AST.Attribute att in node.Attributes)
            {
                if (att.Name == "Boo.Lang.ModuleAttribute")
                {
                    classType = ClassType.Module;
                }
            }
            DomRegion    region = GetClientRegion(node);
            DefaultClass c      = new DefaultClass(_cu, classType, GetModifier(node), region, OuterClass);

            c.FullyQualifiedName = node.FullName;
            if (_currentClass.Count > 0)
            {
                _currentClass.Peek().InnerClasses.Add(c);
            }
            else
            {
                _cu.Classes.Add(c);
            }
            _currentClass.Push(c);
            ConvertAttributes(node, c);
            ConvertTemplates(node, c);
            if (node.BaseTypes != null)
            {
                foreach (AST.TypeReference r in node.BaseTypes)
                {
                    c.BaseTypes.Add(CreateReturnType(r));
                }
            }
        }
Пример #2
0
        public void FindAllMethodsFromArrayWithParameterCountReturnsExpectedMethods()
        {
            DefaultClass  c       = CreateClass();
            DefaultMethod method1 = new DefaultMethod(c, "abc");

            method1.Parameters.Add(CreateParameter("a"));

            DefaultMethod method2 = new DefaultMethod(c, "abc");

            method2.Parameters.Add(CreateParameter("a"));
            method2.Parameters.Add(CreateParameter("b"));

            DefaultMethod method3 = new DefaultMethod(c, "abc");

            method3.Parameters.Add(CreateParameter("c"));

            ArrayList items = new ArrayList();

            items.Add(method1);
            items.Add(method2);
            items.Add(method3);

            List <IMethod> expectedMethods = new List <IMethod>();

            expectedMethods.Add(method1);
            expectedMethods.Add(method3);

            int            parameterCount = 1;
            List <IMethod> methods        = PythonCompletionItemsHelper.FindAllMethodsFromCollection("abc", parameterCount, items);

            Assert.AreEqual(expectedMethods, methods);
        }
Пример #3
0
    public async Task GetOrSetAsync_ShouldReturnValueWhenValueIsNotInMemoryCache()
    {
        var storedValue = new DefaultClass(42);

        var memoryFlowMock = new Mock <IMemoryFlow>();

        memoryFlowMock.Setup(f => f.TryGetValue(It.IsAny <string>(), out storedValue))
        .Returns(false)
        .Verifiable();
        memoryFlowMock.Setup(f => f.Set(It.IsAny <string>(), It.IsAny <DefaultClass>(), It.IsAny <MemoryCacheEntryOptions>()))
        .Verifiable();

        var distributedFlowMock = new Mock <IDistributedFlow>();

        distributedFlowMock.Setup(f => f.RefreshAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
        .Verifiable();
        distributedFlowMock.Setup(f => f.GetOrSetAsync(It.IsAny <string>(), It.IsAny <Func <Task <DefaultClass> > >(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>()))
        .ReturnsAsync(storedValue)
        .Verifiable();

        var cache  = new DoubleFlow(distributedFlowMock.Object, memoryFlowMock.Object);
        var result = await cache.GetOrSetAsync("key", () => Task.FromResult(storedValue), TimeSpan.MaxValue);

        Assert.Equal(storedValue, result);
        memoryFlowMock.Verify(f => f.TryGetValue(It.IsAny <string>(), out storedValue), Times.Once);
        memoryFlowMock.Verify(f => f.Set(It.IsAny <string>(), It.IsAny <DefaultClass>(), It.IsAny <MemoryCacheEntryOptions>()), Times.Once);
        distributedFlowMock.Verify(f => f.RefreshAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()), Times.Never);
        distributedFlowMock.Verify(f => f.GetOrSetAsync(It.IsAny <string>(), It.IsAny <Func <Task <DefaultClass> > >(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>()), Times.Once);
    }
Пример #4
0
        public override object VisitPropertyDeclaration(AST.PropertyDeclaration propertyDeclaration, object data)
        {
            DomRegion region     = GetRegion(propertyDeclaration.StartLocation, propertyDeclaration.EndLocation);
            DomRegion bodyRegion = GetRegion(propertyDeclaration.BodyStart, propertyDeclaration.BodyEnd);

            IReturnType  type = CreateReturnType(propertyDeclaration.TypeReference);
            DefaultClass c    = GetCurrentClass();

            DefaultProperty property = new DefaultProperty(propertyDeclaration.Name, type, ConvertModifier(propertyDeclaration.Modifier), region, bodyRegion, GetCurrentClass());

            if (propertyDeclaration.HasGetRegion)
            {
                property.GetterRegion    = GetRegion(propertyDeclaration.GetRegion.StartLocation, propertyDeclaration.GetRegion.EndLocation);
                property.CanGet          = true;
                property.GetterModifiers = ConvertModifier(propertyDeclaration.GetRegion.Modifier, ModifierEnum.None);
            }
            if (propertyDeclaration.HasSetRegion)
            {
                property.SetterRegion    = GetRegion(propertyDeclaration.SetRegion.StartLocation, propertyDeclaration.SetRegion.EndLocation);
                property.CanSet          = true;
                property.SetterModifiers = ConvertModifier(propertyDeclaration.SetRegion.Modifier, ModifierEnum.None);
            }
            property.Documentation = GetDocumentation(region.BeginLine, propertyDeclaration.Attributes);
            ConvertAttributes(propertyDeclaration, property);
            c.Properties.Add(property);
            return(null);
        }
Пример #5
0
        void CreateDelegate(DefaultClass c, string name, AST.TypeReference returnType, IList <AST.TemplateDefinition> templates, IList <AST.ParameterDeclarationExpression> parameters)
        {
            c.BaseTypes.Add(c.ProjectContent.SystemTypes.Delegate);
            if (currentClass.Count > 0)
            {
                DefaultClass cur = GetCurrentClass();
                cur.InnerClasses.Add(c);
                c.FullyQualifiedName = cur.FullyQualifiedName + '.' + name;
            }
            else
            {
                c.FullyQualifiedName = PrependCurrentNamespace(name);
                cu.Classes.Add(c);
            }
            c.UsingScope = currentNamespace;
            currentClass.Push(c);             // necessary for CreateReturnType
            ConvertTemplates(templates, c);

            List <IParameter> p = new List <IParameter>();

            if (parameters != null)
            {
                foreach (AST.ParameterDeclarationExpression param in parameters)
                {
                    p.Add(CreateParameter(param));
                }
            }
            AnonymousMethodReturnType.AddDefaultDelegateMethod(c, CreateReturnType(returnType), p);

            currentClass.Pop();
        }
Пример #6
0
        IParameter ConvertParameter(ParameterInfo paramInfo, IMethod method)
        {
            DefaultClass      c          = new DefaultClass(compilationUnit, paramInfo.ParameterType.FullName);
            DefaultReturnType returnType = new DefaultReturnType(c);

            return(new DefaultParameter(paramInfo.Name, returnType, DomRegion.Empty));
        }
Пример #7
0
        public override object VisitIndexerDeclaration(AST.IndexerDeclaration indexerDeclaration, object data)
        {
            DomRegion       region     = GetRegion(indexerDeclaration.StartLocation, indexerDeclaration.EndLocation);
            DomRegion       bodyRegion = GetRegion(indexerDeclaration.BodyStart, indexerDeclaration.BodyEnd);
            DefaultProperty i          = new DefaultProperty("Indexer", CreateReturnType(indexerDeclaration.TypeReference), ConvertModifier(indexerDeclaration.Modifier), region, bodyRegion, GetCurrentClass());

            i.IsIndexer = true;
            if (indexerDeclaration.HasGetRegion)
            {
                i.GetterRegion    = GetRegion(indexerDeclaration.GetRegion.StartLocation, indexerDeclaration.GetRegion.EndLocation);
                i.CanGet          = true;
                i.GetterModifiers = ConvertModifier(indexerDeclaration.GetRegion.Modifier, ModifierEnum.None);
            }
            if (indexerDeclaration.HasSetRegion)
            {
                i.SetterRegion    = GetRegion(indexerDeclaration.SetRegion.StartLocation, indexerDeclaration.SetRegion.EndLocation);
                i.CanSet          = true;
                i.SetterModifiers = ConvertModifier(indexerDeclaration.SetRegion.Modifier, ModifierEnum.None);
            }
            i.Documentation = GetDocumentation(region.BeginLine, indexerDeclaration.Attributes);
            ConvertAttributes(indexerDeclaration, i);
            if (indexerDeclaration.Parameters != null)
            {
                foreach (AST.ParameterDeclarationExpression par in indexerDeclaration.Parameters)
                {
                    i.Parameters.Add(CreateParameter(par));
                }
            }
            DefaultClass c = GetCurrentClass();

            c.Properties.Add(i);
            return(null);
        }
Пример #8
0
    public void GetOrSet_ShouldReturnValueWhenValueIsInMemoryCache()
    {
        var storedValue = new DefaultClass(42);

        var memoryFlowMock = new Mock <IMemoryFlow>();

        memoryFlowMock.Setup(f => f.TryGetValue(It.IsAny <string>(), out storedValue))
        .Returns(true)
        .Verifiable();
        memoryFlowMock.Setup(f => f.Set(It.IsAny <string>(), It.IsAny <DefaultClass>(), It.IsAny <TimeSpan>()))
        .Verifiable();

        var distributedFlowMock = new Mock <IDistributedFlow>();

        distributedFlowMock.Setup(f => f.Refresh(It.IsAny <string>()))
        .Verifiable();
        distributedFlowMock.Setup(f => f.GetOrSet(It.IsAny <string>(), It.IsAny <Func <DefaultClass> >(), It.IsAny <DistributedCacheEntryOptions>()))
        .Returns(storedValue)
        .Verifiable();

        var cache  = new DoubleFlow(distributedFlowMock.Object, memoryFlowMock.Object);
        var result = cache.GetOrSet("key", () => storedValue, TimeSpan.MaxValue);

        Assert.Equal(storedValue, result);
        memoryFlowMock.Verify(f => f.TryGetValue(It.IsAny <string>(), out storedValue), Times.Once);
        memoryFlowMock.Verify(f => f.Set(It.IsAny <string>(), It.IsAny <DefaultClass>(), It.IsAny <TimeSpan>()), Times.Never);
        distributedFlowMock.Verify(f => f.Refresh(It.IsAny <string>()), Times.Once);
        distributedFlowMock.Verify(f => f.GetOrSet(It.IsAny <string>(), It.IsAny <Func <DefaultClass> >(), It.IsAny <DistributedCacheEntryOptions>()), Times.Never);
    }
Пример #9
0
    public async Task GetAsync_ShouldGetValueWhenValueIsInDistributedCache()
    {
        var storedValue = new DefaultClass(42);

        var memoryFlowMock = new Mock <IMemoryFlow>();

        memoryFlowMock.Setup(f => f.TryGetValue(It.IsAny <string>(), out storedValue))
        .Returns(false)
        .Verifiable();
        memoryFlowMock.Setup(f => f.Set(It.IsAny <string>(), It.IsAny <DefaultClass>(), It.IsAny <TimeSpan>()))
        .Verifiable();

        var distributedFlowMock = new Mock <IDistributedFlow>();

        distributedFlowMock.Setup(f => f.GetAsync <DefaultClass>(It.IsAny <string>(), It.IsAny <CancellationToken>()))
        .ReturnsAsync(storedValue)
        .Verifiable();

        var cache  = new DoubleFlow(distributedFlowMock.Object, memoryFlowMock.Object);
        var result = await cache.GetAsync <DefaultClass>("key", TimeSpan.Zero);

        Assert.Equal(storedValue, result);
        memoryFlowMock.Verify(f => f.TryGetValue(It.IsAny <string>(), out storedValue), Times.Once);
        memoryFlowMock.Verify(f => f.Set(It.IsAny <string>(), It.IsAny <DefaultClass>(), It.IsAny <TimeSpan>()), Times.Never);
        distributedFlowMock.Verify(f => f.GetAsync <DefaultClass>(It.IsAny <string>(), It.IsAny <CancellationToken>()), Times.Once);
    }
Пример #10
0
    public void TryGetValue_ShouldReturnTrueWhenValueInDistributedCache()
    {
        var storedValue = new DefaultClass(42);

        var memoryFlowMock = new Mock <IMemoryFlow>();

        memoryFlowMock.Setup(f => f.TryGetValue(It.IsAny <string>(), out storedValue))
        .Returns(false)
        .Verifiable();
        memoryFlowMock.Setup(f => f.Set(It.IsAny <string>(), It.IsAny <DefaultClass>(), It.IsAny <MemoryCacheEntryOptions>()))
        .Verifiable();

        var distributedFlowMock = new Mock <IDistributedFlow>();

        distributedFlowMock.Setup(f => f.TryGetValue(It.IsAny <string>(), out storedValue))
        .Returns(true)
        .Verifiable();

        var cache   = new DoubleFlow(distributedFlowMock.Object, memoryFlowMock.Object);
        var isFound = cache.TryGetValue("key", out DefaultClass result, TimeSpan.MaxValue);

        Assert.True(isFound);
        Assert.Equal(storedValue, result);
        memoryFlowMock.Verify(f => f.TryGetValue(It.IsAny <string>(), out storedValue), Times.Once);
        memoryFlowMock.Verify(f => f.Set(It.IsAny <string>(), It.IsAny <DefaultClass>(), It.IsAny <MemoryCacheEntryOptions>()), Times.Never);
        distributedFlowMock.Verify(f => f.TryGetValue(It.IsAny <string>(), out storedValue), Times.Once);
    }
        public override object VisitMethodDeclaration(AST.MethodDeclaration methodDeclaration, object data)
        {
            DomRegion    region     = GetRegion(methodDeclaration.StartLocation, methodDeclaration.EndLocation);
            DomRegion    bodyRegion = GetRegion(methodDeclaration.EndLocation, methodDeclaration.Body != null ? methodDeclaration.Body.EndLocation : RefParser.Location.Empty);
            DefaultClass c          = GetCurrentClass();

            DefaultMethod method = new DefaultMethod(methodDeclaration.Name, null, ConvertModifier(methodDeclaration.Modifier), region, bodyRegion, GetCurrentClass());

            method.Documentation = GetDocumentation(region.BeginLine, methodDeclaration.Attributes);
            ConvertTemplates(methodDeclaration.Templates, method);
            method.ReturnType = CreateReturnType(methodDeclaration.TypeReference, method);
            ConvertAttributes(methodDeclaration, method);
            if (methodDeclaration.Parameters != null && methodDeclaration.Parameters.Count > 0)
            {
                foreach (AST.ParameterDeclarationExpression par in methodDeclaration.Parameters)
                {
                    method.Parameters.Add(CreateParameter(par, method));
                }
            }
            else
            {
                method.Parameters = DefaultParameter.EmptyParameterList;
            }
            c.Methods.Add(method);
            return(null);
        }
        public override object VisitConstructorDeclaration(AST.ConstructorDeclaration constructorDeclaration, object data)
        {
            DomRegion    region     = GetRegion(constructorDeclaration.StartLocation, constructorDeclaration.EndLocation);
            DomRegion    bodyRegion = GetRegion(constructorDeclaration.EndLocation, constructorDeclaration.Body != null ? constructorDeclaration.Body.EndLocation : RefParser.Location.Empty);
            DefaultClass c          = GetCurrentClass();

            Constructor constructor = new Constructor(ConvertModifier(constructorDeclaration.Modifier), region, bodyRegion, GetCurrentClass());

            constructor.Documentation = GetDocumentation(region.BeginLine, constructorDeclaration.Attributes);
            ConvertAttributes(constructorDeclaration, constructor);
            if (constructorDeclaration.Parameters != null)
            {
                foreach (AST.ParameterDeclarationExpression par in constructorDeclaration.Parameters)
                {
                    constructor.Parameters.Add(CreateParameter(par));
                }
            }

            if (constructor.Modifiers.HasFlag(ModifierEnum.Static))
            {
                constructor.Modifiers = ConvertModifier(constructorDeclaration.Modifier, ModifierEnum.None);
            }

            c.Methods.Add(constructor);
            return(null);
        }
Пример #13
0
 /// <summary>
 /// Creates the dummy class that is used to hold global methods.
 /// </summary>
 void CreateGlobalClass()
 {
     if (globalClass == null)
     {
         globalClass = new DefaultClass(compilationUnit, currentNamespace);
         compilationUnit.Classes.Add(globalClass);
     }
 }
Пример #14
0
        public PermissionWindows()
        {
            InitializeComponent();
            DefaultClass df = new DefaultClass();

            CmbUserName.AddUserName();
            Getchkbox();
        }
Пример #15
0
 /// <summary>
 /// Creates the dummy class that is used to hold global methods.
 /// </summary>
 void CreateGlobalClass()
 {
     if (globalClass == null)
     {
         globalClass = new DefaultClass(compilationUnit, Path.GetFileNameWithoutExtension(compilationUnit.FileName));
         compilationUnit.Classes.Add(globalClass);
     }
 }
Пример #16
0
        protected override void Walk(ModuleDefinition node)
        {
            globalClass = CreateClass(node);

            currentClass = globalClass;
            base.Walk(node);
            currentClass = null;
        }
        public void ExpressionResultContextShowItemReturnsTrueForIMethod()
        {
            MockProjectContent     projectContent = new MockProjectContent();
            DefaultCompilationUnit unit           = new DefaultCompilationUnit(projectContent);
            DefaultClass           c      = new DefaultClass(unit, "MyClass");
            DefaultMethod          method = new DefaultMethod(c, "Test");

            Assert.IsTrue(expressionResult.Context.ShowEntry(method));
        }
Пример #18
0
        /// <summary>
        /// Builds Visual Basic's "My" namespace for the specified project.
        /// </summary>
        public static void BuildNamespace(VBNetProject project, IProjectContent pc)
        {
            ICompilationUnit cu = new DefaultCompilationUnit(pc);
            //cu.FileName = "GeneratedMyNamespace.vb"; // leave FileName null - fixes SD2-854
            string ns;

            if (project.RootNamespace == null || project.RootNamespace.Length == 0)
            {
                ns = "My";
            }
            else
            {
                ns = project.RootNamespace + ".My";
            }
            IClass myApp  = CreateMyApplication(cu, project, ns);
            IClass myComp = CreateMyComputer(cu, project, ns);

            cu.Classes.Add(myApp);
            cu.Classes.Add(myComp);

            IClass myForms = null;

            if (project.OutputType == OutputType.WinExe)
            {
                myForms = CreateMyForms(cu, project, ns);
                cu.Classes.Add(myForms);
            }
            DefaultClass c = new DefaultClass(cu, ns + ".MyProject");

            c.ClassType = ClassType.Module;
            c.Modifiers = ModifierEnum.Internal | ModifierEnum.Partial | ModifierEnum.Sealed | ModifierEnum.Synthetic;
            c.Attributes.Add(new DefaultAttribute(CreateTypeRef(cu, "Microsoft.VisualBasic.HideModuleNameAttribute")));

            // we need to use GetClassReturnType instead of DefaultReturnType because we need
            // a reference to the compound class.
            c.Properties.Add(new DefaultProperty("Application",
                                                 new GetClassReturnType(pc, myApp.FullyQualifiedName, 0),
                                                 ModifierEnum.Public | ModifierEnum.Static,
                                                 DomRegion.Empty, DomRegion.Empty, c));
            c.Properties.Add(new DefaultProperty("Computer",
                                                 new GetClassReturnType(pc, myComp.FullyQualifiedName, 0),
                                                 ModifierEnum.Public | ModifierEnum.Static,
                                                 DomRegion.Empty, DomRegion.Empty, c));
            if (myForms != null)
            {
                c.Properties.Add(new DefaultProperty("Forms",
                                                     new GetClassReturnType(pc, myForms.FullyQualifiedName, 0),
                                                     ModifierEnum.Public | ModifierEnum.Static,
                                                     DomRegion.Empty, DomRegion.Empty, c));
            }
            c.Properties.Add(new DefaultProperty("User",
                                                 new GetClassReturnType(pc, "Microsoft.VisualBasic.ApplicationServices.User", 0),
                                                 ModifierEnum.Public | ModifierEnum.Static,
                                                 DomRegion.Empty, DomRegion.Empty, c));
            cu.Classes.Add(c);
            pc.UpdateCompilationUnit(null, cu, cu.FileName);
        }
Пример #19
0
        public void TypeParameterPassedToBaseClassTestClassDerivingFromList()
        {
            DefaultClass listDerivingClass = CreateClassDerivingFromListOfString();

            IReturnType res = MemberLookupHelper.GetTypeParameterPassedToBaseClass(listDerivingClass.DefaultReturnType,
                                                                                   EnumerableClass, 0);

            Assert.AreEqual("System.String", res.FullyQualifiedName);
        }
Пример #20
0
        DefaultClass CreateClass(ModuleDefinition node)
        {
            DefaultClass c = new DefaultClass(compilationUnit, node.QualifiedName.Name);

            c.Region     = GetRegion(node.Location);
            c.BodyRegion = GetClassBodyRegion(node.Body.Location, node.QualifiedName.Location.End);
            compilationUnit.Classes.Add(c);
            return(c);
        }
Пример #21
0
        public PythonModuleCompletionItems(PythonStandardModuleType moduleType)
        {
            projectContent  = new DefaultProjectContent();
            compilationUnit = new DefaultCompilationUnit(projectContent);
            moduleClass     = new DefaultClass(compilationUnit, moduleType.Name);

            AddCompletionItemsForType(moduleType.Type);
            AddStandardCompletionItems();
        }
        void AddWebViewPageBaseClass(DefaultClass webViewPageClass, IReturnType modelType)
        {
            IClass webViewPageBaseClass = webViewPageClass.ProjectContent.GetClass("System.Web.Mvc.WebViewPage", 1);

            if (webViewPageBaseClass != null)
            {
                IReturnType returnType = GetWebViewPageBaseClassReturnType(webViewPageBaseClass, modelType);
                webViewPageClass.BaseTypes.Add(returnType);
            }
        }
Пример #23
0
        static IClass CreateMyComputer(ICompilationUnit cu, string ns)
        {
            DefaultClass c = new DefaultClass(cu, ns + ".MyComputer");

            c.ClassType = ClassType.Class;
            c.Modifiers = ModifierEnum.Internal | ModifierEnum.Sealed | ModifierEnum.Partial | ModifierEnum.Synthetic;
            c.Attributes.Add(new DefaultAttribute(CreateTypeRef(cu, "Microsoft.VisualBasic.HideModuleNameAttribute")));
            c.BaseTypes.Add(CreateTypeRef(cu, "Microsoft.VisualBasic.Devices.Computer"));
            return(c);
        }
        protected override ExpressionResult GetExpressionResult()
        {
            List <ICompletionEntry> namespaceItems = new List <ICompletionEntry>();
            DefaultClass            consoleClass   = new DefaultClass(compilationUnit, "System.Console");

            namespaceItems.Add(consoleClass);
            projectContent.AddExistingNamespaceContents("System", namespaceItems);

            return(new ExpressionResult("MySystem", ExpressionContext.Default));
        }
Пример #25
0
        public void FindClassFromArrayReturnsExpectedClass()
        {
            DefaultClass c = CreateClass();

            ArrayList items = new ArrayList();

            items.Add(c);

            Assert.AreEqual(c, PythonCompletionItemsHelper.FindClassFromCollection("Test", items));
        }
Пример #26
0
        public void FindClassFromArrayReturnsExpectedNullForUnknownClassName()
        {
            DefaultClass c = CreateClass();

            ArrayList items = new ArrayList();

            items.Add(c);

            Assert.IsNull(PythonCompletionItemsHelper.FindClassFromCollection("unknown-class-name", items));
        }
        DefaultClass CreateWebViewPageClass(RazorCompilationUnit compilationUnit)
        {
            var webViewPageClass = new DefaultClass(compilationUnit, "RazorWebViewPage")
            {
                Region = new DomRegion(1, 0, 3, 0)
            };
            IReturnType modelType = GetModelReturnType(compilationUnit);

            AddWebViewPageBaseClass(webViewPageClass, modelType);
            return(webViewPageClass);
        }
Пример #28
0
        public void FindFieldFromArrayReturnsExpectedNullForUnknownField()
        {
            DefaultClass c     = CreateClass();
            DefaultField field = new DefaultField(c, "field");

            ArrayList items = new ArrayList();

            items.Add(field);

            Assert.IsNull(PythonCompletionItemsHelper.FindFieldFromCollection("unknown-field-name", items));
        }
Пример #29
0
        public override object VisitDelegateDeclaration(AST.DelegateDeclaration delegateDeclaration, object data)
        {
            DomRegion    region = GetRegion(delegateDeclaration.StartLocation, delegateDeclaration.EndLocation);
            DefaultClass c      = new DefaultClass(cu, ClassType.Delegate, ConvertTypeModifier(delegateDeclaration.Modifier), region, GetCurrentClass());

            c.Documentation = GetDocumentation(region.BeginLine, delegateDeclaration.Attributes);
            ConvertAttributes(delegateDeclaration, c);
            CreateDelegate(c, delegateDeclaration.Name, delegateDeclaration.ReturnType,
                           delegateDeclaration.Templates, delegateDeclaration.Parameters);
            return(c);
        }
Пример #30
0
		internal static void ApplySpecialsFromAttributes(DefaultClass c)
		{
			foreach (IAttribute att in c.Attributes) {
				if (att.Name == "Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute"
				    || att.Name == "Boo.Lang.ModuleAttribute")
				{
					c.ClassType = ClassType.Module;
					break;
				}
			}
		}
Пример #31
0
        protected override void Walk(ClassDefinition node)
        {
            DefaultClass c = CreateClass(node);

            AddBaseType(c, node);

            // Walk through all the class items.
            currentClass = c;
            base.Walk(node);
            currentClass = null;
        }
        public void Build_happy_path()
        {
            var mocks = new MockRepository();
            var buildSession =
                mocks.StrictMock<BuildSession>();

            var theDefault = new DefaultClass();

            using (mocks.Record())
            {
                Expect.Call(buildSession.CreateInstance(typeof (IDefault))).Return(theDefault);
            }

            using (mocks.Playback())
            {
                var instance = new DefaultInstance();
                Assert.AreSame(theDefault, instance.Build(typeof (IDefault), buildSession));
            }
        }
		public void NestedInterfaceInGenericClass()
		{
			// See SD2-1626
			DefaultProjectContent pc = new DefaultProjectContent();
			pc.ReferencedContents.Add(SharedProjectContentRegistryForTests.Instance.Mscorlib);
			
			DefaultCompilationUnit cu = new DefaultCompilationUnit(pc);
			DefaultClass container = new DefaultClass(cu, "TestClass");
			container.TypeParameters.Add(new DefaultTypeParameter(container, "T", 0));
			
			DefaultClass innerClass = new DefaultClass(cu, container);
			innerClass.FullyQualifiedName = "TestClass.INestedInterface";
			innerClass.ClassType = ClassType.Interface;
			innerClass.TypeParameters.Add(new DefaultTypeParameter(innerClass, "T", 0));
			innerClass.Properties.Add(new DefaultProperty(innerClass, "P") {
			                          	ReturnType = new GenericReturnType(innerClass.TypeParameters[0]),
			                          	CanGet = true
			                          });
			container.InnerClasses.Add(innerClass);
			pc.AddClassToNamespaceList(container);
			
			DefaultClass targetClass = new DefaultClass(cu, "TargetClass");
			List<AbstractNode> nodes = new List<AbstractNode>();
			
			IReturnType interf = new SearchClassReturnType(pc, targetClass, 0, 0, "TestClass.INestedInterface", 1);
			interf = new ConstructedReturnType(interf, new IReturnType[] { SharedProjectContentRegistryForTests.Instance.Mscorlib.GetClass("System.String", 0).DefaultReturnType });
			
			CSharpCodeGenerator codeGen = new CSharpCodeGenerator();
			codeGen.ImplementInterface(nodes, interf, true, targetClass);
			
			Assert.AreEqual(1, nodes.Count);
			CSharpOutputVisitor output = new CSharpOutputVisitor();
			output.Options.IndentationChar = ' ';
			output.Options.IndentSize = 2;
			nodes[0].AcceptVisitor(output, null);
			Assert.AreEqual("string TestClass<string>.INestedInterface.P {\n  get {\n    throw new NotImplementedException();\n  }\n}", output.Text.Replace("\r", "").Trim());
		}
		void ConvertTemplates(IList<AST.TemplateDefinition> templateList, DefaultClass c)
		{
			int index = 0;
			if (templateList.Count == 0) {
				c.TypeParameters = DefaultTypeParameter.EmptyTypeParameterList;
			} else {
				foreach (AST.TemplateDefinition template in templateList) {
					c.TypeParameters.Add(ConvertConstraints(template, new DefaultTypeParameter(c, template.Name, index++)));
				}
			}
		}
Пример #35
0
 void CreateDefaultClass(string fullyQualifiedName)
 {
     projectContent = new DefaultProjectContent();
     compilationUnit = new DefaultCompilationUnit(projectContent);
     defaultClass = new DefaultClass(compilationUnit, fullyQualifiedName);
 }
		public override object VisitEventDeclaration(AST.EventDeclaration eventDeclaration, object data)
		{
			DomRegion region     = GetRegion(eventDeclaration.StartLocation, eventDeclaration.EndLocation);
			DomRegion bodyRegion = GetRegion(eventDeclaration.BodyStart,     eventDeclaration.BodyEnd);
			DefaultClass c = GetCurrentClass();
			
			IReturnType type;
			if (eventDeclaration.TypeReference.IsNull) {
				DefaultClass del = new DefaultClass(cu, ClassType.Delegate,
				                                    ConvertModifier(eventDeclaration.Modifier),
				                                    region, c);
				del.Modifiers |= ModifierEnum.Synthetic;
				CreateDelegate(del, eventDeclaration.Name + "EventHandler",
				               new AST.TypeReference("System.Void", true),
				               new AST.TemplateDefinition[0],
				               eventDeclaration.Parameters);
				type = del.DefaultReturnType;
			} else {
				type = CreateReturnType(eventDeclaration.TypeReference);
			}
			DefaultEvent e = new DefaultEvent(eventDeclaration.Name, type, ConvertModifier(eventDeclaration.Modifier), region, bodyRegion, c);
			ConvertAttributes(eventDeclaration, e);
			AddInterfaceImplementations(e, eventDeclaration);
			c.Events.Add(e);
			
			e.Documentation = GetDocumentation(region.BeginLine, eventDeclaration.Attributes);
			if (eventDeclaration.HasAddRegion) {
				e.AddMethod = new DefaultMethod(e.DeclaringType, "add_" + e.Name) {
					Parameters = { new DefaultParameter("value", e.ReturnType, DomRegion.Empty) },
					Region = GetRegion(eventDeclaration.AddRegion.StartLocation, eventDeclaration.AddRegion.EndLocation),
					BodyRegion = GetRegion(eventDeclaration.AddRegion.Block.StartLocation, eventDeclaration.AddRegion.Block.EndLocation)
				};
			}
			if (eventDeclaration.HasRemoveRegion) {
				e.RemoveMethod = new DefaultMethod(e.DeclaringType, "remove_" + e.Name) {
					Parameters = { new DefaultParameter("value", e.ReturnType, DomRegion.Empty) },
					Region = GetRegion(eventDeclaration.RemoveRegion.StartLocation, eventDeclaration.RemoveRegion.EndLocation),
					BodyRegion = GetRegion(eventDeclaration.RemoveRegion.Block.StartLocation, eventDeclaration.RemoveRegion.Block.EndLocation)
				};
			}
			return null;
		}
		public override object VisitTypeDeclaration(AST.TypeDeclaration typeDeclaration, object data)
		{
			DomRegion region = GetRegion(typeDeclaration.StartLocation, typeDeclaration.EndLocation);
			DomRegion bodyRegion = GetRegion(typeDeclaration.BodyStartLocation, typeDeclaration.EndLocation);
			
			DefaultClass c = new DefaultClass(cu, TranslateClassType(typeDeclaration.Type), ConvertTypeModifier(typeDeclaration.Modifier), region, GetCurrentClass());
			c.BodyRegion = bodyRegion;
			ConvertAttributes(typeDeclaration, c);
			c.Documentation = GetDocumentation(region.BeginLine, typeDeclaration.Attributes);
			
			if (currentClass.Count > 0) {
				DefaultClass cur = GetCurrentClass();
				cur.InnerClasses.Add(c);
				c.FullyQualifiedName = cur.FullyQualifiedName + '.' + typeDeclaration.Name;
			} else {
				if (currentNamespace.Count == 0) {
					c.FullyQualifiedName = typeDeclaration.Name;
				} else {
					c.FullyQualifiedName = currentNamespace.Peek() + '.' + typeDeclaration.Name;
				}
				cu.Classes.Add(c);
			}
			currentClass.Push(c);
			
			if (c.ClassType != ClassType.Enum && typeDeclaration.BaseTypes != null) {
				foreach (AST.TypeReference type in typeDeclaration.BaseTypes) {
					IReturnType rt = CreateReturnType(type);
					if (rt != null) {
						c.BaseTypes.Add(rt);
					}
				}
			}
			
			ConvertTemplates(typeDeclaration.Templates, c); // resolve constrains in context of the class
			
			object ret = typeDeclaration.AcceptChildren(this, data);
			currentClass.Pop();
			
			if (c.ClassType == ClassType.Module) {
				foreach (IField f in c.Fields) {
					f.Modifiers |= ModifierEnum.Static;
				}
				foreach (IMethod m in c.Methods) {
					m.Modifiers |= ModifierEnum.Static;
				}
				foreach (IProperty p in c.Properties) {
					p.Modifiers |= ModifierEnum.Static;
				}
				foreach (IEvent e in c.Events) {
					e.Modifiers |= ModifierEnum.Static;
				}
			}
			
			return ret;
		}
		public override object VisitDelegateDeclaration(AST.DelegateDeclaration delegateDeclaration, object data)
		{
			DomRegion region = GetRegion(delegateDeclaration.StartLocation, delegateDeclaration.EndLocation);
			DefaultClass c = new DefaultClass(cu, ClassType.Delegate, ConvertTypeModifier(delegateDeclaration.Modifier), region, GetCurrentClass());
			c.Documentation = GetDocumentation(region.BeginLine, delegateDeclaration.Attributes);
			ConvertAttributes(delegateDeclaration, c);
			CreateDelegate(c, delegateDeclaration.Name, delegateDeclaration.ReturnType,
			               delegateDeclaration.Templates, delegateDeclaration.Parameters);
			return c;
		}
		void CreateDelegate(DefaultClass c, string name, AST.TypeReference returnType, IList<AST.TemplateDefinition> templates, IList<AST.ParameterDeclarationExpression> parameters)
		{
			c.BaseTypes.Add(c.ProjectContent.SystemTypes.MulticastDelegate);
			DefaultClass outerClass = GetCurrentClass();
			if (outerClass != null) {
				outerClass.InnerClasses.Add(c);
				c.FullyQualifiedName = outerClass.FullyQualifiedName + '.' + name;
			} else {
				c.FullyQualifiedName = PrependCurrentNamespace(name);
				cu.Classes.Add(c);
			}
			c.UsingScope = currentNamespace;
			currentClass.Push(c); // necessary for CreateReturnType
			ConvertTemplates(outerClass, templates, c);
			
			List<IParameter> p = new List<IParameter>();
			if (parameters != null) {
				foreach (AST.ParameterDeclarationExpression param in parameters) {
					p.Add(CreateParameter(param));
				}
			}
			AnonymousMethodReturnType.AddDefaultDelegateMethod(c, CreateReturnType(returnType), p);
			
			currentClass.Pop();
		}
		void ConvertTemplates(DefaultClass outerClass, IList<AST.TemplateDefinition> templateList, DefaultClass c)
		{
			int outerClassTypeParameterCount = outerClass != null ? outerClass.TypeParameters.Count : 0;
			if (templateList.Count == 0 && outerClassTypeParameterCount == 0) {
				c.TypeParameters = DefaultTypeParameter.EmptyTypeParameterList;
			} else {
				Debug.Assert(c.TypeParameters.Count == 0);
				
				int index = 0;
				if (outerClassTypeParameterCount > 0) {
					foreach (DefaultTypeParameter outerTypeParamter in outerClass.TypeParameters) {
						DefaultTypeParameter p = new DefaultTypeParameter(c, outerTypeParamter.Name, index++);
						p.HasConstructableConstraint = outerTypeParamter.HasConstructableConstraint;
						p.HasReferenceTypeConstraint = outerTypeParamter.HasReferenceTypeConstraint;
						p.HasValueTypeConstraint = outerTypeParamter.HasValueTypeConstraint;
						p.Attributes.AddRange(outerTypeParamter.Attributes);
						p.Constraints.AddRange(outerTypeParamter.Constraints);
						c.TypeParameters.Add(p);
					}
				}
				
				foreach (AST.TemplateDefinition template in templateList) {
					c.TypeParameters.Add(new DefaultTypeParameter(c, template.Name, index++));
				}
				// converting the constraints requires that the type parameters are already present
				for (int i = 0; i < templateList.Count; i++) {
					ConvertConstraints(templateList[i], (DefaultTypeParameter)c.TypeParameters[i + outerClassTypeParameterCount]);
				}
			}
		}
		public override object VisitTypeDeclaration(AST.TypeDeclaration typeDeclaration, object data)
		{
			DomRegion region = GetRegion(typeDeclaration.StartLocation, typeDeclaration.EndLocation);
			DomRegion bodyRegion = GetRegion(typeDeclaration.BodyStartLocation, typeDeclaration.EndLocation);
			
			DefaultClass c = new DefaultClass(cu, TranslateClassType(typeDeclaration.Type), ConvertTypeModifier(typeDeclaration.Modifier), region, GetCurrentClass());
			if (c.IsStatic) {
				// static classes are also abstract and sealed at the same time
				c.Modifiers |= ModifierEnum.Abstract | ModifierEnum.Sealed;
			}
			c.BodyRegion = bodyRegion;
			ConvertAttributes(typeDeclaration, c);
			c.Documentation = GetDocumentation(region.BeginLine, typeDeclaration.Attributes);
			
			DefaultClass outerClass = GetCurrentClass();
			if (outerClass != null) {
				outerClass.InnerClasses.Add(c);
				c.FullyQualifiedName = outerClass.FullyQualifiedName + '.' + typeDeclaration.Name;
			} else {
				c.FullyQualifiedName = PrependCurrentNamespace(typeDeclaration.Name);
				cu.Classes.Add(c);
			}
			c.UsingScope = currentNamespace;
			currentClass.Push(c);
			
			ConvertTemplates(outerClass, typeDeclaration.Templates, c); // resolve constrains in context of the class
			// templates must be converted before base types because base types may refer to generic types
			
			if (c.ClassType != ClassType.Enum && typeDeclaration.BaseTypes != null) {
				foreach (AST.TypeReference type in typeDeclaration.BaseTypes) {
					IReturnType rt = CreateReturnType(type, null, TypeVisitor.ReturnTypeOptions.BaseTypeReference);
					if (rt != null) {
						c.BaseTypes.Add(rt);
					}
				}
			}
			
			object ret = typeDeclaration.AcceptChildren(this, data);
			currentClass.Pop();
			
			if (c.ClassType == ClassType.Module) {
				foreach (DefaultField f in c.Fields) {
					f.Modifiers |= ModifierEnum.Static;
				}
				foreach (DefaultMethod m in c.Methods) {
					m.Modifiers |= ModifierEnum.Static;
				}
				foreach (DefaultProperty p in c.Properties) {
					p.Modifiers |= ModifierEnum.Static;
				}
				foreach (DefaultEvent e in c.Events) {
					e.Modifiers |= ModifierEnum.Static;
				}
			}
			
			return ret;
		}
 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;
 }
Пример #43
0
		DefaultClass CreateAnonymousTypeClass(CollectionInitializerExpression initializer)
		{
			List<IReturnType> fieldTypes = new List<IReturnType>();
			List<string> fieldNames = new List<string>();
			
			foreach (Expression expr in initializer.CreateExpressions) {
				if (expr is NamedArgumentExpression) {
					// use right part only
					fieldTypes.Add( ResolveType(((NamedArgumentExpression)expr).Expression) );
				} else {
					fieldTypes.Add( ResolveType(expr) );
				}
				
				fieldNames.Add(GetAnonymousTypeFieldName(expr));
			}
			
			StringBuilder nameBuilder = new StringBuilder();
			nameBuilder.Append('{');
			for (int i = 0; i < fieldTypes.Count; i++) {
				if (i > 0) nameBuilder.Append(", ");
				nameBuilder.Append(fieldNames[i]);
				nameBuilder.Append(" : ");
				if (fieldTypes[i] != null) {
					nameBuilder.Append(fieldTypes[i].DotNetName);
				}
			}
			nameBuilder.Append('}');
			
			DefaultClass c = new DefaultClass(new DefaultCompilationUnit(resolver.ProjectContent), nameBuilder.ToString());
			c.Modifiers = ModifierEnum.Internal | ModifierEnum.Synthetic | ModifierEnum.Sealed;
			for (int i = 0; i < fieldTypes.Count; i++) {
				DefaultProperty p = new DefaultProperty(fieldNames[i], fieldTypes[i], ModifierEnum.Public | ModifierEnum.Synthetic, DomRegion.Empty, DomRegion.Empty, c);
				p.CanGet = true;
				p.CanSet = false;
				c.Properties.Add(p);
			}
			return c;
		}
		public override object VisitEventDeclaration(AST.EventDeclaration eventDeclaration, object data)
		{
			DomRegion region     = GetRegion(eventDeclaration.StartLocation, eventDeclaration.EndLocation);
			DomRegion bodyRegion = GetRegion(eventDeclaration.BodyStart,     eventDeclaration.BodyEnd);
			DefaultClass c = GetCurrentClass();
			
			IReturnType type;
			if (eventDeclaration.TypeReference.IsNull) {
				DefaultClass del = new DefaultClass(cu, ClassType.Delegate,
				                                    ConvertModifier(eventDeclaration.Modifier),
				                                    region, c);
				del.Modifiers |= ModifierEnum.Synthetic;
				CreateDelegate(del, eventDeclaration.Name + "EventHandler",
				               new AST.TypeReference("System.Void"),
				               new AST.TemplateDefinition[0],
				               eventDeclaration.Parameters);
				type = del.DefaultReturnType;
			} else {
				type = CreateReturnType(eventDeclaration.TypeReference);
			}
			DefaultEvent e = new DefaultEvent(eventDeclaration.Name, type, ConvertModifier(eventDeclaration.Modifier), region, bodyRegion, c);
			ConvertAttributes(eventDeclaration, e);
			c.Events.Add(e);
			if (e != null) {
				e.Documentation = GetDocumentation(region.BeginLine, eventDeclaration.Attributes);
			} else {
				LoggingService.Warn("NRefactoryASTConvertVisitor: " + eventDeclaration + " has no events!");
			}
			return null;
		}
		internal static void ApplySpecialsFromAttributes(DefaultClass c)
		{
			foreach (IAttribute att in c.Attributes) {
				if (att.AttributeType.FullyQualifiedName == "Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute"
				    || att.AttributeType.FullyQualifiedName == "System.Runtime.CompilerServices.CompilerGlobalScopeAttribute")
				{
					c.ClassType = ClassType.Module;
					break;
				}
			}
		}
		void CreateDelegate(DefaultClass c, string name, AST.TypeReference returnType, IList<AST.TemplateDefinition> templates, IList<AST.ParameterDeclarationExpression> parameters)
		{
			c.BaseTypes.Add(c.ProjectContent.SystemTypes.Delegate);
			if (currentClass.Count > 0) {
				DefaultClass cur = GetCurrentClass();
				cur.InnerClasses.Add(c);
				c.FullyQualifiedName = cur.FullyQualifiedName + '.' + name;
			} else {
				if (currentNamespace.Count == 0) {
					c.FullyQualifiedName = name;
				} else {
					c.FullyQualifiedName = currentNamespace.Peek() + '.' + name;
				}
				cu.Classes.Add(c);
			}
			currentClass.Push(c); // necessary for CreateReturnType
			ConvertTemplates(templates, c);
			
			List<IParameter> p = new List<IParameter>();
			if (parameters != null) {
				foreach (AST.ParameterDeclarationExpression param in parameters) {
					p.Add(CreateParameter(param));
				}
			}
			AnonymousMethodReturnType.AddDefaultDelegateMethod(c, CreateReturnType(returnType), p);
			
			currentClass.Pop();
		}