Ejemplo n.º 1
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var viewModel = new TaskManagementViewModel();

            DataContext = viewModel;

            Yield.Call(viewModel.Activate());
        }
Ejemplo n.º 2
0
        public void UpdateYield(Yield yield)
        {
            Yield yieldUpdate = db.Yields.FirstOrDefault(y => y.idYield == yield.idYield);

            yieldUpdate.date       = yield.date;
            yieldUpdate.totalYield = yield.totalYield;
            db.SaveChanges();
        }
Ejemplo n.º 3
0
 private void HandleItemSelected(Yield yield)
 {
     if (yield == null)
     {
         return;
     }
     Navigation.PushAsync(new ReviewContentYieldJobsPage(yield.YieldId));
 }
Ejemplo n.º 4
0
 private void HandleItemSelected(Yield yield)
 {
     if (yield == null)
     {
         return;
     }
     Navigation.PushAsync(new EditYieldPage(yield.YieldId));
     // selectedItemText = plant.Name;
 }
Ejemplo n.º 5
0
        private static void HandleReturnValue(object returnValue)
        {
            var routine = returnValue as IEnumerable <IAction>;

            if (routine != null)
            {
                Yield.Call((routine));
            }
        }
Ejemplo n.º 6
0
        void downloadButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(urlTextBox.Text))
            {
                return;
            }

            Yield.Call(BackgroundDownload(new Uri(urlTextBox.Text), queueListBox.Items.Count));
        }
 private void HandleItemSelected(Yield yield)
 {
     if (yield == null)
     {
         return;
     }
     Navigation.PushAsync(new ReviewContentYieldJobsPage(yield.YieldId));
     this.Navigation.RemovePage(this.Navigation.NavigationStack[this.Navigation.NavigationStack.Count - 2]);
 }
Ejemplo n.º 8
0
        public void MetodaFibonacciVraćaNiz()
        {
            var niz = Yield.FibonacciIEnumerable();

            // provjera da rezultat nije neka kolekcija
            Assert.IsTrue(niz.GetType().GetProperty("Count") == null && niz.GetType().GetProperty("Length") == null);
            Assert.AreEqual(0, niz.ElementAt(0));
            Assert.AreEqual(1, niz.ElementAt(1));
            Assert.AreEqual(8, niz.ElementAt(6));
        }
Ejemplo n.º 9
0
 private IEnumerator TimeUpdate(float time)
 {
     while (0 < time)
     {
         TimerText.text = TIME_MESSAGE + time;
         time--;
         yield return(Yield.WaitForSecond(1.0f));
     }
     NextStage();
 }
Ejemplo n.º 10
0
        public EditYieldViewModel(INavigation navigation, string yieldId)
        {
            this.Navigation = navigation;
            Title           = "Update Yield";

            Plants = GetPlantNameVarieties();
            Years  = GetYears();

            _yield = _realmInstance.Find <Yield>(yieldId);
        }
Ejemplo n.º 11
0
        private static void FindForwards(Yield @short, Yield[] yields, double spotTarget)
        {
            var context = SolverContext.GetContext();

            context.ClearModel();
            var model = context.CreateModel();

            var forwards = new Decision[yields.Length];

            for (var i = 0; i < forwards.Length; i++)
            {
                model.AddDecision(forwards[i] = new Decision(Domain.RealNonnegative, null));
            }

            Term fwd        = @short.Forward;
            var  spotFactor = Model.Power(1d + @short.Spot / 100d, @short.Term / 252d);
            var  diff       = new Term[forwards.Length + 1];

            diff[0] = 0;

            for (var i = 0; i < forwards.Length; i++)
            {
                var termDelta     = yields[i].Term - (i == 0 ? @short.Term : yields[i - 1].Term);
                var forwardFactor = Model.Power(1d + forwards[i] / 100d, termDelta / 252d);
                spotFactor *= forwardFactor;
                diff[i + 1] = forwards[i] - (i == 0 ? fwd : forwards[i - 1]);
            }

            var spot = (Model.Power(spotFactor, 252d / yields.Last().Term) - 1d) * 100d;

            var diff2 = new Term[diff.Length - 1];

            for (var i = 1; i < diff.Length; i++)
            {
                diff2[i - 1] = diff[i] - diff[i - 1];
            }

            var diff3 = new Term[diff2.Length - 1];

            for (var i = 1; i < diff2.Length; i++)
            {
                diff3[i - 1] = diff2[i] - diff2[i - 1];
            }

            var goal = Model.Sum(Model.Abs(spot - spotTarget), Model.Abs(Model.Sum(diff3)));

            model.AddGoal("erro", GoalKind.Minimize, goal);

            context.Solve();

            for (var i = 0; i < forwards.Length; i++)
            {
                yields[i].Forward = forwards[i].GetDouble();
            }
        }
Ejemplo n.º 12
0
 void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
     else if (instance != this)
     {
         Destroy(gameObject);
     }
 }
Ejemplo n.º 13
0
 public void Add(Yield y)
 {
     if (this.toggle)
     {
         this.Ying.Add(y);
     }
     else
     {
         this.Yang.Add(y);
     }
 }
Ejemplo n.º 14
0
        private void ClearState()
        {
            if (_yield != null)
            {
                _yield.Finilize();
            }

            _yield                = new Yield();
            _enumerationTask      = null;
            _enumerationException = null;
        }
Ejemplo n.º 15
0
        public static LuaTable CreateTable()
        {
            LuaTable coroutine = new LuaTable();

            coroutine["create"]  = new LuaInteropDelegateFunc <LuaFunction, LuaThread>(create);
            coroutine["resume"]  = new LuaInteropDelegate(resume);
            coroutine["running"] = new LuaInteropDelegateFunc <LuaThread>(running);
            coroutine["status"]  = new LuaInteropDelegateFunc <LuaThread, string>(status);
            coroutine["wrap"]    = new LuaInteropDelegateFunc <LuaFunction, LuaValue>(wrap);
            coroutine["yield"]   = new Yield();
            return(coroutine);
        }
Ejemplo n.º 16
0
        public void UpdateYield(Yield yield)
        {
            _context.Attach(yield);
            _context.Entry(yield).Property("NamePlant").IsModified             = true;
            _context.Entry(yield).Property("PlantVariety").IsModified          = true;
            _context.Entry(yield).Property("Count").IsModified                 = true;
            _context.Entry(yield).Property("YieldUnit").IsModified             = true;
            _context.Entry(yield).Property("AdditionalInformation").IsModified = true;
            _context.Entry(yield).Property("WarehouseId").IsModified           = true;

            _context.SaveChanges();
        }
