Esempio n. 1
0
        /// <summary>
        /// Retrieves each element of an array with its key if any.
        /// </summary>
        /// <param name="array">An array or object.</param>
        /// <returns>The current element.</returns>
        public static IEnumerable LoopEach(object array)
        {
            if (array == null)
                yield break;

            var info = new LoopInfo { type = LoopType.Each };
            loops.Push(info);

            var type = array.GetType();

            if (typeof(IDictionary).IsAssignableFrom(type))
            {
                var dictionary = (IDictionary)array;

                foreach (var key in dictionary.Keys)
                {
                    info.result = new[] { key, dictionary[key] };
                    info.index++;
                    yield return info.result;
                }
            }
            else if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                var enumerator = ((IEnumerable)array).GetEnumerator();

                while (enumerator.MoveNext())
                {
                    info.result = new[] { null, enumerator.Current };
                    info.index++;
                    yield return info.result;
                }
            }

            loops.Pop();
        }
Esempio n. 2
0
        private void SolvePuzzle2(IList <string> list)
        {
            List <Tuple <string, int> > commands = GetCommands(list);
            List <Tuple <string, int> > workcopy;
            LoopInfo li     = new LoopInfo();
            int      testid = 0;

            do
            {
                if (commands[testid].Item1 == "acc")
                {
                    testid++;
                    continue;
                }

                workcopy = MakeCopyOfCommands(commands);

                switch (workcopy[testid].Item1)
                {
                case "jmp": workcopy[testid] = new Tuple <string, int>("nop", workcopy[testid].Item2); break;

                case "nop": workcopy[testid] = new Tuple <string, int>("jmp", workcopy[testid].Item2); break;
                }

                li = TestForLoop(workcopy);
                testid++;
            }while (li.IsLoop);

            Helper.Logger.Log(Name, $"Acc: {li.Acc}");
        }
 public void onEndDrag(int endingNode)
 {
     if (!isValid)
     {
         Destroy(loops[endingNode]);
     }
     else
     {
         loopInfoBeingModified        = loopInfos[endingNode];
         loopInfoBeingModified.origin = 0;
         float willSnapTo = maximumHeights[0];
         for (int i = 0; i < maximumHeights.Length; i++)
         {
             if (topPosition > maximumHeights[i])
             {
                 break;
             }
             willSnapTo = maximumHeights[i];
             loopInfoBeingModified.origin = i;
         }
         topPosition = willSnapTo;
         applyPositions();
         loopInfos[endingNode].initialCurveY = arrowTransform.localPosition.y;
         loopSizeMenu.SetActive(true);
     }
     resetAllCounts();
     for (int i = 0; i < loopInfos.Length; i++)
     {
         if (loopInfos[i])
         {
             loopInfos[i].howManyAbove  = countParentLoops(i, endingNode, loopInfos[i].origin);
             loopInfos[i].howManyInside = countInnerLoops(i, endingNode, loopInfos[i].origin);
         }
     }
 }
            /// <summary>
            /// Starts a new loop
            /// </summary>
            /// <param name="startIndex">The index on the string where the loop starts</param>
            /// <param name="numIterations">The number of iterations of the loop</param>
            public void StartLoop(int startIndex, int numIterations)
            {
                //If this loop is not started, start it, otherwise start the nested loop
                if (this.startIndex == -1)
                {
                    //Store start index and number of iterations
                    this.startIndex    = startIndex;
                    this.numIterations = numIterations;
                }
                else
                {
                    //If attempted to start nested loops when not allowed, throw exception
                    if (!allowNestedLoops)
                    {
                        throw new Exception("Nested loops are not allowed");
                    }

                    //If the nested loop has not been made, make it
                    if (nestedLoop == null)
                    {
                        nestedLoop = new LoopInfo();
                    }

                    //Start the nested loop
                    nestedLoop.StartLoop(startIndex, numIterations);
                }
            }
    public void chooseAmount(int amount)
    {
        LoopInfo info = loopInfoBeingModified;

        info.amount = amount;
        loopSizeMenu.SetActive(false);
    }
Esempio n. 6
0
        /// <summary>
        /// Retrieves the lines in a text file, one at a time.
        /// </summary>
        /// <param name="input">The name of the text file whose contents will be read by the loop.</param>
        /// <param name="output">The optional name of the file to be kept open for the duration of the loop.</param>
        /// <returns></returns>
        public static IEnumerable LoopRead(string input, string output)
        {
            if (!File.Exists(input))
            {
                yield break;
            }

            StreamWriter writer = null;

            if (output == "*")
            {
                writer = new StreamWriter(Console.OpenStandardOutput());
            }
            else if (!string.IsNullOrEmpty(output))
            {
                bool binary = output[0] == '*';

                if (binary)
                {
                    output = output.Substring(1);
                }

                if (output.Length == 0 || !File.Exists(output))
                {
                    yield break;
                }

                writer = new StreamWriter(File.OpenWrite(output));

                if (binary)
                {
                    writer.NewLine = "\n";
                }
            }

            var info = new LoopInfo
            {
                type = LoopType.File
            };

            loops.Push(info);

            var    reader = File.OpenText(input);
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                if (writer != null)
                {
                    writer.WriteLine(line);
                }

                info.result = line;
                info.index++;

                yield return(line);
            }

            loops.Pop();
        }
Esempio n. 7
0
        public bool IterateLoop(int count, ref int targetPos)
        {
            if (m_loops.Count > 0)
            {
                LoopInfo info = m_loops[m_loops.Count - 1];
                if (info.Iterations == -1)
                {
                    info.Iterations = count;
                }

                info.Iterations--;
                if (info.Iterations <= 0)
                {
                    m_loops.RemoveAt(m_loops.Count - 1);
                    return(false);
                }
                else
                {
                    targetPos = info.LoopPos;
                    return(true);
                }
            }
            else
            {
                return(false);
            }
        }
