Пример #1
0
		public CaseClause(DList<Statement, CaseClause> Children, TextSpan Location, TextSpan HeaderLocation, TextPoint Colon)
		{
			this.colon = Colon;
			this.location = Location;
			this.Children = Children;
			this.HeaderLocation = HeaderLocation;
		}
Пример #2
0
		public SLE.LambdaExpression BindAndTransform (DList<MJCP.Statement, MJCP.BlockStatement> statements, MJCP.BindingInfo bindingInfo, bool Print)
		{
			Init ();
			//TODO test to know the internal of this and know the use of bindinginfo
			builder.Body = SLE.Expression.Block (Generate (statements, bindingInfo, Print));
			return builder.MakeLambda ();
		}
Пример #3
0
		public void BlockTest ()
		{
			parser = new Parser ("{}".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.IsInstanceOfType (typeof (BlockStatement), it.Element, "#3.1");
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #4
0
		public void VarTest ()
		{
			parser = new Parser ("var a = 10;".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement > list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement,BlockStatement>.Iterator(list);
			Assert.IsInstanceOfType (typeof(VariableDeclarationStatement), it.Element, "#1.1");
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #5
0
 static bool AddIfFarEnough(DList <DragPoint> points, DragPoint dp)
 {
     if (points.Count == 0 || points.Last.Point.Sub(dp.Point).Quadrance() >= MathEx.Square(MinDistBetweenDragPoints))
     {
         points.Add(dp);
         return(true);
     }
     return(false);
 }
Пример #6
0
 private void DealListShow()
 {
     DList.Items.Clear();
     foreach (DealListEntity DLE in DLEL)
     {
         ItemData data = new ItemData(DLE.deal, DLE.name, DLE.id, DLE.date.ToString("yyyy/MM/dd"), DLE.type, DLE.money.ToString(), DLE.number.ToString(), DLE.taxrate.ToString(), DLE.commission.ToString(), DLE.explain, DLE.remark);
         DList.Items.Add(data);
     }
     DList.UpdateLayout();
 }
Пример #7
0
    private void bandlist()
    {
        DataTable dt = ptbll.GetList();

        DList.Items.Clear();
        DList.DataSource     = dt.DefaultView;
        DList.DataTextField  = "TypeName";
        DList.DataValueField = "ID";
        DList.DataBind();
    }
Пример #8
0
 public bool DropRemainingNodesRequested;             // Any macro can set this flag
 public bool DropRemainingNodesIfRequested()
 {
     if (DropRemainingNodesRequested && !IsTarget)
     {
         NodeQueue            = new DList <Pair <LNode, int> >();       // informs
         OldAndRemainingNodes = LNode.List();
         _remainingNodes      = null;
     }
     return(DropRemainingNodesRequested);
 }
Пример #9
0
 public SwitchStatement(Expression Value, DList <CaseClause, SwitchStatement> Cases, TextSpan Location, TextSpan HeaderLocation, TextPoint LeftParen, TextPoint RightParen, TextPoint LeftBrace)
     : base(Operation.Switch, Location)
 {
     this.Value          = Value;
     this.Cases          = Cases;
     this.HeaderLocation = HeaderLocation;
     this.LeftParen      = LeftParen;
     this.RightParen     = RightParen;
     this.LeftBrace      = LeftBrace;
 }
Пример #10
0
		public SwitchStatement(Expression Value, DList<CaseClause, SwitchStatement> Cases, TextSpan Location, TextSpan HeaderLocation, TextPoint LeftParen, TextPoint RightParen, TextPoint LeftBrace)
			:base(Operation.Switch,Location)
		{
			this.Value = Value;
			this.Cases = Cases;
			this.HeaderLocation = HeaderLocation;
			this.LeftParen = LeftParen;
			this.RightParen = RightParen;
			this.LeftBrace = LeftBrace;
		}
Пример #11
0
 public void Accept(DList type, StringBuilder line)
 {
     line.Append('{');
     foreach (var d in type.Datas)
     {
         d.Apply(this, line);
         line.Append(',');
     }
     line.Append('}');
 }
Пример #12
0
        public void DListItemTest_Set()
        {
            int[]       arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DList <int> list = new DList <int>(arr);

            list[0] = 100;
            Assert.AreEqual(list[0], 100);
            list[9] = 100;
            Assert.AreEqual(list[9], 100);
        }
Пример #13
0
        public void Clear()
        {
            var list = new DList <int> {
                1
            };

            list.Clear();

            list.Any().ShouldBeFalse();
        }
Пример #14
0
        public void DListItemTest_Get()
        {
            int[]       arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DList <int> list = new DList <int>(arr);

            for (int i = 0; i < arr.Length; ++i)
            {
                Assert.AreEqual(arr[i], list[i]);
            }
        }
Пример #15
0
        public void Insert()
        {
            var list = new DList <int> {
                1, 3
            };

            list.Insert(1, 2);

            list.ShouldBe(new[] { 1, 2, 3 });
        }
Пример #16
0
 internal Enumerator(InternalDList <T> list, DList <T> wrapper)
 {
     size1        = list.FirstHalfSize;
     i            = list._start;
     stop         = i + size1;
     stop2        = list._count - size1;
     array        = list._array;
     wrapper      = wrapper ?? NoWrapper;
     this.wrapper = wrapper;
     oldCount     = wrapper.Count;
 }
Пример #17
0
		public void FunctionTest ()
		{
			parser = new Parser ("function foo() {}".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.IsInstanceOfType (typeof (FunctionStatement), it.Element, "#2.1");
			FunctionStatement foo = ((FunctionStatement)it.Element);
			Assert.AreEqual ("foo", foo.Function.Name.Spelling, "#2.2");
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #18
0
        public void DListCopyToTest()
        {
            int[]       arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DList <int> list = new DList <int>(arr);;

            int[] mas = new int[list.Count];
            list.CopyTo(mas, 0);
            for (int i = 0; i < arr.Length; ++i)
            {
                Assert.AreEqual(arr[i], mas[i]);
            }
        }
 public string this[string columnName]
 {
     get
     {
         if (columnName.Equals( "Selected"))
         {
             if (!DList.Select(m => m.Number).Contains(Selected))
                 return "Selected number must be in the combo list";
         }
         return null;
     }
 }
Пример #20
0
        public override IListSource <ITagSpan <ITag> > RunAnalysis(ITextSnapshot snapshot,
                                                                   SparseAList <EditorToken> eTokens, CancellationToken cancellationToken)
        {
            var sourceFile = new TextSnapshotAsSourceFile(snapshot);
            var tokens     = ToNormalTokens(eTokens);
            var results    = new DList <ITagSpan <ClassificationTag> >();
            var parser     = new MyLesParser(tokens, sourceFile, TraceMessageSink.Value, results);
            var _          = parser.StmtList();

            results.Sort((t1, t2) => t1.Span.Start.Position.CompareTo(t2.Span.Start.Position));
            return(results);
        }
Пример #21
0
        public void DListRemoveTest()
        {
            int[]       arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DList <int> list = new DList <int>(arr);

            list.Remove(1);
            Assert.AreEqual(9, list.Count);
            Assert.AreEqual(2, list[0]);
            list.Remove(10);
            Assert.AreEqual(8, list.Count);
            Assert.AreEqual(9, list[7]);
        }
Пример #22
0
        public void DListEnumeratorTest()
        {
            int[]       arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DList <int> list = new DList <int>(arr);;

            int index = 0;

            foreach (int val in list)
            {
                Assert.AreEqual(arr[index++], val);
            }
        }
Пример #23
0
        public void DListContainsTest()
        {
            int[]       arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DList <int> list = new DList <int>(arr);

            Assert.IsTrue(list.Contains(1));
            Assert.IsTrue(list.Contains(6));
            Assert.IsTrue(list.Contains(10));
            Assert.IsFalse(list.Contains(-1));
            Assert.IsFalse(list.Contains(25));
            Assert.IsFalse(list.Contains(Int32.MinValue));
            Assert.IsFalse(list.Contains(Int32.MaxValue));
        }
Пример #24
0
		protected override VList<LNode> AttachTriviaTo(ref LNode node, IListSource<Token> trivia, TriviaLocation loc, LNode parent, int indexInParent)
		{
			int nli;
			if (loc == TriviaLocation.Trailing && indexInParent == 1 && parent != null && parent.Calls(CodeSymbols.If, 3) && 
				(nli = trivia.LastIndexWhere(t => t.Type() == TokenType.Newline)) != -1) {
				// The 'else' keyword is invisible here, but it often appears on a line by 
				// itself; remove a newline to avoid creating a blank line when printing.
				var triviaSans = new DList<Token>(trivia);
				triviaSans.RemoveAt(nli);
				trivia = triviaSans;
			}
			return base.AttachTriviaTo(ref node, trivia, loc, parent, indexInParent);
		}
Пример #25
0
 internal static void Flatten(DList <Token> input, DList <Token> output, ref bool hasChildren)
 {
     foreach (var token in input)
     {
         output.Add(token);
         var c = token.Children;
         if (c != null && c.Count != 0)
         {
             hasChildren = true;
             Flatten(c, output, ref hasChildren);
         }
     }
 }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        DataSet                  ds = new DataSet();
        SqlDataAdapter           da = new SqlDataAdapter();
        Dictionary <int, string> CorrectAnswers = new Dictionary <int, string>();
        Dictionary <int, string> UserAnswers = new Dictionary <int, string>();
        int Count = 0, TotalQuestion = 0;

        con = new SqlConnection(ConnectionString());
        try
        {
            command.Connection  = con;
            command.CommandText = "Select * from  ExamQuestions";
            da.SelectCommand    = command;
            con.Open();
            da.Fill(ds, "Examination");
            foreach (DataRow DRow in ds.Tables["Examination"].Rows)
            {
                CorrectAnswers.Add(Int32.Parse(DRow["QuestionId"].ToString()), DRow["Answer"].ToString());
            }

            foreach (DataListItem DList in DataList1.Items)
            {
                TotalQuestion++;
                RadioButton OptionA    = (RadioButton)DList.FindControl("rdbOptionA");
                RadioButton OptionB    = (RadioButton)DList.FindControl("rdbOptionB");
                RadioButton OptionC    = (RadioButton)DList.FindControl("rdbOptionC");
                RadioButton OptionD    = (RadioButton)DList.FindControl("rdbOptionD");
                HiddenField QuestionId = (HiddenField)DList.FindControl("hfQuestionId");
                UserAnswers.Add(Int32.Parse(QuestionId.Value), (OptionA.Checked == true) ? "A" : ((OptionB.Checked == true) ? "B" : ((OptionC.Checked == true) ? "C" : "D")));
            }

            foreach (KeyValuePair <int, string> UserAnsKeyValue in UserAnswers)
            {
                if (UserAnsKeyValue.Value == CorrectAnswers[UserAnsKeyValue.Key])
                {
                    Count++;
                }
            }
            Response.Redirect("~/Result.aspx?Result=" + Count + "&TotalQuestion=" + TotalQuestion);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            command.Dispose();
        }
    }
Пример #27
0
		public DList<Statement, BlockStatement> ParseProgram (ref List<Comment> Comments, ref BindingInfo BindingInfo)
		{
			Init ();
			DList<Statement, BlockStatement> result = new DList<Statement, BlockStatement> ();
			while (current.Kind != Token.Type.EndOfInput) {
				if (current.Kind == Token.Type.function)
					result.Append (ParseFunctionDeclaration ());
				else
					result.Append (ParseStatement ());
				Next ();
			}
			Comments = lexer.Comments;
			return result;
		}
Пример #28
0
        internal Iterator <T> GetIterator(int start, int subcount, DList <T> wrapper)
        {
            Debug.Assert((uint)start <= _count && subcount >= 0);
            InternalDList <T> temp;

            if (subcount > _count - start)
            {
                subcount = _count - start;
            }
            temp._start = IncMod(_start, start);
            temp._count = subcount;
            temp._array = _array;
            return(temp.GetIterator(wrapper));
        }
Пример #29
0
        public void DListAddTest()
        {
            DList <int> list = new DList <int>();

            Assert.IsNotNull(list);
            Assert.AreEqual(0, list.Count);
            list.Add(100);
            Assert.AreEqual(1, list.Count);
            for (int i = 0; i < 10000; ++i)
            {
                list.Add(i);
            }
            Assert.AreEqual(10001, list.Count);
        }
Пример #30
0
        public void DListInsertTest()
        {
            int[]       arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DList <int> list = new DList <int>(arr);

            list.Insert(0, 100);
            Assert.AreEqual(11, list.Count);
            Assert.AreEqual(100, list[0]);
            Assert.AreEqual(1, list[1]);
            list.Insert(10, 1000);
            Assert.AreEqual(12, list.Count);
            Assert.AreEqual(1000, list[10]);
            Assert.AreEqual(10, list[11]);
        }
Пример #31
0
        public void Remove()
        {
            var list = new DList <int> {
                0, 1, 2
            };

            list.Remove(item => item == 1).ShouldBe(1);

            list.ShouldBe(new[] { 0, 2 });

            list.Remove(1);

            list.ShouldBe(new[] { 0 });
        }
Пример #32
0
        public void DListIndexOfTest()
        {
            int[]       arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            DList <int> list = new DList <int>(arr);


            Assert.AreEqual(0, list.IndexOf(1));
            Assert.AreEqual(9, list.IndexOf(10));
            Assert.AreEqual(4, list.IndexOf(5));
            Assert.AreEqual(-1, list.IndexOf(0));
            Assert.AreEqual(-1, list.IndexOf(100));
            Assert.AreEqual(-1, list.IndexOf(Int32.MinValue));
            Assert.AreEqual(-1, list.IndexOf(Int32.MaxValue));
        }
Пример #33
0
        public void DListCtorTest()
        {
            DList <int> list = new DList <int>();

            Assert.IsNotNull(list);
            Assert.AreEqual(0, list.Count);
            Assert.AreEqual(false, list.IsReadOnly);

            DList <string> listA = new DList <string>();

            Assert.IsNotNull(listA);
            Assert.AreEqual(0, listA.Count);
            Assert.AreEqual(false, listA.IsReadOnly);
        }
Пример #34
0
        public SLE.LambdaExpression CompileProgram(char[] Input, ref List <Diagnostic> Diagnostics, ref bool IncompleteInput, bool PrintExpressions)
        {
            IdentifierMappingTable idmtable        = new IdentifierMappingTable();
            IdentifierTable        idtable         = new IdentifierTable();
            Parser         parser                  = new Parser(Input, new IdentifierTable(), true);//tode get ecma from somewhere
            List <Comment> comments                = null;
            BindingInfo    bindinginfo             = null;
            DList <Statement, BlockStatement> list = parser.ParseProgram(ref comments, ref bindinginfo);

            Diagnostics     = parser.Diagnostics;
            IncompleteInput = parser.SyntaxIncomplete();
            RowanGenerator gen = new RowanGenerator(idmtable, idtable.InsertIdentifier("this"), idtable.InsertIdentifier("arguments"));

            return(gen.BindAndTransform(list, bindinginfo, PrintExpressions));
        }
Пример #35
0
        protected override VList <LNode> AttachTriviaTo(ref LNode node, IListSource <Token> trivia, TriviaLocation loc, LNode parent, int indexInParent)
        {
            int nli;

            if (loc == TriviaLocation.Trailing && indexInParent == 1 && parent != null && parent.Calls(CodeSymbols.If, 3) &&
                (nli = trivia.LastIndexWhere(t => t.Type() == TokenType.Newline)) != -1)
            {
                // The 'else' keyword is invisible here, but it often appears on a line by
                // itself; remove a newline to avoid creating a blank line when printing.
                var triviaSans = new DList <Token>(trivia);
                triviaSans.RemoveAt(nli);
                trivia = triviaSans;
            }
            return(base.AttachTriviaTo(ref node, trivia, loc, parent, indexInParent));
        }
Пример #36
0
        public static IListSource <Point> ComputeConvexHull(List <Point> points, bool sortInPlace)
        {
            if (points.Count < 2)
            {
                return(new DList <Point>((IReadOnlyList <Point>)points));
            }
            if (!sortInPlace)
            {
                points = new List <Point>(points);
            }
            points.Sort((a, b) =>
                        a.X == b.X ? a.Y.CompareTo(b.Y) : a.X > b.X ? 1 : -1);

            // Importantly, DList provides O(1) insertion at beginning and end
            DList <Point> hull = new DList <Point>();
            int           L = 0, U = 0;   // size of lower and upper hulls

            // Builds a hull such that the output polygon starts at the leftmost point.
            for (int i = points.Count - 1; i >= 0; i--)
            {
                // right turn (clockwise) => negative cross product (for Y-up coords)
                Point p = points[i], p1;

                // build lower hull (at end of output list)
                while (L >= 2 && (p1 = hull.Last).Sub(hull[hull.Count - 2]).Cross(p.Sub(p1)) >= 0)
                {
                    hull.RemoveAt(hull.Count - 1);
                    L--;
                }
                hull.PushLast(p);
                L++;

                // build upper hull (at beginning of output list)
                while (U >= 2 && (p1 = hull.First).Sub(hull[1]).Cross(p.Sub(p1)) <= 0)
                {
                    hull.RemoveAt(0);
                    U--;
                }
                if (U != 0)                 // when U == 0, share the point added above
                {
                    hull.PushFirst(p);
                }
                U++;
                Debug.Assert(U + L == hull.Count + 1);
            }
            hull.RemoveAt(hull.Count - 1);
            return(hull);
        }
Пример #37
0
        public void TestCustomPrinters_InheritanceTest()
        {
            // ReversedListSource<T> is sufficiently complicated for this test. Inheritance:
            //
            // Many other interfaces         Many other interfaces (including IListSource)
            //       ^                            ^
            //       |                            |
            // ICollectionImpl<T>            IListAndListSource<T>
            //       ^                            ^
            //       |                            |
            // ReadOnlyCollectionBase<T>     IListImpl<T>
            //       ^                            ^
            //       |                            |
            // ListSourceBase<T>------------------/
            //       ^
            //       |
            // ReversedListSource<T>

            var lht = new LiteralHandlerTable();

            Assert.IsTrue(lht.AddPrinter(false, typeof(IListAndListSource <int>), PrintFirstElem));
            Assert.IsTrue(lht.AddPrinter(false, typeof(IListSource <int>), PrintFail));            // Won't be used

            var list = new DList <int> {
                123, 456, 789
            };
            var rlist = new ReversedListSource <int>(list);
            var sb    = new StringBuilder();

            Assert.AreEqual("list!", lht.TryPrint(CL(rlist, "list!"), sb).Left.Value.Name);
            Assert.AreEqual("789", sb.ToString());

            // Now add something that will have higher priority...
            Assert.IsTrue(lht.AddPrinter(false, typeof(IListImpl <int>), PrintFirstChar));
            Assert.AreEqual("eels", lht.TryPrint(CL(rlist, "cool!"), sb).Left.Value.Name);
            Assert.AreEqual(1, sb.Length);

            // Printer for base class ReadOnlyCollectionBase takes priority over interface IListImpl.
            // And that one will fail. But the fallback will succeed.
            Assert.IsTrue(lht.AddPrinter(false, typeof(ReadOnlyCollectionBase <int>), PrintFail));
            Assert.AreEqual("eels", lht.TryPrint(CL(rlist, "..."), sb).Left.Value.Name);
            Assert.AreEqual(1, sb.ToString().Length);

            // Now install a printer that will succeed
            Assert.IsTrue(lht.AddPrinter(true, typeof(ReadOnlyCollectionBase <int>), PrintFirstElem));
            Assert.AreEqual("cool!", lht.TryPrint(CL(rlist, "cool!"), sb).Left.Value.Name);
            Assert.AreEqual("789", sb.ToString());
        }
Пример #38
0
        public static DList <Token> ToNormalTokens(SparseAList <EditorToken> eTokens)
        {
            var output = new DList <Token>();
            int?index  = null;

            for (;;)
            {
                EditorToken eTok = eTokens.NextHigherItem(ref index);
                if (index == null)
                {
                    break;
                }
                output.Add(eTok.ToToken(index.Value));
            }
            return(output);
        }
Пример #39
0
		public static void Loyc_Essentials()
		{
			MiniTest.RunTests.Run(new ListExtTests());
			MiniTest.RunTests.Run(new MathExTests());
			MiniTest.RunTests.Run(new UStringTests());
			MiniTest.RunTests.Run(new StringExtTests());
			MiniTest.RunTests.Run(new HashTagsTests());
			MiniTest.RunTests.Run(new LocalizeTests());
			MiniTest.RunTests.Run(new SymbolTests());
			MiniTest.RunTests.Run(new ThreadExTests());
			MiniTest.RunTests.Run(new ListTests<InternalList<int>>(false, delegate(int n) { var l = InternalList<int>.Empty; l.Resize(n); return l; }));
			MiniTest.RunTests.Run(new ListRangeTests<InternalList<int>>(false, delegate() { return InternalList<int>.Empty; }));
			MiniTest.RunTests.Run(new ListTests<DList<int>>(false, delegate(int n) { var l = new DList<int>(); l.Resize(n); return l; }));
			MiniTest.RunTests.Run(new DequeTests<DList<int>>(delegate() { return new DList<int>(); }));
			MiniTest.RunTests.Run(new ListRangeTests<DList<int>>(false, delegate() { return new DList<int>(); }));
			MiniTest.RunTests.Run(new GTests());
		}
        public static PointF[] ComputeConvexHull(List<PointF> points, bool sortInPlace = false)
        {
            if (!sortInPlace)
                points = new List<PointF>(points);
            points.Sort((a, b) =>
              a.X == b.X ? a.Y.CompareTo(b.Y) : (a.X > b.X ? 1 : -1));

            DList<PointF> hull = new DList<PointF>();
            int L = 0, U = 0; // size of lower and upper hulls

            // Builds a hull such that the output polygon starts at the leftmost point.
            for (int i = points.Count - 1; i >= 0; i--)
            {
                PointF p = points[i], p1;

                // build lower hull (at end of output list)
                while (L >= 2 && cross((p1 = hull.Last),hull[hull.Count - 2], points[i]) >= 0)
                {
                    hull.RemoveAt(hull.Count - 1);
                    L--;
                }
                hull.PushLast(p);
                L++;

                // build upper hull (at beginning of output list)
                while (U >= 2 && cross((p1 = hull.First), (hull[1]), points[i]) <= 0)
                {
                    hull.RemoveAt(0);
                    U--;
                }
                if (U != 0) // when U=0, share the point added above
                    hull.PushFirst(p);
                U++;
            }

            try {

                hull.RemoveAt(hull.Count - 1);

            } catch (System.Exception) {

            }

            return hull.ToArray();
        }
Пример #41
0
		void FireStructureChangedUnder(RowVM row)
		{
			if (row == null) { // roots changed
				// Reestablish dependencies from model to ViewModel
				_tree.Roots.DependentSentry.OnGet();
				StructureChanged(this, new TreePathEventArgs());
			} else {
				// Reestablish dependencies from model to ViewModel
				row.Children.DependentSentry.OnGet();
				TreePath path;
				if (row.Model.Parent == null)
					path = new TreePath(row);
				else {
					var list = new DList<RowVM>();
					for (; row != null; row = row.Parent)
						list.PushFirst(row);
					path = new TreePath(list.ToArray());
				}
				StructureChanged(this, new TreePathEventArgs(path));
			}
		}
Пример #42
0
		public void AddTest ()
		{
			Parser parser = new Parser ("var i = 5 + 1;".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.IsInstanceOfType (typeof (VariableDeclarationStatement), it.Element, "#8.1");
			VariableDeclarationStatement varst = ((VariableDeclarationStatement)it.Element);
			Assert.AreEqual ("i", varst.Declarations[0].Declaration.Name.Spelling, "#8.2");
			Assert.IsInstanceOfType (typeof (InitializerVariableDeclaration), varst.Declarations[0].Declaration, "#8.3");
			InitializerVariableDeclaration ini = (InitializerVariableDeclaration)varst.Declarations[0].Declaration;
			Assert.IsInstanceOfType (typeof (BinaryOperatorExpression), ini.Initializer, "#8.4");
			Assert.AreEqual (Expression.Operation.Plus, ini.Initializer.Opcode, "#8.5");			 
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #43
0
		private void TestLes(string input, string expectOutput, int expectMessages = 0, Severity expectSev = 0)
		{
			using (G.PushTLV(Token.ToStringStrategyTLV, TokenExt.ToString))
			{
				MessageHolder errorList;
				var input2 = StripInitialNewline(input);
				var lexer = new LesLexer(input2, errorList = new MessageHolder());
				var wrapr = new LesIndentTokenGenerator(lexer);
				var output = new DList<Token>();
				for (var t = wrapr.NextToken(); t.HasValue; t = wrapr.NextToken())
					output.Add(t.Value);
				var expectTokens = new LesLexer(expectOutput, MessageSink.Console).Buffered().Select(t =>
					t.Type() == TokenType.LBrack ? t.WithType((int)TokenType.Indent) :
					t.Type() == TokenType.RBrack ? t.WithType((int)TokenType.Dedent) : t).ToList();

				AreEqual(expectMessages, errorList.List.Count);
				if (expectMessages > 0)
					AreEqual(expectSev, errorList.List.Max(m => m.Severity));
				ExpectList(output, expectTokens, false);
			}
		}
Пример #44
0
		private void Test(string input, string expectOutput, int expectMessages = 0, Severity expectSev = 0)
		{
			// Install token-to-string stategy to aid debugging
			using (G.PushTLV(Token.ToStringStrategyTLV, t => (t.Value ?? ((CalcTokenType)t.TypeInt).ToString()).ToString())) {
				MessageHolder errorList;
				var input2 = StripInitialNewline(input);
				var lexer = new CalculatorLexer(input2) { ErrorSink = errorList = new MessageHolder() };
				var wrapr = new IndentTokenGenerator(lexer, allIndTrig, new Token((int)CalcTokenType.Semicolon, 0, 0, null)) {
					EolIndentTriggers = eolIndTrig, 
					IndentToken = new Token((int)CalcTokenType.LBrace, 0, 0, null),
					DedentToken = new Token((int)CalcTokenType.RBrace, 0, 0, null),
				};
				var output = new DList<Token>();
				for (var t = wrapr.NextToken(); t.HasValue; t = wrapr.NextToken())
					output.Add(t.Value);
				var expectTokens = new CalculatorLexer(expectOutput).Buffered().ToList();
				
				AreEqual(expectMessages, errorList.List.Count);
				if (expectMessages > 0)
					AreEqual(expectSev, errorList.List.Max(m => m.Severity));
				ExpectList(output, expectTokens, false);
			}
		}
Пример #45
0
		public void WhileTest ()
		{
			parser = new Parser ("while (true) { }".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.IsInstanceOfType (typeof (WhileStatement), it.Element, "#5.1");
			WhileStatement whilest = ((WhileStatement)it.Element);
			Assert.AreEqual (Expression.Operation.@true, whilest.Condition.Opcode,  "#5.2");
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #46
0
		public static DList<Token> ToNormalTokens(SparseAList<EditorToken> eTokens)
		{
			var output = new DList<Token>();
			int? index = null;
			for (;;) {
				EditorToken eTok = eTokens.NextHigherItem(ref index);
				if (index == null) break;
				output.Add(eTok.ToToken(index.Value));
			}
			return output;
		}
Пример #47
0
		public ValueCaseClause(Expression Value, DList<Statement, CaseClause> Children, TextSpan Location, TextSpan HeaderLocation, TextPoint Colon)
			:base(Children, Location, HeaderLocation, Colon)
		{
			this.Value = Value;
		}
Пример #48
0
		public void switchTest ()
		{
			parser = new Parser ("switch (test) { case a: break; default: break;}".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.IsInstanceOfType (typeof (SwitchStatement), it.Element, "#9.1");
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #49
0
		public void DoWhileTest ()
		{
			parser = new Parser ("do { }while (true);".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.IsInstanceOfType (typeof (DoStatement), it.Element, "#6.1");
			DoStatement dost = ((DoStatement)it.Element);
			Assert.AreEqual (Expression.Operation.@true, dost.Condition.Opcode, "#6.2");
			Assert.IsTrue (parser.SyntaxOK (), PrintSyntax ("#6", parser));
		}
Пример #50
0
				public void ApplyPrematchData(Pred pred, DList<Prematched> path)
				{
					_path = path;
					_index = 0;
					_reachedInnerAlts = false;
					pred.Call(this);
				}
Пример #51
0
			void ScanTree(PredictionTree tree, Alts alts, DList<Prematched> path)
			{
				int oldCount = path.Count;
				while (path.Count <= tree.Lookahead)
					path.Add(new Prematched { Terminals = Anything });
				Prematched pm = path.Last;

				if (tree.IsAssertionLevel)
				{
					foreach (PredictionBranch b in tree.Children)
					{
						var old = pm.AndPreds.Clone();
						var verified = Enumerable.Aggregate(b.AndPreds, (set1, set2) => (set1.Union(set2))); // usually empty if more than one
						pm.AndPreds.UnionWith(verified);

						if (b.Sub.Tree != null) {
							ScanTree(b.Sub.Tree, alts, path);
						} else {
							Debug.Assert(b.Sub.Alt != ErrorAlt);
							if (b.Sub.Alt == ExitAlt)
								_apply.ApplyPrematchData(alts.Next, path);
							else
								_apply.ApplyPrematchData(alts.Arms[b.Sub.Alt], path);
						}
						pm.AndPreds = old;
					}
				}
				else // !IsAssertionLevel (terminal-matching level)
				{
					bool needErrorBranch = LLPG.NeedsErrorBranch(tree, alts);

					for (int i = 0; i < tree.Children.Count; i++) {
						PredictionBranch b = tree.Children[i];
						IPGTerminalSet set = b.Set;
						if (!needErrorBranch && i + 1 == tree.Children.Count)
							// Add all the default cases
							set = set.Union(tree.TotalCoverage.Inverted());
						pm.Terminals = set;
						if (b.Sub.Tree != null) {
							ScanTree(b.Sub.Tree, alts, path);
						} else {
							if (b.Sub.Alt == ExitAlt)
								_apply.ApplyPrematchData(alts.Next, path);
							else if (b.Sub.Alt != ErrorAlt)
								_apply.ApplyPrematchData(alts.Arms[b.Sub.Alt], path);
						}
					}
					path.PopLast();
				}
				path.Resize(oldCount);
			}
Пример #52
0
		public void IfTest ()
		{
			parser = new Parser ("if (true) { } else  ;".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.IsInstanceOfType (typeof (IfStatement), it.Element, "#4.1");
			IfStatement ifelse = ((IfStatement)it.Element);
			Assert.AreEqual (Expression.Operation.@true, ifelse.Condition.Opcode, "#4.2");
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #53
0
		public void UnitTest()
		{
			// Testing the injector in isolation (without parser integration) is clunky, 
			// so I'm only doing it once.
			//00	{
			//10		// Leading Comment 1
			//20		/* Leading Comment 2 */
			//30		/* Leading Comment 3 */ x = y; // Trailing Comment 1
			//40		/* Trailing Comment 2 */
			//50		
			//60		y = z; TheEnd();
			//70	}
			var trivia = new DList<Token> {
				T(TT.Newline, 10, 1, WhitespaceTag.Value),
				T(TT.SLComment, 11, 1, "// Leading Comment 1"),
				T(TT.Newline, 20, 1, WhitespaceTag.Value),
				T(TT.MLComment, 21, 1, "/* Leading Comment 2 */"),
				T(TT.Newline, 30, 1, WhitespaceTag.Value),
				T(TT.MLComment, 31, 1, "/* Leading Comment 3 */"),
				T(TT.SLComment, 39, 1, "// Trailing Comment 1"),
				T(TT.Newline, 40, 1, WhitespaceTag.Value),
				T(TT.MLComment, 41, 1, "/* Trailing Comment 2 */"),
				T(TT.Newline, 50, 1, WhitespaceTag.Value),
				T(TT.Newline, 60, 1, WhitespaceTag.Value),
				T(TT.Newline, 70, 1, WhitespaceTag.Value),
			};
			var root = F.Braces(LNode.List(
				F.Call(S.Assign, LNode.List(F.Id("x", 33, 1), F.Id("y", 37, 1)), 33, 37),
				F.Call(S.Assign, LNode.List(F.Id("y", 61, 1), F.Id("z", 65, 1)), 61, 65),
				F.Call("TheEnd", 66, 67)
			), 0, 71);
			// Expected results
			var expected = Les2LanguageService.Value.Parse(
				@"@[#trivia_SLComment("" Leading Comment 1""),
				  #trivia_MLComment("" Leading Comment 2 ""),
				  #trivia_newline,
				  #trivia_MLComment("" Leading Comment 3 ""),
				  #trivia_trailing(
				    #trivia_SLComment("" Trailing Comment 1""),
				    #trivia_MLComment("" Trailing Comment 2 ""),
				    #trivia_newline)] 
				x = y;
				y = z;
				@[#trivia_appendStatement] TheEnd();", preserveComments: false);

			var injector = new StandardTriviaInjector(trivia, F.File, (int)TT.Newline, "/*", "*/", "//");
			{
				var results = injector.Run(root.Args.GetEnumerator()).ToList();
				AreEqual(3, results.Count);
				AreEqual(expected[0].PlusAttrBefore(F.Id(S.TriviaNewline)), results[0]);
				AreEqual(expected[1], results[1]);
				AreEqual(expected[2], results[2]);
			}
			{
				var results = injector.Run(new List<LNode> { root }.GetEnumerator()).ToList();
				AreEqual(1, results.Count);
				var result = results[0];
				IsTrue(result.Calls(S.Braces, 3));
				AreEqual(expected[0], result[0]);
				AreEqual(expected[1], result[1]);
				AreEqual(expected[2], result[2]);
			}
		}
Пример #54
0
		public void TestProcessCommandLineArguments1()
		{
			string commandLine = "-abZ -ab123 and -a=Foo --Apple:No -b plantain --a %TEMP% @notExpanded --banana -Z --empty=";
			var args = G.SplitCommandLineArguments(commandLine);
			
			var shortOpts = new Dictionary<char, string> { { 'a', null }, { 'b', "banana" } };
			var twoArgOptions = new InvertibleSet<string>(new[] { "banana" });
			var options = new DList<KeyValuePair<string, string>>();
			UG.ProcessCommandLineArguments(args, options, null, shortOpts, twoArgOptions, expandEnvVars: false);

			ExpectList(args.AsListSource(), "-abZ", "and", "%TEMP%", "@notExpanded", "-Z");
			ExpectList(options, P("a", null), P("banana", "123"), P("a", "Foo"), P("apple", "No"), P("banana", "plantain"), P("a", null), P("banana", null), P("empty", ""));
		}
Пример #55
0
		public DefaultCaseClause(DList<Statement, CaseClause> Children, TextSpan Location, TextSpan HeaderLocation, TextPoint Colon)
			:base(Children,Location,HeaderLocation,Colon)
		{
		}
Пример #56
0
		public void EmptyTest ()
		{
			parser = new Parser (";".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.AreEqual (Statement.Operation.Empty, it.Element.Opcode, "#12.1");
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #57
0
		public void ForTest ()
		{
			parser = new Parser ("for (var i = 0 ; i < 5 ; i++ ) { break; }".ToCharArray ());
			List<Comment> comments = new List<Comment> ();
			DList<Statement, BlockStatement> list = parser.ParseProgram (ref comments);
			DList<Statement, BlockStatement>.Iterator it = new DList<Statement, BlockStatement>.Iterator (list);
			Assert.IsInstanceOfType (typeof (DeclarationForStatement), it.Element, "#7.1");
			DeclarationForStatement forst = ((DeclarationForStatement)it.Element);
			Assert.IsInstanceOfType (typeof (BlockStatement), forst.Body, "#7.2");
			it = new DList<Statement, BlockStatement>.Iterator (((BlockStatement)forst.Body).Children);
			Assert.IsInstanceOfType (typeof (BreakOrContinueStatement), it.Element, "#7.3");
			Assert.IsTrue (parser.SyntaxOK ());
		}
Пример #58
0
		public BlockStatement (DList<Statement, BlockStatement> Children, TextSpan Location) 
			:base(Statement.Operation.Block, Location)
		{
			this.Children = Children;
		}
Пример #59
0
		public void TestProcessCommandLineArguments2()
		{
			// Generate two options files, where the first refers to the second
			string atFolder = Environment.ExpandEnvironmentVariables("%TEMP%");
			string file1 = "test ProcessCmdLine 1.txt";
			string file2 = "test ProcessCmdLine 2.txt";
			StreamWriter w = new StreamWriter(Path.Combine(atFolder, file1));
			w.WriteLine("\"@"+file2+"\" fox--jumps\n--over");
			w.Close();
			w = new StreamWriter(Path.Combine(atFolder, file2));
			w.WriteLine("these arguments are ignored (arg limit exceeded)");
			w.Close();

			// Expand command line and ensure that the arg limit is enforced
			List<string> args = G.SplitCommandLineArguments("\"@"+file1+"\" \"lazy dog\"");
			var options = new DList<KeyValuePair<string, string>>();
			var msgs = new MessageHolder();
			using (MessageSink.SetDefault(msgs))
				UG.ProcessCommandLineArguments(args, options, atFolder, null, null, 5);

			ExpectList(args.AsListSource(), "@"+file1, "@"+file2, "fox--jumps", "lazy dog");
			ExpectList(options, P("over", null));
			ExpectList(msgs.List.Select(msg => msg.ToString()).AsListSource(),
				"@test ProcessCmdLine 2.txt: Warning: Limit of 5 commands exceeded");
		}
Пример #60
0
		public static IListSource<Point> ComputeConvexHull(List<Point> points, bool sortInPlace)
		{
			if (!sortInPlace)
				points = new List<Point>(points);
			points.Sort((a, b) => 
				a.X == b.X ? a.Y.CompareTo(b.Y) : a.X > b.X ? 1 : -1);

			// Importantly, DList provides O(1) insertion at beginning and end
			DList<Point> hull = new DList<Point>();
			int L = 0, U = 0; // size of lower and upper hulls

			// Builds a hull such that the output polygon starts at the leftmost point.
			for (int i = points.Count - 1; i >= 0 ; i--)
			{
				// right turn (clockwise) => negative cross product (for Y-up coords)
				Point p = points[i], p1;

				// build lower hull (at end of output list)
				while (L >= 2 && (p1 = hull.Last).Sub(hull[hull.Count-2]).Cross(p.Sub(p1)) >= 0) {
					hull.RemoveAt(hull.Count-1);
					L--;
				}
				hull.PushLast(p);
				L++;

				// build upper hull (at beginning of output list)
				while (U >= 2 && (p1 = hull.First).Sub(hull[1]).Cross(p.Sub(p1)) <= 0) {
					hull.RemoveAt(0);
					U--;
				}
				if (U != 0) // when U == 0, share the point added above
					hull.PushFirst(p);
				U++;
				Debug.Assert(U + L == hull.Count + 1);
			}
			hull.RemoveAt(hull.Count - 1);
			return hull;
		}