public override AttributeNode VisitAttributeNode(AttributeNode attribute)
        {
            if (attribute == null) return null;

            if (attribute.Type.Namespace != null && ContractNodes.ContractNamespace.Matches(attribute.Type.Namespace))
            {
                switch (attribute.Type.Name.Name)
                {
                    case "ContractClassAttribute":
                    case "ContractInvariantMethodAttribute":
                    case "ContractClassForAttribute":
                    case "ContractVerificationAttribute":
                    case "ContractPublicPropertyNameAttribute":
                    case "ContractArgumentValidatorAttribute":
                    case "ContractAbbreviatorAttribute":
                    case "ContractOptionAttribute":
                    case "ContractRuntimeIgnoredAttribute":
                    case "PureAttribute":
                        return attribute;
                    default:
                        return null;
                    // Don't propagate any other attributes from System.Diagnostics.Contracts, they might be types defined only in mscorlib.contracts.dll
                }
            }

            return base.VisitAttributeNode(attribute);
        }
Esempio n. 2
0
        public virtual bool IsExposedAttribute(AttributeNode attribute) {
            if (attribute == null) throw new ArgumentNullException("attribute");

            // check whether attribte type is exposed
            TypeNode attributeType = attribute.Type;
            if (!IsExposedType(attributeType)) return (false);

            // check whether expressions used to instantiate attribute are exposed
            ExpressionList expressions = attribute.Expressions;
            for (int i = 0; i < expressions.Count; i++) {
                if (!IsExposedExpression(expressions[i])) return (false);
            }

            // apply user filters to attribute
            return (attributeFilter.IsExposedType(attributeType));
        }
Esempio n. 3
0
 public override Expression VisitAttributeConstructor(AttributeNode attribute)
 {
     throw new NotImplementedException("Node type not yet supported");
 }
Esempio n. 4
0
        internal static void TryAddCompilerGeneratedAttribute(Member member, System.AttributeTargets targets)
        {
          Contract.Requires(member != null);

            if (HelperMethods.compilerGeneratedAttributeNode == null) return;
            Member compilerGenerated = HelperMethods.compilerGeneratedAttributeNode.GetConstructor();
            AttributeNode compilerGeneratedAttribute = new AttributeNode(new MemberBinding(null, compilerGenerated), null, targets);
            member.Attributes.Add(compilerGeneratedAttribute);
        }
Esempio n. 5
0
        public static ThreeValued IsMutableHeapIndependent(AttributeNode attr)
        {
            string category, setting;
            bool value;

            if (IsContractOptionAttribute(attr, out category, out setting, out value))
            {
                if (string.Compare("reads", category, true) == 0)
                {
                    if (string.Compare("mutable", setting, true) == 0)
                    {
                        if (!value) return ThreeValued.True;
                        
                        return ThreeValued.False;
                    }
                }
            }

            return ThreeValued.Maybe;
        }
Esempio n. 6
0
 public virtual AttributeNode VisitAttributeNode(AttributeNode attribute)
 {
     if (attribute == null) return null;
     attribute.Constructor = this.VisitAttributeConstructor(attribute);
     attribute.Expressions = this.VisitExpressionList(attribute.Expressions);
     return attribute;
 }
Esempio n. 7
0
    /// <summary>
    /// Tries to reuse or create the attribute
    /// </summary>
    private static InstanceInitializer GetRuntimeContractsAttributeCtor(AssemblyNode assembly)
    {
      EnumNode runtimeContractsFlags = assembly.GetType(ContractNodes.ContractNamespace, Identifier.For("RuntimeContractsFlags")) as EnumNode;
      Class RuntimeContractsAttributeClass = assembly.GetType(ContractNodes.ContractNamespace, Identifier.For("RuntimeContractsAttribute")) as Class;

      if (runtimeContractsFlags == null)
      {
        #region Add [Flags]
        Member flagsConstructor = RewriteHelper.flagsAttributeNode.GetConstructor();
        AttributeNode flagsAttribute = new AttributeNode(new MemberBinding(null, flagsConstructor), null, AttributeTargets.Class);
        #endregion Add [Flags]
        runtimeContractsFlags = new EnumNode(assembly,
          null, /* declaringType */
          new AttributeList(2),
          TypeFlags.Sealed,
          ContractNodes.ContractNamespace,
          Identifier.For("RuntimeContractsFlags"),
          new InterfaceList(),
          new MemberList());
        runtimeContractsFlags.Attributes.Add(flagsAttribute);
        RewriteHelper.TryAddCompilerGeneratedAttribute(runtimeContractsFlags);
        runtimeContractsFlags.UnderlyingType = SystemTypes.Int32;

        Type copyFrom = typeof(RuntimeContractEmitFlags);
        foreach (System.Reflection.FieldInfo fi in copyFrom.GetFields())
        {
          if (fi.IsLiteral)
          {
            AddEnumValue(runtimeContractsFlags, fi.Name, fi.GetRawConstantValue());
          }
        }
        assembly.Types.Add(runtimeContractsFlags);

      }


      InstanceInitializer ctor = (RuntimeContractsAttributeClass == null) ? null : RuntimeContractsAttributeClass.GetConstructor(runtimeContractsFlags);

      if (RuntimeContractsAttributeClass == null)
      {
        RuntimeContractsAttributeClass = new Class(assembly,
          null, /* declaringType */
          new AttributeList(),
          TypeFlags.Sealed,
          ContractNodes.ContractNamespace,
          Identifier.For("RuntimeContractsAttribute"),
          SystemTypes.Attribute,
          new InterfaceList(),
          new MemberList(0));

        RewriteHelper.TryAddCompilerGeneratedAttribute(RuntimeContractsAttributeClass);
        assembly.Types.Add(RuntimeContractsAttributeClass);
      }
      if (ctor == null) {

        Block returnBlock = new Block(new StatementList(new Return()));

        Block body = new Block(new StatementList());
        Block b = new Block(new StatementList());
        ParameterList pl = new ParameterList();
        Parameter levelParameter = new Parameter(Identifier.For("contractFlags"), runtimeContractsFlags);
        pl.Add(levelParameter);

        ctor = new InstanceInitializer(RuntimeContractsAttributeClass, null, pl, body);
        ctor.Flags = MethodFlags.Assembly | MethodFlags.HideBySig | MethodFlags.SpecialName | MethodFlags.RTSpecialName;

        Method baseCtor = SystemTypes.Attribute.GetConstructor();

        b.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(null, baseCtor), new ExpressionList(ctor.ThisParameter))));
        b.Statements.Add(returnBlock);
        body.Statements.Add(b);

        RuntimeContractsAttributeClass.Members.Add(ctor);
      }

      return ctor;
    }