Esempio n. 8
0
 public LoopItem(Func <TModel, int, T> listFunc, HtmlHelper <TModel> htmlHelper, T item, LoopInfo loopInfo)
 {
     Item        = item;
     Info        = loopInfo;
     _listFunc   = listFunc;
     _htmlHelper = htmlHelper;
     _currentIndexedExpression = loopInfo.CurrentExpression;
 }
Esempio n. 9
0
            public LoopInfo Clamp(LoopInfo other)
            {
                LoopInfo newPack = new LoopInfo {
                    Left = Mathf.Max(Left, other.Left)
                };

                newPack.Length = Mathf.Min(Left + Length, other.Left + other.Length) - newPack.Left;
                return(newPack);
            }
Esempio n. 10
0
 public void recoverSize()
 {
     info = GetComponentInChildren <LoopInfo>();
     if (info)
     {
         origin   = info.origin;
         loopSize = info.amount;
     }
 }
Esempio n. 11
0
        protected override void UpdateContents()
        {
            UpdatePageSize();
            LoopInfo clampedRange = CalcViewRange();

            if (clampedRange != viewRange)
            {
                UpdateViewRange(clampedRange.Left);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Perform a series of commands repeatedly: either the specified number of times or until break is encountered.
        /// </summary>
        /// <param name="n">How many times (iterations) to perform the loop.</param>
        /// <returns></returns>
        public static IEnumerable Loop(int n)
        {
            var info = new LoopInfo { type = LoopType.Normal };
            loops.Push(info);

            for (int i = 0; i < n;)
            {
                info.index = i;
                yield return ++i;
            }

            loops.Pop();
        }
Esempio n. 13
0
        /// <summary>
        /// Retrieves the contents of the specified registry subkey, one item at a time.
        /// </summary>
        /// <param name="root">Must be either HKEY_LOCAL_MACHINE (or HKLM), HKEY_USERS (or HKU), HKEY_CURRENT_USER (or HKCU), HKEY_CLASSES_ROOT (or HKCR), or HKEY_CURRENT_CONFIG (or HKCC).</param>
        /// <param name="key">The name of the key (e.g. Software\SomeApplication). If blank or omitted, the contents of RootKey will be retrieved.</param>
        /// <param name="subkeys">
        /// <list>
        /// <item><code>1</code> subkeys contained within Key are not retrieved (only the values);</item>
        /// <item><code>1</code> all values and subkeys are retrieved;</item>
        /// <item><code>2</code> only the subkeys are retrieved (not the values).</item>
        /// </list>
        /// </param>
        /// <param name="recurse"><code>1</code> to recurse into subkeys, <code>0</code> otherwise.</param>
        /// <returns></returns>
        public static IEnumerable LoopRegistry(string root, string key, int subkeys, bool recurse)
        {
            var info = new LoopInfo {
                type = LoopType.Registry
            };

            loops.Push(info);

            loops.Pop();

            yield break;

            // TODO: registry loop
        }
Esempio n. 14
0
        private LoopInfo CalcViewRange()
        {
            float    curPos       = CurDirectionPos - (TemplateDiv) * PreOutLook - Padding.y;
            int      scrollIndex  = ScrollPosToScrollStep(curPos);
            LoopInfo clampedRange = new LoopInfo
            {
                Left = scrollIndex + PageStepLen > ScrollSteps ? ScrollSteps - PageStepLen : scrollIndex
            };

            if (clampedRange.Left < 0)
            {
                clampedRange.Left = 0;
            }
            clampedRange.Length = PageStepLen;
            return(clampedRange);
        }
Esempio n. 15
0
        public void StartLoop(int pos)
        {
            foreach (var cur in m_loops)
            {
                if (cur.LoopPos == pos)
                {
                    return;
                }
            }

            LoopInfo info = new LoopInfo();

            info.LoopPos    = pos;
            info.Iterations = -1;
            m_loops.Add(info);
        }
Esempio n. 16
0
        /// <summary>
        /// Perform a series of commands repeatedly: either the specified number of times or until break is encountered.
        /// </summary>
        /// <param name="n">How many times (iterations) to perform the loop.</param>
        /// <returns></returns>
        public static IEnumerable Loop(int n)
        {
            var info = new LoopInfo {
                type = LoopType.Normal
            };

            loops.Push(info);

            for (int i = 0; i < n;)
            {
                info.index = i;
                yield return(++i);
            }

            loops.Pop();
        }
Esempio n. 17
0
        private void UpdateViewRange(int scrollStep)
        {
            LoopInfo target = new LoopInfo
            {
                Left   = scrollStep,
                Length = PageStepLen
            };
            int viewCount = Mathf.Min(ItemCount - target.Left * PageDiv, PageSize);

            if (viewCount < 0)
            {
                viewCount = 0;
            }
            int deltaSize = viewCount - viewList.Count;

            for (int i = 0; i < deltaSize; i++)
            {
                viewList.Add(null);
            }
            LoopInfo intersection = target.Clamp(viewRange);
            int      sstart       = 0;
            int      scount       = 0;

            if (intersection.Length > 0)
            {
                sstart = Mathf.Max(0, target.GetOffset(intersection.Left) * PageDiv);
                scount = Mathf.Min(intersection.Length * PageDiv, viewCount);
                var sdir = target.GetOffset(viewRange.Left) * PageDiv;
                MoveItems(viewList, sstart - sdir, scount, sdir);
            }
            for (int i = 0; i < -deltaSize; i++)
            {
                DisposeItem(viewList, viewList.Count - 1);
            }
            int a = sstart;
            int b = a + scount - 1;

            for (int i = 0; i < viewCount; i++)
            {
                if (i < a || i > b)
                {
                    UpdateItem(viewList, i, OffsetByPage(target, i));
                }
            }
            viewRange.Left   = scrollStep;
            viewRange.Length = PageStepLen;
        }
Esempio n. 18
0
        //----- method -----

        public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
        {
            var playable = ScriptPlayable <LoopBehaviour> .Create(graph);

            var loopInfo = new LoopInfo(name)
            {
                Loop = true
            };

            var beheviour = playable.GetBehaviour();

            beheviour.PlayableDirector = owner.GetComponent <PlayableDirector>();

            beheviour.LoopInfo = loopInfo;

            return(playable);
        }
Esempio n. 19
0
        private LoopInfo TestForLoop(List <Tuple <string, int> > commands)
        {
            var retval = new LoopInfo()
            {
                IsLoop = true
            };

            bool[] commandhit = new bool[commands.Count];

            int cmdN = 0;

            while (true)
            {
                if (cmdN >= commands.Count)
                {
                    retval.IsLoop = false;
                    break;
                }

                if (commandhit[cmdN])
                {
                    break;
                }

                commandhit[cmdN] = true;

                if (commands[cmdN].Item1 == "acc")
                {
                    retval.Acc += commands[cmdN].Item2;
                }

                if (commands[cmdN].Item1 == "jmp")
                {
                    cmdN += commands[cmdN].Item2;
                }
                else
                {
                    cmdN++;
                }
            }

            return(retval);
        }
Esempio n. 20
0
        /// <summary>
        /// Retrieves the specified files or folders, one at a time.
        /// </summary>
        /// <param name="pattern">The name of a single file or folder, or a wildcard pattern.</param>
        /// <param name="folders">One of the following digits, or blank to use the default:
        /// <list>
        /// <item><code>1</code> (default) folders are not retrieved (only files);</item>
        /// <item><code>1</code> all files and folders that match the wildcard pattern are retrieved;</item>
        /// <item><code>2</code> only folders are retrieved (no files).</item>
        /// </list>
        /// </param>
        /// <param name="recurse"><code>1</code> to recurse into subfolders, <code>0</code> otherwise.</param>
        /// <returns></returns>
        public static IEnumerable LoopFile(string pattern, int folders, bool recurse)
        {
            var info = new LoopInfo {
                type = LoopType.Directory
            };

            loops.Push(info);

            string[] list = Directory.GetFiles(pattern, string.Empty, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            foreach (var file in list)
            {
                info.result = file;
                info.index++;
                yield return(file);
            }

            loops.Pop();
        }
Esempio n. 21
0
        /// <summary>
        /// Retrieves each element of an array with its key if any.
        /// </summary>
        /// <param name="array">An array or object.</param>
        /// <returns>The current element.</returns>
        public static IEnumerable LoopEach(object array)
        {
            if (array == null)
            {
                yield break;
            }

            var info = new LoopInfo
            {
                type = LoopType.Each
            };

            loops.Push(info);

            var type = array.GetType();

            if (typeof(IDictionary).IsAssignableFrom(type))
            {
                var dictionary = (IDictionary)array;

                foreach (var key in dictionary.Keys)
                {
                    info.result = new[] { key, dictionary[key] };
                    info.index++;
                    yield return(info.result);
                }
            }
            else if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                var enumerator = ((IEnumerable)array).GetEnumerator();

                while (enumerator.MoveNext())
                {
                    info.result = new[] { null, enumerator.Current };
                    info.index++;
                    yield return(info.result);
                }
            }

            loops.Pop();
        }
Esempio n. 22
0
		} // Break
	
	
	// Return a statement which associated the specified LoopInfo with
	// an enclosing statement.  This should be called for switch statements,
	// and for any labeled statement which is not a loop statement.
	public StmtFrag LabeledStmt(LoopInfo loopInfo, StmtFrag stmt)
		{
		CSharpLoopInfo csLoopInfo = (CSharpLoopInfo)loopInfo;
		CSharpStmtFrag frag = new CSharpStmtFrag(csLoopInfo.loc);
		
		frag.Append(stmt);
		frag.Append("breakTarget_{0}: {1}", csLoopInfo.index + 1, "{}");
		
		return frag;
		} // LabeledStmt
Esempio n. 23
0
    public Instruction Next()
    {
        if (index >= Instructions.Count)
        {
            return(null);
        }

        currentInstruction = Instructions[index];
        switch (currentInstruction.Type)
        {
        case InstructionType.Loop:
            index++;
            loopInfos.Push(new LoopInfo(index, (int)currentInstruction.Parameter));
            return(Next());

        case InstructionType.EndLoop:
            LoopInfo currentLoop = loopInfos.Peek();
            currentLoop.count--;
            if (currentLoop.count == 0)
            {
                loopInfos.Pop();
                index++;
            }
            else
            {
                index = currentLoop.index;
            }
            return(Next());

        case InstructionType.Sync:
            if (SyncLocked)
            {
                if (waitingForSync)
                {
                    if (waitingForSyncIndex == SyncIndex)
                    {
                        return(currentInstruction);
                    }
                    else
                    {
                        waitingForSync = false;
                        index++;
                        return(Next());
                    }
                }
                else
                {
                    SyncLocked     = false;
                    waitingForSync = false;
                    index++;
                    return(Next());
                }
            }
            else
            {
                if (waitingForSync)
                {
                    waitingForSync = false;
                    index++;
                    return(Next());
                }
                else
                {
                    SyncLocked = true;
                    SyncIndex++;
                    waitingForSync      = true;
                    waitingForSyncIndex = SyncIndex;
                    return(currentInstruction);
                }
            }
        }

        if (stepIndex >= currentInstruction.StepCount)
        {
            index++;
            stepIndex = 1;
        }
        else
        {
            stepIndex++;
        }
        return(currentInstruction);
    }
Esempio n. 24
0
        /// <summary>
        /// Retrieves substrings (fields) from a string, one at a time.
        /// </summary>
        /// <param name="input">The string to parse.</param>
        /// <param name="delimiters">One of the following:
        /// <list>
        /// <item>the word <code>CSV</code> to parse in comma seperated value format;</item>
        /// <item>a sequence of characters to treat as delimiters;</item>
        /// <item>blank to parse each character of the string.</item>
        /// </list>
        /// </param>
        /// <param name="omit">An optional list of characters (case sensitive) to exclude from the beginning and end of each substring.</param>
        /// <returns></returns>
        public static IEnumerable LoopParse(string input, string delimiters, string omit)
        {
            var info = new LoopInfo { type = LoopType.Parse };
            loops.Push(info);

            if (delimiters.ToLowerInvariant() == Keyword_CSV)
            {
                var reader = new StringReader(input);
                var part = new StringBuilder();
                bool str = false, next = false;

                while (true)
                {
                    int current = reader.Read();
                    if (current == -1)
                        goto collect;

                    const char tokenStr = '"', tokenDelim = ',';

                    var sym = (char)current;

                    switch (sym)
                    {
                        case tokenStr:
                            if (str)
                            {
                                if ((char)reader.Peek() == tokenStr)
                                {
                                    part.Append(tokenStr);
                                    reader.Read();
                                }
                                else
                                    str = false;
                            }
                            else
                            {
                                if (next)
                                    part.Append(tokenStr);
                                else
                                    str = true;
                            }
                            break;

                        case tokenDelim:
                            if (str)
                                goto default;
                            goto collect; // sorry

                        default:
                            next = true;
                            part.Append(sym);
                            break;
                    }

                    continue;

                collect:
                    next = false;
                    string result = part.ToString();
                    part.Length = 0;
                    info.result = result;
                    info.index++;
                    yield return result;
                    if (current == -1)
                        break;
                }
            } else {
                string[] parts;
                var remove = omit.ToCharArray();

                if(string.IsNullOrEmpty(delimiters)) {
                    var chars = input.ToCharArray();
                    parts = new string[chars.Length];
                    for(int i=0; i < chars.Length; i++)
                        parts[i] = chars[i].ToString();
                }else
                    parts = input.Split(delimiters.ToCharArray(), StringSplitOptions.None);

                foreach (var part in parts)
                {
                    var result = part.Trim(remove);
                    if(string.IsNullOrEmpty(result))
                        continue;
                    info.result = result;
                    info.index++;
                    yield return result;
                }
            }

            loops.Pop();
        }
Esempio n. 25
0
        /// <summary>
        /// Retrieves the contents of the specified registry subkey, one item at a time.
        /// </summary>
        /// <param name="root">Must be either HKEY_LOCAL_MACHINE (or HKLM), HKEY_USERS (or HKU), HKEY_CURRENT_USER (or HKCU), HKEY_CLASSES_ROOT (or HKCR), or HKEY_CURRENT_CONFIG (or HKCC).</param>
        /// <param name="key">The name of the key (e.g. Software\SomeApplication). If blank or omitted, the contents of RootKey will be retrieved.</param>
        /// <param name="subkeys">
        /// <list>
        /// <item><code>1</code> subkeys contained within Key are not retrieved (only the values);</item>
        /// <item><code>1</code> all values and subkeys are retrieved;</item>
        /// <item><code>2</code> only the subkeys are retrieved (not the values).</item>
        /// </list>
        /// </param>
        /// <param name="recurse"><code>1</code> to recurse into subkeys, <code>0</code> otherwise.</param>
        /// <returns></returns>
        public static IEnumerable LoopRegistry(string root, string key, int subkeys, bool recurse)
        {
            var info = new LoopInfo { type = LoopType.Registry };
            loops.Push(info);

            loops.Pop();

            yield break;

            // TODO: registry loop
        }
Esempio n. 26
0
		} // For
	
	
	// Return a for/in statement.
	public StmtFrag ForIn( LoopInfo loopInfo, StmtFrag init,
						   ExprFrag lhs, ExprFrag rhs, StmtFrag body )
		{
		CSharpLoopInfo csLoopInfo = (CSharpLoopInfo)loopInfo;
		
		// HACK snewman 8/15/01: implement for/in statements.
		throw new ParseError( "For/In statements not yet implemented",
							  csLoopInfo.loc );
		} // ForIn