Ejemplo n.º 17
0
        private void cmbRecipeYields_SelectedIndexChanged(object sender, EventArgs e)
        {
            lstRecipeIngredients.Items.Clear();
            Yield selectedYield = cmbRecipeYields.SelectedItem as Yield;

            if (selectedYield != null)
            {
                foreach (Ingredient ingredient in recipe.Ingredients)
                {
                    lstRecipeIngredients.Items.Add(ingredient.ToString(cmbRecipeYields.SelectedIndex));
                }
            }
        }
Ejemplo n.º 18
0
 private void Dispose()
 {
     if (_iterator != null)
     {
         try {
             _iterator.Dispose();
         } catch (Exception e) {
             _log.WarnExceptionMethodCall(e, "Dispose");
         } finally {
             _iterator = null;
         }
     }
 }
Ejemplo n.º 19
0
        public async Task <IActionResult> Post([FromBody] Yield yield)
        {
            try
            {
                this.aIValuationsContext.Yield.Add(yield);
                await this.aIValuationsContext.SaveChangesAsync().ConfigureAwait(false);

                return(this.CreatedAtAction("GetMarkovState", new { id = yield.ID }, yield));
            }
            catch (Exception ex)
            {
                return(this.BadRequest(ex.Message));
            }
        }
Ejemplo n.º 20
0
        public override int GetHashCode()
        {
            var hashCode = -2052112293;

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(ExecId);

            hashCode = hashCode * -1521134295 + Commission.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Currency);

            hashCode = hashCode * -1521134295 + RealizedPnl.GetHashCode();
            hashCode = hashCode * -1521134295 + Yield.GetHashCode();
            hashCode = hashCode * -1521134295 + YieldRedemptionDate.GetHashCode();
            return(hashCode);
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            Func <double> inner = () => 0.3D;
            Func <double> outer = () => inner();

            var b1 = new Bond("bond1", face: 100, ytm: outer, T: 1, t0: 0);

            Console.WriteLine(b1.Ytm()); // 0.30

            inner = () => 0.2D;
            Console.WriteLine(b1.Ytm()); // 0.20


            var y = new Yield("yield2", ytm: 0.3D);

            var b2 = new Bond("bond2", face: 100, ytm: y.Ytm, T: 1, t0: 0);

            Console.WriteLine(b2.Ytm()); // 0.30

            y.Ytm = 0.2D.Wrap();
            Console.WriteLine(b2.Ytm()); // 0.20



            Console.WriteLine(b2.ToString());


            inner = 1.Wrap();

            Console.WriteLine(b2.ToString());


            var y1 = new Yield("yield1", 0.2D);     // valid
            var y2 = new Yield("yield2", 1);        // valid, int can implicitly cast to double
            var y3 = new Yield("yield3");           // valid, use default value
            var y4 = new Yield("yield4", y1.Ytm);   // valid, use a reference of another variable
            var y5 = new Yield("yield5", y1.Ytm()); // valid, use a static value of another variable, won't update with y1
            //var y6 = new Yield("yield6", y1); // invalid, y1 is neither a double or a Func<double> recommended supported


            var bond2 = new Bond("bond2", face: 100);

            bond2.P   = 90.Wrap();
            bond2.Dm  = 1.7.Wrap();
            bond2.Cov = 60.Wrap();


            Console.Read();
        }
Ejemplo n.º 22
0
        private int GetBarYieldIndex(Yield barYield)
        {
            switch (barYield)
            {
            case Yield.Random:      return(0);

            case Yield.Bar1:        return(1);

            case Yield.Bar2:        return(2);

            case Yield.Bar3:        return(3);
            }

            return(0);
        }
Ejemplo n.º 23
0
        private static int RunAndCopy(ref IList <Yield> target, ref IList <Yield> source)
        {
            int count = 0;

            target.Clear();
            foreach (Yield y in source)
            {
                Yield result = y.Invoke();
                if (null != result)
                {
                    target.Add(result);
                    count++;
                }
            }
            return(count);
        }
Ejemplo n.º 24
0
        private Task <CalcCropsViewModel> GetCropAsync(string fldName)
        {
            CalcCropsViewModel mvm = new CalcCropsViewModel();

            mvm.cropList = new List <DisplayCrop>();

            List <FieldCrop> fldCrops = _ud.GetFieldCrops(fldName);

            foreach (var m in fldCrops)
            {
                Crop  cp  = new Crop();
                Yield yld = new Yield();

                if (!string.IsNullOrEmpty(m.cropOther))
                {
                    cp.cropname = m.cropOther + "*";
                    yld         = _sd.GetYield(1);
                }
                else
                {
                    cp  = _sd.GetCrop(Convert.ToInt32(m.cropId));
                    yld = _sd.GetYield(cp.yieldcd);
                }

                if (m.coverCropHarvested.HasValue)
                {
                    cp.cropname = m.coverCropHarvested.Value ? cp.cropname + "(harvested)" : cp.cropname;
                }

                DisplayCrop dm = new DisplayCrop()
                {
                    fldNm    = fldName,
                    cropId   = Convert.ToInt32(m.id),
                    cropName = cp.cropname,
                    yield    = m.yield.ToString() + " tons/ac (" + yld.yielddesc + ")",
                    reqN     = (m.reqN * -1).ToString(),
                    reqP     = (m.reqP2o5 * -1).ToString(),
                    reqK     = (m.reqK2o * -1).ToString(),
                    remN     = (m.remN * -1).ToString(),
                    remP     = (m.remP2o5 * -1).ToString(),
                    remK     = (m.remK2o * -1).ToString()
                };
                mvm.cropList.Add(dm);
            }

            return(Task.FromResult(mvm));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Read mining beacon sheet.
        /// </summary>
        public static Dictionary <MineInfoKey, GlobalMineInfo> ReadMineSheet()
        {
            string[][] miningSheet = ReadSheet("mines.txt");
            if (miningSheet == null)
            {
                return(null);
            }

            Dictionary <MineInfoKey, GlobalMineInfo> infoRecords = new Dictionary <MineInfoKey, GlobalMineInfo>(miningSheet.GetLength(0));

            // Read rows
            for (int i = 0; i < miningSheet.GetLength(0); ++i)
            {
                string[] row = miningSheet[i];

                // Skip rows that don't contain enough data (probably empty line)
                if (row.Length < 7)
                {
                    continue;
                }

                string strYield     = row[0];                                           // Yield
                int    nVariant     = ReadInt(row[1]);                                  // Variant
                int    initialYield = ReadInt(row[2]);                                  // Initial_Yield_%
                int    peakTruck    = ReadInt(row[3]);                                  // Peak_Truck
                int    peakYield    = ReadInt(row[4]);                                  // Peak_Yield_%
                int    minTruck     = ReadInt(row[5]);                                  // Min_Truck
                int    minYield     = ReadInt(row[6]);                                  // Min_Yield_%

                Yield yield = Yield.Bar3;

                switch (strYield)
                {
                case "High":    yield = Yield.Bar3;             break;

                case "Med":             yield = Yield.Bar2;             break;

                case "Low":             yield = Yield.Bar1;             break;
                }

                Variant variant = (Variant)nVariant;

                infoRecords[new MineInfoKey(yield, variant)] = new GlobalMineInfo(yield, variant, initialYield, peakTruck, peakYield, minTruck, minYield);
            }

            return(infoRecords);
        }
Ejemplo n.º 26
0
        public List <Yield> GetYields()
        {
            JArray array  = (JArray)rss["agri"]["nmp"]["yields"]["yield"];
            var    yields = new List <Yield>();

            foreach (var r in array)
            {
                var yield = new Yield
                {
                    Id        = Convert.ToInt32(r["id"].ToString()),
                    YieldDesc = r["yielddesc"].ToString()
                };
                yields.Add(yield);
            }

            return(yields);
        }
Ejemplo n.º 27
0
        // POST api/<controller>
        public HttpResponseMessage Post([FromBody] Yield yield)
        {
            try
            {
                Context.Amounts.Add(new Yield()
                {
                    Name       = yield.Name,
                    Quantity   = yield.Quantity,
                    MetricUnit = yield.MetricUnit
                });
                Context.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.Created, true));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ExceptionMessageHelper.GetErrorMessage(ex)));
            }
        }