Esempio n. 8
0
    private Method MakeRequiresWithExceptionMethod(string name)
    {
      Parameter conditionParameter = new Parameter(Identifier.For("condition"), SystemTypes.Boolean);
      Parameter messageParameter = new Parameter(Identifier.For("msg"), SystemTypes.String);
      Parameter conditionTextParameter = new Parameter(Identifier.For("conditionTxt"), SystemTypes.String);
      MethodClassParameter typeArg = new MethodClassParameter();
      ParameterList pl = new ParameterList(conditionParameter, messageParameter, conditionTextParameter);

      Block body = new Block(new StatementList());
      Method m = new Method(this.RuntimeContractType, null, Identifier.For(name), pl, SystemTypes.Void, body);
      m.Flags = MethodFlags.Assembly | MethodFlags.Static;
      m.Attributes = new AttributeList();
      m.TemplateParameters = new TypeNodeList(typeArg);
      m.IsGeneric = true;
      this.RuntimeContractType.Members.Add(m);

      typeArg.Name = Identifier.For("TException");
      typeArg.DeclaringMember = m;
      typeArg.BaseClass = SystemTypes.Exception;
      typeArg.ParameterListIndex = 0;
      typeArg.DeclaringModule = this.RuntimeContractType.DeclaringModule;

      Block returnBlock = new Block(new StatementList(new Return()));

      Block b = new Block(new StatementList());
      b.Statements.Add(new Branch(conditionParameter, returnBlock));
      //
      // Generate the following
      //

      // // message == null means: yes we handled it. Otherwise it is the localized failure message
      // var message = RaiseFailureEvent(ContractFailureKind.Precondition, userMessage, conditionString, null);
      // #if assertOnFailure
      // if (message != null) {
      //   Assert(false, message);
      // }
      // #endif

      var messageLocal = new Local(Identifier.For("msg"), SystemTypes.String);
      
      ExpressionList elist = new ExpressionList();
      elist.Add(this.PreconditionKind);
      elist.Add(messageParameter);
      elist.Add(conditionTextParameter);
      elist.Add(Literal.Null);
      b.Statements.Add(new AssignmentStatement(messageLocal, new MethodCall(new MemberBinding(null, this.RaiseFailureEventMethod), elist)));

      if (this.AssertOnFailure)
      {
        var assertMethod = GetSystemDiagnosticsAssertMethod();
        if (assertMethod != null)
        {
          var skipAssert = new Block();
          b.Statements.Add(new Branch(new UnaryExpression(messageLocal, NodeType.LogicalNot), skipAssert));
          // emit assert call
          ExpressionList assertelist = new ExpressionList();
          assertelist.Add(Literal.False);
          assertelist.Add(messageLocal);
          b.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(null, assertMethod), assertelist)));
          b.Statements.Add(skipAssert);
        }
      }
      // // construct exception
      // Exception obj = null;
      // ConstructorInfo ci = typeof(TException).GetConstructor(new[] { typeof(string), typeof(string) });
      // if (ci != null)
      // {
      //   if (reflection.firstArgName == "paramName") {
      //     exceptionObject = ci.Invoke(new[] { userMessage, message }) as Exception;
      //   }
      //   else {
      //     exceptionObject = ci.Invoke(new[] { message, userMessage }) as Exception;
      //   }
      // }
      // else {
      //   ci = typeof(TException).GetConstructor(new[] { typeof(string) });
      //   if (ci != null)
      //   {
      //     exceptionObject = ci.Invoke(new[] { message }) as Exception;
      //   }
      // }
      var exceptionLocal = new Local(Identifier.For("obj"), SystemTypes.Exception);
      b.Statements.Add(new AssignmentStatement(exceptionLocal, Literal.Null));
      var constructorInfoType = TypeNode.GetTypeNode(typeof(System.Reflection.ConstructorInfo));
      Contract.Assume(constructorInfoType != null);
      var methodBaseType = TypeNode.GetTypeNode(typeof(System.Reflection.MethodBase));
      Contract.Assume(methodBaseType != null);
      var constructorLocal = new Local(Identifier.For("ci"), constructorInfoType);
      Contract.Assume(SystemTypes.Type != null);
      var getConstructorMethod = SystemTypes.Type.GetMethod(Identifier.For("GetConstructor"), SystemTypes.Type.GetArrayType(1));
      var typeofExceptionArg = GetTypeFromHandleExpression(typeArg);
      var typeofString = GetTypeFromHandleExpression(SystemTypes.String);
      var typeArrayLocal = new Local(Identifier.For("typeArray"), SystemTypes.Type.GetArrayType(1));
      var typeArray2 = new ConstructArray();
      typeArray2.ElementType = SystemTypes.Type;
      typeArray2.Rank = 1;
      typeArray2.Operands = new ExpressionList(Literal.Int32Two);
      var typeArrayInit2 = new Block(new StatementList());
      typeArrayInit2.Statements.Add(new AssignmentStatement(typeArrayLocal, typeArray2));
      typeArrayInit2.Statements.Add(new AssignmentStatement(new Indexer(typeArrayLocal, new ExpressionList(Literal.Int32Zero), SystemTypes.Type), typeofString));
      typeArrayInit2.Statements.Add(new AssignmentStatement(new Indexer(typeArrayLocal, new ExpressionList(Literal.Int32One), SystemTypes.Type), typeofString));
      typeArrayInit2.Statements.Add(new ExpressionStatement(typeArrayLocal));
      var typeArrayExpression2 = new BlockExpression(typeArrayInit2);
      b.Statements.Add(new AssignmentStatement(constructorLocal, new MethodCall(new MemberBinding(typeofExceptionArg, getConstructorMethod), new ExpressionList(typeArrayExpression2))));
      var elseBlock = new Block();
      b.Statements.Add(new Branch(new UnaryExpression(constructorLocal, NodeType.LogicalNot), elseBlock));
      var endifBlock2 = new Block();

      var invokeMethod = constructorInfoType.GetMethod(Identifier.For("Invoke"), SystemTypes.Object.GetArrayType(1));
      var argArray2 = new ConstructArray();
      argArray2.ElementType = SystemTypes.Object;
      argArray2.Rank = 1;
      argArray2.Operands = new ExpressionList(Literal.Int32Two);
      var argArrayLocal = new Local(Identifier.For("argArray"), SystemTypes.Object.GetArrayType(1));

      var parameterInfoType = TypeNode.GetTypeNode(typeof(System.Reflection.ParameterInfo));
      Contract.Assume(parameterInfoType != null);
      var parametersMethod = methodBaseType.GetMethod(Identifier.For("GetParameters"));
      var get_NameMethod = parameterInfoType.GetMethod(Identifier.For("get_Name"));
      var string_op_EqualityMethod = SystemTypes.String.GetMethod(Identifier.For("op_Equality"), SystemTypes.String, SystemTypes.String);
      var elseArgMsgBlock = new Block();
      var endIfArgMsgBlock = new Block();
      b.Statements.Add(new Branch(new UnaryExpression(new MethodCall(new MemberBinding(null, string_op_EqualityMethod), new ExpressionList(new MethodCall(new MemberBinding(new Indexer(new MethodCall(new MemberBinding(constructorLocal, parametersMethod), new ExpressionList(), NodeType.Callvirt), new ExpressionList(Literal.Int32Zero), parameterInfoType), get_NameMethod), new ExpressionList(), NodeType.Callvirt), new Literal("paramName", SystemTypes.String))), NodeType.LogicalNot), elseArgMsgBlock));

      var argArrayInit2 = new Block(new StatementList());
      argArrayInit2.Statements.Add(new AssignmentStatement(argArrayLocal, argArray2));
      argArrayInit2.Statements.Add(new AssignmentStatement(new Indexer(argArrayLocal, new ExpressionList(Literal.Int32Zero), SystemTypes.Object), messageParameter));
      argArrayInit2.Statements.Add(new AssignmentStatement(new Indexer(argArrayLocal, new ExpressionList(Literal.Int32One), SystemTypes.Object), messageLocal));
      argArrayInit2.Statements.Add(new ExpressionStatement(argArrayLocal));
      var argArrayExpression2 = new BlockExpression(argArrayInit2);
      b.Statements.Add(new AssignmentStatement(exceptionLocal, new BinaryExpression(new MethodCall(new MemberBinding(constructorLocal, invokeMethod), new ExpressionList(argArrayExpression2)), new Literal(SystemTypes.Exception), NodeType.Isinst)));
      b.Statements.Add(new Branch(null, endIfArgMsgBlock));
 
      b.Statements.Add(elseArgMsgBlock);
      var argArrayInit2_1 = new Block(new StatementList());
      argArrayInit2_1.Statements.Add(new AssignmentStatement(argArrayLocal, argArray2));
      argArrayInit2_1.Statements.Add(new AssignmentStatement(new Indexer(argArrayLocal, new ExpressionList(Literal.Int32Zero), SystemTypes.Object), messageLocal));
      argArrayInit2_1.Statements.Add(new AssignmentStatement(new Indexer(argArrayLocal, new ExpressionList(Literal.Int32One), SystemTypes.Object), messageParameter));
      argArrayInit2_1.Statements.Add(new ExpressionStatement(argArrayLocal));
      var argArrayExpression2_1 = new BlockExpression(argArrayInit2_1);
      b.Statements.Add(new AssignmentStatement(exceptionLocal, new BinaryExpression(new MethodCall(new MemberBinding(constructorLocal, invokeMethod), new ExpressionList(argArrayExpression2_1)), new Literal(SystemTypes.Exception), NodeType.Isinst)));

      b.Statements.Add(endIfArgMsgBlock);

      b.Statements.Add(new Branch(null, endifBlock2));

      b.Statements.Add(elseBlock);
      var typeArray1 = new ConstructArray();
      typeArray1.ElementType = SystemTypes.Type;
      typeArray1.Rank = 1;
      typeArray1.Operands = new ExpressionList(Literal.Int32One);
      var typeArrayInit1 = new Block(new StatementList());
      typeArrayInit1.Statements.Add(new AssignmentStatement(typeArrayLocal, typeArray1));
      typeArrayInit1.Statements.Add(new AssignmentStatement(new Indexer(typeArrayLocal, new ExpressionList(Literal.Int32Zero), SystemTypes.Type), typeofString));
      typeArrayInit1.Statements.Add(new ExpressionStatement(typeArrayLocal));
      var typeArrayExpression1 = new BlockExpression(typeArrayInit1);
      b.Statements.Add(new AssignmentStatement(constructorLocal, new MethodCall(new MemberBinding(typeofExceptionArg, getConstructorMethod), new ExpressionList(typeArrayExpression1))));

      b.Statements.Add(new Branch(new UnaryExpression(constructorLocal, NodeType.LogicalNot), endifBlock2));
      var argArray1 = new ConstructArray();
      argArray1.ElementType = SystemTypes.Object;
      argArray1.Rank = 1;
      argArray1.Operands = new ExpressionList(Literal.Int32One);
      var argArrayInit1 = new Block(new StatementList());
      argArrayInit1.Statements.Add(new AssignmentStatement(argArrayLocal, argArray1));
      argArrayInit1.Statements.Add(new AssignmentStatement(new Indexer(argArrayLocal, new ExpressionList(Literal.Int32Zero), SystemTypes.Object), messageLocal));
      argArrayInit1.Statements.Add(new ExpressionStatement(argArrayLocal));
      var argArrayExpression1 = new BlockExpression(argArrayInit1);
      b.Statements.Add(new AssignmentStatement(exceptionLocal, new BinaryExpression(new MethodCall(new MemberBinding(constructorLocal, invokeMethod), new ExpressionList(argArrayExpression1)), new Literal(SystemTypes.Exception), NodeType.Isinst)));

      b.Statements.Add(endifBlock2);

      // // throw it
      // if (exceptionObject == null)
      // {
      //   throw new ArgumentException(displayMessage, message);
      // }
      // else
      // {
      //   throw exceptionObject;
      // }
      var thenBlock3 = new Block();

      b.Statements.Add(new Branch(exceptionLocal, thenBlock3));
      b.Statements.Add(new Throw(new Construct(new MemberBinding(null, SystemTypes.ArgumentException.GetConstructor(SystemTypes.String, SystemTypes.String)), new ExpressionList(messageLocal, messageParameter))));
      b.Statements.Add(thenBlock3);
      b.Statements.Add(new Throw(exceptionLocal));
      b.Statements.Add(returnBlock);
      Contract.Assume(body.Statements != null);
      body.Statements.Add(b);

      Member constructor = null;
      AttributeNode attribute = null;

      #region Add [DebuggerNonUserCodeAttribute]
      if (this.HideFromDebugger) {
        TypeNode debuggerNonUserCode = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Diagnostics"), Identifier.For("DebuggerNonUserCodeAttribute"));
        if (debuggerNonUserCode != null)
        {
            constructor = debuggerNonUserCode.GetConstructor();
            attribute = new AttributeNode(new MemberBinding(null, constructor), null, AttributeTargets.Method);
            m.Attributes.Add(attribute);
        }
      }
      #endregion Add [DebuggerNonUserCodeAttribute]

      TypeNode reliabilityContract = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("ReliabilityContractAttribute"));
      TypeNode consistency = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("Consistency"));
      TypeNode cer = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("Cer"));
      if (reliabilityContract != null && consistency != null && cer != null)
      {
          constructor = reliabilityContract.GetConstructor(consistency, cer);
          if (constructor != null)
          {
              attribute = new AttributeNode(
                new MemberBinding(null, constructor),
                new ExpressionList(
                  new Literal(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, consistency),
                  new Literal(System.Runtime.ConstrainedExecution.Cer.MayFail, cer)),
                  AttributeTargets.Method
                  );
              m.Attributes.Add(attribute);
          }
      }
      return m;
    }
