Example #1
0
        public FieldReference(Module moduleBeingBuilt, FieldSymbol underlyingField)
            : base(moduleBeingBuilt)
        {
            Contract.ThrowIfNull(underlyingField);

            this.UnderlyingField = underlyingField;
        }
 public LockInfo(
     FieldDeclarationSyntax declaration,
     FieldSymbol symbol,
     AttributeData associatedAttribute,
     SemanticModel semanticModel)
     : base(declaration, symbol, associatedAttribute, semanticModel)
 {
 }
 public GuardedFieldInfo(
     FieldDeclarationSyntax declaration,
     FieldSymbol symbol,
     AttributeData associatedAttribute,
     SemanticModel semanticModel)
     : base(declaration, symbol, associatedAttribute, semanticModel)
 {
     _declaredLockHierarchy = LockHierarchy.FromStringList(Attribute.ConstructorArguments.SelectMany(arg => arg.Values.Select(argVal => argVal.Value.ToString())).ToList());
 }
        internal void AddField(FieldSymbol fieldSymbol)
        {
            Debug.Assert(fieldSymbol != null);

            // TODO--need to turn this guy into a token in conjuction with emitter
            stream.Add(fieldSymbol);
            this.PutSymbol(fieldSymbol);
            codesize += 4; // <token>
        }
        protected internal override object VisitField(FieldSymbol symbol, ArrayBuilder<SymbolDescriptionPart> builder)
        {
            AddAccessibilityIfRequired(symbol, builder);

            AddMemberModifiersIfRequired(symbol, builder);

            AddFieldModifiersIfRequired(symbol, builder);

            //TODO: custom modifiers

            if (format.MemberFlags.HasFlag(MemberFlags.IncludeType))
            {
                VisitType(symbol.Type, builder);
                AddSpace(builder);
            }

            builder.Add(new SymbolDescriptionPart
            {
                Kind = SymbolDescriptionPartKind.FieldName,
                Text = symbol.Name,
            });

            return null;
        }
Example #6
0
        private BoundExpression MakeTupleFieldAccessAndReportUseSiteDiagnostics(BoundExpression tuple, SyntaxNode syntax, FieldSymbol field)
        {
            // Use default field rather than implicitly named fields since
            // fields from inferred names are not usable in C# 7.0.
            field = field.CorrespondingTupleField ?? field;

            DiagnosticInfo useSiteInfo = field.GetUseSiteDiagnostic();

            if ((object)useSiteInfo != null && useSiteInfo.Severity == DiagnosticSeverity.Error)
            {
                Symbol.ReportUseSiteDiagnostic(useSiteInfo, _diagnostics, syntax.Location);
            }

            return(MakeTupleFieldAccess(syntax, field, tuple, null, LookupResultKind.Empty));
        }
Example #7
0
        public void AccessCheckApi1()
        {
            CSharpCompilation c              = CreateCompilationWithMscorlib(@"
using System.Collections.Generic;
class A
{
    static private int priv;
    static public int pub;
    protected int prot;
    static private Foo 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));
        }
Example #8
0
        private BoundExpression MakeEventAccess(
            CSharpSyntaxNode syntax,
            BoundExpression rewrittenReceiver,
            EventSymbol eventSymbol,
            ConstantValue constantValueOpt,
            LookupResultKind resultKind,
            TypeSymbol type)
        {
            Debug.Assert(eventSymbol.HasAssociatedField);

            FieldSymbol fieldSymbol = eventSymbol.AssociatedField;

            Debug.Assert((object)fieldSymbol != null);

            if (!eventSymbol.IsWindowsRuntimeEvent)
            {
                return(MakeFieldAccess(syntax, rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type));
            }

            NamedTypeSymbol fieldType = (NamedTypeSymbol)fieldSymbol.Type;

            Debug.Assert(fieldType.Name == "EventRegistrationTokenTable");

            // _tokenTable
            BoundFieldAccess fieldAccess = new BoundFieldAccess(
                syntax,
                fieldSymbol.IsStatic ? null : rewrittenReceiver,
                fieldSymbol,
                constantValueOpt: null)
            {
                WasCompilerGenerated = true
            };

            BoundExpression getOrCreateCall;

            MethodSymbol getOrCreateMethod;

            if (TryGetWellKnownTypeMember(syntax, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable, out getOrCreateMethod))
            {
                getOrCreateMethod = getOrCreateMethod.AsMember(fieldType);

                // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable)
                getOrCreateCall = BoundCall.Synthesized(
                    syntax,
                    receiverOpt: null,
                    method: getOrCreateMethod,
                    arg0: fieldAccess);
            }
            else
            {
                getOrCreateCall = new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray <Symbol> .Empty, ImmutableArray.Create <BoundNode>(fieldAccess), ErrorTypeSymbol.UnknownResultType);
            }

            PropertySymbol invocationListProperty;

            if (TryGetWellKnownTypeMember(syntax, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, out invocationListProperty))
            {
                MethodSymbol invocationListAccessor = invocationListProperty.GetMethod;

                if ((object)invocationListAccessor == null)
                {
                    string accessorName = SourcePropertyAccessorSymbol.GetAccessorName(invocationListProperty.Name,
                                                                                       getNotSet: true,
                                                                                       isWinMdOutput: invocationListProperty.IsCompilationOutputWinMdObj());
                    diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, invocationListProperty.ContainingType, accessorName), syntax.Location);
                }
                else
                {
                    invocationListAccessor = invocationListAccessor.AsMember(fieldType);
                    return(factory.Call(getOrCreateCall, invocationListAccessor));
                }
            }

            return(new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray <Symbol> .Empty, ImmutableArray.Create <BoundNode>(getOrCreateCall), ErrorTypeSymbol.UnknownResultType));
        }
Example #9
0
 public override Symbol VisitField(FieldSymbol symbol)
 {
     return(this.VisitNamedTypeMember(symbol, AreFieldsEqual));
 }
        public SpecializedFieldReference(FieldSymbol underlyingField)
        {
            Debug.Assert((object)underlyingField != null);

            _underlyingField = underlyingField;
        }
Example #11
0
        public FlatOperand Resolve(FieldSymbol field, FlatOperand into_lvalue, List<FlatStatement> instructions)
        {
            string field_name = field.Name;

            TypeExtraInfo tei = Chunk.GetTypeExtraInfo(field.ContainingType);
            if (tei == null)
            {
                throw new NotImplementedException("field of type without fields declarations? " + field.ContainingType.GetFullyQualifiedName());
            }

            int nField;
            if (tei.FieldNames.TryGetValue(field_name, out nField))
            {
                FieldExtraInfo fei = tei.Fields[nField];

                // non-static field
                return FlatOperand.FieldRef(nField, FlatValue.FromType(fei.Type));
            }
            if (tei.StaticFieldNames.TryGetValue(field_name, out nField))
            {
                // static field

                throw new NotImplementedException("static field from type " + field.ContainingType.GetFullyQualifiedName());
            }

            throw new NotImplementedException("missing field from type " + field.ContainingType.GetFullyQualifiedName());
        }
Example #12
0
 public virtual void VisitField(FieldSymbol symbol)
 {
     DefaultVisit(symbol);
 }