Esempio n. 27
0
 private bool Equals(LoopInfo other)
 {
     return(Left == other.Left && Length == other.Length);
 }
Esempio n. 28
0
		} // ParseForStatement
	
	
	// Parse a Statement.
	private StmtFrag ParseStatement(FunctionInfo info)
		{
		StringCollection labels = MatchLabelSet();
		
		if (tok.TryMatchKeyword("do"))
			{
			LoopInfo loopInfo = gen.NewLoopInfo( curCGFuncInfo, tok.Prev().loc,
												 labels );
			loops.Push(loopInfo);
			
			StmtFrag body = ParseStatement(info);
			tok.MatchKeyword("while");
			tok.MatchOp("(");
			ExprFrag condition = ParseExpression(info, true);
			tok.MatchOp(")");
			tok.MatchOp(";");
			
			LoopInfo temp = (LoopInfo) loops.Pop();
			Trace.Assert(temp == loopInfo);
			
			return gen.DoWhile(loopInfo, body, condition);
			}
		else if (tok.TryMatchKeyword("while"))
			{
			LoopInfo loopInfo = gen.NewLoopInfo( curCGFuncInfo, tok.Prev().loc,
												 labels );
			loops.Push(loopInfo);
			
			tok.MatchOp("(");
			ExprFrag condition = ParseExpression(info, true);
			tok.MatchOp(")");
			StmtFrag body = ParseStatement(info);
			
			LoopInfo temp = (LoopInfo) loops.Pop();
			Trace.Assert(temp == loopInfo);
			
			return gen.WhileDo(loopInfo, condition, body);
			}
		else if (tok.TryMatchKeyword("for"))
			return ParseForStatement(info, labels);
		else
			{
			bool isSwitch = tok.PeekKeyword("switch");
			LoopInfo labelInfo = null;
			if (labels != null || isSwitch)
				{
				labelInfo = gen.NewLabeledStmtInfo( curCGFuncInfo, tok.Prev().loc,
													labels, isSwitch );
				loops.Push(labelInfo);
				}
			
			StmtFrag stmt;
			if (tok.PeekOp("{"))
				stmt = ParseBlock(info);
			else if (tok.TryMatchKeyword("var"))
				{
				stmt = gen.NewStmtFrag(tok.Prev().loc);
				
				do
					{
					string varName;
					SrcLoc varLoc;
					stmt.Append(ParseVariableDeclaration( info, true, out varName,
														  out varLoc ));
					}
				while (tok.TryMatchOp(","));
				tok.MatchOp(";");
				}
			else if (tok.TryMatchOp(";"))
				{
				// EmptyStatement
				stmt = gen.NewStmtFrag(tok.Prev().loc);
				}
			else if (tok.TryMatchKeyword("if"))
				{
				SrcLoc ifLoc = tok.Prev().loc;
				
				tok.MatchOp("(");
				ExprFrag condition = ParseExpression(info, true);
				tok.MatchOp(")");
				
				StmtFrag ifClause = ParseStatement(info);
				StmtFrag elseClause = null;
				if (tok.TryMatchKeyword("else"))
					elseClause = ParseStatement(info);
				
				stmt = gen.IfThenElse(ifLoc, condition, ifClause, elseClause);
				}
			else if (tok.TryMatchKeyword("continue"))
				{
				SrcLoc continueLoc = tok.Prev().loc;
				
				// HACK snewman 8/7/01: the grammar (ContinueStatement) specifies
				// "no LineTerminator here".
				string id;
				tok.TryMatchID(out id);
				tok.MatchOp(";");
				
				stmt = gen.Continue(continueLoc, id, CloneStack(loops));
				}
			else if (tok.TryMatchKeyword("break"))
				{
				SrcLoc breakLoc = tok.Prev().loc;
				
				// HACK snewman 8/7/01: the grammar (BreakStatement) specifies
				// "no LineTerminator here".
				string id;
				tok.TryMatchID(out id);
				tok.MatchOp(";");
				
				stmt = gen.Break(breakLoc, id, CloneStack(loops));
				}
			else if (tok.TryMatchKeyword("return"))
				{
				SrcLoc returnLoc = tok.Prev().loc;
				
				// HACK snewman 8/7/01: the grammar (ReturnStatement) specifies
				// "no LineTerminator here".
				if (tok.TryMatchOp(";"))
					stmt = gen.Return(returnLoc, null);
				else
					{
					ExprFrag value = ParseExpression(info, true);
					tok.MatchOp(";");
					stmt = gen.Return(returnLoc, value);
					}
				
				}
			else if (tok.TryMatchKeyword("with"))
				{
				SrcLoc withLoc = tok.Prev().loc;
				
				tok.MatchOp("(");
				ExprFrag value = ParseExpression(info, true);
				tok.MatchOp(")");
				
				WithInfo withInfo = gen.NewWithInfo(curCGFuncInfo, withLoc);
				withs.Push(withInfo);
				
				StmtFrag body = ParseStatement(info);
				
				WithInfo temp = (WithInfo) withs.Pop();
				Trace.Assert(temp == withInfo);
				
				stmt = gen.With(withInfo, value, body);
				}
			else if (tok.TryMatchKeyword("switch"))
				{
				SrcLoc switchLoc = tok.Prev().loc;
				SwitchInfo switchInfo = gen.NewSwitchInfo();
				
				tok.MatchOp("(");
				ExprFrag switchValue = ParseExpression(info, true);
				tok.MatchOp(")");
				
				tok.MatchOp("{");
				while (!tok.TryMatchOp("}"))
					{
					ExprFrag caseValue;
					if (tok.TryMatchKeyword("default"))
						caseValue = null;
					else
						{
						tok.MatchKeyword("case");
						caseValue = ParseExpression(info, true);
						}
					
					StmtFrag clauseStmt = null;
					tok.MatchOp(":");
					while ( !tok.PeekOp("}") && !tok.PeekKeyword("case") &&
							!tok.PeekKeyword("default") )
						{
						StmtFrag tempStmt = ParseStatement(info);
						if (clauseStmt == null)
							clauseStmt = tempStmt;
						else
							clauseStmt.Append(tempStmt);
						}
					
					switchInfo.AddCase(caseValue, clauseStmt);
					}
				
				stmt = gen.Switch(switchLoc, switchValue, switchInfo);
				}
			else if (tok.TryMatchKeyword("throw"))
				{
				SrcLoc throwLoc = tok.Prev().loc;
				
				// HACK snewman 8/7/01: the grammar (ThrowStatement) specifies
				// "no LineTerminator here".
				ExprFrag value = ParseExpression(info, true);
				tok.MatchOp(";");
				
				stmt = gen.Throw(throwLoc, value);
				}
			else if (tok.TryMatchKeyword("try"))
				{
				SrcLoc tryLoc = tok.Prev().loc;
				StmtFrag tryBody = ParseBlock(info);
				String catchVar        = null;
				WithInfo catchWithInfo = null;
				StmtFrag catchBody     = null;
				StmtFrag finallyBody   = null;
				
				if (tok.TryMatchKeyword("catch"))
					{
					SrcLoc catchLoc = tok.Prev().loc;
					
					tok.MatchOp("(");
					catchVar = tok.MatchID();
					tok.MatchOp(")");
					
					catchWithInfo = gen.NewWithInfo(curCGFuncInfo, catchLoc);
					withs.Push(catchWithInfo);
					
					catchBody = ParseBlock(info);
					
					WithInfo temp = (WithInfo) withs.Pop();
					Trace.Assert(temp == catchWithInfo);
					}
				
				if (tok.TryMatchKeyword("finally"))
					finallyBody = ParseBlock(info);
				
				stmt = gen.TryCatchFinally( tryLoc, tryBody, catchVar,
											catchWithInfo, catchBody, finallyBody );
				}
			else
				{
				ExprFrag expr = ParseExpression(info, true);
				tok.MatchOp(";");
				stmt = gen.ExpressionStmt(expr);
				}
			
			if (labelInfo != null)
				{
				LoopInfo temp2 = (LoopInfo) loops.Pop();
				Trace.Assert(temp2 == labelInfo);
				
				stmt = gen.LabeledStmt(labelInfo, stmt);
				}
			
			return stmt;
			}
		
		} // ParseStatement