Esempio n. 9
0
    public static TypeNode GetAttrType(AttributeNode attr, int position, Identifier id) {
      // Could be positional, e.g [XmlElement("foo", typeof(foo))]
      if (attr.Expressions != null) {
        if ( attr.Expressions.Length > position) {

          if (attr.Expressions[position] is Literal) {
            return (TypeNode)((Literal)attr.Expressions[position]).Value;
          } else if (attr.Expressions[position] is UnaryExpression) {
            UnaryExpression ue = attr.Expressions[position] as UnaryExpression;
            if (ue.NodeType == NodeType.Typeof && ue.Operand is Literal) {
              return (TypeNode)((Literal)ue.Operand).Value;
            }
          }
        }
        // or it could be a NamedArgument [XmlElement(Type=typeof(foo))]
        for (int i = 0, n = attr.Expressions.Length; i < n; i++) {
          Expression e = attr.Expressions[i];
          if (e is NamedArgument) {
            NamedArgument na = (NamedArgument)e;
            if (na.Name.UniqueKey == id.UniqueKey) {
              return (TypeNode)((Literal)na.Value).Value;
            }
          }
        }
      }
      return null;
    }
Esempio n. 10
0
 public static Identifier GetXmlName(Identifier id, AttributeNode attr) {
   // e.g [XmlElement("foo",Namespace="uri")]
   Identifier nspace = null;
   if (attr.Expressions != null) {
     for (int i = 0, n = attr.Expressions.Length; i < n; i++) {
       Expression e = attr.Expressions[i];
       if (e is Literal) {
         id = Identifier.For((string)((Literal)e).Value);
       } else if (e is NamedArgument) {
         NamedArgument na = (NamedArgument)e;
         if (na.Name.UniqueKey == SchemaElementDecl.NameId.UniqueKey) {
           id = Identifier.For((string)((Literal)na.Value).Value);
         } else if (na.Name.UniqueKey == SchemaElementDecl.NamespaceId.UniqueKey) {
           nspace = Identifier.For((string)((Literal)na.Value).Value);
         }
       }
     } 
   }
   id.Prefix = nspace;
   return id;
 }
Esempio n. 11
0
 internal TypeNode GetAttributeType(AttributeNode attr) {
   if (attr == null) return null; // must be a type error.
   TypeNode attrType = null;
   MemberBinding mb = attr.Constructor as MemberBinding;
   if (mb != null)
     attrType = mb.BoundMember.DeclaringType;
   else {
     Literal lit = attr.Constructor as Literal;
     if (lit == null) return null;
     attrType = lit.Value as TypeNode;
   }
   return attrType;
 }
Esempio n. 12
0
 public AttributedStatement(AttributeNode attr, Statement statement)
     : this()
 {
     this.Attributes = new AttributeList(1);
     this.Attributes.Add(attr);
     this.Statement = statement;
 }