Example #13
0
        public void Test2()
        {
            var oldMsCorLib = TestReferences.NetFx.v4_0_21006.mscorlib;
            var newMsCorLib = MscorlibRef;

            var source = @"
public class Modifiers
{
    public volatile int volatileFld;

    void F1(System.DateTime* p)
    {
    }
}
";

            CSharpCompilation c1 = CSharpCompilation.Create("C1", new[] { Parse(source) }, new[] { oldMsCorLib });

            var c1Assembly = c1.Assembly;

            var r1 = new CSharpCompilationReference(c1);
            CSharpCompilation c2 = CSharpCompilation.Create("C2", references: new[] { newMsCorLib, r1 });
            var c1AsmRef         = c2.GetReferencedAssemblySymbol(r1);

            Assert.NotSame(c1Assembly, c1AsmRef);

            var mscorlibAssembly = c2.GetReferencedAssemblySymbol(newMsCorLib);

            Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib));

            var modifiers = c2.GlobalNamespace.GetTypeMembers("Modifiers").Single();

            Assert.IsType <RetargetingNamedTypeSymbol>(modifiers);

            FieldSymbol volatileFld = modifiers.GetMembers("volatileFld").OfType <FieldSymbol>().Single();

            Assert.Equal(1, volatileFld.TypeWithAnnotations.CustomModifiers.Length);

            var volatileFldMod = volatileFld.TypeWithAnnotations.CustomModifiers[0];

            Assert.False(volatileFldMod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsVolatile", volatileFldMod.Modifier.ToTestDisplayString());
            Assert.Equal(SpecialType.System_Int32, volatileFld.Type.SpecialType);
            Assert.Same(mscorlibAssembly, ((CSharpCustomModifier)volatileFldMod).ModifierSymbol.ContainingAssembly);

            Assert.Equal("volatileFld", volatileFld.Name);
            Assert.True(volatileFld.IsVolatile);
            Assert.Same(volatileFld, volatileFld.OriginalDefinition);
            Assert.Null(volatileFld.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false));
            Assert.Null(volatileFld.ConstantValue);
            Assert.Null(volatileFld.AssociatedSymbol);
            Assert.Same(c1AsmRef, volatileFld.ContainingAssembly);
            Assert.Same(c1AsmRef.Modules[0], volatileFld.ContainingModule);
            Assert.Same(modifiers, volatileFld.ContainingSymbol);
            Assert.Equal(Accessibility.Public, volatileFld.DeclaredAccessibility);
            Assert.False(volatileFld.IsConst);
            Assert.False(volatileFld.IsReadOnly);
            Assert.False(volatileFld.IsStatic);
            Assert.Same(volatileFld.ContainingModule, ((RetargetingFieldSymbol)volatileFld).RetargetingModule);
            Assert.Same(c1Assembly, ((RetargetingFieldSymbol)volatileFld).UnderlyingField.ContainingAssembly);

            MethodSymbol m1 = modifiers.GetMembers("F1").OfType <MethodSymbol>().Single();

            Assert.Equal(0, m1.ReturnTypeWithAnnotations.CustomModifiers.Length);
            Assert.True(!m1.ExplicitInterfaceImplementations.IsDefault);
            Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length);
            Assert.False(m1.HidesBaseMethodsByName);
            Assert.False(m1.IsExtensionMethod);
            Assert.Equal(((RetargetingMethodSymbol)m1).UnderlyingMethod.CallingConvention, m1.CallingConvention);
            Assert.Null(m1.AssociatedSymbol);
            Assert.Same(c1AsmRef.Modules[0], m1.ContainingModule);

            ParameterSymbol p1 = m1.Parameters[0];

            Assert.Equal(0, p1.TypeWithAnnotations.CustomModifiers.Length);
            Assert.Same(c1AsmRef.Modules[0], p1.ContainingModule);
            Assert.False(p1.HasExplicitDefaultValue, "Parameter has default value");
            Assert.Equal(0, p1.Ordinal);

            //PointerTypeSymbol p1Type = (PointerTypeSymbol)p1.Type;

            //Assert.Same(mscorlibAssembly, p1Type.ContainingAssembly);
            //Assert.Equal(SpecialType.System_DateTime, p1Type.PointedAtType.SpecialType);
            //Assert.Equal(0, p1Type.CustomModifiers.Count);
        }
Example #14
0
 public ExprFieldInfo(FieldSymbol f, AggregateType ft)
 {
     Field     = f;
     FieldType = ft;
 }
Example #15
0
 public static string GetErrorReportingName(FieldSymbol field)
 {
     return(GetErrorReportingName(field.ContainingType) + "." + field.Name);
 }
Example #16
0
        /// <summary>
        /// Special HasHome for fields.
        /// Fields have readable homes when they are not constants.
        /// Fields have writeable homes unless they are readonly and used outside of the constructor.
        /// </summary>
        private bool HasHome(BoundFieldAccess fieldAccess, bool needWriteable)
        {
            FieldSymbol field = fieldAccess.FieldSymbol;

            // const fields are literal values with no homes. (ex: decimal.Zero)
            if (field.IsConst)
            {
                return(false);
            }

            if (!needWriteable && !EnablePEVerifyCompat())
            {
                return(true);
            }

            // Some field accesses must be values; values do not have homes.
            if (fieldAccess.IsByValue)
            {
                return(false);
            }

            if (!field.IsReadOnly)
            {
                // in a case if we have a writeable struct field with a receiver that only has a readable home we would need to pass it via a temp.
                // it would be advantageous to make a temp for the field, not for the the outer struct, since the field is smaller and we can get to is by feching references.
                // NOTE: this would not be profitable if we have to satisfy verifier, since for verifiability
                //       we would not be able to dig for the inner field using references and the outer struct will have to be copied to a temp anyways.
                if (!EnablePEVerifyCompat())
                {
                    Debug.Assert(needWriteable == true);

                    var receiver = fieldAccess.ReceiverOpt;
                    if (receiver?.Type.IsValueType == true)
                    {
                        // Check receiver:
                        // has writeable home -> return true - the whole chain has writeable home (also a more common case)
                        // has readable home -> return false - we need to copy the field
                        // otherwise         -> return true  - the copy will be made at higher level so the leaf field can have writeable home

                        return(HasHome(receiver, needWriteable: true) ||
                               !HasHome(receiver, needWriteable: false));
                    }
                }

                return(true);
            }

            // while readonly fields have home it is not valid to refer to it when not constructing.
            if (field.ContainingType != _method.ContainingType)
            {
                return(false);
            }

            if (field.IsStatic)
            {
                return(_method.MethodKind == MethodKind.StaticConstructor);
            }
            else
            {
                return(_method.MethodKind == MethodKind.Constructor &&
                       fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference);
            }
        }