Ejemplo n.º 28
0
        public bool AddYield(int idCow, double yieldMilk, DateTime?date = null)
        {
            try
            {
                DateTime dateYield;
                dateYield = (date ?? DateTime.Now);
                dateYield = new DateTime(dateYield.Year, dateYield.Month, dateYield.Day);

                //Verifica se a vaca existe
                Cow cowValid = repoCow.GetCow(idCow);
                if (cowValid != null)
                {
                    Lactation currentLact = cowValid.lactations.FirstOrDefault(l => l.finished == false);
                    Yield     yieldDay    = currentLact.yields.FirstOrDefault(y => y.date.Year == dateYield.Year && y.date.Month == dateYield.Month && y.date.Day == dateYield.Day);
                    if (yieldDay == null)
                    {
                        //Insere os dados na lactação corrente
                        Yield yield = new Yield
                        {
                            idLactation  = currentLact.idLactation,
                            totalYield   = yieldMilk,
                            date         = dateYield,
                            dayLactation = (int)(dateYield - currentLact.dateBirth).TotalDays
                        };
                        repoCow.AddYield(yield);
                    }
                    else
                    {
                        //Altera a produção do dia atual somando a quantidade informada
                        yieldDay.totalYield += yieldMilk;
                        repoCow.UpdateYield(yieldDay);
                    }
                    return(true);
                }
            }
            catch (Exception e)
            {
                //throw;
            }

            return(false);
        }
Ejemplo n.º 29
0
        //функция для инициирования валидации
        private void validate()
        {
            int x1 = 0;

            flag = false;
            Initial_investment_amount += " ";
            flag = true;
            x1   = Initial_investment_amount.Length - 1;
            Initial_investment_amount = Initial_investment_amount.Substring(0, x1);

            flag   = false;
            Yield += " ";
            flag   = true;
            x1     = Yield.Length - 1;
            Yield  = Yield.Substring(0, x1);

            flag            = false;
            Capitalization += " ";
            flag            = true;
            x1              = Capitalization.Length - 1;
            Capitalization  = Capitalization.Substring(0, x1);

            flag          = false;
            Addon_amount += " ";
            flag          = true;
            x1            = Addon_amount.Length - 1;
            Addon_amount  = Addon_amount.Substring(0, x1);

            flag = false;
            Number_of_additions += " ";
            flag = true;
            x1   = Number_of_additions.Length - 1;
            Number_of_additions = Number_of_additions.Substring(0, x1);

            flag = false;
            Total_investment_term += " ";
            flag = true;
            x1   = Total_investment_term.Length - 1;
            Total_investment_term = Total_investment_term.Substring(0, x1);

            flag = false;
        }
Ejemplo n.º 30
0
        }                                                                                             // %


        public GlobalMineInfo(
            Yield yield,
            Variant variant,

            int initialYield,
            int peakTruck,
            int peakYield,
            int minTruck,
            int minYield
            )
        {
            MineYield   = yield;
            MineVariant = variant;

            InitialYield = initialYield;
            PeakTruck    = peakTruck;
            PeakYield    = peakYield;
            MinTruck     = minTruck;
            MinYield     = minYield;
        }