Esempio n. 13
0
 public override AttributeNode VisitUnknownAssemblyAttribute(TypeNode attrType, AttributeNode attr, AssemblyNode target) {
   if (attrType == Runtime.PostCompilationPluginAttributeType) {
     SpecSharpCompilation ssCompilation = this.ssCompilation;
     if (ssCompilation == null) { Debug.Assert(false); return null; }
     //        if (this.currentPreprocessorDefinedSymbols == null || !this.currentPreprocessorDefinedSymbols.ContainsKey("CODE_ANALYSIS"))
     //          return null;
     ExpressionList args = attr.Expressions;
     if (args != null && args.Count > 0) {
       UnaryExpression expr = args[0] as UnaryExpression;
       NamedArgument nArg = args[0] as NamedArgument;
       if (nArg != null) expr = nArg.Value as UnaryExpression;
       if (expr == null || expr.Type != SystemTypes.Type) return null;
       Literal typeLit = expr.Operand as Literal;
       if (typeLit == null) return null;
       TypeNode pluginType = (TypeNode)typeLit.Value;
       if (!pluginType.IsNormalized) {
         this.HandleError(typeLit, Error.PluginTypeMustAlreadyBeCompiled, this.GetTypeName(pluginType));
         return null;
       }
       ssCompilation.AddPlugin(pluginType, (TypeSystem)this.typeSystem, typeLit);
     }
     attr.IsPseudoAttribute = true;
     return attr;
   }
   return base.VisitUnknownAssemblyAttribute(attrType, attr, target);
 }
Esempio n. 14
0
 public override AttributeNode VisitParameterAttribute(AttributeNode attr, Parameter parameter) {
   attr = base.VisitParameterAttribute(attr, parameter);
   if (attr == null) return null;
   if (attr.Type == SystemTypes.ParamArrayAttribute && attr.SourceContext.Document != null)
     this.HandleError(attr, Error.ExplicitParamArray, this.GetTypeName(SystemTypes.ParamArrayAttribute));
   if ((IsAdditive(attr) || IsInside(attr) || attr.Type == SystemTypes.CapturedAttribute || attr.Type == SystemTypes.NoDefaultContractAttribute)
       && parameter.Type != null && parameter.Type.IsValueType) {
     this.HandleError(attr, Error.AttributeAllowedOnlyOnReferenceTypeParameters, this.GetTypeName(attr.Type));
   }
   if (attr.Type == SystemTypes.CapturedAttribute && parameter.IsOut) {
     this.HandleError(attr, Error.AttributeNotAllowedOnlyOnInParameters, this.GetTypeName(attr.Type));
   }
   return attr;
 }
Esempio n. 15
0
 private bool IsInside(AttributeNode attr) {
   if (attr == null || attr.Type != SystemTypes.InsideAttribute) return false;
   ExpressionList exprs = attr.Expressions;
   if (exprs == null || exprs.Count != 1) return true;
   Literal lit = exprs[0] as Literal;
   if (lit != null && (lit.Value is bool)) return (bool)lit.Value;
   else return false;
 }
Esempio n. 16
0
    private Class MakeContractException() {
      Class contractExceptionType;

      #region If we're rewriting an assembly for v4 or above and it *isn't* Silverlight (so serialization support is needed), then use new embedded dll as the type
      if (4 <= TargetPlatform.MajorVersion) {
        var iSafeSerializationData = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.Serialization"), Identifier.For("ISafeSerializationData")) as Interface;
        if (iSafeSerializationData != null) {
          // Just much easier to write the C# and have the compiler generate everything than to try and create it all manually
          System.Reflection.Assembly embeddedAssembly;
          Stream embeddedAssemblyStream;
          embeddedAssembly = System.Reflection.Assembly.GetExecutingAssembly();
          embeddedAssemblyStream = embeddedAssembly.GetManifestResourceStream("Microsoft.Contracts.Foxtrot.InternalException.dll");
          byte[] data = new byte[0];
          using (var br = new BinaryReader(embeddedAssemblyStream)) {
            var len = embeddedAssemblyStream.Length;
            if (len < Int32.MaxValue)
              data = br.ReadBytes((int)len);
            AssemblyNode assemblyNode = AssemblyNode.GetAssembly(data, TargetPlatform.StaticAssemblyCache, true, false, true);
            contractExceptionType = assemblyNode.GetType(Identifier.For(""), Identifier.For("ContractException")) as Class;
          }
          if (contractExceptionType == null)
            throw new RewriteException("Tried to create the ContractException type from the embedded dll, but failed");
          var d = new Duplicator(this.targetAssembly, this.RuntimeContractType);
          d.FindTypesToBeDuplicated(new TypeNodeList(contractExceptionType));

          var ct = d.Visit(contractExceptionType);
          contractExceptionType = (Class)ct;
          contractExceptionType.Flags |= TypeFlags.NestedPrivate;
          this.RuntimeContractType.Members.Add(contractExceptionType);
          return contractExceptionType;
        }
      }
      #endregion

      contractExceptionType = new Class(this.targetAssembly, this.RuntimeContractType, new AttributeList(), TypeFlags.Class | TypeFlags.NestedPrivate | TypeFlags.Serializable, null, Identifier.For("ContractException"), SystemTypes.Exception, null, null);

      RewriteHelper.TryAddCompilerGeneratedAttribute(contractExceptionType);

      var kindField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_Kind"), contractNodes.ContractFailureKind, null);
      var userField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_UserMessage"), SystemTypes.String, null);
      var condField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_Condition"), SystemTypes.String, null);
      contractExceptionType.Members.Add(kindField);
      contractExceptionType.Members.Add(userField);
      contractExceptionType.Members.Add(condField);

      #region Constructor for setting the fields
      var parameters = new ParameterList();
      var kindParam = new Parameter(Identifier.For("kind"), this.contractNodes.ContractFailureKind);
      var failureParam = new Parameter(Identifier.For("failure"), SystemTypes.String);
      var usermsgParam = new Parameter(Identifier.For("usermsg"), SystemTypes.String);
      var conditionParam = new Parameter(Identifier.For("condition"), SystemTypes.String);
      var innerParam = new Parameter(Identifier.For("inner"), SystemTypes.Exception);
      parameters.Add(kindParam);
      parameters.Add(failureParam);
      parameters.Add(usermsgParam);
      parameters.Add(conditionParam);
      parameters.Add(innerParam);
      var body = new Block(new StatementList());
      var ctor = new InstanceInitializer(contractExceptionType, null, parameters, body);
      ctor.Flags |= MethodFlags.Public | MethodFlags.HideBySig;
      ctor.CallingConvention = CallingConventionFlags.HasThis;
      body.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(ctor.ThisParameter, contractExceptionType.BaseClass.GetConstructor(SystemTypes.String, SystemTypes.Exception)), new ExpressionList(failureParam, innerParam))));
      body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, kindField), kindParam));
      body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, userField), usermsgParam));
      body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, condField), conditionParam));
      body.Statements.Add(new Return());
      contractExceptionType.Members.Add(ctor);
      #endregion

      if (SystemTypes.SerializationInfo != null && SystemTypes.SerializationInfo.BaseClass != null) {
        // Silverlight (e.g.) is a platform that doesn't support serialization. So check to make sure the type really exists.
        // 
        var baseCtor = SystemTypes.Exception.GetConstructor(SystemTypes.SerializationInfo, SystemTypes.StreamingContext);

        if (baseCtor != null) {
          #region Deserialization Constructor
          parameters = new ParameterList();
          var info = new Parameter(Identifier.For("info"), SystemTypes.SerializationInfo);
          var context = new Parameter(Identifier.For("context"), SystemTypes.StreamingContext);
          parameters.Add(info);
          parameters.Add(context);
          body = new Block(new StatementList());
          ctor = new InstanceInitializer(contractExceptionType, null, parameters, body);
          ctor.Flags |= MethodFlags.Private | MethodFlags.HideBySig;
          ctor.CallingConvention = CallingConventionFlags.HasThis;
          // : base(info, context) 
          body.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(ctor.ThisParameter, baseCtor), new ExpressionList(info, context))));
          // _Kind = (ContractFailureKind)info.GetInt32("Kind");
          var getInt32 = SystemTypes.SerializationInfo.GetMethod(Identifier.For("GetInt32"), SystemTypes.String);
          body.Statements.Add(new AssignmentStatement(
              new MemberBinding(new This(), kindField),
              new MethodCall(new MemberBinding(info, getInt32), new ExpressionList(new Literal("Kind", SystemTypes.String)))
              ));
          // _UserMessage = info.GetString("UserMessage");
          var getString = SystemTypes.SerializationInfo.GetMethod(Identifier.For("GetString"), SystemTypes.String);
          body.Statements.Add(new AssignmentStatement(
              new MemberBinding(new This(), userField),
              new MethodCall(new MemberBinding(info, getString), new ExpressionList(new Literal("UserMessage", SystemTypes.String)))
              ));
          // _Condition = info.GetString("Condition");
          body.Statements.Add(new AssignmentStatement(
              new MemberBinding(new This(), condField),
              new MethodCall(new MemberBinding(info, getString), new ExpressionList(new Literal("Condition", SystemTypes.String)))
              ));
          body.Statements.Add(new Return());
          contractExceptionType.Members.Add(ctor);
          #endregion

          #region GetObjectData

          var securityCriticalCtor = SystemTypes.SecurityCriticalAttribute.GetConstructor();
          var securityCriticalAttribute = new AttributeNode(new MemberBinding(null, securityCriticalCtor), null, System.AttributeTargets.Method);
          var attrs = new AttributeList(securityCriticalAttribute);
          parameters = new ParameterList();
          info = new Parameter(Identifier.For("info"), SystemTypes.SerializationInfo);
          context = new Parameter(Identifier.For("context"), SystemTypes.StreamingContext);
          parameters.Add(info);
          parameters.Add(context);
          body = new Block(new StatementList());
          var getObjectDataName = Identifier.For("GetObjectData");
          var getObjectData = new Method(contractExceptionType, attrs, getObjectDataName, parameters, SystemTypes.Void, body);
          getObjectData.CallingConvention = CallingConventionFlags.HasThis;
          // public override
          getObjectData.Flags = MethodFlags.Public | MethodFlags.Virtual;
          // base.GetObjectData(info, context);
          var baseGetObjectData = SystemTypes.Exception.GetMethod(getObjectDataName, SystemTypes.SerializationInfo, SystemTypes.StreamingContext);
          body.Statements.Add(new ExpressionStatement(
            new MethodCall(new MemberBinding(new This(), baseGetObjectData), new ExpressionList(info, context), NodeType.Call, SystemTypes.Void)
            ));
          // info.AddValue("Kind", _Kind);
          var addValueObject = SystemTypes.SerializationInfo.GetMethod(Identifier.For("AddValue"), SystemTypes.String, SystemTypes.Object);
          body.Statements.Add(new ExpressionStatement(
            new MethodCall(new MemberBinding(info, addValueObject), new ExpressionList(new Literal("Kind", SystemTypes.String), new BinaryExpression(new MemberBinding(new This(), kindField), new Literal(contractNodes.ContractFailureKind), NodeType.Box)), NodeType.Call, SystemTypes.Void)
            ));
          // info.AddValue("UserMessage", _UserMessage);
          body.Statements.Add(new ExpressionStatement(
            new MethodCall(new MemberBinding(info, addValueObject), new ExpressionList(new Literal("UserMessage", SystemTypes.String), new MemberBinding(new This(), userField)), NodeType.Call, SystemTypes.Void)
            ));
          // info.AddValue("Condition", _Condition);
          body.Statements.Add(new ExpressionStatement(
            new MethodCall(new MemberBinding(info, addValueObject), new ExpressionList(new Literal("Condition", SystemTypes.String), new MemberBinding(new This(), condField)), NodeType.Call, SystemTypes.Void)
            ));

          body.Statements.Add(new Return());
          contractExceptionType.Members.Add(getObjectData);
          #endregion
        }
      }

      this.RuntimeContractType.Members.Add(contractExceptionType);
      return contractExceptionType;
    }