Esempio n. 29
0
		} // MatchLabelSet
	
	
	// Parse a for statement.  The caller should already have matched
	// the "for" keyword.
	private StmtFrag ParseForStatement(FunctionInfo info, StringCollection labels)
		{
		LoopInfo loopInfo = gen.NewLoopInfo(curCGFuncInfo, tok.Prev().loc, labels);
		loops.Push(loopInfo);
		
		// HACK snewman 8/13/01: need to review this section against the
		// specific semantics for "for" statements, and especially for/in
		// statements, in section 12.6 of the ECMA spec.
		
		tok.MatchOp("(");
		
		bool isIn;			  // True for for/in, false otherwise
		StmtFrag init=null;   // Initializer; used for both types of loop
		ExprFrag cond=null;   // Condition; only used for non-in loops
		ExprFrag update=null; // Update step; only used for non-in loops
		ExprFrag inLHS=null;  // LHS expression where in loops put prop names
		ExprFrag inRHS=null;  // RHS object that in loops iterate over
		if (tok.TryMatchKeyword("var"))
			{
			string varName;
			SrcLoc varLoc;
			init = ParseVariableDeclaration(info, false, out varName, out varLoc);
			
			isIn = tok.TryMatchKeyword("in");
			if (isIn)
				inLHS = gen.IdentifierExpr( varLoc, varName, info,
											CloneStack(withs) );
			else
				{
				while (tok.TryMatchOp(","))
					init.Append(ParseVariableDeclaration( info, false, out varName,
														  out varLoc ));
				}
			
			}
		else
			{
			if (!tok.PeekOp(";"))
				{
				ExprFrag initExpr = ParseExpression(info, false, 99);
				isIn = tok.TryMatchKeyword("in");
				
				if (isIn)
					inLHS = initExpr;
				else
					init = gen.ExpressionStmt(initExpr);
				
				}
			else
				isIn = false;
			
			}
		
		if (isIn)
			inRHS = ParseExpression(info, true);
		else
			{
			tok.MatchOp(";");
			if (!tok.PeekOp(";"))
				cond = ParseExpression(info, true);
			
			tok.MatchOp(";");
			if (!tok.PeekOp(")"))
				update = ParseExpression(info, true);
			}
		
		tok.MatchOp(")");
		
		StmtFrag body = ParseStatement(info);
		
		LoopInfo temp = (LoopInfo) loops.Pop();
		Trace.Assert(temp == loopInfo);
		
		if (isIn)
			return gen.ForIn(loopInfo, init, inLHS, inRHS, body);
		else
			return gen.For(loopInfo, init, cond, update, body);
		
		} // ParseForStatement
