internal PersistedCredential(Guid userId, byte[] payload, byte[] token)
 {
     MethodContract.NotNull(payload, nameof(payload));
     this.userId   = userId;
     this.rawData  = payload;
     this.rawToken = token;
 }
Beispiel #2
0
        public CorsHandler(IHttpHandler next, CorsOptions options)
        {
            MethodContract.NotNull(next, nameof(next));
            MethodContract.NotNull(options, nameof(options));

            //lock it down so it can't change while in use
            this.options = new CorsOptions();
            foreach (string cur in options.Origins)
            {
                this.options.Origins.Add(cur);
            }

            foreach (string cur in options.RequestHeaders)
            {
                this.options.RequestHeaders.Add(cur);
            }

            foreach (string cur in options.ResponseHeaders)
            {
                this.options.ResponseHeaders.Add(cur);
            }

            foreach (HttpVerbs cur in options.Verbs)
            {
                foreach (string v in CorsConstants.SimpleMethods) //short list, so not horrible esp. since we do this once per corshandler instance
                {
                    this.hasNonSimpleVerbs = this.hasNonSimpleVerbs || v.Equals(cur.ToString());
                }
                this.options.Verbs.Add(cur);
            }

            this.options.PreflightMaxAge     = options.PreflightMaxAge;
            this.options.SupportsCredentials = options.SupportsCredentials;
            this.Next = next;
        }