Esempio n. 17
0
    /// <summary>
    /// Constructs (and returns) a method that looks like this:
    /// 
    ///   [System.Diagnostics.DebuggerNonUserCodeAttribute]
    ///   [System.Runtime.ConstrainedExecution.ReliabilityContractReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
    ///   static void name(bool condition, string message, string conditionText){
    ///     if (!condition) {
    ///       System.Diagnostics.Contracts.Contract.Failure(kind, message, conditionText, null);
    ///     }
    ///   }
    ///
    /// Or, if the ContractFailureKind is PostconditionOnException, then the generated method
    /// gets an extra parameter which is an Exception and that parameter is passed to Contract.Failure instead of null
    /// </summary>
    private Method MakeMethod(string name, ContractFailureKind kind)
    {
      Parameter conditionParameter = new Parameter(Identifier.For("condition"), SystemTypes.Boolean);
      Parameter messageParameter = new Parameter(Identifier.For("msg"), SystemTypes.String);
      Parameter conditionTextParameter = new Parameter(Identifier.For("conditionTxt"), SystemTypes.String);
      Parameter exceptionParameter = new Parameter(Identifier.For("originalException"), SystemTypes.Exception);

      Block returnBlock = new Block(new StatementList(new Return()));

      Block body = new Block(new StatementList());
      Block b = new Block(new StatementList());
      b.Statements.Add(new Branch(conditionParameter, returnBlock));
      ExpressionList elist = new ExpressionList();
      elist.Add(TranslateKindForBackwardCompatibility(kind));
      elist.Add(messageParameter);
      elist.Add(conditionTextParameter);
      if (kind == ContractFailureKind.PostconditionOnException)
      {
        elist.Add(exceptionParameter);
      }
      else
      {
        elist.Add(Literal.Null);
      }
      b.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(null, this.FailureMethod), elist)));
      b.Statements.Add(returnBlock);
      body.Statements.Add(b);

      ParameterList pl = new ParameterList(conditionParameter, messageParameter, conditionTextParameter);
      if (kind == ContractFailureKind.PostconditionOnException)
      {
        pl.Add(exceptionParameter);
      }
      Method m = new Method(this.RuntimeContractType, null, Identifier.For(name), pl, SystemTypes.Void, body);
      m.Flags = MethodFlags.Assembly | MethodFlags.Static;
      m.Attributes = new AttributeList();
      this.RuntimeContractType.Members.Add(m);

      Member constructor = null;
      AttributeNode attribute = null;

      #region Add [DebuggerNonUserCodeAttribute]
      if (this.HideFromDebugger) {
        TypeNode debuggerNonUserCode = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Diagnostics"), Identifier.For("DebuggerNonUserCodeAttribute"));
        if (debuggerNonUserCode != null)
        {
          constructor = debuggerNonUserCode.GetConstructor();
          attribute = new AttributeNode(new MemberBinding(null, constructor), null, AttributeTargets.Method);
          m.Attributes.Add(attribute);
        }
      }
      #endregion Add [DebuggerNonUserCodeAttribute]

      TypeNode reliabilityContract = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("ReliabilityContractAttribute"));
      TypeNode consistency = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("Consistency"));
      TypeNode cer = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("Cer"));
      if (reliabilityContract != null && consistency != null && cer != null) {
        constructor = reliabilityContract.GetConstructor(consistency, cer);
        if (constructor != null) {
          attribute = new AttributeNode(
            new MemberBinding(null, constructor),
            new ExpressionList(
              new Literal(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, consistency),
              new Literal(System.Runtime.ConstrainedExecution.Cer.MayFail, cer)),
              AttributeTargets.Method
              );
          m.Attributes.Add(attribute);
        }
      }
      return m;
    }