Ejemplo n.º 31
0
    public virtual Differences VisitYield(Yield yield1, Yield yield2){
      Differences differences = new Differences(yield1, yield2);
      if (yield1 == null || yield2 == null){
        if (yield1 != yield2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++;
        return differences;
      }
      Yield changes = (Yield)yield2.Clone();
      Yield deletions = (Yield)yield2.Clone();
      Yield insertions = (Yield)yield2.Clone();

      Differences diff = this.VisitExpression(yield1.Expression, yield2.Expression);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Expression = diff.Changes as Expression;
      deletions.Expression = diff.Deletions as Expression;
      insertions.Expression = diff.Insertions as Expression;
      Debug.Assert(diff.Changes == changes.Expression && diff.Deletions == deletions.Expression && diff.Insertions == insertions.Expression);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      if (differences.NumberOfDifferences == 0){
        differences.Changes = null;
        differences.Deletions = null;
        differences.Insertions = null;
      }else{
        differences.Changes = changes;
        differences.Deletions = deletions;
        differences.Insertions = insertions;
      }
      return differences;
    }
Ejemplo n.º 32
0
 public override Statement VisitYield(Yield Yield){
   if (Yield == null) return null;
   if (this.iteratorEntryPoints == null) return null;
   object[] trys = this.currentTryStatements.ToArray();
   StatementList statements = new StatementList();
   Block result = new Block(statements);
   if (Yield.Expression == null)
     statements.Add(this.VisitReturn(new Return(Literal.False, Yield.SourceContext)));
   else{
     Statement astat = new AssignmentStatement(new MemberBinding(this.currentThisParameter, this.currentIteratorValue), this.VisitExpression(Yield.Expression));
     astat.SourceContext = Yield.SourceContext;
     statements.Add(astat);
     Expression index = new Literal(this.iteratorEntryPoints.Count, SystemTypes.Int32);
     statements.Add(new AssignmentStatement(new MemberBinding(this.currentThisParameter, this.currentIteratorEntryPoint), index));
     statements.Add(this.VisitReturn(new Return(new Literal(true, SystemTypes.Boolean))));
   }
   Block blockAfterReturn = new Block();
   statements.Add(blockAfterReturn);
   Block blockAfterHandlers = new Block(new StatementList());
   for (int i = trys.Length; i-- > 0; ) {
     Try t = (Try)trys[i];
     //this.AddExceptionHandlers(t, this.currentExceptionBlock, blockAfterReturn, blockAfterHandlers);
   }
   statements.Add(blockAfterHandlers);
   this.iteratorEntryPoints.Add(blockAfterHandlers);
   for (int i = trys.Length; i-- > 0; ){
     //TODO: all but the outermost finally block should itself be a try-finally
     Try t = (Try)trys[i];
     blockAfterHandlers.Statements.Add(this.VisitBlock(t.Finally.Block));
   }
   this.currentExceptionBlock = new Block();
   return result;
 }
Ejemplo n.º 33
0
 public virtual Statement VisitYield(Yield Yield1, Yield Yield2)
 {
     if (Yield1 == null) return null;
     if (Yield2 == null)
         Yield1.Expression = this.VisitExpression(Yield1.Expression, null);
     else
         Yield1.Expression = this.VisitExpression(Yield1.Expression, Yield2.Expression);
     return Yield1;
 }
Ejemplo n.º 34
0
 public override Statement VisitYield(Yield Yield)
 {
     if (Yield == null) return null;
     return base.VisitYield((Yield)Yield.Clone());
 }
Ejemplo n.º 35
0
 public override Statement VisitYield(Yield Yield){
   if (Yield == null) return null;
   Expression e = Yield.Expression = this.VisitExpression(Yield.Expression);
   if (e == null) return Yield;
   TypeNode eType = e.Type;
   if (eType == null) return Yield;
   TypeNode elemType = this.typeSystem.GetStreamElementType(eType, this.TypeViewer);
   if (eType is TupleType) elemType = eType;
   TypeNode rType = this.currentMethod.ReturnType;
   if (rType == null){ //REVIEW: what happens when rType is null because of an earlier error?
     this.currentMethod.ReturnType = 
       new StreamTypeExpression(new TypeUnionExpression(new TypeNodeList(elemType)));
   }else if (rType is StreamTypeExpression)
     ((TypeUnionExpression)((StreamTypeExpression)rType).ElementType).Types.Add(elemType);
   return Yield;
 }
Ejemplo n.º 36
0
		public virtual object Visit (Yield yieldStatement)
		{
			return null;
		}
Ejemplo n.º 37
0
void case_983()
#line 6552 "cs-parser.jay"
{
		Error_SyntaxError (yyToken);

		var lt = (LocatedToken) yyVals[-3+yyTop];
		string s = lt.Value;
		if (s != "yield"){
			report.Error (1003, lt.Location, "; expected");
		} else if (yyVals[-1+yyTop] == null) {
			report.Error (1627, GetLocation (yyVals[0+yyTop]), "Expression expected after yield return");
		} else if (lang_version == LanguageVersion.ISO_1){
			FeatureIsNotAvailable (lt.Location, "iterators");
		}
		
		current_block.Explicit.RegisterIteratorYield ();
		yyVal = new Yield ((Expression) yyVals[-1+yyTop], lt.Location);
		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]));
	  }
Ejemplo n.º 38
0
 public override Statement VisitYield(Yield Yield) {
   if (Yield == null) return null;
   if (this.currentFinallyClause != null) {
     this.HandleError(Yield, Error.BadFinallyLeave);
     return null;
   }
   if (this.insideCatchClause) {
     this.HandleError(Yield, Error.CannotYieldFromCatchClause);
     return null;
   }
   if (this.returnNode != null) {
     this.HandleError(this.returnNode, Error.ReturnNotAllowed);
     this.returnNode = null;
   }
   if (this.currentMethod == null) {
     Debug.Assert(false);
     return null;
   }
   if (Yield.Expression == null) {
     this.yieldNode = Yield;
     return Yield;
   }
   Expression e = Yield.Expression = this.VisitExpression(Yield.Expression);
   if (e == null) return null;
   TypeNode returnType = TypeNode.StripModifiers(this.currentMethod.ReturnType);
   if (returnType == null) return null;
   if (returnType.Template != SystemTypes.GenericIEnumerable && returnType.Template != SystemTypes.GenericIEnumerator &&
     returnType != SystemTypes.IEnumerable && returnType != SystemTypes.IEnumerator) {
     this.HandleError(Yield, Error.WrongReturnTypeForIterator, this.GetMethodSignature(this.currentMethod), this.GetTypeName(returnType));
     return null;
   }
   this.yieldNode = Yield;
   TypeNode eType = e.Type;
   TypeNode elemType;
   if (returnType == SystemTypes.IEnumerable || returnType == SystemTypes.IEnumerator)
     elemType = SystemTypes.Object;
   else
     elemType = this.typeSystem.GetStreamElementType(returnType, this.TypeViewer);
   Expression testCoercion = this.typeSystem.TryImplicitCoercion(e, elemType, this.TypeViewer);
   if (testCoercion != null || eType is TupleType || elemType == SystemTypes.Object)
     Yield.Expression = this.typeSystem.ImplicitCoercion(e, elemType, this.TypeViewer);
   else {
     e = this.typeSystem.ImplicitCoercion(e, returnType, this.TypeViewer);
     Local loc = new Local(elemType);
     ForEach forEach = new ForEach();
     forEach.TargetVariable = loc;
     forEach.TargetVariableType = loc.Type;
     forEach.SourceEnumerable = this.VisitEnumerableCollection(new Local(returnType), loc.Type);
     ((CollectionEnumerator)forEach.SourceEnumerable).Collection = e;
     forEach.Body = new Block(new StatementList(new Yield(loc)));
     forEach.ScopeForTemporaryVariables = new BlockScope(this.currentMethod.Scope, forEach.Body);
     return forEach;
   }
   return Yield;
 }