Esempio n. 30
0
        private void validate(Element el)
        {
            C.Nn(el);

            switch (el)
            {
            case Declr d:
                validate(d.Ident);
                if (d.Exp != null)
                {
                    validate(d.Exp);
                }
                break;

            case Assign a:
                validate(a.Exp);
                validate(a.To);
                break;

            case Ident i:
                break;

            case Return r:
                if (LoopStack.Count != 0)
                {
                    LoopStack.Peek().HasReturn = true;
                }
                break;

            case FnApply fna:
                validate(fna.Fn);
                foreach (var fnaa in fna.Arguments)
                {
                    validate(fnaa);
                }
                break;

            case Fn f:
                foreach (var fp in f.Parameters)
                {
                    validate(fp);
                }
                validate(f.Sequence);
                break;

            case When w:
                validate(w.Test);
                validate(w.Then);
                if (w.Otherwise != null)
                {
                    validate(w.Otherwise);
                }
                break;

            case Loop l:
                var loopInfo = new LoopInfo();
                LoopStack.Push(loopInfo);
                validate(l.Body);
                if (!(loopInfo.HasBreak || loopInfo.HasReturn))
                {
                    throw prog.RemarkList.ContinueOrReturnRequiredInLoop(l);
                }
                LoopStack.Pop();
                break;

            case Continue cont:
                if (LoopStack.Count != 0)
                {
                    LoopStack.Peek().HasContinue = true;
                }
                else
                {
                    throw prog.RemarkList.ContinueOutsideLoop(cont);
                }
                break;

            case Break brk:
                if (LoopStack.Count != 0)
                {
                    LoopStack.Peek().HasBreak = true;
                }
                else
                {
                    throw prog.RemarkList.BreakOutsideLoop(brk);
                }
                break;

            case ArrConstructor ae:
                foreach (var aa in ae.Arguments)
                {
                    validate(aa);
                }
                break;

            case MemberAccess ma:
                validate(ma.Exp);
                validate(ma.Ident);
                break;

            case New n:
                foreach (var nb in n.Body)
                {
                    validate(nb);
                }
                break;

            case Value ve:
                break;

            case Sequence seq:
                foreach (var item in seq)
                {
                    validate(item);
                }
                break;

            case Toss ts:
                validate(ts.Exception);
                break;

            case Attempt att:
                validate(att.Body);
                if (att.Grab == null && att.AtLast == null)
                {
                    throw prog.RemarkList.AttemptMustHaveGrabOrAtLastOrBoth(att);
                }
                if (att.Grab != null)
                {
                    validate(att.Grab);
                }
                if (att.AtLast != null)
                {
                    validate(att.AtLast);
                }
                break;

            case Import imp:
                validate(imp.QualifiedIdent);
                break;

            case Spec spec:
                break;

            default:
                throw new NotSupportedException();
            }
        }