Esempio n. 18
0
 private Parameter ParseParameter(TokenSet followers, bool allowRefParameters, bool namesAreOptional, bool typesAreOptional){
   Parameter p = new Parameter();
   p.SourceContext = this.scanner.CurrentSourceContext;
   Token tok = this.currentToken;
   p.Attributes = this.ParseAttributes(null, followers|Parser.ParameterTypeStart);
   p.Flags = ParameterFlags.None;
   bool byRef = false;
   switch(this.currentToken){
     case Token.Out:
       //TODO: error if !allowRefParameters && typesAreOptional
       p.Flags = ParameterFlags.Out;
       goto case Token.Ref;
     case Token.Ref:
       //TODO: error if !allowRefParameters && typesAreOptional
       if (!allowRefParameters)
         this.HandleError(Error.IndexerWithRefParam);
       byRef = true;
       this.GetNextToken();
       if (this.currentToken == Token.Params){
         this.HandleError(Error.ParamsCantBeRefOut);
         this.GetNextToken();
       }
       break;
     case Token.Params:
       //TODO: error if !allowRefParameters && typesAreOptional
       Literal lit = new Literal(TypeExpressionFor("System", "ParamArrayAttribute"), null, this.scanner.CurrentSourceContext);
       AttributeNode paramsAttribute = new AttributeNode(lit, null);
       if (p.Attributes == null) p.Attributes = new AttributeList(1);
       p.Attributes.Add(paramsAttribute);
       this.GetNextToken();
       if (this.currentToken == Token.Out || this.currentToken == Token.Ref){
         this.HandleError(Error.ParamsCantBeRefOut);
         if (this.currentToken == Token.Out) goto case Token.Out;
         goto case Token.Ref;
       }
       break;
   }
   bool voidParam = false;
   if (this.currentToken == Token.Void){
     if (this.inUnsafeCode){
       TypeNode voidT = this.TypeExpressionFor(Token.Void);
       SourceContext sctx = this.scanner.CurrentSourceContext;
       this.GetNextToken();
       sctx.EndPos = this.scanner.endPos;
       this.Skip(Token.Multiply);
       p.Type = p.TypeExpression = new PointerTypeExpression(voidT, sctx);
     }else{
       this.HandleError(Error.NoVoidParameter);
       p.Type = this.TypeExpressionFor(Token.Object);
       p.TypeExpression = new TypeExpression(this.scanner.GetIdentifier(), this.scanner.CurrentSourceContext);
       this.GetNextToken();
       voidParam = true;
     }
   }else if (this.currentToken == Token.Delegate)
     p.Type = p.TypeExpression = this.ParseDelegateDeclaration(null, null, null, TypeFlags.None, p.SourceContext, followers);
   else if (p.Type == null){
     p.Type = p.TypeExpression = this.ParseTypeExpression(null, followers|Parser.IdentifierOrNonReservedKeyword);
   }
   if (byRef) p.Type = p.TypeExpression = new ReferenceTypeExpression(p.Type);
   if ((this.currentToken == Token.Comma || this.currentToken == Token.RightParenthesis) && p.TypeExpression is TypeExpression &&
     ((TypeExpression)p.TypeExpression).Expression is Identifier && typesAreOptional) {
     p.Name = (Identifier)((TypeExpression)p.TypeExpression).Expression;
     p.Type = p.TypeExpression = null;
   }else{
     p.Name = this.scanner.GetIdentifier();
   }
   p.SourceContext.EndPos = this.scanner.endPos;
   if (!voidParam || Parser.IdentifierOrNonReservedKeyword[this.currentToken]){
     if (Parser.IdentifierOrNonReservedKeyword[this.currentToken])
       this.GetNextToken();
     else{
       if (namesAreOptional)
         p.Name = Identifier.Empty;
       else
         this.SkipIdentifierOrNonReservedKeyword();
     }
   }
   if (this.currentToken == Token.LeftBracket){
     this.HandleError(Error.BadArraySyntax);
     int endPos = this.scanner.endPos;
     int rank = this.ParseRankSpecifier(true, followers|Token.LeftBracket);
     if (rank > 0)
       p.Type = p.TypeExpression = this.ParseArrayType(rank, p.Type, followers);
     else{
       this.currentToken = Token.LeftBracket;
       this.scanner.endPos = endPos;
       this.GetNextToken();
       while (!this.scanner.TokenIsFirstAfterLineBreak &&
         this.currentToken != Token.RightBracket && this.currentToken != Token.Comma && this.currentToken != Token.RightParenthesis)
         this.GetNextToken();
       if (this.currentToken == Token.RightBracket) this.GetNextToken();
     }
   }else if (this.currentToken == Token.Assign){
     this.HandleError(Error.NoDefaultArgs);
     this.GetNextToken();
     if (Parser.UnaryStart[this.currentToken]){
       this.ParseExpression(followers);
       return p;
     }
   }
   this.SkipTo(followers);
   return p;
 }
Esempio n. 19
0
    /// <summary>
    /// Adds a flag to an assembly that designates it as having runtime contract checks.
    /// Does this by defining the type of the attribute and then marking the assembly with
    /// and instance of that attribute.
    /// </summary>
    /// <param name="assembly">Assembly to flag.</param>
    private void SetRuntimeContractFlag(AssemblyNode assembly) {

      InstanceInitializer ctor = GetRuntimeContractsAttributeCtor(assembly);
      ExpressionList args = new ExpressionList();
      args.Add(new Literal(this.contractEmitFlags, ctor.Parameters[0].Type));
      AttributeNode attribute = new AttributeNode(new MemberBinding(null, ctor), args, AttributeTargets.Assembly);
      assembly.Attributes.Add(attribute);
    }