Ejemplo n.º 39
0
    public override Expression VisitComprehension(Comprehension comprehension) {
      if (comprehension == null) return null;
      if ((this.insideMethodContract || this.insideInvariant) &&
        this.currentMethod != null && this.currentMethod.DeclaringType != null && this.currentMethod.DeclaringType is ClosureClass) {
        // for now we don't allow comprehensions that end up creating closures in contracts because we aren't
        // able to deserialize them for cross-assembly inheritance and for static verification
        this.HandleError(comprehension, Error.GeneralComprehensionsNotAllowedInMethodContracts);
        return null;
      }
      if (comprehension.BindingsAndFilters != null) {
        for (int i = 0; i < comprehension.BindingsAndFilters.Count; i++) {
          Expression bindingOrFilter = comprehension.BindingsAndFilters[i];
          ComprehensionBinding comprehensionBinding = bindingOrFilter as ComprehensionBinding;
          if (comprehensionBinding != null) {
            comprehensionBinding.TargetVariableType = this.VisitTypeReference(comprehensionBinding.TargetVariableType);
            comprehensionBinding.TargetVariable = this.VisitTargetExpression(comprehensionBinding.TargetVariable);
            comprehensionBinding.AsTargetVariableType = this.VisitTypeReference(comprehensionBinding.AsTargetVariableType);
            comprehensionBinding.SourceEnumerable = this.VisitEnumerableCollection(comprehensionBinding.SourceEnumerable, comprehensionBinding.TargetVariableType);
            if (comprehensionBinding.AsTargetVariableType != null) {
              if (comprehensionBinding.AsTargetVariableType.IsValueType) {
                this.HandleError(comprehensionBinding, Error.AsMustHaveReferenceType, this.GetTypeName(comprehensionBinding.AsTargetVariableType));
                return null;
              } else if (!this.GetTypeView(comprehensionBinding.AsTargetVariableType).IsAssignableTo(comprehensionBinding.TargetVariableType)) {
                this.HandleError(comprehensionBinding, Error.ImpossibleCast, this.GetTypeName(comprehensionBinding.TargetVariableType), this.GetTypeName(comprehensionBinding.AsTargetVariableType));
                return null;
              }
            }
            if (comprehensionBinding.TargetVariableType == null) {
              return null; //REVIEW: does Normalizer care about this being non null. Perhaps it should check for it and fail gracefully.
              //If so, there is no neeed to stop the error checking this abruptly
            }
          } else { // it should be a filter
            comprehension.BindingsAndFilters[i] = this.VisitBooleanExpression(bindingOrFilter);
            if (comprehension.BindingsAndFilters[i] == null) {
              // then something went wrong, bail out and null out this entire comprehension
              return null;
            }
          }
        }
      }
      comprehension.Elements = this.VisitExpressionList(comprehension.Elements);
      if (comprehension.Elements == null) return null;
      TypeNode comprehensionType = TypeNode.StripModifiers(comprehension.Type);
      if (comprehensionType == null) return null;
      TypeNode eltType = null;
      if (comprehension.nonEnumerableTypeCtor == null) {
        // then this comprehension is within a quantifier
        // the elements need to be of the type the quantifier consumes
        if (comprehensionType.TemplateArguments ==null || comprehensionType.TemplateArguments.Count ==0) {
          this.HandleError(comprehension, Error.NoSuchType, this.GetTypeName(comprehensionType));
          return null;
        }
        if (comprehensionType.Template != SystemTypes.GenericIEnumerable ||
          comprehensionType.TemplateArguments == null || comprehensionType.TemplateArguments.Count != 1) {
          return null; //Resolver failed, bail out
        }
        eltType = comprehensionType.TemplateArguments[0];
      } else {
        // this comprehension is within a "new T{...}" expression.
        // the resolver put the unified type that was computed for the elements into a temporary place
        // so that the type of the comprehension could be modified to be T since it took the place of
        // the construct node that had been representing the "new T{...}" expression.
        //        if (comprehension.Type.Template != SystemTypes.GenericIEnumerable ||
        //          comprehension.Type.TemplateArguments == null || comprehension.Type.TemplateArguments.Length != 1){
        //          return null; //Resolver failed, bail out
        //        }
        if (comprehension.TemporaryHackToHoldType == null) {
          return null;
        }
        TypeNode temp = TypeNode.StripModifiers(comprehension.TemporaryHackToHoldType);
        if (temp.Template != SystemTypes.GenericIEnumerable ||
          temp.TemplateArguments == null || temp.TemplateArguments.Count != 1) {
          return null; //Resolver failed, bail out
        }
        eltType = temp.TemplateArguments[0];
      }
      if (eltType == null) { Debug.Assert(false); return null; }
      for (int i = 0, n = comprehension.Elements.Count; i < n; i++) {
        Expression e = comprehension.Elements[i];
        if (e == null) continue;
        comprehension.Elements[i] = e = this.typeSystem.ImplicitCoercion(e, eltType, this.TypeViewer);
        if (e == null) return null; //REVIEW: Normalizer should not rely on these elements not being null, so why not just continue?
      }
      if (comprehension.nonEnumerableTypeCtor == null) {
        if (!this.insideMethodContract && !this.insideAssertOrAssume && !this.insideQuantifier) {
          this.yieldNode = new Yield(); //
        }
      } else {
        InstanceInitializer c = comprehension.nonEnumerableTypeCtor as InstanceInitializer;
        if (c != null) {
          if (c.DeclaringType != null && c.DeclaringType.IsAbstract) {
            if (c.DeclaringType.IsSealed)
              this.HandleError(comprehension, Error.ConstructsAbstractSealedClass, this.GetTypeName(c.DeclaringType));
            else
              this.HandleError(comprehension, Error.ConstructsAbstractClass, this.GetTypeName(c.DeclaringType));
          } else if (this.NotAccessible(c)) {
            this.HandleError(comprehension, Error.MemberNotVisible, this.GetMemberSignature(c));
            return null;
          }
          this.CheckForObsolesence(comprehension, c);
          if (this.NotAccessible(comprehension.AddMethod)) {
            this.HandleError(comprehension, Error.MemberNotVisible, this.GetMethodSignature(comprehension.AddMethod));
            return null;
          }
          this.CheckForObsolesence(comprehension, comprehension.AddMethod);
        }

      }
      return comprehension;
    }