Esempio n. 31
0
 private int OffsetByPage(LoopInfo view, int offset)
 {
     return(offset + view.Left * PageDiv);
 }
        public IEnumerable <string> Transform(ForNode item)
        {
            _EncounteredOutputStyleBlock = true;
            if (!(ShouldRender && _EncounteredOutputStyleBlock))
            {
                yield break;
            }

            object?evalObj;

            if (item.Expression != null)
            {
                evalObj = Environment.Evaluation.EvaluateDynamic(item.Expression.Expression, Scopes);
            }
            else
            {
                evalObj = item.AlreadyEvaluatedObject;
            }

            Func <object?[], object?> loopFunction = args =>
            {
                if (args?.Length != 1)
                {
                    throw new NotImplementedException();
                }
                return(new ForNode(item.PrimaryBlock, item.ElseBlock, item.VariableNames,
                                   args[0], item.Filter, item.Recursive,
                                   item.EndParsingNode, item.WhiteSpaceControl));
            };

            var arr = CollectionEx.ToArray(evalObj) ?? Array.Empty <object>();

            if (item.Filter != null)
            {
                var filtered = new List <object?>();
                foreach (var arrItem in arr)
                {
                    var unpacked = ReflectionHelpers.Unpack(arrItem, item.VariableNames.Length);
                    Scopes.Push($"ForNode | Filter: {item.Filter} Item: {arrItem}");
                    for (var i = 0; i < unpacked.Length; ++i)
                    {
                        Scopes.Current.DefineAndSetVariable(item.VariableNames[i], unpacked[i]);
                    }
                    var result = Environment.Evaluation.EvaluateDynamic(item.Filter.Expression, Scopes);
                    Scopes.Pop($"ForNode | Filter: {item.Filter} Item: {arrItem}");
                    if (TypeCoercion.GetTruthy(result))
                    {
                        filtered.Add(arrItem);
                    }
                }
                arr = filtered.ToArray();
            }

            if (arr.Length == 0 && item.ElseBlock != null)
            {
                foreach (var output in item.ElseBlock.Transform(this))
                {
                    yield return(output);
                }
                yield break;
            }


            var depth = 0;

            if (Scopes.Current.TryGetVariable <LoopInfo>("loop", out var previousLoopInfo) && previousLoopInfo != null)
            {
                depth = previousLoopInfo.depth0 + 1;
            }

            var loopInfo = new LoopInfo(arr, loopFunction, depth);

            for (var index = 0; index < arr.Length; ++index)
            {
                loopInfo.index0 = index;
                var arrItem  = arr[index];
                var unpacked = ReflectionHelpers.Unpack(arrItem, item.VariableNames.Length);

                Scopes.Push($"ForNode: {item.Expression} Item: {arrItem}");
                for (var i = 0; i < unpacked.Length; ++i)
                {
                    Scopes.Current.DefineAndSetVariable(item.VariableNames[i], unpacked[i]);
                }
                Scopes.Current.DefineAndSetVariable("loop", loopInfo);
                foreach (var output in item.PrimaryBlock.Transform(this))
                {
                    yield return(output);
                }
                Scopes.Pop($"ForNode: {item.Expression} Item: {arrItem}");
            }
            yield break;
        }