Esempio n. 20
0
 private void ParseProperty(TypeNode parentType, AttributeList attributes, TokenList modifierTokens,
   SourceContextList modifierContexts, object sctx, TypeNode type, TypeNode interfaceType, Identifier name, TokenSet followers){
   SourceContext ctx = (SourceContext)sctx;
   ctx.EndPos = this.scanner.endPos;
   bool isIndexer = this.currentToken == Token.This && name.UniqueIdKey == StandardIds.Item.UniqueIdKey;
   Debug.Assert(this.currentToken == Token.LeftBrace || isIndexer);
   this.GetNextToken();
   ParameterList paramList = null;
   if (isIndexer){
     if (interfaceType == null){
       AttributeNode defaultMember = new AttributeNode();
       defaultMember.Constructor = new Literal(TypeExpressionFor("System", "Reflection", "DefaultMemberAttribute"));
       defaultMember.Expressions = new ExpressionList(1);
       defaultMember.Expressions.Add(new Literal("Item"));
       if (parentType.Attributes == null) parentType.Attributes = new AttributeList(1);
       parentType.Attributes.Add(defaultMember);
     }
     paramList = this.ParseParameters(Token.RightBracket, followers|Token.LeftBrace);
     this.Skip(Token.LeftBrace);
   }
   Property p = new Property(parentType, attributes, PropertyFlags.None, name, null, null);
   parentType.Members.Add(p);
   p.SourceContext = ctx;
   p.Documentation = this.LastDocComment;
   p.Type = p.TypeExpression = type;
   MethodFlags mflags;
   if (interfaceType != null){
     p.ImplementedTypeExpressions = p.ImplementedTypes = new TypeNodeList(interfaceType);
     mflags = MethodFlags.Private|MethodFlags.HideBySig|MethodFlags.NewSlot|MethodFlags.Final|MethodFlags.Virtual|MethodFlags.SpecialName;
     for (int i = 0, n = modifierContexts == null ? 0 : modifierContexts.Length; i < n; i++) {
       if (modifierTokens[i] == Token.Extern)
         mflags |= MethodFlags.PInvokeImpl;
       else if (modifierTokens[i] == Token.Unsafe) {
         if (!this.allowUnsafeCode) {
           this.allowUnsafeCode = true;
           this.HandleError(modifierContexts[i], Error.IllegalUnsafe);
         }
         this.inUnsafeCode = true;
       } else
         this.HandleError(modifierContexts[i], Error.InvalidModifier, modifierContexts[i].SourceText);
     }
   }else
     mflags = this.GetMethodFlags(modifierTokens, modifierContexts, parentType, p)|MethodFlags.SpecialName;
   if ((mflags & MethodFlags.Static) != 0 && parentType is Interface){
     this.HandleError(name.SourceContext, Error.InvalidModifier, "static");
     mflags &= ~MethodFlags.Static;
     mflags |= MethodFlags.Abstract;
   }
   TokenSet followersOrRightBrace = followers|Token.RightBrace;
   bool accessorModifiersAlreadySpecified = false;
   MethodFlags accessorFlags = mflags;
   while (Parser.GetOrLeftBracketOrSetOrModifier[this.currentToken]){
     SourceContext sc = this.scanner.CurrentSourceContext;
     AttributeList accessorAttrs = this.ParseAttributes(null, followers|Token.Get|Token.Set|Token.LeftBrace);
     switch (this.currentToken){
       case Token.Get:{
         if (p.Getter != null)
           this.HandleError(Error.DuplicateAccessor);
         SourceContext scntx = this.scanner.CurrentSourceContext;
         this.GetNextToken();
         Method m = new Method(parentType, accessorAttrs, new Identifier("get_"+name.ToString()), paramList, type, null);
         m.SourceContext = sc;
         m.ReturnTypeExpression = type;
         m.Name.SourceContext = scntx;
         if ((accessorFlags & MethodFlags.Static) == 0)
           m.CallingConvention = CallingConventionFlags.HasThis;
         parentType.Members.Add(m);
         m.Flags = accessorFlags|MethodFlags.HideBySig;
         if (interfaceType != null)
           m.ImplementedTypeExpressions = m.ImplementedTypes = new TypeNodeList(interfaceType);
         bool swallowedSemicolonAlready = false;
         bool bodyAllowed = true;
         if (this.currentToken == Token.Semicolon){
           m.SourceContext.EndPos = this.scanner.endPos;
           this.GetNextToken();
           bodyAllowed = false;
           swallowedSemicolonAlready = true;
         }
         this.ParseMethodContract(m, followers|Token.LeftBrace|Token.Semicolon, ref swallowedSemicolonAlready);
         if (bodyAllowed)
           m.Body = this.ParseBody(m, sc, followersOrRightBrace|Token.Set, swallowedSemicolonAlready);
         else if (!swallowedSemicolonAlready)
           this.SkipSemiColon(followersOrRightBrace|Token.Set);
         p.Getter = m;
         m.DeclaringMember = p;
         accessorFlags = mflags;
         break;}
       case Token.Set:{
         if (p.Setter != null)
           this.HandleError(Error.DuplicateAccessor);
         SourceContext scntx = this.scanner.CurrentSourceContext;
         this.GetNextToken();
         ParameterList parList = new ParameterList();
         if (paramList != null)
           for (int i = 0, n = paramList.Count; i < n; i++) parList.Add((Parameter)paramList[i].Clone());
         parList.Add(new Parameter(null, ParameterFlags.None, Identifier.For("value"), type, null, null));
         Method m = new Method(parentType, accessorAttrs, new Identifier("set_"+name.ToString()), parList, this.TypeExpressionFor(Token.Void), null);
         m.SourceContext = sc;
         m.Name.SourceContext = scntx;
         if ((accessorFlags & MethodFlags.Static) == 0)
           m.CallingConvention = CallingConventionFlags.HasThis;
         parentType.Members.Add(m);
         m.Flags = accessorFlags|MethodFlags.HideBySig;
         if (interfaceType != null)
           m.ImplementedTypeExpressions = m.ImplementedTypes = new TypeNodeList(interfaceType);
         bool swallowedSemicolonAlready = false;
         bool bodyAllowed = true;
         if (this.currentToken == Token.Semicolon) {
           m.SourceContext.EndPos = this.scanner.endPos;
           this.GetNextToken();
           bodyAllowed = false;
           swallowedSemicolonAlready = true;
         }
         this.ParseMethodContract(m, followers|Token.LeftBrace|Token.Semicolon, ref swallowedSemicolonAlready);
         if (bodyAllowed)
           m.Body = this.ParseBody(m, sc, followersOrRightBrace|Token.Get, swallowedSemicolonAlready);
         else if (!swallowedSemicolonAlready)
           this.SkipSemiColon(followersOrRightBrace|Token.Get);
         p.Setter = m;
         m.DeclaringMember = p;
         accessorFlags = mflags;
         break;}
       case Token.Protected:
       case Token.Internal:
       case Token.Private:
         if (parentType is Interface || interfaceType != null || accessorModifiersAlreadySpecified)
           goto case Token.New;
         accessorFlags = this.ParseAccessorModifiers(mflags);
         accessorModifiersAlreadySpecified = true;
         break;
       case Token.Public:
       case Token.New:
       case Token.Abstract:
       case Token.Sealed:
       case Token.Static:
       case Token.Readonly:
       case Token.Volatile:
       case Token.Virtual:
       case Token.Override:
       case Token.Extern:
       case Token.Unsafe:
         this.HandleError(Error.NoModifiersOnAccessor);
         this.GetNextToken();
         break;
       default:
         this.SkipTo(followersOrRightBrace, Error.GetOrSetExpected);
         break;
     }
   }
   p.SourceContext.EndPos = this.scanner.endPos;
   Error e = Error.GetOrSetExpected;
   if (p.Getter == null && p.Setter == null) p.Parameters = paramList;
   if (p.Getter != null && p.Setter != null) e = Error.ExpectedRightBrace;
   if ((p.Getter == null || p.Setter == null) && this.sink != null && this.currentToken == Token.Identifier){
     p.SourceContext.EndPos = this.scanner.startPos-1;
     KeywordCompletionList keywords;
     if (p.Getter != null)
       keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("set"));
     else if (p.Setter != null)
       keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("get"));
     else
       keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("get"), new KeywordCompletion("set"));
     parentType.Members.Add(keywords);
     this.GetNextToken();
     this.SkipTo(followers);
     return;
   }
   this.ParseBracket(ctx, Token.RightBrace, followers, e);
 }
Esempio n. 21
0
 public virtual Expression VisitAttributeConstructor(AttributeNode attribute)
 {
     if (attribute == null) return null;
     return this.VisitExpression(attribute.Constructor);
 }