Ejemplo n.º 40
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;
    }    
Ejemplo n.º 41
0
    public override Method VisitMethod(Method method) {
      if (method == null) return null;
      if (method.IsNormalized) return method;
      this.MayReferenceThisAndBase = !(method is InstanceInitializer) || method.DeclaringType == null || method.DeclaringType.IsValueType;
      if (method.Name != null && method.Name.UniqueIdKey == StandardIds.Finalize.UniqueIdKey && method.HasCompilerGeneratedSignature &&
        method.DeclaringType is Class && ((Class)method.DeclaringType).IsAbstractSealedContainerForStatics)
        this.HandleError(method.Name, Error.DestructorInAbstractSealedClass);
      method.Attributes = this.VisitAttributeList(method.Attributes, method);
      method.ReturnAttributes = this.VisitAttributeList(method.ReturnAttributes);
      method.SecurityAttributes = this.VisitSecurityAttributeList(method.SecurityAttributes);
      if ((method.ReturnType == SystemTypes.DynamicallyTypedReference || method.ReturnType == SystemTypes.ArgIterator) && 
      (this.currentOptions == null || !this.currentOptions.NoStandardLibrary) ) {
        this.HandleError(method.Name, Error.CannotReturnTypedReference, this.GetTypeName(method.ReturnType));
        method.ReturnType = SystemTypes.Object;
      }
      if (method.Body != null) {
        if (method.DeclaringType is Interface && !method.IsStatic) {
          this.HandleError(method.Name, Error.InterfaceMemberHasBody, this.GetMethodSignature(method));
          method.Body = null;
        } else if (method.IsAbstract) {
          this.HandleError(method.Name, Error.AbstractHasBody, this.GetMethodSignature(method));
          method.Body = null;
        }
      } else if (!method.IsAbstract && !method.IsExtern && !this.isCompilingAContractAssembly) {
        this.HandleError(method.Name, Error.ConcreteMissingBody, this.GetMethodSignature(method));
        return null;
      } else if (method.TemplateParameters != null && method.TemplateParameters.Count > 0 && !this.useGenerics) {
        SourceContext ctx = method.TemplateParameters[0].SourceContext;
        ctx.EndPos = method.TemplateParameters[method.TemplateParameters.Count-1].SourceContext.EndPos;
        Debug.Assert(ctx.EndPos >= ctx.StartPos);
        Node n = new UnaryExpression();
        n.SourceContext = ctx;
        if (method.DeclaringType is Interface)
          this.HandleError(n, Error.AbstractInterfaceMethod);
        else
          this.HandleError(n, Error.AbstractMethodTemplate);
        return null;
      }
      BlockScope savedCurrentFinallyClause = this.currentFinallyClause;
      Method savedCurrentMethod = this.currentMethod;
      Return savedReturnNode = this.returnNode;
      Yield savedYieldNode = this.yieldNode;
      this.currentFinallyClause = null;
      this.currentMethod = method;
      this.returnNode = null;
      this.yieldNode = null;
      MethodScope scope = method.Scope;
      this.CheckForDuplicateDeclarations(scope);

      if ((this.currentPreprocessorDefinedSymbols != null && this.currentPreprocessorDefinedSymbols.ContainsKey("DefaultExposeBlocks")) &&
        !method.IsStatic && !(method is InstanceInitializer) && method.DeclaringType is Class && 
        !method.IsAbstract && method.CciKind == CciMemberKind.Regular && method.ApplyDefaultContract) {
        This thisOb = method.ThisParameter;
        MethodCall thisIsExposable = new MethodCall(
          new MemberBinding(null, SystemTypes.Guard.GetMethod(Identifier.For("FrameIsExposable"),
            SystemTypes.Object, SystemTypes.Type)),
            new ExpressionList(thisOb, new UnaryExpression(new Literal(method.DeclaringType, SystemTypes.Type),
            NodeType.Typeof, OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type))), NodeType.Call,
            SystemTypes.Boolean, method.Body.SourceContext);
        Assumption assumption = new Assumption(thisIsExposable);
        Expose expose = new Expose(NodeType.Write);
        expose.SourceContext = method.Body.SourceContext;
        expose.Instance = thisOb;
        expose.Body = method.Body;
        if (this.currentOptions != null && this.currentOptions.DisableGuardedClassesChecks)
          method.Body = new Block(new StatementList(assumption, expose));
        else
          method.Body = new Block(new StatementList(expose));
      }


      #region Check contract rules for all interface methods and base methods this method implements/overrides
      bool ok = true;
      if (method.IsVirtual && !method.IsCompilerControlled) {
        // 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) {
          ok &= this.CheckContractRules(overridden, method, method.DeclaringType);
        }
        for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplementedInterfaceMethods[i];
          ok &= this.CheckContractRules(ifaceMethod, method, method.DeclaringType);
        }
        for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i];
          ok &= this.CheckContractRules(ifaceMethod, method, method.DeclaringType);
        }
      }
      #endregion

      #region Contract Inheritance for method overrides and interface implementations (do this somewhere else?)
      // This needs to be done here (and not in VisitMethodContract) because method might not even have a contract
      if (method.IsVirtual && ok && !method.IsCompilerControlled) {
        // use FindNearest..., can't rely on method.OverriddenMethod since it might not be set further up the chain
        Method overridden = method.DeclaringType.FindNearestOverriddenMethod(method);
        // FindNearestOverriddenMethod doesn't care if method is "new" or an "override", so explicity test IsVirtual property
        MethodContract cumulativeContract = method.Contract == null ? new MethodContract(method) : method.Contract;
        bool somethingWasCopied = false;
        while (overridden != null && overridden.IsVirtual) {
          if (overridden.Contract != null) {
            cumulativeContract.CopyFrom(overridden.Contract);
            somethingWasCopied = true;
            break;
          }
          overridden = overridden.DeclaringType.FindNearestOverriddenMethod(overridden);
        }
        // Can inherit from at most one interface method
        bool ifaceContractWasCopied = false;
        for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplementedInterfaceMethods[i];
          if (ifaceMethod == null) continue;
          if (ifaceMethod.Contract != null) {
            if (ifaceContractWasCopied) {
              this.HandleError(method, Error.RequiresNotAllowedInInterfaceImplementation, this.GetMethodSignature(ifaceMethod));
              break;
            }
            cumulativeContract.CopyFrom(ifaceMethod.Contract);
            somethingWasCopied = true;
            ifaceContractWasCopied = true;
          }
        }
        for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i];
          if (ifaceMethod == null) continue;
          if (ifaceMethod.Contract != null) {
            if (ifaceContractWasCopied) {
              this.HandleError(method, Error.RequiresNotAllowedInInterfaceImplementation, this.GetMethodSignature(ifaceMethod));
              break;
            }
            cumulativeContract.CopyFrom(ifaceMethod.Contract);
            somethingWasCopied = true;
            ifaceContractWasCopied = true;
          }
        }
        if (method.Contract == null && somethingWasCopied) { // otherwise it was already copied into the method's contract 
          method.Contract = cumulativeContract;
        }
      }
      #endregion
      
      // For checked exceptions, the actual exceptions thrown must be a subset of the allowed exceptions
      TypeNodeList aes = new TypeNodeList();
      if (method.Contract != null && method.Contract.Ensures != null) {
        for (int i = 0, n = method.Contract.Ensures.Count; i < n; i++) {
          EnsuresExceptional ee = method.Contract.Ensures[i] as EnsuresExceptional;
          if (ee == null || ee.Inherited) continue;
          aes.Add(ee.Type);
        }
      }
      TypeNodeList saveAllowedExceptions = this.allowedExceptions;
      this.allowedExceptions = aes;
      // don't check method body of proxy methods.
      Method result = (method is ProxyMethod) ? method : base.VisitMethod(method);
      this.allowedExceptions = saveAllowedExceptions;


      if (this.yieldNode != null && TypeNode.StripModifiers(method.ReturnType) is Interface) {
        StatementList statements = new StatementList(1);
        TypeNode elementType = SystemTypes.Object;
        Interface stype = (Interface)TypeNode.StripModifiers(method.ReturnType);
        if (stype.TemplateArguments != null && stype.TemplateArguments.Count == 1) elementType = stype.TemplateArguments[0];
        Class state = scope.ClosureClass;
        elementType = scope.FixTypeReference(elementType);
        state.Flags |= TypeFlags.Abstract; //So that no complaints are given about missing methods added by Normalizer
        state.Interfaces = new InterfaceList(5);
        state.Interfaces.Add(SystemTypes.IEnumerable);
        state.Interfaces.Add((Interface)SystemTypes.GenericIEnumerator.GetTemplateInstance(this.currentType, elementType));
        state.Interfaces.Add(SystemTypes.IEnumerator);
        state.Interfaces.Add(SystemTypes.IDisposable);
        state.Interfaces.Add((Interface)SystemTypes.GenericIEnumerable.GetTemplateInstance(this.currentType, elementType));
        //Add these methods so that Normalizer can find them even when reference to iterator is forward
        Method moveNext = new Method(state, null, StandardIds.MoveNext, null, SystemTypes.Boolean, null);
        moveNext.CallingConvention = CallingConventionFlags.HasThis;
        moveNext.Flags = MethodFlags.Public|MethodFlags.Virtual;
        moveNext.Body = new Block(new StatementList());
        state.Members.Add(moveNext);
        Method getCurrent = new Method(state, null, StandardIds.getCurrent, null, elementType, null);
        getCurrent.CallingConvention = CallingConventionFlags.HasThis;
        getCurrent.Flags = MethodFlags.Public|MethodFlags.Virtual|MethodFlags.SpecialName;
        getCurrent.Body = new Block(new StatementList());
        state.Members.Add(getCurrent);
        Return ret = new Return(new ConstructIterator(state, method.Body, elementType, state));
        if (method.Name.SourceContext.Document != null) {
          ret.SourceContext = method.SourceContext;
          ret.SourceContext.EndPos = method.Name.SourceContext.EndPos;
          Debug.Assert(ret.SourceContext.EndPos >= ret.SourceContext.StartPos);
        }
        statements.Add(ret);
        method.Body = new Block(statements);
        method.Body.Scope = new BlockScope(scope, method.Body);
      }
      if (method.IsStatic && method.IsVirtual && !method.IsSpecialName) {
        method.Flags &= ~MethodFlags.Static;
        this.HandleError(method.Name, Error.StaticNotVirtual, this.GetMethodSignature(method));
      }
      if (!method.OverridesBaseClassMember) {
        if (method.NodeType == NodeType.InstanceInitializer || !method.IsSpecialName) {
          if (!(method.DeclaringType is Interface) && !(method.DeclaringType is DelegateNode)) {
            if (this.IsLessAccessible(method.ReturnType, method)) {
              this.HandleError(method.Name, Error.ReturnTypeLessAccessibleThanMethod, this.GetTypeName(method.ReturnType), this.GetMethodSignature(method));
              this.HandleRelatedError(method.ReturnType);
            }
            this.CheckParameterTypeAccessibility(method.Parameters, method);
          }
        } else {
          if (method.Name != null && Checker.OperatorName[method.Name.UniqueIdKey] != null) {
            if (this.IsLessAccessible(method.ReturnType, method)) {
              this.HandleError(method.Name, Error.ReturnTypeLessAccessibleThanOperator, this.GetTypeName(method.ReturnType), this.GetMethodSignature(method));
              this.HandleRelatedError(method.ReturnType);
            }
            this.CheckParameterTypeAccessibility(method.Parameters, method);
          }
        }
      }

      if (!method.IsSpecialName) {
        TypeNodeList implementedTypes = method.ImplementedTypes;
        if (implementedTypes != null) {
          InterfaceList declaringTypeInterfaces = this.GetTypeView(method.DeclaringType).Interfaces;
          for (int i = 0, n = implementedTypes.Count; i < n; i++) {
            Interface iface = implementedTypes[i] as Interface;
            if (iface == null) continue;
            if (!this.IsAllowedAsImplementedType(declaringTypeInterfaces, iface)) {
              Node offendingNode = method.ImplementedTypeExpressions[i];
              this.HandleError(offendingNode, Error.ContainingTypeDoesNotImplement, this.GetMethodSignature(method), this.GetTypeName(iface));
              this.HandleRelatedError(iface);
              implementedTypes = null;
              break;
            }
          }
        }
        MethodList implementedMethods = method.ImplementedInterfaceMethods;
        for (int i = 0, n = implementedTypes == null ? 0 : implementedTypes.Count; i < n; i++) {
          Interface iface = implementedTypes[i] as Interface;
          if (iface == null) continue;
          Method m = implementedMethods == null ? null : implementedMethods[i];
          if (m == null) {
            this.HandleError(method.Name, Error.InterfaceMemberNotFound, this.GetMemberSignature(method), this.GetTypeName(iface));
            this.HandleRelatedError(iface);
          } else if (m.IsSpecialName)
            this.HandleError(method.Name, Error.CannotExplicitlyImplementAccessor, this.GetMethodSignature(method), this.GetMethodSignature(m));
        }
      }
      if ((method.Flags & MethodFlags.PInvokeImpl) != 0) {
        Error e = Error.None;
        if (this.shadowedAssembly != null) {
          // Make sure this method has a counterpart in the shadowed method
          TypeNode type = this.GetCorrespondingShadowedTypeNode(method.DeclaringType);
          if (type == null) {
            this.HandleError(method.DeclaringType, Error.TypeMissingInShadowedAssembly, this.GetTypeName(method.DeclaringType));
          } else {
            int numParams = method.Parameters == null ? 0 : method.Parameters.Count;
            TypeNode[] types = new TypeNode[numParams];
            for (int i = 0; i < numParams; i++) { types[i] = this.GetCorrespondingShadowedTypeNode(TypeNode.StripModifiers(method.Parameters[i].Type)); }
            if (this.GetTypeView(type).GetMethod(method.Name, types) == null) {
              this.HandleError(method, Error.MethodMissingInShadowedAssembly, this.GetMethodSignature(method));
            }
          }
        } else if (this.isCompilingAContractAssembly)
          e = Error.None;
        else if (method.Body != null)
          e = Error.PInvokeHasBody;
        else if (method.IsAbstract)
          e = Error.AbstractAndExtern;
        else if (method.PInvokeImportName == null || method.PInvokeModule == null) {
          if (method.Attributes == null || method.Attributes.Count == 0)
            e = Error.PInvokeWithoutModuleOrImportName;
          else
            method.Flags &= ~MethodFlags.PInvokeImpl;
        }
        if (e != Error.None)
          this.HandleError(method.Name, e, this.GetMethodSignature(method));
      }
      if (method.IsPropertySetter && (method.IsPure || method.IsConfined || method.IsStateIndependent)) {
        this.HandleError(method, Error.MemberCannotBeAnnotatedAsPure, this.GetMethodSignature(method));
      }
      this.currentFinallyClause = savedCurrentFinallyClause;
      this.currentMethod = savedCurrentMethod;
      this.returnNode = savedReturnNode;
      this.yieldNode = savedYieldNode;
      return result;
    }