Esempio n. 33
0
 private int GetPageOffset(LoopInfo view, int index)
 {
     return(index - view.Left * PageDiv);
 }
Esempio n. 34
0
        /// <summary>
        /// Retrieves the lines in a text file, one at a time.
        /// </summary>
        /// <param name="input">The name of the text file whose contents will be read by the loop.</param>
        /// <param name="output">The optional name of the file to be kept open for the duration of the loop.</param>
        /// <returns></returns>
        public static IEnumerable LoopRead(string input, string output)
        {
            if (!File.Exists(input))
                yield break;

            StreamWriter writer = null;

            if (output == "*")
            {
                writer = new StreamWriter(Console.OpenStandardOutput());
            }
            else if (!string.IsNullOrEmpty(output))
            {
                bool binary = output[0] == '*';

                if (binary)
                    output = output.Substring(1);

                if (output.Length == 0 || !File.Exists(output))
                    yield break;

                writer = new StreamWriter(File.OpenWrite(output));

                if (binary)
                    writer.NewLine = "\n";
            }

            var info = new LoopInfo { type = LoopType.File };
            loops.Push(info);
            
            var reader = File.OpenText(input);
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                if (writer != null)
                    writer.WriteLine(line);

                info.result = line;
                info.index++;

                yield return line;
            }

            loops.Pop();
        }