Example #17
0
        /// <summary>
        /// Recursive workhorse method for the method <see cref="GetAggregateFields"/>.
        /// </summary>
        ///
        /// <param name="aggregateType">Type of the aggregate that is being accessed.</param>
        /// <param name="offset">Offset of the access from the start of the aggregate,
        /// in bits.</param>
        /// <param name="accessType">Type of the aggregate access.</param>
        /// <param name="accessBitSize">Bit-size of the aggregate access.</param>
        /// <param name="getArrayElements">True if, and only if, the elements of
        /// a fixed-size array should be treated as separate fields of the aggregate.</param>
        /// <param name="accessSoFar">Expression that represents the access so far.</param>
        /// <param name="path">Path that contains the aggregate.</param>
        /// <returns>List of AggregateField objects, each of which represents
        /// the aggregate fields that the input aggregate access overlaps.</returns>
        private static List <AggregateField> GetAggregateFieldsHelper(AggregateType aggregateType,
                                                                      int offset, Phx.Types.Type accessType, int accessBitSize, bool getArrayElements,
                                                                      Expression accessSoFar, Path path)
        {
            Utilities.Configuration config = path.Config;
            List <AggregateField>   result = new List <AggregateField>();

            int         completedOffset    = 0;
            FieldSymbol currentFieldSymbol = aggregateType.FieldSymbolList;

            while (currentFieldSymbol != null)
            {
                /* Obtain the necessary information from the current field symbol. */
                string         fieldName        = currentFieldSymbol.ToString();
                int            fieldStartOffset = currentFieldSymbol.BitOffset;
                Phx.Types.Type fieldType        = currentFieldSymbol.Type;
                int            fieldEndOffset   = (fieldStartOffset + (int)fieldType.BitSize) - 1;

                /* Move to the next field symbol for the subsequent iteration. */
                currentFieldSymbol = currentFieldSymbol.NextFieldSymbol;
                if (fieldStartOffset < completedOffset)
                {
                    /* Skip this field if it starts at an offset in the part of
                     * the aggregate that has already been examined. */
                    continue;
                }
                else
                {
                    /* Move the completed offset pointer to the end of the field currently
                     * being examined. This indicates that, after this iteration
                     * is complete, the part of the aggregate prior to the pointer
                     * has already been examined. */
                    completedOffset = fieldEndOffset;
                }

                if (((offset <= fieldStartOffset) &&
                     (fieldStartOffset <= (offset + accessBitSize) - 1)) ||
                    ((offset > fieldStartOffset) && (offset <= fieldEndOffset)))
                {
                    /* Attach a unique identifier to each field name. */
                    string newFieldName = String.Format("{0}{1}{2}{3}",
                                                        config.IDENT_FIELD, fieldName,
                                                        config.IDENT_AGGREGATE, GetAggregateName(aggregateType));

                    /* Make an array variable Expression for the field, since we represent
                     * aggregate accesses as accesses into an array. */
                    Expression newArrayVar =
                        new Expression(OperatorStore.ArrayVariableOp, newFieldName);
                    newArrayVar.Type = Phx.Types.PointerType.New(aggregateType.TypeTable,
                                                                 Phx.Types.PointerTypeKind.UnmanagedPointer, path.Config.WORD_BITSIZE,
                                                                 fieldType, fieldType.TypeSymbol);
                    path.AddVariable(newArrayVar);

                    /* Convert the array variable Expression into the equivalent
                     * pointer Expression, represented as a dereferencing function. */
                    newArrayVar = ExpressionHelper.MakeDereferencingFunction(newArrayVar, path);

                    /* Apply the dereferencing function on the Expression generated so far. */
                    List <Expression> argExprs = new List <Expression>();
                    argExprs.Add(accessSoFar);
                    argExprs.Add(new Constant(0, config.WORD_BITSIZE));

                    Expression fieldAccessExpr =
                        ExpressionHelper.ApplyFunction(newArrayVar, argExprs, path);
                    fieldAccessExpr = ExpressionHelper.LookupAndReplaceOffset(fieldAccessExpr,
                                                                              fieldType, false, path);

                    if (fieldType.IsAggregateType)
                    {
                        /* Recurse into the field, if the field is itself an aggregate. */
                        AggregateType         innerAggregateType   = fieldType.AsAggregateType;
                        List <AggregateField> innerAggregateFields =
                            GetAggregateFieldsHelper(innerAggregateType,
                                                     Math.Max((offset - fieldStartOffset), 0),
                                                     accessType,
                                                     (accessBitSize - Math.Max(fieldStartOffset - offset, 0)),
                                                     getArrayElements, fieldAccessExpr, path);
                        foreach (AggregateField innerAggregateField in innerAggregateFields)
                        {
                            /* Include the offset of the field inside
                             * the enclosing aggregate type. */
                            innerAggregateField.StartOffset += fieldStartOffset;
                            result.Add(innerAggregateField);
                        }
                    }
                    else if (fieldType.IsUnmanagedArrayType &&
                             !ExpressionHelper.AreSameTypes(fieldType, accessType) &&
                             getArrayElements)
                    {
                        List <Pair <Expression, int> > arrayElements =
                            ExpressionHelper.GetArrayElementsInRange(fieldAccessExpr,
                                                                     Math.Max((offset - fieldStartOffset), 0),
                                                                     (accessBitSize - Math.Max(fieldStartOffset - offset, 0)),
                                                                     path);
                        foreach (Pair <Expression, int> arrayElementAndOffset in arrayElements)
                        {
                            Expression arrayElementExpr   = arrayElementAndOffset.First;
                            int        arrayElementOffset = arrayElementAndOffset.Second;

                            result.Add(new AggregateField(aggregateType,
                                                          arrayElementExpr, (fieldStartOffset + arrayElementOffset),
                                                          arrayElementExpr.BitSize));
                        }
                    }
                    else
                    {
                        result.Add(new AggregateField(aggregateType,
                                                      fieldAccessExpr, fieldStartOffset, fieldType.BitSize));
                    }
                }
            }

            Trace.Assert(result.Count > 0, "PHOENIX: Field(s) not found.");
            return(result);
        }
 public override object VisitField(FieldSymbol symbol, object argument)
 {
     throw ExceptionUtilities.Unreachable;
 }
Example #19
0
        private Symbol GetNodeSymbol(BoundNode node)
        {
            while (node != null)
            {
                switch (node.Kind)
                {
                case BoundKind.FieldAccess:
                {
                    var fieldAccess = (BoundFieldAccess)node;
                    if (MayRequireTracking(fieldAccess.ReceiverOpt, fieldAccess.FieldSymbol))
                    {
                        node = fieldAccess.ReceiverOpt;
                        continue;
                    }

                    return(null);
                }

                case BoundKind.LocalDeclaration:
                {
                    return(((BoundLocalDeclaration)node).LocalSymbol);
                }

                case BoundKind.ThisReference:
                {
                    return(MethodThisParameter);
                }

                case BoundKind.Local:
                {
                    return(((BoundLocal)node).LocalSymbol);
                }

                case BoundKind.Parameter:
                {
                    return(((BoundParameter)node).ParameterSymbol);
                }

                case BoundKind.CatchBlock:
                {
                    var local = ((BoundCatchBlock)node).LocalOpt;
                    Debug.Assert((object)local == null || local.DeclarationKind == LocalDeclarationKind.CatchVariable);
                    return((object)local != null ? local : null);
                }

                case BoundKind.ForEachStatement:
                {
                    return(((BoundForEachStatement)node).IterationVariable);
                }

                case BoundKind.RangeVariable:
                {
                    return(((BoundRangeVariable)node).RangeVariableSymbol);
                }

                case BoundKind.EventAccess:
                {
                    var         eventAccess     = (BoundEventAccess)node;
                    FieldSymbol associatedField = eventAccess.EventSymbol.AssociatedField;
                    if ((object)associatedField != null)
                    {
                        if (MayRequireTracking(eventAccess.ReceiverOpt, associatedField))
                        {
                            node = eventAccess.ReceiverOpt;
                            continue;
                        }
                    }
                    return(null);
                }

                default:
                {
                    return(null);
                }
                }
            }

            return(null);
        }
Example #20
0
 public void Init(FieldSymbol f, AggregateType ft)
 {
     _field = f;
     _fieldType = ft;
 }