Ejemplo n.º 42
0
            internal static expr Convert(Compiler.Ast.Expression expr, expr_context ctx) {
                expr ast;

                if (expr is ConstantExpression)
                    ast = Convert((ConstantExpression)expr);
                else if (expr is NameExpression)
                    ast = new Name((NameExpression)expr, ctx);
                else if (expr is UnaryExpression)
                    ast = new UnaryOp((UnaryExpression)expr);
                else if (expr is BinaryExpression)
                    ast = Convert((BinaryExpression)expr);
                else if (expr is AndExpression)
                    ast = new BoolOp((AndExpression)expr);
                else if (expr is OrExpression)
                    ast = new BoolOp((OrExpression)expr);
                else if (expr is CallExpression)
                    ast = new Call((CallExpression)expr);
                else if (expr is ParenthesisExpression)
                    return Convert(((ParenthesisExpression)expr).Expression);
                else if (expr is LambdaExpression)
                    ast = new Lambda((LambdaExpression)expr);
                else if (expr is ListExpression)
                    ast = new List((ListExpression)expr, ctx);
                else if (expr is TupleExpression)
                    ast = new Tuple((TupleExpression)expr, ctx);
                else if (expr is DictionaryExpression)
                    ast = new Dict((DictionaryExpression)expr);
                else if (expr is ListComprehension)
                    ast = new ListComp((ListComprehension)expr);
                else if (expr is GeneratorExpression)
                    ast = new GeneratorExp((GeneratorExpression)expr);
                else if (expr is MemberExpression)
                    ast = new Attribute((MemberExpression)expr, ctx);
                else if (expr is YieldExpression)
                    ast = new Yield((YieldExpression)expr);
                else if (expr is ConditionalExpression)
                    ast = new IfExp((ConditionalExpression)expr);
                else if (expr is IndexExpression)
                    ast = new Subscript((IndexExpression)expr, ctx);
                else if (expr is SliceExpression)
                    ast = new Slice((SliceExpression)expr);
                else if (expr is BackQuoteExpression)
                    ast = new Repr((BackQuoteExpression)expr);
                else
                    throw new ArgumentTypeException("Unexpected expression type: " + expr.GetType());

                ast.GetSourceLocation(expr);
                return ast;
            }