Esempio n. 22
0
 private AttributeList ParseAttributes(Namespace ns, TokenSet followers){
   if (this.currentToken != Token.LeftBracket) return null;
   AttributeList attributes = new AttributeList();
   bool allowGlobalAttributes = ns != null && ns.Name == Identifier.Empty &&
     (ns.NestedNamespaces == null || ns.NestedNamespaces.Count == 0) && (ns.Types == null || ns.Types.Count == 0);
   while(this.currentToken == Token.LeftBracket){
     SourceContext sctx = this.scanner.CurrentSourceContext;
     this.GetNextToken();
     AttributeTargets flags = (AttributeTargets)0;
     Identifier id = this.scanner.GetIdentifier();
     SourceContext attrCtx = this.scanner.CurrentSourceContext;
     switch(this.currentToken){
       case Token.Event:
       case Token.Identifier:
       case Token.Return:
         this.GetNextToken();
         if (this.currentToken == Token.Colon){
           this.GetNextToken();
           int key = id.UniqueIdKey;
           if (key == Parser.assemblyId.UniqueIdKey)
             flags = AttributeTargets.Assembly;
           else if (key == Parser.eventId.UniqueIdKey)
             flags = AttributeTargets.Event;
           else if (key == Parser.fieldId.UniqueIdKey)
             flags = AttributeTargets.Field;
           else if (key == Parser.methodId.UniqueIdKey)
             flags = AttributeTargets.Method|AttributeTargets.Constructor;
           else if (key == Parser.moduleId.UniqueIdKey)
             flags = AttributeTargets.Module;
           else if (key == Parser.paramId.UniqueIdKey)
             flags = AttributeTargets.Parameter;
           else if (key == Parser.propertyId.UniqueIdKey)
             flags = AttributeTargets.Property;
           else if (key == Parser.returnId.UniqueIdKey)
             flags = AttributeTargets.ReturnValue;
           else if (key == Parser.typeId.UniqueIdKey)
             flags = AttributeTargets.Class|AttributeTargets.Delegate|AttributeTargets.Enum|AttributeTargets.Interface|AttributeTargets.Struct;
           else{
             flags = (AttributeTargets)int.MaxValue;
             this.HandleError(Error.InvalidAttributeLocation, id.ToString());
           }
           id = this.scanner.GetIdentifier();
           this.SkipIdentifierOrNonReservedKeyword();
         }
         break;
       default:
         this.SkipIdentifierOrNonReservedKeyword();
         break;
     }
     for(;;){
       AttributeNode attr = new AttributeNode();
       attr.SourceContext = attrCtx;
       attr.Target = flags;
       if (this.currentToken == Token.DoubleColon){
         Identifier prefix = id;
         this.GetNextToken();
         id = this.scanner.GetIdentifier();
         id.Prefix = prefix;
         id.SourceContext.StartPos = prefix.SourceContext.StartPos;
         this.SkipIdentifierOrNonReservedKeyword();
       }
       if (this.sink != null) this.sink.StartName(id);
       if (this.currentToken == Token.Dot)
         attr.Constructor = this.ParseQualifiedIdentifier(id, followers|Token.Comma|Token.LeftParenthesis|Token.RightBracket);
       else
         attr.Constructor = id;
       this.ParseAttributeArguments(attr, followers|Token.Comma|Token.RightBracket);
       if (flags != (AttributeTargets)int.MaxValue){
         if (allowGlobalAttributes && (flags == AttributeTargets.Assembly || flags == AttributeTargets.Module)){
           if (ns.Attributes == null) ns.Attributes = new AttributeList();
           ns.Attributes.Add(attr);
         }else
           attributes.Add(attr);
       }
       if (this.currentToken != Token.Comma) break;
       this.GetNextToken();
       if (this.currentToken == Token.RightBracket) break;
       id = this.scanner.GetIdentifier();
       this.SkipIdentifierOrNonReservedKeyword();
     }
     this.ParseBracket(sctx, Token.RightBracket, followers, Error.ExpectedRightBracket);
   }
   this.SkipTo(followers);
   return attributes;
 }
Esempio n. 23
0
        public static ThreeValued ContractOption(AttributeNode attr, string category, string setting)
        {
            string c, s;
            bool value;

            if (IsContractOptionAttribute(attr, out c, out s, out value))
            {
                if (category.Equals(c, StringComparison.OrdinalIgnoreCase))
                {
                    if (setting.Equals(s, StringComparison.OrdinalIgnoreCase))
                    {
                        if (value) return ThreeValued.True;

                        return ThreeValued.False;
                    }
                }
            }

            return ThreeValued.Maybe;
        }
Esempio n. 24
0
 private void ParseAttributeArguments(AttributeNode attr, TokenSet followers){
   if (this.currentToken != Token.LeftParenthesis) return;
   SourceContext sctx = this.scanner.CurrentSourceContext;
   if (this.sink != null) this.sink.StartParameters(sctx);
   this.GetNextToken();
   ExpressionList expressions = attr.Expressions = new ExpressionList();
   bool hadNamedArgument = false;
   while (this.currentToken != Token.RightParenthesis){
     SourceContext sctx1 = this.scanner.CurrentSourceContext;
     Expression expr = this.ParseExpression(followers|Token.Comma|Token.RightParenthesis);
     if (expr != null){
       if (this.sink != null) {
         sctx1.EndPos = this.scanner.endPos;
         this.sink.NextParameter(sctx1);
       }
       AssignmentExpression aExpr = expr as AssignmentExpression;
       if (aExpr != null){
         AssignmentStatement aStat = (AssignmentStatement)aExpr.AssignmentStatement;
         Identifier id = aStat.Target as Identifier;
         if (id == null){
           this.HandleError(aStat.Target.SourceContext, Error.ExpectedIdentifier);
           expr = null;
         }else
           expr = new NamedArgument(id, aStat.Source, expr.SourceContext);
         hadNamedArgument = true;
       }else if (hadNamedArgument)
         this.HandleError(expr.SourceContext, Error.NamedArgumentExpected);
     }
     expressions.Add(expr);
     if (this.currentToken != Token.Comma) break;
     this.GetNextToken();
   }
   attr.SourceContext.EndPos = this.scanner.endPos;
   if (this.sink != null && this.currentToken != Token.EndOfFile) this.sink.EndParameters(this.scanner.CurrentSourceContext);
   this.ParseBracket(sctx, Token.RightParenthesis, followers, Error.ExpectedRightParenthesis);
 }
Esempio n. 25
0
        public static bool IsContractOptionAttribute(AttributeNode attr, out string category, out string setting,
            out bool toggle)
        {
            category = null;
            setting = null;
            toggle = false;

            if (attr == null)
            {
                return false;
            }
            
            if (attr.Type == null) return false;
            
            if (!ContractNodes.ContractOptionAttributeName.Matches(attr.Type.Name)) return false;
            
            if (attr.Expressions == null) return false;
            
            if (attr.Expressions.Count != 3) return false;
            
            if (!AsLiteralString(attr.Expressions[0], out category)) return false;
            
            if (!AsLiteralString(attr.Expressions[1], out setting)) return false;
            
            if (!AsLiteralBool(attr.Expressions[2], out toggle)) return false;
            
            return true;
        }
Esempio n. 26
0
 public override Expression VisitAttributeConstructor(AttributeNode attribute)
 {
     if (attribute == null || attribute.Constructor == null) return null;
     return this.VisitExpression((Expression)attribute.Constructor.Clone());
 }
Esempio n. 27
0
        internal static void TryAddDebuggerBrowsableNeverAttribute(Member member, System.AttributeTargets targets)
        {
            Contract.Requires(member != null);

            try
            {
                if (HelperMethods.debuggerBrowsableAttributeNode == null) return;
                if (HelperMethods.debuggerBrowsableStateType == null) return;
                var ctor = HelperMethods.debuggerBrowsableAttributeNode.GetConstructor(HelperMethods.debuggerBrowsableStateType);
                var args = new ExpressionList(Literal.Int32Zero);
                var attribute = new AttributeNode(new MemberBinding(null, ctor), args, targets);
                member.Attributes.Add(attribute);
            }
            catch
            { }
        }
Esempio n. 28
0
 public override AttributeNode VisitAttributeNode(AttributeNode attribute)
 {
     if (attribute == null) return null;
     return base.VisitAttributeNode((AttributeNode)attribute.Clone());
 }
Esempio n. 29
0
        public override AttributeNode VisitAttributeNode(AttributeNode attribute)
        {
            // Ignore the ParamArray attribute
            if (attribute.Constructor is MemberBinding)
            {
                MemberBinding mb = (MemberBinding)attribute.Constructor;

                if (mb.BoundMember.DeclaringType.Name.Name == "ParamArrayAttribute")
                    return attribute;
            }

            WriteStart("[");
            this.VisitExpression(attribute.Constructor);
            Write("(");
            this.VisitExpressionList(attribute.Expressions);
            WriteFinish(")]");
            return attribute;
        }
Esempio n. 30
0
        /// <summary>
        /// This is used to see if an attribute type is exposed
        /// </summary>
        /// <param name="attribute">The attribute node to check</param>
        /// <returns>True if the attribute is exposed, false if not</returns>
        public virtual bool IsExposedAttribute(AttributeNode attribute)
        {
            if(attribute == null)
                throw new ArgumentNullException("attribute");

            // Check whether the attribute type is exposed
            TypeNode attributeType = attribute.Type;

            if(!this.IsExposedType(attributeType))
                return false;

            // Check whether expressions used to instantiate the attribute are exposed
            foreach(var expression in attribute.Expressions)
                if(!this.IsExposedExpression(expression))
                    return false;

            // If excluding attributes, just check for ones that are required
            if(!this.IncludeAttributes)
                return attributeFilter.IsRequiredType(attributeType);

            // Apply user filters to the attribute
            return attributeFilter.IsExposedType(attributeType);
        }