Beispiel #3
0
        public HttpListenerServerListener(IEnumerable <string> urls, IHttpHandler handler) : base()
        {
            MethodContract.NotNull(urls, nameof(urls));
            MethodContract.NotNull(handler, nameof(handler));
            foreach (string url in urls)
            {
                Uri x;
                MethodContract.Assert(Uri.TryCreate(url, UriKind.Absolute, out x), string.Format("{0} not a valid uri", nameof(urls)));
                MethodContract.Assert(x.Scheme == Uri.UriSchemeHttp || x.Scheme == Uri.UriSchemeHttps, string.Format("{0} not a valid http/https uri", nameof(urls)));
                if (url.EndsWith("/"))
                {
                    this.urls.Add(url);
                }
                else
                {
                    this.urls.Add(url + '/');
                }
            }

            this.handler  = handler;
            this.listener = new System.Net.HttpListener();
            this.listener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous;
            foreach (string uri in this.urls)
            {
                this.listener.Prefixes.Add(uri);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Replaces any MemberBindings of the form (this,x) in the methodContract with a method call where the method
        /// being called is P where x is a private field of the source type that has been marked as [ContractPublicPropertyName("P")].
        /// </summary>
        /// <param name="targetType"></param>
        /// <param name="sourceType"></param>
        /// <param name="methodContract"></param>
        internal static void ReplacePrivateFieldsThatHavePublicProperties(TypeNode targetType,
                                                                          TypeNode sourceType,
                                                                          MethodContract methodContract,
                                                                          ContractNodes contractNodes
                                                                          )
        {
            Contract.Requires(sourceType != null);

            Dictionary <Field, Method> field2Getter = new Dictionary <Field, Method>();

            for (int i = 0, n = /*sourceType.Members == null ? 0 : */ sourceType.Members.Count; i < n; i++)
            {
                Field f = sourceType.Members[i] as Field;
                if (f == null)
                {
                    continue;
                }
                string propertyName = HelperMethods.GetStringFromAttribute(f, ContractNodes.SpecPublicAttributeName);
                if (propertyName != null)
                {
                    Property p = sourceType.GetProperty(Identifier.For(propertyName));
                    if (p != null)
                    {
                        field2Getter.Add(f, p.Getter);
                    }
                }
            }
            if (0 < field2Getter.Count)
            {
                SubstitutePropertyGetterForField s = new SubstitutePropertyGetterForField(field2Getter);
                s.Visit(methodContract);
            }
            return;
        }
 public UserPasswordCredential(string userName, string password)
 {
     MethodContract.NotNull(userName, nameof(userName));
     MethodContract.NotNull(password, nameof(password));
     this.userName = userName;
     this.password = password;
 }
Beispiel #6
0
        //TODO -- allow insert of record with NULL taxa iff -> (lifestage==null, count==0, indMass==NaN, whole==0)
        public FishDiet(Guid id, Guid fishId, CompoundIdentity taxaId, string vialId, string gutsampleid, string lifestage, uint?count, float sampleMass, float indMass, uint?wholeAnimalsWeighed, string description)
        {
            MethodContract.Assert(!Guid.Empty.Equals(id), nameof(id));
            MethodContract.Assert(!Guid.Empty.Equals(fishId), nameof(fishId));
            //MethodContract.NotNullOrEmpty(taxaId, nameof(taxaId));
            if (taxaId.IsNullOrEmpty())
            {
                if (count.HasValue && count > 0)
                {
                    throw new ArgumentException("for null taxa must have 0 or null count");
                }
            }

            this.Identity            = id;
            this.fishId              = fishId;
            this.taxaId              = taxaId;
            this.VialId              = vialId;
            this.GutSampleId         = gutsampleid;
            this.LifeStage           = lifestage;
            this.Count               = count;
            this.SampleMass          = sampleMass;
            this.IndividualMass      = indMass;
            this.WholeAnimalsWeighed = wholeAnimalsWeighed;
            this.Description         = description;
        }
Beispiel #7
0
        public static string GenerateSalt(int saltLength, char minChar, char maxChar, Random generator, ISet <int> suppressedChars)
        {
            MethodContract.Assert(minChar < maxChar, nameof(minChar) + " must be less than " + nameof(maxChar));
            int min = (int)minChar;
            int max = (int)maxChar;

            char[]        sb      = new char[saltLength]; //buckets to fill
            HashSet <int> visited = new HashSet <int>();  //buckets visited

            int count      = 0;
            int lastBucket = 0;
            int bucket     = GetBucketIndex(visited, saltLength, lastBucket, generator.Next(1, (saltLength - count) + 1));
            int cur;

            while (count < saltLength)
            {
                cur = generator.Next(min, max + 1);
                if (suppressedChars == null || !suppressedChars.Contains(cur))
                {
                    sb[bucket] = (char)cur;
                    lastBucket = bucket;
                    bucket     = GetBucketIndex(visited, saltLength, lastBucket, generator.Next(1, (saltLength - count) + 1));
                    count++;
                }
            }

            return(new string(sb));
        }
  Expression IContractDeserializer.ParseContract (MethodContract mc, string text, ErrorNodeList errs)
  {
    Expression expression = null;
    currentMethodContract = mc;
    currentMethod = null;
    currentType = null;
    if (mc != null){
      currentMethod = mc.DeclaringMethod;
      currentType = currentMethod.DeclaringType;
    }
    try{
      Parser.ParseContract(this.assembly, text, out expression);
    }catch (Exception e){
      ErrorNodeList eList = errs != null ? errs : this.ErrorList;
      if (eList != null){
#if OLDERRORS
        ErrorHandler eh = new ErrorHandler(eList);
        eh.HandleError(mc,System.Compiler.Error.GenericError,"Deserializer error: " + e.Message);
#else
        this.assembly.MetadataImportErrors.Add(e);
#endif
      }
      throw e;
    }
    return expression;
  }
Beispiel #9
0
        public SimpleFileHandler(string localPath, IEnumerable <string> defaultFiles, MimeTypes mimeTypes, FileExtensions allowed, FileExtensions disallowed)
            : base()
        {
            MethodContract.NotNull(localPath, nameof(localPath));
            MethodContract.NotNull(defaultFiles, nameof(defaultFiles));
            MethodContract.NotNull(mimeTypes, nameof(mimeTypes));

            this.mapper    = new DirectoryMapper(localPath);
            this.mimeTypes = mimeTypes;
            if (defaultFiles != null)
            {
                foreach (string curFil in defaultFiles)
                {
                    this.defaultFiles.Add(curFil);
                }
            }

            if (allowed != null)
            {
                this.allowedExtensions = allowed;
            }
            else
            {
                this.allowedExtensions = new FileExtensions();
            }

            if (disallowed != null)
            {
                this.disallowedExtensions = disallowed;
            }
            else
            {
                this.disallowedExtensions = new FileExtensions();
            }
        }
Beispiel #10
0
        private static ContractConsistencyInfo ComputeExposureForMethod(Method m)
        {
            ContractConsistencyInfo ei = null;

            if (!cache.ContainsKey(m))
            {
                ei = new ContractConsistencyInfo();
                MethodContract contract = m.Contract;
                if (!m.ApplyDefaultContract && !m.IsPropertyGetter)
                {
                    ei.Init(m, ei.requiresExposable, false);
                    ei.Init(m, ei.ensuresExposable, false);
                    ContractVisitor requiresVisitor = new ContractVisitor(ei.requiresExposable, m);
                    // requiresVisitor.VisitMethodContract(contract);
                    requiresVisitor.VisitRequiresList(contract.Requires);
                    ContractVisitor ensuresVisitor = new ContractVisitor(ei.ensuresExposable, m);
                    ensuresVisitor.VisitEnsuresList(contract.Ensures);
                }
                else
                {
                    ei.Init(m, ei.requiresExposable, true);
                    ei.Init(m, ei.ensuresExposable, true);
                }
            }
            else
            {
                ei = cache[m];
            }
            return(ei);
        }
 internal PersistedCredential(Guid userId, string payload, string token)
 {
     MethodContract.NotNull(payload, nameof(payload));
     this.userId    = userId;
     this.text      = payload;
     this.textToken = token;
 }
Beispiel #12
0
        public SingleServerTaskPool(IListener <T> listener, IHandler <T> handler, ServerTaskPoolOptions options)
        {
            MethodContract.NotNull(listener, nameof(listener));
            MethodContract.NotNull(handler, nameof(handler));
            MethodContract.NotNull(options, nameof(options));

            Setup((Func <T>)listener.GetContext, (Action <T>)handler.Handle, options);
        }
Beispiel #13
0
        public VegTreeSampleDTO(CompoundIdentity taxaUnitId, float dbh, string description)
        {
            MethodContract.NotNullOrEmpty(taxaUnitId, nameof(taxaUnitId));

            this.TaxaUnitId         = taxaUnitId;
            this.DiameterBreastHigh = dbh;
            this.Description        = description;
        }
Beispiel #14
0
        public FieldTeamMember(CompoundIdentity personId, CompoundIdentity fieldTeamMemberRoleId)
        {
            MethodContract.NotNull(personId, nameof(personId));
            MethodContract.NotNull(fieldTeamMemberRoleId, nameof(fieldTeamMemberRoleId));

            this.PersonId = personId;
            this.fieldTeamMemberRoleId = fieldTeamMemberRoleId;
        }
Beispiel #15
0
        public VegHerbSampleDTO(CompoundIdentity taxaUnitId, float percentCover, string description)
        {
            MethodContract.NotNullOrEmpty(taxaUnitId, nameof(taxaUnitId));

            this.TaxaUnitId   = taxaUnitId;
            this.PercentCover = percentCover;
            this.Description  = description;
        }
Beispiel #16
0
 public ProjectStatusType(CompoundIdentity id, string name, string description)
 {
     MethodContract.NotNullOrEmpty(id, nameof(id));
     MethodContract.NotNullOrEmpty(name, nameof(name));
     this.Identity    = id;
     this.name        = name;
     this.Description = description;
 }
Beispiel #17
0
        public SingleServerTaskPool(Func <T> listener, Action <T> handler, ServerTaskPoolOptions options)
        {
            MethodContract.NotNull(listener, nameof(listener));
            MethodContract.NotNull(handler, nameof(handler));
            MethodContract.NotNull(options, nameof(options));

            Setup(listener, handler, options);
        }
        public FieldTeamMemberRole(CompoundIdentity id, string name, string description)
        {
            MethodContract.NotNullOrEmpty(id, nameof(id));
            MethodContract.NotNullOrEmpty(name, nameof(name));

            this.Identity    = id;
            this.name        = name;
            this.Description = description;
        }
Beispiel #19
0
        public VegShrubSampleDTO(CompoundIdentity taxaUnitId, string sizeClass, uint count, string description)
        {
            MethodContract.NotNullOrEmpty(taxaUnitId, nameof(taxaUnitId));

            this.TaxaUnitId  = taxaUnitId;
            this.SizeClass   = sizeClass;
            this.Count       = count;
            this.Description = description;
        }
Beispiel #20
0
 internal HandoffEvent(Func <T> listener, Action <T> handler, int maxQueueSize)
 {
     MethodContract.NotNull(listener, nameof(listener));
     MethodContract.NotNull(handler, nameof(handler));
     MethodContract.Assert(maxQueueSize > 0, nameof(maxQueueSize));
     this.listen       = listener;
     this.handle       = handler;
     this.maxQueueSize = maxQueueSize;
 }
        public static TaskPool CreateScavengingTaskPool(Action toRun, TaskPoolOptions options)
        {
            MethodContract.NotNull(toRun, nameof(toRun));
            ScavengingTaskPoolRunner runner = new ScavengingTaskPoolRunner(toRun);
            TaskPool pool = new TaskPool(runner.Run, options);

            runner.pool = pool;
            return(pool);
        }
Beispiel #22
0
        internal KnownArchetype(CompoundIdentity id, string name, string description)
        {
            MethodContract.Assert(!id.IsNullOrEmpty(), nameof(id));
            MethodContract.NotNullOrEmpty(name, nameof(name));

            this.Id          = id;
            this.name        = name;
            this.Description = description;
        }
Beispiel #23
0
        public Organization(CompoundIdentity id, string name, string description)
        {
            MethodContract.NotNull(id, nameof(id));
            MethodContract.NotNullOrEmpty(name, nameof(name));

            this.Identity    = id;
            this.name        = name;
            this.Description = description;
        }
Beispiel #24
0
        private void SetContainingBlockForContracts()
        {
            MethodContract mc = this.Compilation.ContractProvider.GetMethodContractFor(this) as MethodContract;

            if (mc != null)
            {
                mc.SetContainingBlock(this);
            }
        }
Beispiel #25
0
 public Person(CompoundIdentity id, string firstName, string lastName)
 {
     MethodContract.NotNullOrEmpty(id, nameof(id));
     MethodContract.NotNullOrEmpty(firstName, nameof(firstName));
     MethodContract.NotNullOrEmpty(lastName, nameof(lastName));
     this.Identity  = id;
     this.firstName = firstName;
     this.lastName  = lastName;
 }
Beispiel #26
0
        public virtual void VisitMethodContract(MethodContract node)
        {
            if (node == null)
            {
                return;
            }

            VisitRequiresList(node.Requires);
            VisitEnsuresList(node.Ensures);
        }
 protected OrganizationHierarchy(CompoundIdentity identity, CompoundIdentity owningOrgId, string name, string description)
 {
     MethodContract.NotNullOrEmpty(identity, nameof(identity));
     MethodContract.NotNullOrEmpty(owningOrgId, nameof(owningOrgId));
     MethodContract.NotNullOrEmpty(name, nameof(name));
     this.Identity    = identity;
     this.owningOrgId = owningOrgId;
     this.name        = name;
     this.Description = description;
 }
Beispiel #28
0
        public TreeSampleDTO(Guid vegSampleId, VegTreeSampleDTO innerItem)
        {
            MethodContract.NotNull(innerItem, nameof(innerItem));
            MethodContract.Assert(!Guid.Empty.Equals(vegSampleId), nameof(vegSampleId));

            this.VegSampleId        = vegSampleId;
            this.TaxaUnitId         = innerItem.TaxaUnitId;
            this.DiameterBreastHigh = innerItem.DiameterBreastHigh;
            this.Description        = innerItem.Description;
        }
Beispiel #29
0
        public InstrumentArchetypeInstance(CompoundIdentity instrumentId, CompoundIdentity archetypeId, string data)
        {
            MethodContract.Assert(!InstrumentId.IsNullOrEmpty(), nameof(instrumentId));
            MethodContract.Assert(!archetypeId.IsNullOrEmpty(), nameof(archetypeId));
            MethodContract.NotNullOrEmpty(data, nameof(data));

            this.InstrumentId = instrumentId;
            this.ArchetypeId  = archetypeId;
            this.Data         = data;
        }
Beispiel #30
0
        public TreeSampleDTO(Guid vegSampleId, CompoundIdentity taxaUnitId, float dbh, string description)
        {
            MethodContract.NotNullOrEmpty(taxaUnitId, nameof(taxaUnitId));
            MethodContract.Assert(!Guid.Empty.Equals(vegSampleId), nameof(vegSampleId));

            this.VegSampleId        = vegSampleId;
            this.TaxaUnitId         = taxaUnitId;
            this.DiameterBreastHigh = dbh;
            this.Description        = description;
        }
Beispiel #31
0
        public SensorType(CompoundIdentity id, string name, string description, CompoundIdentity parentId)
        {
            MethodContract.Assert(!id.IsNullOrEmpty(), nameof(id));
            MethodContract.NotNullOrEmpty(name, nameof(name));

            this.Identity    = id;
            this.name        = name;
            this.Description = description;
            this.ParentId    = parentId;
        }
        public override MethodContract VisitMethodContract(MethodContract contract)
        {
            if (contract == null) return null;

            var savedCurrentMethod = this.CurrentMethod;
            this.CurrentMethod = contract.DeclaringMethod;

            try
            {
                return base.VisitMethodContract(contract);
            }
            finally
            {
                this.CurrentMethod = savedCurrentMethod;
            }
        }
Beispiel #33
0
 public override MethodContract VisitMethodContract(MethodContract contract)
 {
   if (contract == null) return null;
   contract = (MethodContract)contract.Clone();
   //^ assume this.TargetMethod != null;
   contract.DeclaringMethod = this.TargetMethod;
   contract.ensures = this.VisitEnsuresList(contract.ensures);
   contract.modifies = this.VisitExpressionList(contract.modifies);
   contract.requires = this.VisitRequiresList(contract.requires);
   return contract;
 }
Beispiel #34
0
        /// <summary>
        /// TODO: figure out if there can be more than one closure initialization in a closureInitializer.
        /// Or other stuff.
        /// </summary>
        private static void DeleteClosureInitialization(Method containing, MethodContract mc, Local closureLocal)
        {
            Contract.Requires(containing != null);
            Contract.Requires(mc != null);
            Contract.Requires(closureLocal != null);

            var b = mc.ContractInitializer;
            mc.PostPreamble = null;

            bool foundStart = false;
            if (b == null || b.Statements == null || !(b.Statements.Count > 0))
            {
                return;
            }

            for (int i = 0; i < b.Statements.Count; i++)
            {
                Statement s = b.Statements[i];
                if (s == null || s.NodeType == NodeType.Nop) continue;

                if (s is Block)
                {
                    // indicates code from an abbreviator call
                    if (foundStart)
                    {
                        // this is the end
                        return;
                    }

                    // skip the block
                    continue;
                }

                Local otherLocal;
                if (IsClosureCreation(containing, s, out otherLocal))
                {
                    if (foundStart)
                    {
                        // this must be the next one
                        return;
                    }

                    if (closureLocal == otherLocal)
                    {
                        foundStart = true;
                    }
                }

                if (foundStart)
                {
                    // delete
                    b.Statements[i] = null; // delete
                }
            }
        }
Beispiel #35
0
 /// <summary>
 /// Visits the specified method contract.
 /// </summary>
 /// <param name="methodContract">The method contract.</param>
 /// <returns></returns>
 protected virtual IMethodContract DeepCopy(MethodContract methodContract)
 {
     methodContract.Allocates = this.DeepCopy(methodContract.Allocates);
       methodContract.Frees = this.DeepCopy(methodContract.Frees);
       methodContract.ModifiedVariables = this.DeepCopy(methodContract.ModifiedVariables);
       methodContract.Postconditions = this.DeepCopy(methodContract.Postconditions);
       methodContract.Preconditions = this.DeepCopy(methodContract.Preconditions);
       methodContract.Reads = this.DeepCopy(methodContract.Reads);
       methodContract.ThrownExceptions = this.DeepCopy(methodContract.ThrownExceptions);
       methodContract.Writes = this.DeepCopy(methodContract.Writes);
       return methodContract;
 }
Beispiel #36
0
 public virtual MethodContract VisitMethodContract(MethodContract contract){
   if (contract == null) return null;
   // don't visit contract.DeclaringMethod
   // don't visit contract.OverriddenMethods
   contract.Requires = this.VisitRequiresList(contract.Requires);
   contract.Ensures = this.VisitEnsuresList(contract.Ensures);
   contract.Modifies = this.VisitExpressionList(contract.Modifies);
   return contract;
 }
Beispiel #37
0
    private void RecordEnsures(
        Method method, 
        ref int oldLocalUniqueNameCounter, 
        List<Block> contractInitializationBlocks, 
        Dictionary<TypeNode, Local> closureLocals, 
        Block oldExpressionPreStateValues, 
        List<Ensures> postconditions, 
        List<Ensures> asyncPostconditions, 
        WrapParametersInOldExpressions wrap, 
        ref EmitAsyncClosure asyncBuilder,
        MethodContract mc)
    {
        RewriteHelper.RecordClosureInitialization(method, mc.ContractInitializer, closureLocals);
        if (this.Emit(RuntimeContractEmitFlags.Ensures) && mc.Ensures != null)
        {
            mc.Ensures = wrap.VisitEnsuresList(mc.Ensures);
            Block oldInits = ProcessOldExpressions(method, mc.Ensures, closureLocals, ref oldLocalUniqueNameCounter);
            if (oldInits != null)
            {
                oldExpressionPreStateValues.Statements.Add(oldInits);
            }
            if (mc.Ensures != null)
            {
                foreach (Ensures ensures in mc.Ensures)
                {
                    if (!EmitEnsures(ensures, method.DeclaringType, this.skipQuantifiers)) continue;
                    postconditions.Add(ensures);
                }
            }
        }
        if (this.Emit(RuntimeContractEmitFlags.AsyncEnsures) && mc.AsyncEnsuresCount > 0)
        {
            mc.AsyncEnsures = wrap.VisitEnsuresList(mc.AsyncEnsures);
            var found = false;
            foreach (Ensures postcondition in mc.AsyncEnsures)
            {
                if (!EmitEnsures(postcondition, method.DeclaringType, this.skipQuantifiers) || asyncPostconditions.Contains(postcondition)) continue;

                EnsureAsyncBuilder(method, contractInitializationBlocks, closureLocals, ref asyncBuilder);
                found = true;
                asyncPostconditions.Add(postcondition);
            }
            if (found)
            {
                Block oldInit = ProcessOldExpressionsInAsync(method, mc.AsyncEnsures, closureLocals, ref oldLocalUniqueNameCounter, asyncBuilder.ClosureClass);
                if (oldInit != null && oldInit.Statements != null && oldInit.Statements.Count > 0)
                {
                    oldExpressionPreStateValues.Statements.Add(oldInit);
                }
            }
        }
    }
Beispiel #38
0
        /// <summary>
        /// Replaces any MemberBindings of the form (this,x) in the methodContract with a method call where the method
        /// being called is P where x is a private field of the source type that has been marked as [ContractPublicPropertyName("P")].
        /// </summary>
        /// <param name="targetType"></param>
        /// <param name="sourceType"></param>
        /// <param name="methodContract"></param>
        internal static void ReplacePrivateFieldsThatHavePublicProperties(TypeNode targetType,
          TypeNode sourceType,
          MethodContract methodContract,
          ContractNodes contractNodes
          )
        {
          Contract.Requires(sourceType != null);

            Dictionary<Field, Method> field2Getter = new Dictionary<Field, Method>();

            for (int i = 0, n = /*sourceType.Members == null ? 0 : */ sourceType.Members.Count; i < n; i++)
            {
                Field f = sourceType.Members[i] as Field;
                if (f == null) continue;
                string propertyName = HelperMethods.GetStringFromAttribute(f, ContractNodes.SpecPublicAttributeName);
                if (propertyName != null)
                {
                    Property p = sourceType.GetProperty(Identifier.For(propertyName));
                    if (p != null)
                    {
                        field2Getter.Add(f, p.Getter);
                    }
                }
            }
            if (0 < field2Getter.Count)
            {
                SubstitutePropertyGetterForField s = new SubstitutePropertyGetterForField(field2Getter);
                s.Visit(methodContract);
            }
            return;
        }
            internal void CheckAbbreviatorEnsures(MethodContract methodContract)
            {
                if (methodContract == null) return;
                
                for (int i = 0; i < methodContract.EnsuresCount; i++)
                {
                    var ens = methodContract.Ensures[i];

                    Contract.Assume(ens != null);
                    Contract.Assume(methodContract.DeclaringMethod != null); // F:
                    
                    this.CheckEnsures(methodContract.DeclaringMethod, ens);
                }

                if (methodContract.ModelEnsuresCount > 0)
                {
                    var modelEnsures = methodContract.ModelEnsures[0];
                    if (modelEnsures != null)
                    {
                        this.HandleError(methodContract.DeclaringMethod, 1074,
                            "ContractAbbreviator methods cannot contain Ensures referring to Model members.",
                            modelEnsures);
                    }
                }
            }
            internal void CheckEnsures(MethodContract contract)
            {
                if (contract == null) return;
                Contract.Assume(contract.DeclaringMethod != null);
                this.CurrentMethod = contract.DeclaringMethod;
                for (int i = 0; i < contract.EnsuresCount; i++)
                {
                    var ens = contract.Ensures[i];
                    CheckPostcondition(ens);
                }

                for (int i = 0; i < contract.ModelEnsuresCount; i++)
                {
                    var ens = contract.ModelEnsures[i];
                    CheckPostcondition(ens);
                }
                
                for (int i = 0; i < contract.AsyncEnsuresCount; i++)
                {
                    var ens = contract.AsyncEnsures[i];
                    CheckPostcondition(ens);
                }
            }
 public override void VisitMethodContract(MethodContract contract)
 {
   // don't visit again...
 }
 private void CheckEnsures(MethodContract methodContract)
 {
     this.postconditionChecker.CheckEnsures(methodContract);
 }
 private static bool HasValidations(MethodContract methodContract)
 {
     return methodContract != null && methodContract.HasLegacyValidations;
 }
internal static int ParseContract (Module assem, string text, out Expression expression)
{
  Debug.Assert(assem != null);
  currentAssembly = assem;

  Scanner.Init(text);

  Errors.SynErr = new ErrorProc(SynErr);
  t = new Token();
  Get();
  Expr(out expression);

  currentMethodContract = null;
  currentMethod = null;
  currentAssembly = null;
  
  return Errors.count;
}
Beispiel #45
0
 public override MethodContract VisitMethodContract(MethodContract contract) {
   bool savedInsideAssertion = this.insideAssertion;
   this.insideAssertion = true;
   try {
     return base.VisitMethodContract(contract);
   } finally {
     this.insideAssertion = savedInsideAssertion;
   }
 }
Beispiel #46
0
		public virtual MethodContract VisitMethodContract (MethodContract node)
		{
			if (node == null)
				return null;

			node.Requires = VisitRequiresList (node.Requires);
			node.Ensures = VisitEnsuresList (node.Ensures);

			return node;
		}
Beispiel #47
0
 public virtual MethodContract VisitMethodContract(MethodContract contract1, MethodContract contract2) {
   if (contract1 == null) return null;
   if (contract2 == null) {
     // don't visit contract.DeclaringMethod
     // don't visit contract.OverriddenMethods
     contract1.Requires = this.VisitRequiresList(contract1.Requires, null);
     contract1.Ensures = this.VisitEnsuresList(contract1.Ensures, null);
     contract1.Modifies = this.VisitExpressionList(contract1.Modifies, null);
   }else{
     // don't visit contract.DeclaringMethod
     // don't visit contract.OverriddenMethods
     contract1.Requires = this.VisitRequiresList(contract1.Requires,contract2.Requires);
     contract1.Ensures = this.VisitEnsuresList(contract1.Ensures,contract2.Ensures);
     contract1.Modifies = this.VisitExpressionList(contract1.Modifies,contract2.Modifies);
   }
   return contract1;
 }
 public override MethodContract VisitMethodContract(MethodContract contract){
   if (contract == null) return null;
   var specializer = this as MethodBodySpecializer;
   if (specializer == null)
   {
     specializer = contract.DeclaringMethod.DeclaringType.DeclaringModule.GetMethodBodySpecializer(this.pars, this.args);
     specializer.CurrentMethod = this.CurrentMethod;
     specializer.CurrentType = this.CurrentType;
   }
   contract.contractInitializer = specializer.VisitBlock(contract.contractInitializer);
   contract.postPreamble = specializer.VisitBlock(contract.postPreamble);
   contract.ensures = specializer.VisitEnsuresList(contract.ensures);
   contract.asyncEnsures = specializer.VisitEnsuresList(contract.asyncEnsures);
   contract.modelEnsures = specializer.VisitEnsuresList(contract.modelEnsures);
   contract.modifies = specializer.VisitExpressionList(contract.modifies);
   contract.requires = specializer.VisitRequiresList(contract.requires);
   return contract;
 }
Beispiel #49
0
 public virtual void VisitMethodContract(MethodContract contract)
 {
   if (contract == null) return;
   // don't visit contract.DeclaringMethod
   // don't visit contract.OverriddenMethods
   this.VisitRequiresList(contract.Requires);
   this.VisitEnsuresList(contract.Ensures);
   this.VisitEnsuresList(contract.ModelEnsures);
   this.VisitExpressionList(contract.Modifies);
   this.VisitEnsuresList(contract.AsyncEnsures);
 }
internal static int ParseContract (Module assem, string text, out Expression expression)
{
  Debug.Assert(assem != null);
  currentAssembly = assem;

  System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(text), false);
  Errors errors = new Errors();
  Scanner scanner = new Scanner(ms, errors, "");

  Parser parser = new Parser(scanner, errors);
  parser.Get();
  parser.Expr(out expression);

  currentMethodContract = null;
  currentMethod = null;
  currentAssembly = null;

  if (parser.errors.count == 0)
  {
     return 0;
  }
  else
  {
     expression = null;
     return parser.errors.count;
  }
}
 private void CheckRequires(MethodContract methodContract)
 {
     this.preconditionChecker.CheckRequires(methodContract);
     this.visibilityChecker.CheckRequires(methodContract);
 }
Beispiel #52
0
    public override MethodContract VisitMethodContract(MethodContract contract) {
      if (contract == null) return null;
      // don't visit contract.DeclaringMethod
      // don't visit contract.OverriddenMethods
      bool savedInsideMethodContract = this.insideMethodContract;
      bool savedUnsafe = this.typeSystem.insideUnsafeCode;
      this.insideMethodContract = true;

      Yield savedYield = this.yieldNode;

      Method method = contract.DeclaringMethod;
      insidePureContract = method.IsPure || method.IsConfined || method.IsStateIndependent;

      if (method != null) {

        this.typeSystem.insideUnsafeCode = method.IsUnsafe;
        if (contract.Ensures != null && contract.Ensures.Count > 0) {
          TrivialHashtable /*TypeNode*/ throwsSet = new TrivialHashtable();
          for (int i = 0, n = contract.Ensures.Count; i < n; i++) {
            EnsuresExceptional e = contract.Ensures[i] as EnsuresExceptional;
            if (e == null) continue;
            if (e.Inherited) continue;
            if (e.Type == null) continue;
            if (!this.GetTypeView(e.Type).IsAssignableTo(SystemTypes.ICheckedException)) {
              this.HandleError(e, Error.UncheckedExceptionInThrowsClause, this.GetTypeName(method.DeclaringType) + "." + method.Name.ToString());
              contract.Ensures[i] = null;
            }
            if (throwsSet[e.Type.UniqueKey] != null) {
              this.HandleError(method, Error.DuplicateThrowsType, this.GetTypeName(method.DeclaringType) + "." + method.Name.ToString());
              contract.Ensures[i] = null;
            } else {
              throwsSet[e.Type.UniqueKey] = e.Type;
            }
          }
        }

        contract.Requires = this.VisitRequiresList(contract.Requires);
        InstanceInitializer ctor = this.currentMethod as InstanceInitializer;
        bool savedMayReferenceThisAndBase = this.MayReferenceThisAndBase;
        if (ctor != null) {
          // method contracts are visited as part of visiting the methods to which they
          // are attached. So their ability to reference "this" is usually the same as
          // the method's ability. But the postcondition of a ctor can mention instance
          // variables.
          this.MayReferenceThisAndBase = true;
        }
        bool savedInsideEnsures = this.insideEnsures;
        this.insideEnsures = true;
        contract.Ensures = this.VisitEnsuresList(contract.Ensures);
        this.insideEnsures = savedInsideEnsures;
        this.MayReferenceThisAndBase = savedMayReferenceThisAndBase;
        bool savedInsideModifies = this.insideModifies;
        this.insideModifies = true;
        contract.Modifies = this.VisitExpressionList(contract.Modifies);
        this.insideModifies = savedInsideModifies;

        //if (method.IsVirtual) {
        //  // use FindNearest..., can't rely on method.OverriddenMethod since it might not be set further up the chain
        //  Method overridden = method.DeclaringType.FindNearestOverriddenMethod(method);
        //  if (overridden != null) {
        //    this.CheckEnsuresListsCompatibility(overridden, method);
        //  }
        //  for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) {
        //    Method ifaceMethod = method.ImplementedInterfaceMethods[i];
        //    this.CheckEnsuresListsCompatibility(ifaceMethod, method);
        //  }
        //  for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) {
        //    Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i];
        //    this.CheckEnsuresListsCompatibility(ifaceMethod, method);
        //  }
        //}
      }
      this.insideMethodContract = savedInsideMethodContract;
      this.typeSystem.insideUnsafeCode = savedUnsafe;
      this.yieldNode = savedYield;      
      return contract;
    }    
        private static bool HasNonValidationContract(MethodContract methodContract)
        {
            if (methodContract == null) return false;

            return methodContract.EnsuresCount > 0 ||
                   Contract.Exists(0, methodContract.RequiresCount,
                       i => !((RequiresPlain) methodContract.Requires[i]).IsFromValidation);
        }
Beispiel #54
0
    // TODO: otherwise clauses on requires, exceptional ensures
    public virtual void SerializeMethodContract(MethodContract mc) {
      if (mc.Requires != null) {
        for (int i = 0, n = mc.Requires.Count; i < n; i++) {
          Requires r = mc.Requires[i];
          if (r == null || r.Condition == null || r.Inherited) continue;
          ExpressionList el = SplitConjuncts(r.Condition);
          for (int j = 0, m = el.Count; j < m; j++) {
            Requires r_prime = new RequiresPlain(el[j]);
            InstanceInitializer ctor = SystemTypes.RequiresAttribute.GetConstructor(SystemTypes.String);
            AttributeNode a = Checker.SerializeExpression(ctor, r_prime.Condition, this.currentModule);
            mc.DeclaringMethod.Attributes.Add(a);
          }
        }
      }
      if (mc.Ensures != null) {
        for (int i = 0, n = mc.Ensures.Count; i < n; i++) {
          EnsuresExceptional ee = mc.Ensures[i] as EnsuresExceptional;
          if (ee != null) {
            if (ee.PostCondition == null) {
              if (ee.Inherited || ee.TypeExpression.SourceContext.Document == null) continue;
              // then it is "throws E;"
              InstanceInitializer ctor = SystemTypes.ThrowsAttribute.GetConstructor(SystemTypes.Type);
              AttributeNode a = Checker.SerializeExpressions(ctor, new ExpressionList(new Literal(ee.Type, SystemTypes.Type)), null, ee.TypeExpression.SourceContext, this.currentModule);
              mc.DeclaringMethod.Attributes.Add(a);
            } else {
              // then it is "throws E ensures Q;" or "throws (E e) ensures Q;"
              // don't split Q into its top-level conjuncts because duplicate throws clauses for the same exception type
              // are not allowed.
              if (ee.Inherited || ee.PostCondition.SourceContext.Document == null) continue;
              InstanceInitializer ctor = SystemTypes.ThrowsAttribute.GetConstructor(SystemTypes.Type, SystemTypes.String);
              AttributeNode a = Checker.SerializeExpressions(ctor,
                new ExpressionList(new Literal(ee.Type, SystemTypes.Type)), 
                new ExpressionList(ee.PostCondition),
                ee.PostCondition.SourceContext,
                this.currentModule);
              mc.DeclaringMethod.Attributes.Add(a);
            }

          } else {
            Ensures e = mc.Ensures[i];
            if (e == null || e.PostCondition == null || e.Inherited || e.PostCondition.SourceContext.Document == null) continue;
            ExpressionList el = SplitConjuncts(e.PostCondition);
            for (int j = 0, m = el.Count; j < m; j++) {
              EnsuresNormal e_prime = new EnsuresNormal(el[j]);
              InstanceInitializer ctor = SystemTypes.EnsuresAttribute.GetConstructor(SystemTypes.String);
              AttributeNode a = Checker.SerializeExpression(ctor, e_prime.PostCondition, this.currentModule);
              mc.DeclaringMethod.Attributes.Add(a);
            }
          }
        }
      }
      if (mc.Modifies != null && mc.Modifies.Count > 0) {
        for (int i = 0, n = mc.Modifies.Count; i < n; i++) {                    
          Expression e = mc.Modifies[i];
          if (e == null || e.SourceContext.Document == null) continue;
          InstanceInitializer ctor = SystemTypes.ModifiesAttribute.GetConstructor(SystemTypes.String);
          AttributeNode a = Checker.SerializeExpression(ctor, e, this.currentModule);          
          mc.DeclaringMethod.Attributes.Add(a);
        }
      }
      return;
    }
            internal void CheckRequires(MethodContract contract)
            {
                if (contract == null) return;

                this.CurrentMethod = contract.DeclaringMethod;
                
                var requiresList = contract.Requires;
                if (requiresList == null) return;
                
                foreach (var req in requiresList)
                {
                    CheckPrecondition(req);
                }
            }
Beispiel #56
0
		public virtual void VisitMethodContract (MethodContract node)
		{
			if (node == null)
				return;

			VisitRequiresList (node.Requires);
			VisitEnsuresList (node.Ensures);
		}
            /// <summary>
            /// If the method contract is for an interface/abstract type, we need to make sure we use the visibility of the target method, not the contract method.
            /// </summary>
            internal void CheckRequires(MethodContract methodContract)
            {
                if (methodContract == null || methodContract.Requires == null) return;

                // F:
                Contract.Assume(methodContract.DeclaringMethod != null);

                Method targetMethod = FindTargetMethod(methodContract.DeclaringMethod);

                foreach (var req in methodContract.Requires)
                {
                    Contract.Assume(req != null); //F:

                    this.CheckRequires(targetMethod, req);
                }
            }
Beispiel #58
0
 /// <summary>
 /// A copy constructor that allocates an instance that is the same as the given template.
 /// </summary>
 /// <param name="template">The template to copy.</param>
 protected MethodContract(MethodContract template)
 {
     if (template.allocates != EmptyListOfExpressions)
     this.allocates = new List<Expression>(template.allocates);
       else
     this.allocates = template.allocates;
       if (template.frees != EmptyListOfExpressions)
     this.frees = new List<Expression>(template.frees);
       else
     this.frees = template.frees;
       if (template.modifiedVariables != EmptyListOfTargetExpressions)
     this.modifiedVariables = new List<AddressableExpression>(template.modifiedVariables);
       else
     this.modifiedVariables = template.modifiedVariables;
       this.mustInline = template.mustInline;
       if (template.postconditions != EmptyListOfPostconditions)
     this.postconditions = new List<Postcondition>(template.postconditions);
       else
     this.postconditions = template.postconditions;
       if (template.preconditions != EmptyListOfPreconditions)
     this.preconditions = new List<Precondition>(template.preconditions);
       else
     this.preconditions = template.preconditions;
       if (template.reads != EmptyListOfExpressions)
     this.reads = new List<Expression>(template.reads);
       else
     this.reads = template.reads;
       if (template.thrownExceptions != EmptyListOfThrownExceptions)
     this.thrownExceptions = new List<ThrownException>(template.thrownExceptions);
       else
     this.thrownExceptions = template.thrownExceptions;
       if (template.writes != EmptyListOfExpressions)
     this.writes = new List<Expression>(template.writes);
       else
     this.writes = template.writes;
       if (template.variants != EmptyListOfExpressions)
     this.variants = new List<Expression>(template.variants);
       else
       this.variants = template.variants;
       this.isPure = template.isPure;
 }
        private void CheckMethodContract(MethodContract contract)
        {
            if (contract == null) return;

            this.CheckRequires(contract);
            this.CheckEnsures(contract);
        }
Beispiel #60
0
 /// <summary>
 /// Makes a copy of this contract, changing the containing block to the given block.
 /// </summary>
 //^ [MustOverride]
 public virtual MethodContract MakeCopyFor(BlockStatement containingBlock)
 {
     if (this.containingBlock == containingBlock) return this;
       MethodContract result = new MethodContract(this);
       result.SetContainingBlock(containingBlock);
       return result;
 }