Ejemplo n.º 43
0
 public virtual Statement VisitYield(Yield Yield){
   if (Yield == null) return null;
   Yield.Expression = this.VisitExpression(Yield.Expression);
   return Yield;
 }
			public override object Visit (Yield yieldStatement)
			{
				var result = new YieldReturnStatement ();
				var location = LocationsBag.GetLocations (yieldStatement);
				
				result.AddChild (new CSharpTokenNode (Convert (yieldStatement.loc), YieldReturnStatement.YieldKeywordRole), YieldReturnStatement.YieldKeywordRole);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location [0]), YieldReturnStatement.ReturnKeywordRole), YieldReturnStatement.ReturnKeywordRole);
				if (yieldStatement.Expr != null)
					result.AddChild ((Expression)yieldStatement.Expr.Accept (this), Roles.Expression);
				if (location != null && location.Count > 1)
					result.AddChild (new CSharpTokenNode (Convert (location [1]), Roles.Semicolon), Roles.Semicolon);
				
				return result;
			}
Ejemplo n.º 45
0
 public virtual void VisitYield(Yield Yield)
 {
   if (Yield == null) return;
   this.VisitExpression(Yield.Expression);
 }
Ejemplo n.º 46
0
 public virtual Statement VisitYield(Yield Yield, Yield changes, Yield deletions, Yield insertions){
   this.UpdateSourceContext(Yield, changes);
   if (Yield == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
     }
   }else if (deletions != null)
     return null;
   return Yield;
 }
Ejemplo n.º 47
0
 public override Statement VisitYield(Yield Yield)
 {
   throw new ApplicationException("unimplemented");
 }