Example #21
0
        public void Test1()
        {
            var oldMsCorLib = TestReferences.NetFx.v4_0_21006.mscorlib;
            var newMsCorLib = MscorlibRef;

            var c1 = CSharpCompilation.Create("C1", references: new[]
            {
                oldMsCorLib,
                TestReferences.SymbolsTests.CustomModifiers.Modifiers.netmodule
            });

            var c1Assembly = c1.Assembly;

            CSharpCompilation c2 = CSharpCompilation.Create("C2", references: new MetadataReference[] { newMsCorLib, new CSharpCompilationReference(c1) });

            var mscorlibAssembly = c2.GetReferencedAssemblySymbol(newMsCorLib);

            Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib));

            var modifiers = c2.GlobalNamespace.GetTypeMembers("Modifiers").Single();

            Assert.IsAssignableFrom <PENamedTypeSymbol>(modifiers);

            FieldSymbol f0 = modifiers.GetMembers("F0").OfType <FieldSymbol>().Single();

            Assert.Equal(1, f0.TypeWithAnnotations.CustomModifiers.Length);

            var f0Mod = f0.TypeWithAnnotations.CustomModifiers[0];

            Assert.True(f0Mod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", f0Mod.Modifier.ToTestDisplayString());
            Assert.Same(mscorlibAssembly, f0Mod.Modifier.ContainingAssembly.GetSymbol());

            MethodSymbol    m1 = modifiers.GetMembers("F1").OfType <MethodSymbol>().Single();
            ParameterSymbol p1 = m1.Parameters[0];
            ParameterSymbol p2 = modifiers.GetMembers("F2").OfType <MethodSymbol>().Single().Parameters[0];

            MethodSymbol    m5 = modifiers.GetMembers("F5").OfType <MethodSymbol>().Single();
            ParameterSymbol p5 = m5.Parameters[0];

            ParameterSymbol p6 = modifiers.GetMembers("F6").OfType <MethodSymbol>().Single().Parameters[0];

            MethodSymbol m7 = modifiers.GetMembers("F7").OfType <MethodSymbol>().Single();

            Assert.Equal(0, m1.ReturnTypeWithAnnotations.CustomModifiers.Length);

            Assert.Equal(1, p1.TypeWithAnnotations.CustomModifiers.Length);

            var p1Mod = p1.TypeWithAnnotations.CustomModifiers[0];

            Assert.True(p1Mod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", p1Mod.Modifier.ToTestDisplayString());
            Assert.Same(mscorlibAssembly, p1Mod.Modifier.ContainingAssembly.GetSymbol());

            Assert.Equal(2, p2.TypeWithAnnotations.CustomModifiers.Length);

            foreach (var p2Mod in p2.TypeWithAnnotations.CustomModifiers)
            {
                Assert.True(p2Mod.IsOptional);
                Assert.Equal("System.Runtime.CompilerServices.IsConst", p2Mod.Modifier.ToTestDisplayString());
                Assert.Same(mscorlibAssembly, p2Mod.Modifier.ContainingAssembly.GetSymbol());
            }

            Assert.True(m5.ReturnsVoid);
            Assert.Equal(1, m5.ReturnTypeWithAnnotations.CustomModifiers.Length);

            var m5Mod = m5.ReturnTypeWithAnnotations.CustomModifiers[0];

            Assert.True(m5Mod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", m5Mod.Modifier.ToTestDisplayString());
            Assert.Same(mscorlibAssembly, m5Mod.Modifier.ContainingAssembly.GetSymbol());

            Assert.Equal(0, p5.TypeWithAnnotations.CustomModifiers.Length);

            ArrayTypeSymbol p5Type = (ArrayTypeSymbol)p5.Type;

            Assert.Equal("System.Int32", p5Type.ElementType.ToTestDisplayString());

            Assert.Equal(1, p5Type.ElementTypeWithAnnotations.CustomModifiers.Length);
            var p5TypeMod = p5Type.ElementTypeWithAnnotations.CustomModifiers[0];

            Assert.True(p5TypeMod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", p5TypeMod.Modifier.ToTestDisplayString());
            Assert.Same(mscorlibAssembly, p5TypeMod.Modifier.ContainingAssembly.GetSymbol());

            Assert.Equal(0, p6.TypeWithAnnotations.CustomModifiers.Length);

            PointerTypeSymbol p6Type = (PointerTypeSymbol)p6.Type;

            Assert.Equal("System.Int32", p6Type.PointedAtType.ToTestDisplayString());

            Assert.Equal(1, p6Type.PointedAtTypeWithAnnotations.CustomModifiers.Length);
            var p6TypeMod = p6Type.PointedAtTypeWithAnnotations.CustomModifiers[0];

            Assert.True(p6TypeMod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", p6TypeMod.Modifier.ToTestDisplayString());
            Assert.Same(mscorlibAssembly, p6TypeMod.Modifier.ContainingAssembly.GetSymbol());

            Assert.False(m7.ReturnsVoid);
            Assert.Equal(1, m7.ReturnTypeWithAnnotations.CustomModifiers.Length);

            var m7Mod = m7.ReturnTypeWithAnnotations.CustomModifiers[0];

            Assert.True(m7Mod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", m7Mod.Modifier.ToTestDisplayString());
            Assert.Same(mscorlibAssembly, m7Mod.Modifier.ContainingAssembly.GetSymbol());
        }
 public FieldDefinition(Module moduleBeingBuilt, FieldSymbol underlyingField)
     : base(moduleBeingBuilt, underlyingField)
 { }
        public void Test1()
        {
            var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
            {
                TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll,
                TestReferences.NetFx.v4_0_21006.mscorlib
            });

            var modifiersModule = assemblies[0].Modules[0];


            var modifiers = modifiersModule.GlobalNamespace.GetTypeMembers("Modifiers").Single();

            FieldSymbol f0 = modifiers.GetMembers("F0").OfType <FieldSymbol>().Single();

            Assert.Equal(1, f0.TypeWithAnnotations.CustomModifiers.Length);

            var f0Mod = f0.TypeWithAnnotations.CustomModifiers[0];

            Assert.True(f0Mod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", f0Mod.Modifier.ToTestDisplayString());

            MethodSymbol    m1 = modifiers.GetMembers("F1").OfType <MethodSymbol>().Single();
            ParameterSymbol p1 = m1.Parameters[0];
            ParameterSymbol p2 = modifiers.GetMembers("F2").OfType <MethodSymbol>().Single().Parameters[0];

            ParameterSymbol p4 = modifiers.GetMembers("F4").OfType <MethodSymbol>().Single().Parameters[0];

            MethodSymbol    m5 = modifiers.GetMembers("F5").OfType <MethodSymbol>().Single();
            ParameterSymbol p5 = m5.Parameters[0];

            ParameterSymbol p6 = modifiers.GetMembers("F6").OfType <MethodSymbol>().Single().Parameters[0];

            MethodSymbol m7 = modifiers.GetMembers("F7").OfType <MethodSymbol>().Single();

            Assert.Equal(0, m1.ReturnTypeWithAnnotations.CustomModifiers.Length);

            Assert.Equal(1, p1.TypeWithAnnotations.CustomModifiers.Length);

            var p1Mod = p1.TypeWithAnnotations.CustomModifiers[0];

            Assert.True(p1Mod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", p1Mod.Modifier.ToTestDisplayString());

            Assert.Equal(2, p2.TypeWithAnnotations.CustomModifiers.Length);

            foreach (var p2Mod in p2.TypeWithAnnotations.CustomModifiers)
            {
                Assert.True(p2Mod.IsOptional);
                Assert.Equal("System.Runtime.CompilerServices.IsConst", p2Mod.Modifier.ToTestDisplayString());
            }

            Assert.Equal(SymbolKind.ErrorType, p4.Type.Kind);

            Assert.True(m5.ReturnsVoid);
            Assert.Equal(1, m5.ReturnTypeWithAnnotations.CustomModifiers.Length);

            var m5Mod = m5.ReturnTypeWithAnnotations.CustomModifiers[0];

            Assert.True(m5Mod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", m5Mod.Modifier.ToTestDisplayString());

            Assert.Equal(0, p5.TypeWithAnnotations.CustomModifiers.Length);

            ArrayTypeSymbol p5Type = (ArrayTypeSymbol)p5.Type;

            Assert.Equal("System.Int32", p5Type.ElementType.ToTestDisplayString());

            Assert.Equal(1, p5Type.ElementTypeWithAnnotations.CustomModifiers.Length);
            var p5TypeMod = p5Type.ElementTypeWithAnnotations.CustomModifiers[0];

            Assert.True(p5TypeMod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", p5TypeMod.Modifier.ToTestDisplayString());

            Assert.Equal(0, p6.TypeWithAnnotations.CustomModifiers.Length);

            PointerTypeSymbol p6Type = (PointerTypeSymbol)p6.Type;

            Assert.Equal("System.Int32", p6Type.PointedAtType.ToTestDisplayString());

            Assert.Equal(1, p6Type.PointedAtTypeWithAnnotations.CustomModifiers.Length);
            var p6TypeMod = p6Type.PointedAtTypeWithAnnotations.CustomModifiers[0];

            Assert.True(p6TypeMod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", p6TypeMod.Modifier.ToTestDisplayString());

            Assert.False(m7.ReturnsVoid);
            Assert.Equal(1, m7.ReturnTypeWithAnnotations.CustomModifiers.Length);

            var m7Mod = m7.ReturnTypeWithAnnotations.CustomModifiers[0];

            Assert.True(m7Mod.IsOptional);
            Assert.Equal("System.Runtime.CompilerServices.IsConst", m7Mod.Modifier.ToTestDisplayString());
        }
Example #24
0
 private static void AppendFieldSymbolInfo(this ICollection<SymbolMarkupToken> markup, FieldSymbol symbol)
 {
     markup.AppendPlainText("(field)");
     markup.AppendSpace();
     markup.AppendType(symbol.ValueType, true);
     markup.AppendSpace();
     markup.AppendType((TypeSymbol) symbol.Parent, false);
     markup.AppendPunctuation(".");
     markup.AppendName(SymbolMarkupKind.FieldName, symbol.Name);
 }
Example #25
0
 private void EmitStaticFieldAddress(FieldSymbol field, SyntaxNode syntaxNode)
 {
     _builder.EmitOpCode(ILOpCode.Ldsflda);
     EmitSymbolToken(field, syntaxNode);
 }
 private void AddVariableCleanup(ArrayBuilder <BoundAssignmentOperator> cleanup, FieldSymbol field)
 {
     if (MightContainReferences(field.Type))
     {
         cleanup.Add(F.AssignmentExpression(F.Field(F.This(), field), F.NullOrDefault(field.Type)));
     }
 }
Example #27
0
 private void EmitSymbolToken(FieldSymbol symbol, CSharpSyntaxNode syntaxNode)
 {
     builder.EmitToken(module.Translate(symbol, syntaxNode, diagnostics), syntaxNode, diagnostics);
 }
Example #28
0
 private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other)
 {
     Debug.Assert(NameComparer.Equals(field.Name, other.Name));
     return(this.comparer.Equals(field.Type, other.Type));
 }
Example #29
0
 private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other)
 {
     Debug.Assert(StringOrdinalComparer.Equals(field.Name, other.Name));
     return(_comparer.Equals(field.Type, other.Type));
 }
 public FieldPlace(Operand target, FieldSymbol field, TextSpan span)
     : base(span)
 {
     Target = target;
     Field  = field;
 }
Example #31
0
        public bool GetRuntimeFieldNumber(FieldSymbol field, out int nField)
        {
            TypeExtraInfo tei = Chunk.GetTypeExtraInfo(field.ContainingType);
            if (tei == null)
            {
                throw new NotImplementedException("field of type without fields declarations? " + field.ContainingType.GetFullyQualifiedName());
            }

            if (tei.ResolveRuntimeField(field.Name, out nField))
            {
                return true;
            }
            if (tei.ResolveRuntimeStaticField(field.Name, out nField))
            {
                return true;
            }
            return false;
        }
Example #32
0
 internal static InitializerSemanticModel Create(SyntaxTreeSemanticModel containingSemanticModel, CSharpSyntaxNode syntax, FieldSymbol fieldSymbol, Binder rootBinder)
 {
     Debug.Assert(containingSemanticModel != null);
     Debug.Assert(syntax.IsKind(SyntaxKind.VariableDeclarator) || syntax.IsKind(SyntaxKind.EnumMemberDeclaration));
     return(new InitializerSemanticModel(syntax, fieldSymbol, rootBinder, containingSemanticModel));
 }
Example #33
0
        public FlatOperand Resolve(FieldSymbol field, FlatOperand fop_type, FlatOperand into_lvalue, List<FlatStatement> instructions)
        {
            string field_name = field.Name;

            TypeExtraInfo tei = Chunk.GetTypeExtraInfo(field.ContainingType);
            if (tei == null)
            {
                throw new NotImplementedException("field of type without fields declarations? " + field.ContainingType.GetFullyQualifiedName());
            }

            if (into_lvalue == null)
            {
                into_lvalue = AllocateRegister("");
                into_lvalue = into_lvalue.GetLValue(this, instructions);
            }

            int nTypeField;
            int nField;
            if (!field.IsStatic)
            {
                if (tei.FieldNames.TryGetValue(field_name, out nTypeField) && tei.ResolveRuntimeField(field_name, out nField))
                {
                    FieldExtraInfo fei = tei.Fields[nTypeField];
                    instructions.Add(FlatStatement.RESOLVEFIELD(into_lvalue, fop_type, FlatOperand.Immediate(FlatValue.Int32(nField))));
                    return into_lvalue.AsRValue(FlatValue.FromType(field.Type));
                }
            }
            else
            {
                // static field
                instructions.Add(FlatStatement.RESOLVESTATICFIELD(into_lvalue, fop_type, FlatOperand.Immediate(FlatValue.String(field_name))));
                return into_lvalue.AsRValue(FlatValue.FromType(field.Type));
            }
            throw new NotImplementedException("missing field from type " + field.ContainingType.GetFullyQualifiedName());
        }
Example #34
0
 /// <summary>
 /// Called when visiting a <see cref="FieldSymbol" />; Override this with specific
 /// implementation; Calling default <see cref="DefaultVisit" /> if it's not overridden
 /// </summary>
 /// <param name="symbol">The visited symbol</param>
 /// <param name="argument">Additional argument</param>
 /// <returns></returns>
 public virtual TResult VisitField(FieldSymbol symbol, TArgument argument)
 {
     return(DefaultVisit(symbol, argument));
 }
Example #35
0
 private static void AppendFieldSymbolInfo(this ICollection<SymbolMarkupToken> markup, FieldSymbol symbol)
 {
     markup.AppendPlainText("(field)");
     markup.AppendSpace();
     markup.AppendType(symbol.ValueType, true);
     markup.AppendSpace();
     markup.AppendType((TypeSymbol) symbol.Parent, false);
     markup.AppendPunctuation(".");
     markup.AppendName(SymbolMarkupKind.FieldName, symbol.Name);
 }
Example #36
0
        /// <summary>
        /// Generate a thread-safe accessor for a WinRT field-like event.
        /// 
        /// Add:
        ///   return EventRegistrationTokenTable&lt;Event&gt;.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddEventHandler(value);
        /// 
        /// Remove:
        ///   EventRegistrationTokenTable&lt;Event&gt;.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).RemoveEventHandler(value);
        /// </summary>
        internal static BoundBlock ConstructFieldLikeEventAccessorBody_WinRT(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, DiagnosticBag diagnostics)
        {
            CSharpSyntaxNode syntax = eventSymbol.CSharpSyntaxNode;

            MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod;
            Debug.Assert((object)accessor != null);

            FieldSymbol field = eventSymbol.AssociatedField;
            Debug.Assert((object)field != null);

            NamedTypeSymbol fieldType = (NamedTypeSymbol)field.Type;
            Debug.Assert(fieldType.Name == "EventRegistrationTokenTable");

            MethodSymbol getOrCreateMethod = (MethodSymbol)Binder.GetWellKnownTypeMember(
                compilation,
                WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable,
                diagnostics,
                syntax: syntax);

            if ((object)getOrCreateMethod == null)
            {
                Debug.Assert(diagnostics.HasAnyErrors());
                return null;
            }

            getOrCreateMethod = getOrCreateMethod.AsMember(fieldType);

            WellKnownMember processHandlerMember = isAddMethod
                ? WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler
                : WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler;

            MethodSymbol processHandlerMethod = (MethodSymbol)Binder.GetWellKnownTypeMember(
                compilation,
                processHandlerMember,
                diagnostics,
                syntax: syntax);

            if ((object)processHandlerMethod == null)
            {
                Debug.Assert(diagnostics.HasAnyErrors());
                return null;
            }

            processHandlerMethod = processHandlerMethod.AsMember(fieldType);

            // _tokenTable
            BoundFieldAccess fieldAccess = new BoundFieldAccess(
                syntax,
                field.IsStatic ? null : new BoundThisReference(syntax, accessor.ThisParameter.Type),
                field,
                constantValueOpt: null)
            { WasCompilerGenerated = true };

            // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable)
            BoundCall getOrCreateCall = BoundCall.Synthesized(
                syntax,
                receiverOpt: null,
                method: getOrCreateMethod,
                arg0: fieldAccess);

            // value
            BoundParameter parameterAccess = new BoundParameter(
                syntax,
                accessor.Parameters[0]);

            // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddHandler(value) // or RemoveHandler
            BoundCall processHandlerCall = BoundCall.Synthesized(
                syntax,
                receiverOpt: getOrCreateCall,
                method: processHandlerMethod,
                arg0: parameterAccess);

            if (isAddMethod)
            {
                // {
                //     return EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddHandler(value);
                // }   
                BoundStatement returnStatement = BoundReturnStatement.Synthesized(syntax, RefKind.None, processHandlerCall);
                return BoundBlock.SynthesizedNoLocals(syntax, returnStatement);
            }
            else
            {
                // {
                //     EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).RemoveHandler(value);
                //     return;
                // }  
                BoundStatement callStatement = new BoundExpressionStatement(syntax, processHandlerCall);
                BoundStatement returnStatement = new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null);
                return BoundBlock.SynthesizedNoLocals(syntax, callStatement, returnStatement);
            }
        }
 public override Microsoft.Cci.IReference VisitField(FieldSymbol symbol, bool a)
 {
     return Translate(symbol, false);
 }
Example #38
0
        // NOTE: can return null if the method has no body.
        internal static BoundBlock BindMethodBody(MethodSymbol method, TypeCompilationState compilationState, DiagnosticBag diagnostics, bool generateDebugInfo, out ConsList <Imports> debugImports)
        {
            debugImports = null;

            BoundStatement constructorInitializer = null;
            BoundBlock     body;

            var compilation = method.DeclaringCompilation;

            var sourceMethod = method as SourceMethodSymbol;

            if ((object)sourceMethod != null)
            {
                if (sourceMethod.IsExtern)
                {
                    if (sourceMethod.BlockSyntax == null)
                    {
                        // Generate warnings only if we are not generating ERR_ExternHasBody error
                        GenerateExternalMethodWarnings(sourceMethod, diagnostics);
                    }
                    return(null);
                }
                else if (sourceMethod.IsParameterlessValueTypeConstructor(requireSynthesized: true))
                {
                    // No body for default struct constructor.
                    return(null);
                }

                var blockSyntax = sourceMethod.BlockSyntax;
                if (blockSyntax != null)
                {
                    var factory        = compilation.GetBinderFactory(sourceMethod.SyntaxTree);
                    var inMethodBinder = factory.GetBinder(blockSyntax);
                    var binder         = new ExecutableCodeBinder(blockSyntax, sourceMethod, inMethodBinder);
                    body = binder.BindBlock(blockSyntax, diagnostics);
                    if (generateDebugInfo)
                    {
                        debugImports = binder.ImportsList;
                    }
                    if (inMethodBinder.IsDirectlyInIterator)
                    {
                        foreach (var parameter in method.Parameters)
                        {
                            if (parameter.RefKind != RefKind.None)
                            {
                                diagnostics.Add(ErrorCode.ERR_BadIteratorArgType, parameter.Locations[0]);
                            }
                            else if (parameter.Type.IsUnsafe())
                            {
                                diagnostics.Add(ErrorCode.ERR_UnsafeIteratorArgType, parameter.Locations[0]);
                            }
                        }

                        if (sourceMethod.IsUnsafe && compilation.Options.AllowUnsafe) // Don't cascade
                        {
                            diagnostics.Add(ErrorCode.ERR_IllegalInnerUnsafe, sourceMethod.Locations[0]);
                        }

                        if (sourceMethod.IsVararg)
                        {
                            // error CS1636: __arglist is not allowed in the parameter list of iterators
                            diagnostics.Add(ErrorCode.ERR_VarargsIterator, sourceMethod.Locations[0]);
                        }
                    }
                }
                else // for [if (blockSyntax != null)]
                {
                    var property = sourceMethod.AssociatedSymbol as SourcePropertySymbol;
                    if ((object)property != null && property.IsAutoProperty)
                    {
                        return(MethodBodySynthesizer.ConstructAutoPropertyAccessorBody(sourceMethod));
                    }

                    if (sourceMethod.IsPrimaryCtor)
                    {
                        body = null;
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            else
            {
                //  synthesized methods should return their bound bodies
                body = null;
            }

            // delegates have constructors but not constructor initializers
            if (method.MethodKind == MethodKind.Constructor && !method.ContainingType.IsDelegateType())
            {
                var initializerInvocation = BindConstructorInitializer(method, diagnostics, compilation);

                if (initializerInvocation != null)
                {
                    constructorInitializer = new BoundExpressionStatement(initializerInvocation.Syntax, initializerInvocation)
                    {
                        WasCompilerGenerated = true
                    };
                    Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer.");
                }
            }

            var statements = ArrayBuilder <BoundStatement> .GetInstance();

            if (constructorInitializer != null)
            {
                statements.Add(constructorInitializer);
            }

            if ((object)sourceMethod != null && sourceMethod.IsPrimaryCtor && (object)((SourceMemberContainerTypeSymbol)sourceMethod.ContainingType).PrimaryCtor == (object)sourceMethod)
            {
                Debug.Assert(method.MethodKind == MethodKind.Constructor && !method.ContainingType.IsDelegateType());
                Debug.Assert(body == null);

                if (sourceMethod.ParameterCount > 0)
                {
                    var factory = new SyntheticBoundNodeFactory(sourceMethod, sourceMethod.SyntaxNode, compilationState, diagnostics);
                    factory.CurrentMethod = sourceMethod;

                    foreach (var parameter in sourceMethod.Parameters)
                    {
                        FieldSymbol field = parameter.PrimaryConstructorParameterBackingField;

                        if ((object)field != null)
                        {
                            statements.Add(factory.Assignment(factory.Field(factory.This(), field),
                                                              factory.Parameter(parameter)));
                        }
                    }
                }
            }

            if (body != null)
            {
                statements.Add(body);
            }

            CSharpSyntaxNode syntax = body != null ? body.Syntax : method.GetNonNullSyntaxNode();

            BoundBlock block;

            if (statements.Count == 1 && statements[0].Kind == ((body == null) ? BoundKind.Block : body.Kind))
            {
                // most common case - we just have a single block for the body.
                block = (BoundBlock)statements[0];
                statements.Free();
            }
            else
            {
                block = new BoundBlock(syntax, default(ImmutableArray <LocalSymbol>), statements.ToImmutableAndFree())
                {
                    WasCompilerGenerated = true
                };
            }

            return(method.MethodKind == MethodKind.Destructor ? MethodBodySynthesizer.ConstructDestructorBody(syntax, method, block) : block);
        }
Example #39
0
 public static FlatValue StaticField(FieldSymbol value)
 {
     return new FlatValue() { ValueType = FlatValueType.VT_StaticField, Object = value };
 }
        private void AddFieldModifiersIfRequired(FieldSymbol symbol, ArrayBuilder<SymbolDescriptionPart> builder)
        {
            if (format.MemberFlags.HasFlag(MemberFlags.IncludeModifiers))
            {
                if (symbol.IsConst)
                {
                    AddKeyword(SyntaxKind.ConstKeyword, builder);
                    AddSpace(builder);
                }

                if (symbol.IsReadOnly)
                {
                    AddKeyword(SyntaxKind.ReadOnlyKeyword, builder);
                    AddSpace(builder);
                }

                if (symbol.IsVolatile)
                {
                    AddKeyword(SyntaxKind.VolatileKeyword, builder);
                    AddSpace(builder);
                }

                //TODO: event
            }
        }
            protected BoundExpression LowerEvaluation(BoundDagEvaluation evaluation)
            {
                BoundExpression input = _tempAllocator.GetTemp(evaluation.Input);

                switch (evaluation)
                {
                case BoundDagFieldEvaluation f:
                {
                    FieldSymbol     field      = f.Field;
                    var             outputTemp = new BoundDagTemp(f.Syntax, field.Type, f);
                    BoundExpression output     = _tempAllocator.GetTemp(outputTemp);
                    BoundExpression access     = _localRewriter.MakeFieldAccess(f.Syntax, input, field, null, LookupResultKind.Viable, field.Type);
                    access.WasCompilerGenerated = true;
                    return(_factory.AssignmentExpression(output, access));
                }

                case BoundDagPropertyEvaluation p:
                {
                    PropertySymbol  property   = p.Property;
                    var             outputTemp = new BoundDagTemp(p.Syntax, property.Type, p);
                    BoundExpression output     = _tempAllocator.GetTemp(outputTemp);
                    return(_factory.AssignmentExpression(output, _localRewriter.MakePropertyAccess(_factory.Syntax, input, property, LookupResultKind.Viable, property.Type, isLeftOfAssignment: false)));
                }

                case BoundDagDeconstructEvaluation d:
                {
                    MethodSymbol method         = d.DeconstructMethod;
                    var          refKindBuilder = ArrayBuilder <RefKind> .GetInstance();

                    var argBuilder = ArrayBuilder <BoundExpression> .GetInstance();

                    BoundExpression receiver;
                    void addArg(RefKind refKind, BoundExpression expression)
                    {
                        refKindBuilder.Add(refKind);
                        argBuilder.Add(expression);
                    }

                    Debug.Assert(method.Name == WellKnownMemberNames.DeconstructMethodName);
                    int extensionExtra;
                    if (method.IsStatic)
                    {
                        Debug.Assert(method.IsExtensionMethod);
                        receiver = _factory.Type(method.ContainingType);
                        addArg(method.ParameterRefKinds[0], input);
                        extensionExtra = 1;
                    }
                    else
                    {
                        receiver       = input;
                        extensionExtra = 0;
                    }

                    for (int i = extensionExtra; i < method.ParameterCount; i++)
                    {
                        ParameterSymbol parameter = method.Parameters[i];
                        Debug.Assert(parameter.RefKind == RefKind.Out);
                        var outputTemp = new BoundDagTemp(d.Syntax, parameter.Type, d, i - extensionExtra);
                        addArg(RefKind.Out, _tempAllocator.GetTemp(outputTemp));
                    }

                    return(_factory.Call(receiver, method, refKindBuilder.ToImmutableAndFree(), argBuilder.ToImmutableAndFree()));
                }

                case BoundDagTypeEvaluation t:
                {
                    TypeSymbol inputType = input.Type;
                    Debug.Assert(inputType is { });
                    if (inputType.IsDynamic())
                    {
                        // Avoid using dynamic conversions for pattern-matching.
                        inputType = _factory.SpecialType(SpecialType.System_Object);
                        input     = _factory.Convert(inputType, input);
                    }

                    TypeSymbol      type       = t.Type;
                    var             outputTemp = new BoundDagTemp(t.Syntax, type, t);
                    BoundExpression output     = _tempAllocator.GetTemp(outputTemp);
                    CompoundUseSiteInfo <AssemblySymbol> useSiteInfo = _localRewriter.GetNewCompoundUseSiteInfo();
                    Conversion conversion = _factory.Compilation.Conversions.ClassifyBuiltInConversion(inputType, output.Type, ref useSiteInfo);
                    _localRewriter._diagnostics.Add(t.Syntax, useSiteInfo);
                    BoundExpression evaluated;
                    if (conversion.Exists)
                    {
                        if (conversion.Kind == ConversionKind.ExplicitNullable &&
                            inputType.GetNullableUnderlyingType().Equals(output.Type, TypeCompareKind.AllIgnoreOptions) &&
                            _localRewriter.TryGetNullableMethod(t.Syntax, inputType, SpecialMember.System_Nullable_T_GetValueOrDefault, out MethodSymbol getValueOrDefault))
                        {
                            // As a special case, since the null test has already been done we can use Nullable<T>.GetValueOrDefault
                            evaluated = _factory.Call(input, getValueOrDefault);
                        }
                        else
                        {
                            evaluated = _factory.Convert(type, input, conversion);
                        }
                    }
                    else
                    {
                        evaluated = _factory.As(input, type);
                    }

                    return(_factory.AssignmentExpression(output, evaluated));
                }
        internal Microsoft.Cci.IFieldReference Translate(FieldSymbol fieldSymbol, bool needDeclaration)
        {
            System.Diagnostics.Debug.Assert(ReferenceEquals(fieldSymbol, fieldSymbol.OriginalDefinition) ||
                !fieldSymbol.Equals(fieldSymbol.OriginalDefinition));

            if (!ReferenceEquals(fieldSymbol, fieldSymbol.OriginalDefinition))
            {
                System.Diagnostics.Debug.Assert(!needDeclaration);

                return fieldSymbol;
            }
            else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType))
            {
                object reference;
                Microsoft.Cci.IFieldReference fieldRef;

                if (genericInstanceMap.TryGetValue(fieldSymbol, out reference))
                {
                    return (Microsoft.Cci.IFieldReference)reference;
                }

                fieldRef = new SpecializedFieldReference(fieldSymbol);

                genericInstanceMap.Add(fieldSymbol, fieldRef);

                return fieldRef;
            }


            return fieldSymbol;
        }
Example #43
0
        private BoundBlock GenerateAwaitForIncompleteTask(LocalSymbol awaiterTemp)
        {
            int stateNumber;
            GeneratedLabelSymbol resumeLabel;

            AddState(out stateNumber, out resumeLabel);

            TypeSymbol awaiterFieldType = awaiterTemp.Type.IsVerifierReference()
                ? F.SpecialType(SpecialType.System_Object)
                : awaiterTemp.Type;

            FieldSymbol awaiterField = GetAwaiterField(awaiterFieldType);

            var blockBuilder = ArrayBuilder <BoundStatement> .GetInstance();

            blockBuilder.Add(
                // this.state = cachedState = stateForLabel
                F.Assignment(F.Field(F.This(), stateField), F.AssignmentExpression(F.Local(cachedState), F.Literal(stateNumber))));

            blockBuilder.Add(
                // Emit await yield point to be injected into PDB
                F.NoOp(NoOpStatementFlavor.AwaitYieldPoint));

            blockBuilder.Add(
                // this.<>t__awaiter = $awaiterTemp
                F.Assignment(
                    F.Field(F.This(), awaiterField),
                    (awaiterField.Type == awaiterTemp.Type)
                        ? F.Local(awaiterTemp)
                        : F.Convert(awaiterFieldType, F.Local(awaiterTemp))));

            blockBuilder.Add(awaiterTemp.Type.IsDynamic()
                ? GenerateAwaitOnCompletedDynamic(awaiterTemp)
                : GenerateAwaitOnCompleted(awaiterTemp.Type, awaiterTemp));

            blockBuilder.Add(
                GenerateReturn(false));

            blockBuilder.Add(
                F.Label(resumeLabel));

            blockBuilder.Add(
                // Emit await resume point to be injected into PDB
                F.NoOp(NoOpStatementFlavor.AwaitResumePoint));

            blockBuilder.Add(
                // $awaiterTemp = this.<>t__awaiter   or   $awaiterTemp = (AwaiterType)this.<>t__awaiter
                // $this.<>t__awaiter = null;
                F.Assignment(
                    F.Local(awaiterTemp),
                    awaiterTemp.Type == awaiterField.Type
                        ? F.Field(F.This(), awaiterField)
                        : F.Convert(awaiterTemp.Type, F.Field(F.This(), awaiterField))));

            blockBuilder.Add(
                F.Assignment(F.Field(F.This(), awaiterField), F.NullOrDefault(awaiterField.Type)));

            blockBuilder.Add(
                // this.state = cachedState = NotStartedStateMachine
                F.Assignment(F.Field(F.This(), stateField), F.AssignmentExpression(F.Local(cachedState), F.Literal(StateMachineStates.NotStartedStateMachine))));

            return(F.Block(blockBuilder.ToImmutableAndFree()));
        }
        internal LoweredDynamicOperation MakeDynamicOperation(
            BoundExpression binderConstruction,
            BoundExpression loweredReceiver,
            RefKind receiverRefKind,
            ImmutableArray <BoundExpression> loweredArguments,
            ImmutableArray <RefKind> refKinds,
            BoundExpression loweredRight,
            TypeSymbol resultType)
        {
            Debug.Assert(!loweredArguments.IsDefault);

            // get well-known types and members we need:
            NamedTypeSymbol delegateTypeOverMethodTypeParameters = GetDelegateType(loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, resultType);
            NamedTypeSymbol callSiteTypeGeneric        = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T);
            MethodSymbol    callSiteFactoryGeneric     = _factory.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Create);
            FieldSymbol     callSiteTargetFieldGeneric = (FieldSymbol)_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Target);
            MethodSymbol    delegateInvoke;

            if (binderConstruction == null ||
                (object)delegateTypeOverMethodTypeParameters == null ||
                delegateTypeOverMethodTypeParameters.IsErrorType() ||
                (object)(delegateInvoke = delegateTypeOverMethodTypeParameters.DelegateInvokeMethod) == null ||
                callSiteTypeGeneric.IsErrorType() ||
                (object)callSiteFactoryGeneric == null ||
                (object)callSiteTargetFieldGeneric == null)
            {
                // CS1969: One or more types required to compile a dynamic expression cannot be found.
                // Dev11 reports it with source location for each dynamic operation, which results in many error messages.
                // The diagnostic that names the specific missing type or member has already been reported.
                _factory.Diagnostics.Add(ErrorCode.ERR_DynamicRequiredTypesMissing, NoLocation.Singleton);

                return(LoweredDynamicOperation.Bad(loweredReceiver, loweredArguments, loweredRight, resultType));
            }

            if ((object)_currentDynamicCallSiteContainer == null)
            {
                _currentDynamicCallSiteContainer = CreateCallSiteContainer(_factory, _methodOrdinal);
            }

            var containerDef = (SynthesizedContainer)_currentDynamicCallSiteContainer.OriginalDefinition;
            var methodToContainerTypeParametersMap = containerDef.TypeMap;

            var callSiteType          = callSiteTypeGeneric.Construct(new[] { delegateTypeOverMethodTypeParameters });
            var callSiteFactoryMethod = callSiteFactoryGeneric.AsMember(callSiteType);
            var callSiteTargetField   = callSiteTargetFieldGeneric.AsMember(callSiteType);
            var callSiteField         = DefineCallSiteStorageSymbol(containerDef, delegateTypeOverMethodTypeParameters, methodToContainerTypeParametersMap);
            var callSiteFieldAccess   = _factory.Field(null, callSiteField);
            var callSiteArguments     = GetCallSiteArguments(callSiteFieldAccess, loweredReceiver, loweredArguments, loweredRight);

            var nullCallSite = _factory.Null(callSiteField.Type);

            var siteInitialization = _factory.Conditional(
                _factory.ObjectEqual(callSiteFieldAccess, nullCallSite),
                _factory.AssignmentExpression(callSiteFieldAccess, _factory.Call(null, callSiteFactoryMethod, binderConstruction)),
                nullCallSite,
                callSiteField.Type);

            var siteInvocation = _factory.Call(
                _factory.Field(callSiteFieldAccess, callSiteTargetField),
                delegateInvoke,
                callSiteArguments);

            return(new LoweredDynamicOperation(_factory, siteInitialization, siteInvocation, resultType));
        }
        private void LearnFromAnyNullPatterns(
            int inputSlot,
            TypeSymbol inputType,
            BoundPattern pattern)
        {
            if (inputSlot <= 0)
            {
                return;
            }

            // https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we
            // can get information for any nodes in the pattern.
            VisitPatternForRewriting(pattern);

            switch (pattern)
            {
            case BoundConstantPattern cp:
                bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null;
                if (isExplicitNullCheck)
                {
                    // Since we're not branching on this null test here, we just infer the top level
                    // nullability.  We'll branch on it later.
                    LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
                }
                break;

            case BoundDeclarationPattern _:
            case BoundDiscardPattern _:
            case BoundITuplePattern _:
            case BoundRelationalPattern _:
                break;     // nothing to learn

            case BoundTypePattern tp:
                if (tp.IsExplicitNotNullTest)
                {
                    LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
                }
                break;

            case BoundRecursivePattern rp:
            {
                if (rp.IsExplicitNotNullTest)
                {
                    LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
                }

                // for positional part: we only learn from tuples (not Deconstruct)
                if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault)
                {
                    var elements = inputType.TupleElements;
                    for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++)
                    {
                        BoundSubpattern item    = rp.Deconstruction[i];
                        FieldSymbol     element = elements[i];
                        LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern);
                    }
                }

                // for property part
                if (!rp.Properties.IsDefault)
                {
                    for (int i = 0, n = rp.Properties.Length; i < n; i++)
                    {
                        BoundSubpattern item   = rp.Properties[i];
                        Symbol          symbol = item.Symbol;
                        if (symbol?.ContainingType.Equals(inputType, TypeCompareKind.AllIgnoreOptions) == true)
                        {
                            LearnFromAnyNullPatterns(GetOrCreateSlot(symbol, inputSlot), symbol.GetTypeOrReturnType().Type, item.Pattern);
                        }
                    }
                }
            }
            break;

            case BoundNegatedPattern p:
                LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated);
                break;

            case BoundBinaryPattern p:
                LearnFromAnyNullPatterns(inputSlot, inputType, p.Left);
                LearnFromAnyNullPatterns(inputSlot, inputType, p.Right);
                break;

            default:
                throw ExceptionUtilities.UnexpectedValue(pattern);
            }
        }
 public GeneratedCodeHeuristics([NotNull] FieldSymbol field)
 {
     Guard.NotNull(field, "field");
     this.field = field;
 }
 public static string GetErrorReportingName(FieldSymbol field)
 {
     return GetErrorReportingName(field.ContainingType) + "." + field.Name;
 }