Esempio n. 35
0
		} // IfThenElse
	
	
	// Return a do...while statement.
	public StmtFrag DoWhile( LoopInfo loopInfo, StmtFrag body,
							 ExprFrag condition )
		{
		CSharpLoopInfo csLoopInfo = (CSharpLoopInfo)loopInfo;
		CSharpStmtFrag frag = new CSharpStmtFrag(csLoopInfo.loc);
		
		CSharpExprFrag csCondition = (CSharpExprFrag)condition;
		frag.Append("do");
		((CSharpStmtFrag)body).Append("continueTarget_{0}:", csLoopInfo.index + 1);
		frag.AppendIndentedBody(body);
		frag.Append("while (Support.BoolTest(" + csCondition.GenerateRHS() + "))");
		frag.Append("breakTarget_{0}: {1}", csLoopInfo.index + 1, "{}");
		
		return frag;
		} // DoWhile
Esempio n. 36
0
        /// <summary>
        /// Retrieves the specified files or folders, one at a time.
        /// </summary>
        /// <param name="pattern">The name of a single file or folder, or a wildcard pattern.</param>
        /// <param name="folders">One of the following digits, or blank to use the default:
        /// <list>
        /// <item><code>1</code> (default) folders are not retrieved (only files);</item>
        /// <item><code>1</code> all files and folders that match the wildcard pattern are retrieved;</item>
        /// <item><code>2</code> only folders are retrieved (no files).</item>
        /// </list>
        /// </param>
        /// <param name="recurse"><code>1</code> to recurse into subfolders, <code>0</code> otherwise.</param>
        /// <returns></returns>
        public static IEnumerable LoopFile(string pattern, int folders, bool recurse)
        {
            var info = new LoopInfo { type = LoopType.Directory };
            loops.Push(info);

            string[] list = Directory.GetFiles(pattern, string.Empty, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            foreach (var file in list)
            {
                info.result = file;
                info.index++;
                yield return file;
            }

            loops.Pop();
        }
Esempio n. 37
0
        /// <summary>
        /// Retrieves substrings (fields) from a string, one at a time.
        /// </summary>
        /// <param name="input">The string to parse.</param>
        /// <param name="delimiters">One of the following:
        /// <list>
        /// <item>the word <code>CSV</code> to parse in comma seperated value format;</item>
        /// <item>a sequence of characters to treat as delimiters;</item>
        /// <item>blank to parse each character of the string.</item>
        /// </list>
        /// </param>
        /// <param name="omit">An optional list of characters (case sensitive) to exclude from the beginning and end of each substring.</param>
        /// <returns></returns>
        public static IEnumerable LoopParse(string input, string delimiters, string omit)
        {
            var info = new LoopInfo {
                type = LoopType.Parse
            };

            loops.Push(info);

            if (delimiters.ToLowerInvariant() == Keyword_CSV)
            {
                var  reader = new StringReader(input);
                var  part = new StringBuilder();
                bool str = false, next = false;

                while (true)
                {
                    int current = reader.Read();
                    if (current == -1)
                    {
                        goto collect;
                    }

                    const char tokenStr = '"', tokenDelim = ',';

                    var sym = (char)current;

                    switch (sym)
                    {
                    case tokenStr:
                        if (str)
                        {
                            if ((char)reader.Peek() == tokenStr)
                            {
                                part.Append(tokenStr);
                                reader.Read();
                            }
                            else
                            {
                                str = false;
                            }
                        }
                        else
                        {
                            if (next)
                            {
                                part.Append(tokenStr);
                            }
                            else
                            {
                                str = true;
                            }
                        }
                        break;

                    case tokenDelim:
                        if (str)
                        {
                            goto default;
                        }
                        goto collect;     // sorry

                    default:
                        next = true;
                        part.Append(sym);
                        break;
                    }

                    continue;

collect:
                    next = false;
                    string result = part.ToString();
                    part.Length = 0;
                    info.result = result;
                    info.index++;
                    yield return(result);

                    if (current == -1)
                    {
                        break;
                    }
                }
            }
            else
            {
                string[] parts;
                var      remove = omit.ToCharArray();

                if (string.IsNullOrEmpty(delimiters))
                {
                    var chars = input.ToCharArray();
                    parts = new string[chars.Length];
                    for (int i = 0; i < chars.Length; i++)
                    {
                        parts[i] = chars[i].ToString();
                    }
                }
                else
                {
                    parts = input.Split(delimiters.ToCharArray(), StringSplitOptions.None);
                }

                foreach (var part in parts)
                {
                    var result = part.Trim(remove);
                    if (string.IsNullOrEmpty(result))
                    {
                        continue;
                    }
                    info.result = result;
                    info.index++;
                    yield return(result);
                }
            }

            loops.Pop();
        }
Esempio n. 38
0
		} // WhileDo
	
	
	// Return a for statement.  init is the loop initializer, cond is the
	// loop control expression, and step is the loop increment expression.
	// Any or all of init, cond, and step can be null.
	public StmtFrag For( LoopInfo loopInfo, StmtFrag init,
						 ExprFrag cond, ExprFrag step, StmtFrag body )
		{
		CSharpLoopInfo csLoopInfo = (CSharpLoopInfo)loopInfo;
		CSharpStmtFrag frag = new CSharpStmtFrag(csLoopInfo.loc);
		
		frag.Append(init);
		
		CSharpExprFrag csCondition = (CSharpExprFrag)cond;
		frag.Append("while (Support.BoolTest(" + csCondition.GenerateRHS() + "))");
		((CSharpStmtFrag)body).Append("continueTarget_{0}:", csLoopInfo.index + 1);
		((CSharpStmtFrag)body).Append(ExpressionStmt(step));
		frag.AppendIndentedBody(body);
		frag.Append("breakTarget_{0}: {1}", csLoopInfo.index + 1, "{}");
		
		return frag;
		} // For