public void ConstFieldWithoutValueErr() { var text = @" class C { const int x; } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol type1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C").Single(); FieldSymbol mem = (FieldSymbol)type1.GetMembers("x").Single(); Assert.Equal("x", mem.Name); Assert.True(mem.IsConst); Assert.False(mem.HasConstantValue); Assert.Equal(null, mem.ConstantValue); }
public void NoPIALocalTypesEquivalentToEachOtherStructAsMethodParameterType() { //Structure - As method parameter type in external assembly (test this by passing the parameter with a variable which was declared in the current assembly) var localTypeSource = @"static class TypeSubstitution { FooStruct myOwnVar = null; public static void Main() { myOwnVar = new FooStruct(); myOwnVar.Structure = -1; ExternalAsm1.Scen1(myOwnVar); } } "; var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: new string[] { localTypeSource }, references: new MetadataReference[] { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1, }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); Assert.Equal(3, localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").Modules.FirstOrDefault().GetReferencedAssemblies().Length); Assert.Equal(3, localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").Modules.FirstOrDefault().GetReferencedAssemblySymbols().Length); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("FooStruct").Single(); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("TypeSubstitution").Single(); FieldSymbol localFieldSymbol = classLocalType.GetMembers("myOwnVar").OfType <FieldSymbol>().Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("ExternalAsm1").Single(); MethodSymbol refMethodSymbol = classRefLocalType.GetMembers("Scen1").OfType <MethodSymbol>().Single(); ImmutableArray <ParameterSymbol> param = refMethodSymbol.Parameters; NoPiaMissingCanonicalTypeSymbol missing = (NoPiaMissingCanonicalTypeSymbol)param.First().Type; Assert.Same(localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1"), missing.EmbeddingAssembly); Assert.Null(missing.Guid); Assert.Equal(canonicalType.ToTestDisplayString(), missing.FullTypeName); Assert.Equal("f9c2d51d-4f44-45f0-9eda-c9d599b58257", missing.Scope); Assert.Equal(canonicalType.ToTestDisplayString(), missing.Identifier); Assert.Same(canonicalType, localFieldSymbol.Type); Assert.IsType <NoPiaMissingCanonicalTypeSymbol>(param[0].Type); }
public void TestStaticConstructor() { var staticConstructorSymbol = _widgetClass .GetMembers(WellKnownMemberNames.StaticConstructorName) .Single(); Assert.Equal( "M:Acme.Widget.#cctor", staticConstructorSymbol.GetDocumentationCommentId() ); Assert.Equal( @"<member name=""M:Acme.Widget.#cctor""> <summary>Static Constructor</summary> </member> ", staticConstructorSymbol.GetDocumentationCommentXml() ); }
public void EventEscapedIdentifier() { var text = @" delegate void @out(); class C1 { @out @in; } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(); FieldSymbol ein = (FieldSymbol)c1.GetMembers("in").Single(); Assert.Equal("in", ein.Name); Assert.Equal("C1.@in", ein.ToString()); NamedTypeSymbol dout = (NamedTypeSymbol)ein.Type; Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); }
public void NoPiaIllegalGenericInstantiationSymbolForPropertyThatTakesGenericOfPIAType2() { //Test a static property that takes Generic(Of NoPIAType) var localTypeSource = @"public class NoPIAGenerics { TypeRefs1 typeRef = null; }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType1 = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single(); var local = classLocalType1.GetMembers("typeRef").OfType <FieldSymbol>().Single(); var importedProperty = local.Type.GetMembers("Property2").OfType <PropertySymbol>().Single(); Assert.Equal(SymbolKind.ErrorType, importedProperty.Type.Kind); Assert.IsType <NoPiaIllegalGenericInstantiationSymbol>(importedProperty.Type); }
public void NoPiaIllegalGenericInstantiationForFieldWithDelegateTypeThatReturnGenericOfPiaType() { //Test declaring field with delegate type that takes generic argument var localTypeSource = @" public class NoPIAGenerics { private static TypeRefs2.Delegate2 Event3; }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace .GetTypeMembers("NoPIAGenerics") .Single(); var var1 = classLocalType.GetMembers("Event3").OfType <FieldSymbol>().Single(); Assert.Equal(SymbolKind.NamedType, var1.Type.Kind); }
public void NoPiaIllegalGenericInstantiationSymboleForFieldWithNestedGenericType() { //Test field with Generic(Of IGeneric(Of NoPIAType)) var localTypeSource = @"public class NoPIAGenerics { NestedConstructs nested = null; }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single(); var localField = classLocalType.GetMembers("nested").OfType <FieldSymbol>().Single(); var importedField = localField.Type.GetMembers("field3").OfType <FieldSymbol>().Single(); Assert.Equal(SymbolKind.ErrorType, importedField.Type.Kind); Assert.IsType <NoPiaIllegalGenericInstantiationSymbol>(importedField.Type); }
public void NoPiaIllegalGenericInstantiationForStaticMethodAccessedThroughImports() { //Test static method accessed through Imports var localTypeSource = @" using MyClass1 = Class1; public class NoPIAGenerics { MyClass1 myclass = null; }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single(); var localField = classLocalType.GetMembers("myclass").OfType <FieldSymbol>().Single(); Assert.Equal(SymbolKind.ErrorType, localField.Type.BaseType.Kind); Assert.IsType <NoPiaIllegalGenericInstantiationSymbol>(localField.Type.BaseType); }
public void NoPIAInterfaceInheritsGenericInterface() { //Test interface that inherits IGeneric(Of NoPIAType) var localTypeSource = @" public class NoPIAGenerics { Interface1 i1 = null; }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType1 = localConsumer.GlobalNamespace .GetTypeMembers("NoPIAGenerics") .Single(); var var1 = classLocalType1.GetMembers("i1").OfType <FieldSymbol>().Single(); Assert.Equal(SymbolKind.NamedType, var1.Type.Kind); Assert.IsAssignableFrom <PENamedTypeSymbol>(var1.Type); }
public void NoPiaStaticMethodAccessedThroughImportsOfGenericClass() { //Test static method accessed through Imports of generic class var localTypeSource = @" using MyGenericClass2 = Class2<ISubFuncProp>; public class NoPIAGenerics { MyGenericClass2 mygeneric = null; }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single(); var localField = classLocalType.GetMembers("mygeneric").OfType <FieldSymbol>().Single(); Assert.Equal(SymbolKind.NamedType, localField.Type.Kind); Assert.IsType <ConstructedNamedTypeSymbol>(localField.Type); }
private static void CheckInnerClassHelper( NamedTypeSymbol innerClass, string methodName, Symbol interfaceEvent ) { var @interface = interfaceEvent.ContainingType; Assert.Equal(1, innerClass.Arity); Assert.Equal(TypeKind.Class, innerClass.TypeKind); Assert.Equal(@interface, innerClass.Interfaces().Single().ConstructedFrom); var innerClassEvent = (EventSymbol)innerClass.GetMembers(methodName).Single(); var innerClassImplementingEvent = innerClassEvent.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceEvent, innerClassImplementingEvent.OriginalDefinition); Assert.Equal(@interface, innerClassImplementingEvent.ContainingType.ConstructedFrom); }
public void NoPIALocalStructImplementInterfaceThatInheritsGenericTypeWithPIATypeParameters() { //Test implementing an interface that inherits IGeneric(Of NoPIAType) var localTypeSource1 = @" public class NoPIAGenerics { Interface1 i1 = new Interface1Impl(); }"; var localConsumer = CreateCompilation(localTypeSource1); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace .GetTypeMembers("NoPIAGenerics") .Single(); var var1 = classLocalType.GetMembers("i1").OfType <FieldSymbol>().Single(); Assert.Equal(SymbolKind.NamedType, var1.Type.Kind); Assert.IsAssignableFrom <PENamedTypeSymbol>(var1.Type); }
public void NoPIATypeSubstitutionForMethodExplicitlyImplementNoPiaInterface() { //Check type substitution for a method of a class that implement PIA interface var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: CSharpTestSource.None, references: new List <MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("ISubFuncProp").Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("SubFuncProp").Single(); MethodSymbol methodSymbol = classRefLocalType.GetMembers("Foo").OfType <MethodSymbol>().Single(); Assert.Equal(0, methodSymbol.ExplicitInterfaceImplementations.Length); }
public void NoPiaIllegalGenericInstantiationSymbolForClassThatInheritsGeneric() { //Test class that inherits Generic<NoPIAType> var localTypeSource = @"public class NoPIAGenerics { Class1 field = null; }"; var localConsumer1 = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType1 = localConsumer1.SourceModule.GlobalNamespace .GetTypeMembers("NoPIAGenerics") .Single(); var localField = classLocalType1.GetMembers("field").OfType <FieldSymbol>().Single(); Assert.Equal(SymbolKind.ErrorType, localField.Type.BaseType().Kind); Assert.IsType <NoPiaIllegalGenericInstantiationSymbol>(localField.Type.BaseType()); }
public void NoPiaIllegalGenericInstantiationSymbolForEventThatTakesGenericOfPiaType() { // Test hooking an event that takes Generic(Of NoPIAType) var localTypeSource = @" public class NoPIAGenerics { TypeRefs2 tr2b = null; }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace .GetTypeMembers("NoPIAGenerics") .Single(); var local = classLocalType.GetMembers("tr2b").OfType <FieldSymbol>().Single(); var importedField = local.Type.GetMembers("Event1").OfType <EventSymbol>().Single(); Assert.Equal(SymbolKind.ErrorType, importedField.Type.Kind); Assert.IsType <NoPiaIllegalGenericInstantiationSymbol>(importedField.Type); }
public void NoPiaIllegalGenericInstantiationSymbolForStaticMethodThatTakesGenericOfInterfacePiaType() { // Test a static method that returns Generic(Of NoPIAType) var localTypeSource = @"public class NoPIAGenerics { TypeRefs1 typeRef = null; }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace .GetTypeMembers("NoPIAGenerics") .Single(); var local = classLocalType.GetMembers("typeRef").OfType <FieldSymbol>().Single(); var importedMethod = local.Type.GetMembers("Method4").OfType <MethodSymbol>().Single(); Assert.Equal(SymbolKind.ErrorType, importedMethod.ReturnType.Kind); Assert.IsType <NoPiaIllegalGenericInstantiationSymbol>(importedMethod.ReturnType); }
private static XElement LoadChildType(NamedTypeSymbol t) { XElement elem = new XElement("type"); elem.Add(new XAttribute("name", t.Name)); if (t.Arity > 0) { string typeParams = string.Empty; foreach (var param in t.TypeParameters) { if (typeParams.Length > 0) { typeParams += ","; } typeParams += param.Name; } elem.Add(new XAttribute("Of", typeParams)); } if ((object)t.BaseType() != null) { elem.Add(new XAttribute("base", t.BaseType().ToTestDisplayString())); } var fields = t.GetMembers() .Where(m => m.Kind == SymbolKind.Field) .OrderBy(f => f.Name) .Cast <FieldSymbol>(); elem.Add(from f in fields select LoadField(f)); var childrenTypes = t.GetTypeMembers().OrderBy(c => c, new NameAndArityComparer()); elem.Add(from c in childrenTypes select LoadChildType(c)); return(elem); }
public override void VisitNamedType(NamedTypeSymbol type) { var previousContext = _nullableContext; _nullableContext = GetNullableContextAttribute(type.GetAttributes()) ?? _nullableContext; ReportSymbol(type); VisitList(type.TypeParameters); foreach (var member in type.GetMembers()) { // Skip accessors since those are covered by associated symbol. if (member.IsAccessor()) { continue; } Visit(member); } _nullableContext = previousContext; }
public void NoPIATypeSubstitutionForClassThatImplementNoPiaInterface() { //Check type substitution when a class implement a PIA interface var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: CSharpTestSource.None, references: new List <MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("ISubFuncProp").Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("SubFuncProp").Single(); MethodSymbol methodSymbol = classRefLocalType.GetMembers("Foo").OfType <MethodSymbol>().Single(); var interfaceType = classRefLocalType.GetDeclaredInterfaces(null).First(); Assert.Same(canonicalType, interfaceType); Assert.IsAssignableFrom <PENamedTypeSymbol>(interfaceType); }
public void NoPIALocalTypesEquivalentToEachOtherEnumAsReturnTypeInExternalAssembly() { //Enum - As return type in external assembly var localTypeSource = @"static class TypeSubstitution { FooEnum myLocalType = 0; public static void Main() { FooEnum myLocalType = 0; myLocalType = ExternalAsm1.Scen3(5); } }"; var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: new string[] { localTypeSource }, references: new List <MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("FooEnum").Single(); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("TypeSubstitution").Single(); FieldSymbol localFieldSymbol = classLocalType.GetMembers("myLocalType").OfType <FieldSymbol>().Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("ExternalAsm1").Single(); MethodSymbol methodSymbol = classRefLocalType.GetMembers("Scen3").OfType <MethodSymbol>().Single(); NoPiaMissingCanonicalTypeSymbol missing = (NoPiaMissingCanonicalTypeSymbol)methodSymbol.ReturnType; Assert.Same(localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1"), missing.EmbeddingAssembly); Assert.Null(missing.Guid); Assert.Equal(canonicalType.ToTestDisplayString(), missing.FullTypeName); Assert.Equal("f9c2d51d-4f44-45f0-9eda-c9d599b58257", missing.Scope); Assert.Equal(canonicalType.ToTestDisplayString(), missing.Identifier); Assert.Same(canonicalType, localFieldSymbol.Type); Assert.IsType <NoPiaMissingCanonicalTypeSymbol>(methodSymbol.ReturnType); }
public override void VisitNamedType(NamedTypeSymbol symbol) { _cancellationToken.ThrowIfCancellationRequested(); var sourceTypeSymbol = symbol as SourceMemberContainerTypeSymbol; if ((object)sourceTypeSymbol != null) { if (_moduleBeingBuilt != null) { // In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a // base type from another assembly) it is necessary for the compiler to generate explicit implementations for // some interface methods. They don't go in the symbol table, but if we are emitting metadata, then we should // generate MethodDef entries for them. foreach ( var synthesizedExplicitImpl in sourceTypeSymbol.GetSynthesizedExplicitImplementations( _cancellationToken ) ) { _moduleBeingBuilt.AddSynthesizedDefinition( symbol, synthesizedExplicitImpl.GetCciAdapter() ); } } } foreach (Symbol member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.Property: case SymbolKind.NamedType: member.Accept(this); break; } } }
private static PropertySymbol GetCustomTaskProperty( SyntheticBoundNodeFactory F, NamedTypeSymbol builderType, NamedTypeSymbol returnType) { const string propertyName = "Task"; var members = builderType.GetMembers(propertyName); foreach (var member in members) { if (member.Kind != SymbolKind.Property) { continue; } var property = (PropertySymbol)member; if ((property.DeclaredAccessibility == Accessibility.Public) && !property.IsStatic && (property.ParameterCount == 0)) { if (!property.Type.TypeSymbol.Equals(returnType, TypeCompareKind.AllIgnoreOptions)) { var badTaskProperty = new CSDiagnostic( new CSDiagnosticInfo(ErrorCode.ERR_BadAsyncMethodBuilderTaskProperty, builderType, returnType, property.Type.TypeSymbol), F.Syntax.Location); F.Diagnostics.Add(badTaskProperty); return(null); } return(property); } } var diagnostic = new CSDiagnostic( new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, builderType, propertyName), F.Syntax.Location); F.Diagnostics.Add(diagnostic); return(null); }
public void NoPIAClassThatInheritsGenericOfNoPIAType() { //Test class that inherits Generic(Of NoPIAType) var localTypeSource1 = @"public class BaseClass : System.Collections.Generic.List<FooStruct> { } public class DrivedClass { public static void Method1(BaseClass c1) { } public static BaseClass Method1() { return null; } }"; var localConsumer = CreateCompilation(localTypeSource1); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("DrivedClass").Single(); foreach (MethodSymbol m in classLocalType.GetMembers("Method1").OfType <MethodSymbol>()) { if (m.Parameters.Length > 0) { Assert.Equal(SymbolKind.Parameter, m.Parameters.Where(arg => arg.Name == "c1").Select(arg => arg).Single().Kind); Assert.True(m.Parameters.Where(arg => arg.Name == "c1").Select(arg => arg).Single().Type.IsFromCompilation(localConsumer)); } if (m.ReturnType.TypeKind != TypeKind.Struct) { Assert.Equal(SymbolKind.NamedType, m.ReturnType.Kind); Assert.True(m.ReturnType.IsFromCompilation(localConsumer)); } } }
public void NoPiaIllegalGenericInstantiationSymboleForFieldWithTwoNestedGenericType() { //Test field with IGeneric(Of IGeneric(Of Generic(Of NoPIAType))) var localTypeSource = @"public class NoPIAGenerics { NestedConstructs nested = New NestedConstructs(); }"; var localConsumer = CreateCompilation(localTypeSource); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single(); var localField = classLocalType.GetMembers("nested").OfType <FieldSymbol>().Single(); var importedField = localField.Type.GetMembers("field5").OfType <FieldSymbol>().Single(); Assert.Equal(SymbolKind.NamedType, importedField.Type.Kind); var outer = ((NamedTypeSymbol)importedField.Type).TypeArguments.Single(); Assert.Equal(SymbolKind.NamedType, outer.Kind); var inner = ((NamedTypeSymbol)outer).TypeArguments.Single(); Assert.Equal(SymbolKind.ErrorType, inner.Kind); }
private static MethodSymbol GetCustomCreateMethod( SyntheticBoundNodeFactory F, NamedTypeSymbol builderType ) { // The Create method's return type is expected to be builderType. // The WellKnownMembers routines aren't able to enforce that, which is why this method exists. const string methodName = "Create"; var members = builderType.GetMembers(methodName); foreach (var member in members) { if (member.Kind != SymbolKind.Method) { continue; } var method = (MethodSymbol)member; if ( (method.DeclaredAccessibility == Accessibility.Public) && method.IsStatic && method.ParameterCount == 0 && !method.IsGenericMethod && method.ReturnType.Equals(builderType, TypeCompareKind.AllIgnoreOptions) ) { return(method); } } F.Diagnostics.Add( ErrorCode.ERR_MissingPredefinedMember, F.Syntax.Location, builderType, methodName ); return(null); }
private BoundExpression BindAnonymousObjectCreation(AnonymousObjectCreationExpressionSyntax node, DiagnosticBag diagnostics) { // prepare var initializers = node.Initializers; int fieldCount = initializers.Count; bool hasError = false; // bind field initializers BoundExpression[] boundExpressions = new BoundExpression[fieldCount]; AnonymousTypeField[] fields = new AnonymousTypeField[fieldCount]; CSharpSyntaxNode[] fieldSyntaxNodes = new CSharpSyntaxNode[fieldCount]; // WARNING: Note that SemanticModel.GetDeclaredSymbol for field initializer node relies on // the fact that the order of properties in anonymous type template corresponds // 1-to-1 to the appropriate filed initializer syntax nodes; This means such // correspondence must be preserved all the time including erroneos scenarios // set of names already used HashSet <string> uniqueFieldNames = new HashSet <string>(); for (int i = 0; i < fieldCount; i++) { AnonymousObjectMemberDeclaratorSyntax fieldInitializer = initializers[i]; NameEqualsSyntax nameEquals = fieldInitializer.NameEquals; ExpressionSyntax expression = fieldInitializer.Expression; SyntaxToken nameToken = default(SyntaxToken); if (nameEquals != null) { nameToken = nameEquals.Name.Identifier; } else { nameToken = expression.ExtractAnonymousTypeMemberName(); } hasError = hasError || expression.HasErrors; boundExpressions[i] = this.BindValue(expression, diagnostics, BindValueKind.RValue); // check the name to be unique string fieldName = null; if (nameToken.CSharpKind() == SyntaxKind.IdentifierToken) { fieldName = nameToken.ValueText; if (uniqueFieldNames.Contains(fieldName)) { // name duplication Error(diagnostics, ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, fieldInitializer); hasError = true; fieldName = null; } else { uniqueFieldNames.Add(fieldName); } } else { // there is something wrong with field's name hasError = true; } // calculate the expression's type and report errors if needed TypeSymbol fieldType = GetAnonymousTypeFieldType(boundExpressions[i], fieldInitializer, diagnostics, ref hasError); // build anonymous type field descriptor fieldSyntaxNodes[i] = (nameToken.CSharpKind() == SyntaxKind.IdentifierToken) ? (CSharpSyntaxNode)nameToken.Parent : fieldInitializer; fields[i] = new AnonymousTypeField(fieldName == null ? '$' + i.ToString() : fieldName, fieldSyntaxNodes[i].Location, fieldType); // NOTE: ERR_InvalidAnonymousTypeMemberDeclarator (CS0746) would be generated by parser if needed } // Create anonymous type AnonymousTypeManager manager = this.Compilation.AnonymousTypeManager; AnonymousTypeDescriptor descriptor = new AnonymousTypeDescriptor(fields.AsImmutableOrNull(), node.NewKeyword.GetLocation()); NamedTypeSymbol anonymousType = manager.ConstructAnonymousTypeSymbol(descriptor); // declarators - bound nodes created for providing semantic info // on anonymous type fields having explicitly specified name ArrayBuilder <BoundAnonymousPropertyDeclaration> declarators = ArrayBuilder <BoundAnonymousPropertyDeclaration> .GetInstance(); for (int i = 0; i < fieldCount; i++) { NameEqualsSyntax explicitName = initializers[i].NameEquals; if (explicitName != null) { AnonymousTypeField field = fields[i]; if (field.Name != null) { // get property symbol and create a bound property declaration node foreach (var symbol in anonymousType.GetMembers(field.Name)) { if (symbol.Kind == SymbolKind.Property) { declarators.Add(new BoundAnonymousPropertyDeclaration(fieldSyntaxNodes[i], (PropertySymbol)symbol, field.Type)); break; } } } } } // check if anonymous object creation is allowed in this context if (!this.IsAnonymousTypesAllowed()) { Error(diagnostics, ErrorCode.ERR_AnonymousTypeNotAvailable, node.NewKeyword); hasError = true; } // Finally create a bound node return(new BoundAnonymousObjectCreationExpression( node, anonymousType.InstanceConstructors[0], boundExpressions.AsImmutableOrNull(), declarators.ToImmutableAndFree(), anonymousType, hasError)); }
public void TestNestedInterface() { Assert.Equal("T:Acme.Widget.IMenuItem", _widgetClass.GetMembers("IMenuItem").Single().GetDocumentationCommentId()); }
public Test01() { string source = @" using System.Diagnostics; [assembly: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [module: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] class TestClass { [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public int testField; [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public int TestProperty { [return: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] get { return testField; } } [return: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public T TestMethod<[DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] T> ([DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] T testParameter) { return testParameter; } }"; var compilation1 = CSharpCompilation.Create( "C1", new[] { Parse(source) }, new[] { OldMsCorLib }, TestOptions.ReleaseDll ); c1 = new CSharpCompilationReference(compilation1); var c1Assembly = compilation1.Assembly; var compilation2 = CSharpCompilation.Create( "C2", references: new MetadataReference[] { NewMsCorLib, c1 } ); c2 = new CSharpCompilationReference(compilation2); var c1AsmRef = compilation2.GetReferencedAssemblySymbol(c1); Assert.NotSame(c1Assembly, c1AsmRef); c1MscorLibAssemblyRef = compilation1.GetReferencedAssemblySymbol(OldMsCorLib); c2MscorlibAssemblyRef = compilation2.GetReferencedAssemblySymbol(NewMsCorLib); Assert.NotSame(c1MscorLibAssemblyRef, c2MscorlibAssemblyRef); oldMsCorLib_systemType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Type"); newMsCorLib_systemType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Type"); Assert.NotSame(oldMsCorLib_systemType, newMsCorLib_systemType); oldMsCorLib_debuggerTypeProxyAttributeType = c1MscorLibAssemblyRef.GetTypeByMetadataName( "System.Diagnostics.DebuggerTypeProxyAttribute" ); newMsCorLib_debuggerTypeProxyAttributeType = c2MscorlibAssemblyRef.GetTypeByMetadataName( "System.Diagnostics.DebuggerTypeProxyAttribute" ); Assert.NotSame( oldMsCorLib_debuggerTypeProxyAttributeType, newMsCorLib_debuggerTypeProxyAttributeType ); oldMsCorLib_debuggerTypeProxyAttributeCtor = (MethodSymbol)oldMsCorLib_debuggerTypeProxyAttributeType .GetMembers(".ctor") .Single( m => ((MethodSymbol)m).ParameterCount == 1 && TypeSymbol.Equals( ((MethodSymbol)m).GetParameterType(0), oldMsCorLib_systemType, TypeCompareKind.ConsiderEverything2 ) ); newMsCorLib_debuggerTypeProxyAttributeCtor = (MethodSymbol)newMsCorLib_debuggerTypeProxyAttributeType .GetMembers(".ctor") .Single( m => ((MethodSymbol)m).ParameterCount == 1 && TypeSymbol.Equals( ((MethodSymbol)m).GetParameterType(0), newMsCorLib_systemType, TypeCompareKind.ConsiderEverything2 ) ); Assert.NotSame( oldMsCorLib_debuggerTypeProxyAttributeCtor, newMsCorLib_debuggerTypeProxyAttributeCtor ); }
private static PropertySymbol FindIndexerWithParameterCount(NamedTypeSymbol type, int parameterCount) { return(type.GetMembers().Where(s => s.Kind == SymbolKind.Property).Cast <PropertySymbol>().Where(p => p.Parameters.Length == parameterCount).Single()); }
public void AccessCheckApi1() { CSharpCompilation c = CreateStandardCompilation(@" using System.Collections.Generic; class A { static private int priv; static public int pub; protected int prot; static private Goo unknowntype; private class K {} private K[] karray; private A[] aarray; private IEnumerable<K> kenum; private IEnumerable<A> aenum; } class B {} class ADerived: A {} class ADerived2: A {} "); NamespaceSymbol globalNS = c.GlobalNamespace; AssemblySymbol sourceAssem = c.SourceModule.ContainingAssembly; AssemblySymbol mscorlibAssem = c.GetReferencedAssemblySymbol(c.ExternalReferences[0]); NamedTypeSymbol classA = globalNS.GetMembers("A").Single() as NamedTypeSymbol; NamedTypeSymbol classADerived = globalNS.GetMembers("ADerived").Single() as NamedTypeSymbol; NamedTypeSymbol classADerived2 = globalNS.GetMembers("ADerived2").Single() as NamedTypeSymbol; NamedTypeSymbol classB = globalNS.GetMembers("B").Single() as NamedTypeSymbol; NamedTypeSymbol classK = classA.GetMembers("K").Single() as NamedTypeSymbol; FieldSymbol privField = classA.GetMembers("priv").Single() as FieldSymbol; FieldSymbol pubField = classA.GetMembers("pub").Single() as FieldSymbol; FieldSymbol protField = classA.GetMembers("prot").Single() as FieldSymbol; TypeSymbol karrayType = (classA.GetMembers("karray").Single() as FieldSymbol).Type; TypeSymbol aarrayType = (classA.GetMembers("aarray").Single() as FieldSymbol).Type; TypeSymbol kenumType = (classA.GetMembers("kenum").Single() as FieldSymbol).Type; TypeSymbol aenumType = (classA.GetMembers("aenum").Single() as FieldSymbol).Type; TypeSymbol unknownType = (classA.GetMembers("unknowntype").Single() as FieldSymbol).Type; var semanticModel = c.GetSemanticModel(c.SyntaxTrees[0]); Assert.True(Symbol.IsSymbolAccessible(classA, classB)); Assert.True(Symbol.IsSymbolAccessible(pubField, classB)); Assert.False(Symbol.IsSymbolAccessible(privField, classB)); Assert.False(Symbol.IsSymbolAccessible(karrayType, classB)); Assert.True(Symbol.IsSymbolAccessible(aarrayType, classB)); Assert.False(Symbol.IsSymbolAccessible(kenumType, classB)); Assert.True(Symbol.IsSymbolAccessible(aenumType, classB)); Assert.True(Symbol.IsSymbolAccessible(unknownType, classB)); Assert.True(Symbol.IsSymbolAccessible(globalNS, classB)); Assert.True(Symbol.IsSymbolAccessible(protField, classA)); Assert.True(Symbol.IsSymbolAccessible(protField, classA, classADerived)); Assert.False(Symbol.IsSymbolAccessible(protField, classB)); Assert.False(Symbol.IsSymbolAccessible(protField, classB, classADerived)); Assert.True(Symbol.IsSymbolAccessible(protField, classA)); Assert.True(Symbol.IsSymbolAccessible(protField, classADerived, classADerived)); Assert.False(Symbol.IsSymbolAccessible(protField, classADerived, classADerived2)); Assert.True(Symbol.IsSymbolAccessible(classA, sourceAssem)); Assert.True(Symbol.IsSymbolAccessible(aarrayType, sourceAssem)); Assert.False(Symbol.IsSymbolAccessible(karrayType, sourceAssem)); Assert.False(Symbol.IsSymbolAccessible(classA, mscorlibAssem)); Assert.True(Symbol.IsSymbolAccessible(unknownType, sourceAssem)); Assert.True(Symbol.IsSymbolAccessible(mscorlibAssem, sourceAssem)); }
/// <summary> /// Adds a new internal class with the given name equivalent to the passed type to the given syntax tree. /// /// Sets `created` to a reference to the newly created type. /// </summary> private static SyntaxNode AddType(NamedTypeSymbol equivTo, string withName, SyntaxNode tree, out TypeSyntax created) { created = Syntax.ParseTypeName(withName); var members = equivTo.GetMembers() .OfType<PropertySymbol>() .Select( s => { var prop = Syntax.PropertyDeclaration( null, Syntax.TokenList(Syntax.ParseToken("public")), Syntax.ParseTypeName(s.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)).WithLeadingTrivia(Syntax.ParseLeadingTrivia(" ")).WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), null, Syntax.Identifier(s.Name), Syntax.AccessorList( Syntax.List( Syntax.AccessorDeclaration( SyntaxKind.GetAccessorDeclaration, null, Syntax.TokenList(), Syntax.ParseToken("get"), null, Syntax.ParseToken(";") ), Syntax.AccessorDeclaration( SyntaxKind.SetAccessorDeclaration, null, Syntax.TokenList(), Syntax.ParseToken("set"), null, Syntax.ParseToken(";") ) ) ) ); return prop; } ) .Cast<MemberDeclarationSyntax>().ToList(); var separators = new List<SyntaxToken>(); for(var i = 0; i < members.Count - 1; i++) separators.Add(Syntax.ParseToken(",")); var obj = Syntax.AnonymousObjectCreationExpression( Syntax.SeparatedList( equivTo.GetMembers() .OfType<PropertySymbol>() .Select( p => { var exp = Syntax.IdentifierName(p.Name); return Syntax.AnonymousObjectMemberDeclarator(exp); } ), separators ) ).WithLeadingTrivia(Syntax.ParseLeadingTrivia(" ")); // Build the ToString() method that anonymous types have to have var toStringRef = Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, obj, Syntax.ParseToken("."), Syntax.IdentifierName("ToString")); var toStringAccess = Syntax.InvocationExpression(toStringRef); var toStringRet = Syntax.ReturnStatement(toStringAccess); var toStringStatements = Syntax.List<StatementSyntax>(toStringRet); var toStringBody = Syntax.Block( Syntax.ParseToken("{"), toStringStatements, Syntax.ParseToken("}") ); var toString = Syntax.MethodDeclaration( null, Syntax.TokenList(Syntax.ParseToken("public").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), Syntax.ParseToken("override").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" "))), Syntax.ParseTypeName("string").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), null, Syntax.Identifier("ToString"), null, Syntax.ParameterList(), null, toStringBody ); members.Add(toString); // Adding GetHashCode override anonymous types must have var hashCodeRef = Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, obj, Syntax.ParseToken("."), Syntax.IdentifierName("GetHashCode")); var hashCodeAccess = Syntax.InvocationExpression(hashCodeRef); var hashCodeRet = Syntax.ReturnStatement(hashCodeAccess); var hashCodeStatements = Syntax.List<StatementSyntax>(hashCodeRet); var hashCodeBody = Syntax.Block( Syntax.ParseToken("{"), hashCodeStatements, Syntax.ParseToken("}") ); var hashCode = Syntax.MethodDeclaration( null, Syntax.TokenList(Syntax.ParseToken("public").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), Syntax.ParseToken("override").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" "))), Syntax.ParseTypeName("int").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), null, Syntax.Identifier("GetHashCode"), null, Syntax.ParameterList(), null, hashCodeBody ); members.Add(hashCode); // Adding Equals method anonymous types must have var equalsAs = Syntax.ParseExpression("o as " + withName); var equalsAssign = Syntax.VariableDeclaration( created.WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), Syntax.SeparatedList( Syntax.VariableDeclarator( Syntax.Identifier("other"), null, Syntax.EqualsValueClause(equalsAs) ) ) ); var equalsEqualsRef = Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, obj, Syntax.ParseToken("."), Syntax.IdentifierName("Equals")); var equalsAccess = Syntax.InvocationExpression(equalsEqualsRef, Syntax.ArgumentList(Syntax.SeparatedList(Syntax.Argument(Syntax.ParseExpression("o"))))); var equalsIf = Syntax.IfStatement( Syntax.ParseExpression("other == null"), Syntax.ReturnStatement(equalsAccess) ); var equalsEqualsExps = equivTo.GetMembers() .OfType<PropertySymbol>() .Select( p => { var n = p.Name; ExpressionSyntax ret; if (p.Type.IsReferenceType) { var strExp = "(" + n + " != null ? " + n + ".Equals(other." + n + ") : (other." + n + " != null ? other." + n + ".Equals(" + n + ") : true ))"; ret = Syntax.ParseExpression(strExp); } else { ret = Syntax.ParseExpression(n + " == other." + n); } return ret.WithLeadingTrivia(Syntax.ParseLeadingTrivia(" ")).WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")); } ).ToList(); ExpressionSyntax equalsBinary = equalsEqualsExps.First(); for (var i = 1; i < equalsEqualsExps.Count; i++) equalsBinary = Syntax.BinaryExpression(SyntaxKind.LogicalAndExpression, equalsBinary, equalsEqualsExps[i]); var equalsBinaryRet = Syntax.ReturnStatement(equalsBinary.WithLeadingTrivia(Syntax.ParseLeadingTrivia(" "))); var equalsStatements = Syntax.List( (StatementSyntax)Syntax.LocalDeclarationStatement(equalsAssign), (StatementSyntax)equalsIf, (StatementSyntax)equalsBinaryRet ); var equalsBody = Syntax.Block( Syntax.ParseToken("{"), equalsStatements, Syntax.ParseToken("}") ); var equals = Syntax.MethodDeclaration( null, Syntax.TokenList(Syntax.ParseToken("public").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), Syntax.ParseToken("override").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" "))), Syntax.ParseTypeName("bool").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), null, Syntax.Identifier("Equals"), null, Syntax.ParameterList( Syntax.SeparatedList( Syntax.Parameter( null, Syntax.TokenList(), Syntax.ParseTypeName("object").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), Syntax.Identifier("o"), null ) ) ), null, equalsBody ); members.Add(equals); var equiv = Syntax.ClassDeclaration( null, Syntax.ParseToken("internal").WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), Syntax.Identifier(withName).WithLeadingTrivia(Syntax.ParseLeadingTrivia(" ")).WithTrailingTrivia(Syntax.ParseTrailingTrivia(" ")), null, null, null, Syntax.List<MemberDeclarationSyntax>(members) ); var namespaces = tree.ChildNodes().OfType<NamespaceDeclarationSyntax>(); if (namespaces.Count() == 0 || namespaces.Count() > 1) { // HACK, better way to insert classes should be considered throw new Exception("Making some assumptions about namespaces, you can only have 1"); } var @namespace = namespaces.Single(); var updated = @namespace.WithMembers( @namespace.Members.Add(equiv) ); return tree.ReplaceNode(@namespace, updated); }