System.Collections.Generic.Stack.Pop()

Here are the examples of the csharp api System.Collections.Generic.Stack.Pop() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4370 Examples 7

19 Source : StackOpHelper.cs
with zlib License
from 0x0ade

public static T Pop<T>()
            => (T) Current.Pop();

19 Source : InterceptorContext.cs
with MIT License
from 1100100

public async Task<IServiceResult> Next()
        {
            var interceptor = (IInterceptor)ServiceProvider.GetRequiredService(Interceptors.Pop());
            return await interceptor.Intercept(this);
        }

19 Source : ExpressionResovle.cs
with Apache License 2.0
from 1448376744

public object VisitConstantValue(Expression expression)
        {
            var names = new Stack<string>();
            var exps = new Stack<Expression>();
            var mifs = new Stack<MemberInfo>();
            if (expression is ConstantExpression constant)
                return constant.Value;
            else if (expression is MemberExpression)
            {
                var temp = expression;
                object value = null;
                while (temp is MemberExpression memberExpression)
                {
                    names.Push(memberExpression.Member.Name);
                    exps.Push(memberExpression.Expression);
                    mifs.Push(memberExpression.Member);
                    temp = memberExpression.Expression;
                }
                foreach (var name in names)
                {
                    var exp = exps.Pop();
                    var mif = mifs.Pop();
                    if (exp is ConstantExpression cex)
                        value = cex.Value;
                    if (mif is PropertyInfo pif)
                        value = pif.GetValue(value);
                    else if (mif is FieldInfo fif)
                        value = fif.GetValue(value);
                }
                return value;
            }
            else
            {
                return Expression.Lambda(expression).Compile().DynamicInvoke();
            }
        }

19 Source : BssmapAnalysisStack.cs
with MIT License
from 1996v

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void PopToken()
        {
            _tokens.Pop();
        }

19 Source : TypeUtils.cs
with MIT License
from 1996v

public static List<MemberInfo> GetAllInterfaceMembers(this Type type)
        {
            Stack<Type> pending = new Stack<Type>();
            pending.Push(type);
            List<MemberInfo> ret = new List<MemberInfo>();
            while (pending.Count > 0)
            {
                Type current = pending.Pop();

                ret.AddRange(current.GetMembers());

                if (current.BaseType != null)
                {
                    pending.Push(current.BaseType);
                }

                foreach (Type x in current.GetInterfaces())
                {
                    pending.Push(x);
                }
            }
            return ret;
        }

19 Source : MyStringExtendTest.cs
with MIT License
from 1996v

public static int PopMyStringSize(this ContextDataSlots context)
        {
            context.TryGetNamedDataSlot("_mystring", out object stackVal);
            var stack = (Stack<int>)stackVal;
            return stack.Pop();
        }

19 Source : TemplateEngin.cs
with MIT License
from 2881099

private static string codeTreeEnd(Stack<string> codeTree, string tag) {
			string ret = string.Empty;
			Stack<int> pop = new Stack<int>();
			foreach (string ct in codeTree) {
				if (ct == "import" ||
					ct == "include") {
					pop.Push(1);
				} else if (ct == tag) {
					pop.Push(2);
					break;
				} else {
					if (string.IsNullOrEmpty(tag) == false) pop.Clear();
					break;
				}
			}
			if (pop.Count == 0 && string.IsNullOrEmpty(tag) == false)
				return string.Concat("语法错误,{", tag, "} {/", tag, "} 并没配对");
			while (pop.Count > 0 && pop.Pop() > 0) codeTree.Pop();
			return ret;
		}

19 Source : TemplateEngin.cs
with MIT License
from 2881099

private static ITemplateOutput Parser(string tplcode, string[] usings, IDictionary options) {
			int view = Interlocked.Increment(ref _view);
			StringBuilder sb = new StringBuilder();
			IDictionary options_copy = new Hashtable();
			foreach (DictionaryEntry options_de in options) options_copy[options_de.Key] = options_de.Value;
			sb.AppendFormat(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;{1}

//namespace TplDynamicCodeGenerate {{
	public clreplaced TplDynamicCodeGenerate_view{0} : FreeSql.Template.TemplateEngin.ITemplateOutput {{
		public FreeSql.Template.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Template.TemplateEngin tEmPlAtEsEnDeR) {{
			FreeSql.Template.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ? 
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() }} :
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() }};
			Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
			Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
			int[] TPL__blocks_stack_peek;
			List<IDictionary> TPL__forc = new List<IDictionary>();
			Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {{
				IDictionary nEwoPtIoNs = new Hashtable();
				foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
					nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
				foreach (IDictionary TPL__forc_dIc in TPL__forc)
					foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
						nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
				return nEwoPtIoNs;
			}});
			FreeSql.Template.TemplateEngin.TemplateIf tPlIf = delegate(object exp) {{
				if (exp is bool) return (bool)exp;
				if (exp == null) return false;
				if (exp is int && (int)exp == 0) return false;
				if (exp is string && (string)exp == string.Empty) return false;
				if (exp is long && (long)exp == 0) return false;
				if (exp is short && (short)exp == 0) return false;
				if (exp is byte && (byte)exp == 0) return false;
				if (exp is double && (double)exp == 0) return false;
				if (exp is float && (float)exp == 0) return false;
				if (exp is decimal && (decimal)exp == 0) return false;
				return true;
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint print = delegate(object[] pArMs) {{
				if (pArMs == null || pArMs.Length == 0) return;
				foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint Print = print;", view, usings?.Any() == true ? $"\r\nusing {string.Join(";\r\nusing ", usings)};" : "");

			#region {miss}...{/miss}块内容将不被解析
			string[] tmp_content_arr = _reg_miss.Split(tplcode);
			if (tmp_content_arr.Length > 1) {
				sb.AppendFormat(@"
			string[] TPL__MISS = new string[{0}];", Math.Ceiling(1.0 * (tmp_content_arr.Length - 1) / 2));
				int miss_len = -1;
				for (int a = 1; a < tmp_content_arr.Length; a += 2) {
					sb.Append(string.Concat(@"
			TPL__MISS[", ++miss_len, @"] = """, Utils.GetConstString(tmp_content_arr[a]), @""";"));
					tmp_content_arr[a] = string.Concat("{#TPL__MISS[", miss_len, "]}");
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			#region 扩展语法如 <div @if="表达式"></div>
			tplcode = htmlSyntax(tplcode, 3); //<div @if="c#表达式" @for="index 1,100"></div>
											  //处理 {% %} 块 c#代码
			tmp_content_arr = _reg_code.Split(tplcode);
			if (tmp_content_arr.Length == 1) {
				tplcode = Utils.GetConstString(tplcode)
					.Replace("{%", "{$TEMPLATE__CODE}")
					.Replace("%}", "{/$TEMPLATE__CODE}");
			} else {
				tmp_content_arr[0] = Utils.GetConstString(tmp_content_arr[0]);
				for (int a = 1; a < tmp_content_arr.Length; a += 4) {
					tmp_content_arr[a] = "{$TEMPLATE__CODE}";
					tmp_content_arr[a + 2] = "{/$TEMPLATE__CODE}";
					tmp_content_arr[a + 3] = Utils.GetConstString(tmp_content_arr[a + 3]);
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			sb.Append(@"
			tOuTpUt.Append(""");

			string error = null;
			int tpl_tmpid = 0;
			int forc_i = 0;
			string extends = null;
			Stack<string> codeTree = new Stack<string>();
			Stack<string> forEndRepl = new Stack<string>();
			sb.Append(_reg.Replace(tplcode, delegate (Match m) {
				string _0 = m.Groups[0].Value;
				if (!string.IsNullOrEmpty(error)) return _0;

				string _1 = m.Groups[1].Value.Trim(' ', '\t');
				string _2 = m.Groups[2].Value
					.Replace("\\\\", "\\")
					.Replace("\\\"", "\"");
				_2 = Utils.ReplaceSingleQuote(_2);

				switch (_1) {
					#region $TEMPLATE__CODE--------------------------------------------------
					case "$TEMPLATE__CODE":
						codeTree.Push(_1);
						return @""");
";
					case "/$TEMPLATE__CODE":
						string pop = codeTree.Pop();
						if (pop != "$TEMPLATE__CODE") {
							codeTree.Push(pop);
							error = "编译出错,{% 与 %} 并没有配对";
							return _0;
						}
						return @"
			tOuTpUt.Append(""";
					#endregion
					case "include":
						return string.Format(@""");
tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
			tOuTpUt.Append(""", _2);
					case "import":
						return _0;
					case "module":
						return _0;
					case "/module":
						return _0;
					case "extends":
						//{extends ../inc/layout.html}
						if (string.IsNullOrEmpty(extends) == false) return _0;
						extends = _2;
						return string.Empty;
					case "block":
						codeTree.Push("block");
						return string.Format(@""");
TPL__blocks_stack_peek = new int[] {{ tOuTpUt.Length, 0 }};
TPL__blocks_stack.Push(TPL__blocks_stack_peek);
TPL__blocks.Add(""{0}"", TPL__blocks_stack_peek);
tOuTpUt.Append(""", _2.Trim(' ', '\t'));
					case "/block":
						codeTreeEnd(codeTree, "block");
						return @""");
TPL__blocks_stack_peek = TPL__blocks_stack.Pop();
TPL__blocks_stack_peek[1] = tOuTpUt.Length - TPL__blocks_stack_peek[0];
tOuTpUt.Append(""";

					#region ##---------------------------------------------------------
					case "#":
						if (_2[0] == '#')
							return string.Format(@""");
			try {{ Print({0}); }} catch {{ }}
			tOuTpUt.Append(""", _2.Substring(1));
						return string.Format(@""");
			Print({0});
			tOuTpUt.Append(""", _2);
					#endregion
					#region for--------------------------------------------------------
					case "for":
						forc_i++;
						int cur_tpl_tmpid = tpl_tmpid;
						string sb_endRepl = string.Empty;
						StringBuilder sbfor = new StringBuilder();
						sbfor.Append(@""");");
						Match mfor = _reg_forin.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{1} != null)
	foreach (var TPL__tmp{0} in TPL__tmp{1}) {{", ++tpl_tmpid, cur_tpl_tmpid + 2);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor2, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = TPL__tmp{2};
		{0} = TPL__tmp{2};
		tOuTpUt.Append(""", mfor1, cur_tpl_tmpid + 1, tpl_tmpid);
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_foron.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							string mfor3 = mfor.Groups[3].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[4].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							if (!string.IsNullOrEmpty(mfor3)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor3, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor3, tpl_tmpid));
								if (options_copy.Contains(mfor3) == false) options_copy[mfor3] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{2} != null)
	foreach (DictionaryEntry TPL__tmp{1} in TPL__tmp{2}) {{
		{0} = TPL__tmp{1}.Key;
		TPL__tmp{3}[""{0}""] = {0};", mfor1, ++tpl_tmpid, cur_tpl_tmpid + 2, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		{0} = TPL__tmp{1}.Value;
		TPL__tmp{2}[""{0}""] = {0};", mfor2, tpl_tmpid, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor3))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor3, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		tOuTpUt.Append(""");
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_forab.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {5};
	{5} = {3} - 1;
	if ({5} == null) {5} = 0;
	var TPL__tmp{2} = {4} + 1;
	while (++{5} < TPL__tmp{2}) {{
		TPL__tmp{0}[""{5}""] = {5};
		tOuTpUt.Append(""", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[2].Value, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 1));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						return _0;
					case "/for":
						if (--forc_i < 0) return _0;
						codeTreeEnd(codeTree, "for");
						return string.Format(@""");
	}}{0}
	TPL__forc.RemoveAt(TPL__forc.Count - 1);
//}})();
			tOuTpUt.Append(""", forEndRepl.Pop());
					#endregion
					#region if---------------------------------------------------------
					case "if":
						codeTree.Push("if");
						return string.Format(@""");
			if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "elseif":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return string.Format(@""");
			}} else if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "else":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return @""");
			} else {
			tOuTpUt.Append(""";
					case "/if":
						codeTreeEnd(codeTree, "if");
						return @""");
			}
			tOuTpUt.Append(""";
						#endregion
				}
				return _0;
			}));

			sb.Append(@""");");
			if (string.IsNullOrEmpty(extends) == false) {
				sb.AppendFormat(@"
FreeSql.Template.TemplateEngin.TemplateReturnInfo eXtEnDs_ReT = tEmPlAtEsEnDeR.RenderFile2(null, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
string rTn_Sb_string = rTn.Sb.ToString();
foreach(string eXtEnDs_ReT_blocks_key in eXtEnDs_ReT.Blocks.Keys) {{
	if (rTn.Blocks.ContainsKey(eXtEnDs_ReT_blocks_key)) {{
		int[] eXtEnDs_ReT_blocks_value = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Remove(eXtEnDs_ReT_blocks_value[0], eXtEnDs_ReT_blocks_value[1]);
		int[] rTn_blocks_value = rTn.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Insert(eXtEnDs_ReT_blocks_value[0], rTn_Sb_string.Substring(rTn_blocks_value[0], rTn_blocks_value[1]));
		foreach(string eXtEnDs_ReT_blocks_keyb in eXtEnDs_ReT.Blocks.Keys) {{
			if (eXtEnDs_ReT_blocks_keyb == eXtEnDs_ReT_blocks_key) continue;
			int[] eXtEnDs_ReT_blocks_valueb = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_keyb];
			if (eXtEnDs_ReT_blocks_valueb[0] >= eXtEnDs_ReT_blocks_value[0])
				eXtEnDs_ReT_blocks_valueb[0] = eXtEnDs_ReT_blocks_valueb[0] - eXtEnDs_ReT_blocks_value[1] + rTn_blocks_value[1];
		}}
		eXtEnDs_ReT_blocks_value[1] = rTn_blocks_value[1];
	}}
}}
return eXtEnDs_ReT;
", extends);
			} else {
				sb.Append(@"
return rTn;");
			}
			sb.Append(@"
		}
	}
//}
");
			var str = "FreeSql.Template.TemplateEngin.TemplatePrint Print = print;";
			int dim_idx = sb.ToString().IndexOf(str) + str.Length;
			foreach (string dic_name in options_copy.Keys) {
				sb.Insert(dim_idx, string.Format(@"
			dynamic {0} = oPtIoNs[""{0}""];", dic_name));
			}
			//Console.WriteLine(sb.ToString());
			return Complie(sb.ToString(), @"TplDynamicCodeGenerate_view" + view);
		}

19 Source : RuntimeGizmoManager.cs
with MIT License
from 39M

public void PopMatrix() {
      matrix = _matrixStack.Pop();
    }

19 Source : JsonReader.cs
with MIT License
from 404Lcc

public bool Read ()
        {
            if (end_of_input)
                return false;

            if (end_of_json) {
                end_of_json = false;
                automaton_stack.Clear ();
                automaton_stack.Push ((int) ParserToken.End);
                automaton_stack.Push ((int) ParserToken.Text);
            }

            parser_in_string = false;
            parser_return    = false;

            token       = JsonToken.None;
            token_value = null;

            if (! read_started) {
                read_started = true;

                if (! ReadToken ())
                    return false;
            }


            int[] entry_symbols;

            while (true) {
                if (parser_return) {
                    if (automaton_stack.Peek () == (int) ParserToken.End)
                        end_of_json = true;

                    return true;
                }

                current_symbol = automaton_stack.Pop ();

                ProcessSymbol ();

                if (current_symbol == current_input) {
                    if (! ReadToken ()) {
                        if (automaton_stack.Peek () != (int) ParserToken.End)
                            throw new JsonException (
                                "Input doesn't evaluate to proper JSON text");

                        if (parser_return)
                            return true;

                        return false;
                    }

                    continue;
                }

                try {

                    entry_symbols =
                        parse_table[current_symbol][current_input];

                } catch (KeyNotFoundException e) {
                    throw new JsonException ((ParserToken) current_input, e);
                }

                if (entry_symbols[0] == (int) ParserToken.Epsilon)
                    continue;

                for (int i = entry_symbols.Length - 1; i >= 0; i--)
                    automaton_stack.Push (entry_symbols[i]);
            }
        }

19 Source : JsonWriter.cs
with MIT License
from 404Lcc

public void WriteArrayEnd ()
        {
            DoValidation (Condition.InArray);
            PutNewline (false);

            ctx_stack.Pop ();
            if (ctx_stack.Count == 1)
                has_reached_end = true;
            else {
                context = ctx_stack.Peek ();
                context.ExpectingValue = false;
            }

            Unindent ();
            Put ("]");
        }

19 Source : JsonWriter.cs
with MIT License
from 404Lcc

public void WriteObjectEnd ()
        {
            DoValidation (Condition.InObject);
            PutNewline (false);

            ctx_stack.Pop ();
            if (ctx_stack.Count == 1)
                has_reached_end = true;
            else {
                context = ctx_stack.Peek ();
                context.ExpectingValue = false;
            }

            Unindent ();
            Put ("}");
        }

19 Source : JSONParser.cs
with MIT License
from 5minlab

static List<string> Split(string json) {
            List<string> splitArray = splitArrayPool.Count > 0 ? splitArrayPool.Pop() : new List<string>();
            splitArray.Clear();
            int parseDepth = 0;
            stringBuilder.Length = 0;
            for (int i = 1; i < json.Length - 1; i++) {
                switch (json[i]) {
                    case '[':
                    case '{':
                        parseDepth++;
                        break;
                    case ']':
                    case '}':
                        parseDepth--;
                        break;
                    case '\"':
                        i = AppendUntilStringEnd(true, i, json);
                        continue;
                    case ',':
                    case ':':
                        if (parseDepth == 0) {
                            splitArray.Add(stringBuilder.ToString());
                            stringBuilder.Length = 0;
                            continue;
                        }
                        break;
                }

                stringBuilder.Append(json[i]);
            }

            splitArray.Add(stringBuilder.ToString());

            return splitArray;
        }

19 Source : SimpleJSON.cs
with MIT License
from 71

public static JSONNode Parse(string aJSON)
        {
            Stack<JSONNode> stack = new Stack<JSONNode>();
            JSONNode ctx = null;
            int i = 0;
            StringBuilder Token = new StringBuilder();
            string TokenName = "";
            bool QuoteMode = false;
            bool TokenIsQuoted = false;
            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                    case '{':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        stack.Push(new JSONObject());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        break;

                    case '[':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }

                        stack.Push(new JSONArray());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        break;

                    case '}':
                    case ']':
                        if (QuoteMode)
                        {

                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (stack.Count == 0)
                            throw new Exception("JSON Parse: Too many closing brackets");

                        stack.Pop();
                        if (Token.Length > 0 || TokenIsQuoted)
                            ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
                        TokenIsQuoted = false;
                        TokenName = "";
                        Token.Length = 0;
                        if (stack.Count > 0)
                            ctx = stack.Peek();
                        break;

                    case ':':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        TokenName = Token.ToString();
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '"':
                        QuoteMode ^= true;
                        TokenIsQuoted |= QuoteMode;
                        break;

                    case ',':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (Token.Length > 0 || TokenIsQuoted)
                            ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
                        TokenIsQuoted = false;
                        TokenName = "";
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '\r':
                    case '\n':
                        break;

                    case ' ':
                    case '\t':
                        if (QuoteMode)
                            Token.Append(aJSON[i]);
                        break;

                    case '\\':
                        ++i;
                        if (QuoteMode)
                        {
                            char C = aJSON[i];
                            switch (C)
                            {
                                case 't':
                                    Token.Append('\t');
                                    break;
                                case 'r':
                                    Token.Append('\r');
                                    break;
                                case 'n':
                                    Token.Append('\n');
                                    break;
                                case 'b':
                                    Token.Append('\b');
                                    break;
                                case 'f':
                                    Token.Append('\f');
                                    break;
                                case 'u':
                                    {
                                        string s = aJSON.Substring(i + 1, 4);
                                        Token.Append((char)int.Parse(
                                            s,
                                            System.Globalization.NumberStyles.AllowHexSpecifier));
                                        i += 4;
                                        break;
                                    }
                                default:
                                    Token.Append(C);
                                    break;
                            }
                        }
                        break;

                    default:
                        Token.Append(aJSON[i]);
                        break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            if (ctx == null)
                return ParseElement(Token.ToString(), TokenIsQuoted);
            return ctx;
        }

19 Source : SimpleJSON.cs
with MIT License
from 734843327

public static JSONNode Parse(string aJSON)
        {
            Stack<JSONNode> stack = new Stack<JSONNode>();
            JSONNode ctx = null;
            int i = 0;
            string Token = "";
            string TokenName = "";
            bool QuoteMode = false;
            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                    case '{':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        stack.Push(new JSONClreplaced());
                        if (ctx != null)
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(stack.Peek());
                            else if (TokenName != "")
                                ctx.Add(TokenName,stack.Peek());
                        }
                        TokenName = "";
                        Token = "";
                        ctx = stack.Peek();
                    break;

                    case '[':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }

                        stack.Push(new JSONArray());
                        if (ctx != null)
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(stack.Peek());
                            else if (TokenName != "")
                                ctx.Add(TokenName,stack.Peek());
                        }
                        TokenName = "";
                        Token = "";
                        ctx = stack.Peek();
                    break;

                    case '}':
                    case ']':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        if (stack.Count == 0)
                            throw new Exception("JSON Parse: Too many closing brackets");

                        stack.Pop();
                        if (Token != "")
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(Token);
                            else if (TokenName != "")
                                ctx.Add(TokenName,Token);
                        }
                        TokenName = "";
                        Token = "";
                        if (stack.Count>0)
                            ctx = stack.Peek();
                    break;

                    case ':':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        TokenName = Token;
                        Token = "";
                    break;

                    case '"':
                        QuoteMode ^= true;
                    break;

                    case ',':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        if (Token != "")
                        {
                            if (ctx is JSONArray)
                                ctx.Add(Token);
                            else if (TokenName != "")
                                ctx.Add(TokenName, Token);
                        }
                        TokenName = "";
                        Token = "";
                    break;

                    case '\r':
                    case '\n':
                    break;

                    case ' ':
                    case '\t':
                        if (QuoteMode)
                            Token += aJSON[i];
                    break;

                    case '\\':
                        ++i;
                        if (QuoteMode)
                        {
                            char C = aJSON[i];
                            switch (C)
                            {
                                case 't' : Token += '\t'; break;
                                case 'r' : Token += '\r'; break;
                                case 'n' : Token += '\n'; break;
                                case 'b' : Token += '\b'; break;
                                case 'f' : Token += '\f'; break;
                                case 'u':
                                {
                                    string s = aJSON.Substring(i+1,4);
                                    Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
                                    i += 4;
                                    break;
                                }
                                default  : Token += C; break;
                            }
                        }
                    break;

                    default:
                        Token += aJSON[i];
                    break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            return ctx;
        }

19 Source : DownloadManager.cs
with GNU General Public License v3.0
from 9vult

public void DownloadNext()
        {
            if (dlQueue.Count <= 0)
            {
                // reset
                totalDownloads = 0;
                completionPercentage = 0.0;
                return;
            }

            IDownload d = dlQueue.Pop();
            d.DownloadCompleted += new DownloadCompletedEventHandler(DLCompletedCallback);
            d.StartDownloading();

            currentDownloadName = d.GetChapterName();
        }

19 Source : MyObjectPool.cs
with Apache License 2.0
from A7ocin

public T Get()
        {
            T t;
            if (this.m_Stack.Count == 0)
            {
                t = ((default(T) == null) ? Activator.CreateInstance<T>() : default(T));
                this.countAll++;
            }
            else
            {
                t = this.m_Stack.Pop();
            }
            if (this.m_ActionOnGet != null)
            {
                this.m_ActionOnGet(t);
            }
            return t;
        }

19 Source : HighlightedLine.cs
with MIT License
from Abdesol

public void MergeWith(HighlightedLine additionalLine)
		{
			if (additionalLine == null)
				return;
#if DEBUG
			ValidateInvariants();
			additionalLine.ValidateInvariants();
#endif

			int pos = 0;
			Stack<int> activeSectionEndOffsets = new Stack<int>();
			int lineEndOffset = this.DoreplacedentLine.EndOffset;
			activeSectionEndOffsets.Push(lineEndOffset);
			foreach (HighlightedSection newSection in additionalLine.Sections) {
				int newSectionStart = newSection.Offset;
				// Track the existing sections using the stack, up to the point where
				// we need to insert the first part of the newSection
				while (pos < this.Sections.Count) {
					HighlightedSection s = this.Sections[pos];
					if (newSection.Offset < s.Offset)
						break;
					while (s.Offset > activeSectionEndOffsets.Peek()) {
						activeSectionEndOffsets.Pop();
					}
					activeSectionEndOffsets.Push(s.Offset + s.Length);
					pos++;
				}
				// Now insert the new section
				// Create a copy of the stack so that we can track the sections we traverse
				// during the insertion process:
				Stack<int> insertionStack = new Stack<int>(activeSectionEndOffsets.Reverse());
				// The stack enumerator reverses the order of the elements, so we call Reverse() to restore
				// the original order.
				int i;
				for (i = pos; i < this.Sections.Count; i++) {
					HighlightedSection s = this.Sections[i];
					if (newSection.Offset + newSection.Length <= s.Offset)
						break;
					// Insert a segment in front of s:
					Insert(ref i, ref newSectionStart, s.Offset, newSection.Color, insertionStack);

					while (s.Offset > insertionStack.Peek()) {
						insertionStack.Pop();
					}
					insertionStack.Push(s.Offset + s.Length);
				}
				Insert(ref i, ref newSectionStart, newSection.Offset + newSection.Length, newSection.Color, insertionStack);
			}

#if DEBUG
			ValidateInvariants();
#endif
		}

19 Source : HighlightedLine.cs
with MIT License
from Abdesol

void Insert(ref int pos, ref int newSectionStart, int insertionEndPos, HighlightingColor color, Stack<int> insertionStack)
		{
			if (newSectionStart >= insertionEndPos) {
				// nothing to insert here
				return;
			}

			while (insertionStack.Peek() <= newSectionStart) {
				insertionStack.Pop();
			}
			while (insertionStack.Peek() < insertionEndPos) {
				int end = insertionStack.Pop();
				// insert the portion from newSectionStart to end
				if (end > newSectionStart) {
					this.Sections.Insert(pos++, new HighlightedSection {
						Offset = newSectionStart,
						Length = end - newSectionStart,
						Color = color
					});
					newSectionStart = end;
				}
			}
			if (insertionEndPos > newSectionStart) {
				this.Sections.Insert(pos++, new HighlightedSection {
					Offset = newSectionStart,
					Length = insertionEndPos - newSectionStart,
					Color = color
				});
				newSectionStart = insertionEndPos;
			}
		}

19 Source : HighlightingEngine.cs
with MIT License
from Abdesol

void HighlightLineInternal()
		{
			position = 0;
			ResetColorStack();
			HighlightingRuleSet currentRuleSet = this.CurrentRuleSet;
			Stack<Match[]> storedMatchArrays = new Stack<Match[]>();
			Match[] matches = AllocateMatchArray(currentRuleSet.Spans.Count);
			Match endSpanMatch = null;

			while (true) {
				for (int i = 0; i < matches.Length; i++) {
					if (matches[i] == null || (matches[i].Success && matches[i].Index < position))
						matches[i] = currentRuleSet.Spans[i].StartExpression.Match(lineText, position);
				}
				if (endSpanMatch == null && !spanStack.IsEmpty)
					endSpanMatch = spanStack.Peek().EndExpression.Match(lineText, position);

				Match firstMatch = Minimum(matches, endSpanMatch);
				if (firstMatch == null)
					break;

				HighlightNonSpans(firstMatch.Index);

				Debug.replacedert(position == firstMatch.Index);

				if (firstMatch == endSpanMatch) {
					HighlightingSpan poppedSpan = spanStack.Peek();
					if (!poppedSpan.SpanColorIncludesEnd)
						PopColor(); // pop SpanColor
					PushColor(poppedSpan.EndColor);
					position = firstMatch.Index + firstMatch.Length;
					PopColor(); // pop EndColor
					if (poppedSpan.SpanColorIncludesEnd)
						PopColor(); // pop SpanColor
					spanStack = spanStack.Pop();
					currentRuleSet = this.CurrentRuleSet;
					//FreeMatchArray(matches);
					if (storedMatchArrays.Count > 0) {
						matches = storedMatchArrays.Pop();
						int index = currentRuleSet.Spans.IndexOf(poppedSpan);
						Debug.replacedert(index >= 0 && index < matches.Length);
						if (matches[index].Index == position) {
							throw new InvalidOperationException(
								"A highlighting span matched 0 characters, which would cause an endless loop.\n" +
								"Change the highlighting definition so that either the start or the end regex matches at least one character.\n" +
								"Start regex: " + poppedSpan.StartExpression + "\n" +
								"End regex: " + poppedSpan.EndExpression);
						}
					} else {
						matches = AllocateMatchArray(currentRuleSet.Spans.Count);
					}
				} else {
					int index = Array.IndexOf(matches, firstMatch);
					Debug.replacedert(index >= 0);
					HighlightingSpan newSpan = currentRuleSet.Spans[index];
					spanStack = spanStack.Push(newSpan);
					currentRuleSet = this.CurrentRuleSet;
					storedMatchArrays.Push(matches);
					matches = AllocateMatchArray(currentRuleSet.Spans.Count);
					if (newSpan.SpanColorIncludesStart)
						PushColor(newSpan.SpanColor);
					PushColor(newSpan.StartColor);
					position = firstMatch.Index + firstMatch.Length;
					PopColor();
					if (!newSpan.SpanColorIncludesStart)
						PushColor(newSpan.SpanColor);
				}
				endSpanMatch = null;
			}
			HighlightNonSpans(lineText.Length);

			PopAllColors();
		}

19 Source : HighlightingEngine.cs
with MIT License
from Abdesol

void PopColor()
		{
			if (highlightedLine == null)
				return;
			HighlightedSection s = highlightedSectionStack.Pop();
			if (s != null) {
				s.Length = (position + lineStartOffset) - s.Offset;
				if (s.Length == 0)
					highlightedLine.Sections.Remove(s);
				else
					lastPoppedSection = s;
			}
		}

19 Source : RichTextModelWriter.cs
with MIT License
from Abdesol

public override void EndSpan()
		{
			currentColor = colorStack.Pop();
			currentColorBegin = doreplacedentTextWriter.InsertionOffset;
		}

19 Source : IndentationReformatter.cs
with MIT License
from Abdesol

public void Step(IDoreplacedentAccessor doc, IndentationSettings set)
		{
			string line = doc.Text;
			if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
			line = line.TrimStart();

			StringBuilder indent = new StringBuilder();
			if (line.Length == 0) {
				// Special treatment for empty lines:
				if (blockComment || (inString && verbatim))
					return;
				indent.Append(block.InnerIndent);
				indent.Append(Repeat(set.IndentString, block.OneLineBlock));
				if (block.Continuation)
					indent.Append(set.IndentString);
				if (doc.Text != indent.ToString())
					doc.Text = indent.ToString();
				return;
			}

			if (TrimEnd(doc))
				line = doc.Text.TrimStart();

			Block oldBlock = block;
			bool startInComment = blockComment;
			bool startInString = (inString && verbatim);

			#region Parse char by char
			lineComment = false;
			inChar = false;
			escape = false;
			if (!verbatim) inString = false;

			lastRealChar = '\n';

			char lastchar = ' ';
			char c = ' ';
			char nextchar = line[0];
			for (int i = 0; i < line.Length; i++) {
				if (lineComment) break; // cancel parsing current line

				lastchar = c;
				c = nextchar;
				if (i + 1 < line.Length)
					nextchar = line[i + 1];
				else
					nextchar = '\n';

				if (escape) {
					escape = false;
					continue;
				}

				#region Check for comment/string chars
				switch (c) {
					case '/':
						if (blockComment && lastchar == '*')
							blockComment = false;
						if (!inString && !inChar) {
							if (!blockComment && nextchar == '/')
								lineComment = true;
							if (!lineComment && nextchar == '*')
								blockComment = true;
						}
						break;
					case '#':
						if (!(inChar || blockComment || inString))
							lineComment = true;
						break;
					case '"':
						if (!(inChar || lineComment || blockComment)) {
							inString = !inString;
							if (!inString && verbatim) {
								if (nextchar == '"') {
									escape = true; // skip escaped quote
									inString = true;
								} else {
									verbatim = false;
								}
							} else if (inString && lastchar == '@') {
								verbatim = true;
							}
						}
						break;
					case '\'':
						if (!(inString || lineComment || blockComment)) {
							inChar = !inChar;
						}
						break;
					case '\\':
						if ((inString && !verbatim) || inChar)
							escape = true; // skip next character
						break;
				}
				#endregion

				if (lineComment || blockComment || inString || inChar) {
					if (wordBuilder.Length > 0)
						block.LastWord = wordBuilder.ToString();
					wordBuilder.Length = 0;
					continue;
				}

				if (!Char.IsWhiteSpace(c) && c != '[' && c != '/') {
					if (block.Bracket == '{')
						block.Continuation = true;
				}

				if (Char.IsLetterOrDigit(c)) {
					wordBuilder.Append(c);
				} else {
					if (wordBuilder.Length > 0)
						block.LastWord = wordBuilder.ToString();
					wordBuilder.Length = 0;
				}

				#region Push/Pop the blocks
				switch (c) {
					case '{':
						block.ResetOneLineBlock();
						blocks.Push(block);
						block.StartLine = doc.LineNumber;
						if (block.LastWord == "switch") {
							block.Indent(set.IndentString + set.IndentString);
							/* oldBlock refers to the previous line, not the previous block
							 * The block we want is not available anymore because it was never pushed.
							 * } else if (oldBlock.OneLineBlock) {
							// Inside a one-line-block is another statement
							// with a full block: indent the inner full block
							// by one additional level
							block.Indent(set, set.IndentString + set.IndentString);
							block.OuterIndent += set.IndentString;
							// Indent current line if it starts with the '{' character
							if (i == 0) {
								oldBlock.InnerIndent += set.IndentString;
							}*/
						} else {
							block.Indent(set);
						}
						block.Bracket = '{';
						break;
					case '}':
						while (block.Bracket != '{') {
							if (blocks.Count == 0) break;
							block = blocks.Pop();
						}
						if (blocks.Count == 0) break;
						block = blocks.Pop();
						block.Continuation = false;
						block.ResetOneLineBlock();
						break;
					case '(':
					case '[':
						blocks.Push(block);
						if (block.StartLine == doc.LineNumber)
							block.InnerIndent = block.OuterIndent;
						else
							block.StartLine = doc.LineNumber;
						block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
									 (oldBlock.Continuation ? set.IndentString : "") +
									 (i == line.Length - 1 ? set.IndentString : new String(' ', i + 1)));
						block.Bracket = c;
						break;
					case ')':
						if (blocks.Count == 0) break;
						if (block.Bracket == '(') {
							block = blocks.Pop();
							if (IsSingleStatementKeyword(block.LastWord))
								block.Continuation = false;
						}
						break;
					case ']':
						if (blocks.Count == 0) break;
						if (block.Bracket == '[')
							block = blocks.Pop();
						break;
					case ';':
					case ',':
						block.Continuation = false;
						block.ResetOneLineBlock();
						break;
					case ':':
						if (block.LastWord == "case"
							|| line.StartsWith("case ", StringComparison.Ordinal)
							|| line.StartsWith(block.LastWord + ":", StringComparison.Ordinal)) {
							block.Continuation = false;
							block.ResetOneLineBlock();
						}
						break;
				}

				if (!Char.IsWhiteSpace(c)) {
					// register this char as last char
					lastRealChar = c;
				}
				#endregion
			}
			#endregion

			if (wordBuilder.Length > 0)
				block.LastWord = wordBuilder.ToString();
			wordBuilder.Length = 0;

			if (startInString) return;
			if (startInComment && line[0] != '*') return;
			if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
				return;

			if (line[0] == '}') {
				indent.Append(oldBlock.OuterIndent);
				oldBlock.ResetOneLineBlock();
				oldBlock.Continuation = false;
			} else {
				indent.Append(oldBlock.InnerIndent);
			}

			if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') {
				indent.Remove(indent.Length - 1, 1);
			} else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') {
				indent.Remove(indent.Length - 1, 1);
			}

			if (line[0] == ':') {
				oldBlock.Continuation = true;
			} else if (lastRealChar == ':' && indent.Length >= set.IndentString.Length) {
				if (block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(block.LastWord + ":", StringComparison.Ordinal))
					indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
			} else if (lastRealChar == ')') {
				if (IsSingleStatementKeyword(block.LastWord)) {
					block.OneLineBlock++;
				}
			} else if (lastRealChar == 'e' && block.LastWord == "else") {
				block.OneLineBlock = Math.Max(1, block.PreviousOneLineBlock);
				block.Continuation = false;
				oldBlock.OneLineBlock = block.OneLineBlock - 1;
			}

			if (doc.IsReadOnly) {
				// We can't change the current line, but we should accept the existing
				// indentation if possible (=if the current statement is not a multiline
				// statement).
				if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
					oldBlock.StartLine == block.StartLine &&
					block.StartLine < doc.LineNumber && lastRealChar != ':') {
					// use indent StringBuilder to get the indentation of the current line
					indent.Length = 0;
					line = doc.Text; // get untrimmed line
					for (int i = 0; i < line.Length; ++i) {
						if (!Char.IsWhiteSpace(line[i]))
							break;
						indent.Append(line[i]);
					}
					// /* */ multiline comments have an extra space - do not count it
					// for the block's indentation.
					if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') {
						indent.Length -= 1;
					}
					block.InnerIndent = indent.ToString();
				}
				return;
			}

			if (line[0] != '{') {
				if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
					indent.Append(set.IndentString);
				indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
			}

			// this is only for blockcomment lines starting with *,
			// all others keep their old indentation
			if (startInComment)
				indent.Append(' ');

			if (indent.Length != (doc.Text.Length - line.Length) ||
				!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
				Char.IsWhiteSpace(doc.Text[indent.Length])) {
				doc.Text = indent.ToString() + line;
			}
		}

19 Source : Rope.cs
with MIT License
from Abdesol

static IEnumerator<T> Enumerate(RopeNode<T> node)
		{
			Stack<RopeNode<T>> stack = new Stack<RopeNode<T>>();
			while (node != null) {
				// go to leftmost node, pushing the right parts that we'll have to visit later
				while (node.contents == null) {
					if (node.height == 0) {
						// go down into function nodes
						node = node.GetContentNode();
						continue;
					}
					Debug.replacedert(node.right != null);
					stack.Push(node.right);
					node = node.left;
				}
				// yield contents of leaf node
				for (int i = 0; i < node.length; i++) {
					yield return node.contents[i];
				}
				// go up to the next node not visited yet
				if (stack.Count > 0)
					node = stack.Pop();
				else
					node = null;
			}
		}

19 Source : XmlFoldingStrategy.cs
with MIT License
from Abdesol

public IEnumerable<NewFolding> CreateNewFoldings(TextDoreplacedent doreplacedent, XmlReader reader, out int firstErrorOffset)
		{
			Stack<XmlFoldStart> stack = new Stack<XmlFoldStart>();
			List<NewFolding> foldMarkers = new List<NewFolding>();
			try {
				while (reader.Read()) {
					switch (reader.NodeType) {
						case XmlNodeType.Element:
							if (!reader.IsEmptyElement) {
								XmlFoldStart newFoldStart = CreateElementFoldStart(doreplacedent, reader);
								stack.Push(newFoldStart);
							}
							break;

						case XmlNodeType.EndElement:
							XmlFoldStart foldStart = stack.Pop();
							CreateElementFold(doreplacedent, foldMarkers, reader, foldStart);
							break;

						case XmlNodeType.Comment:
							CreateCommentFold(doreplacedent, foldMarkers, reader);
							break;
					}
				}
				firstErrorOffset = -1;
			} catch (XmlException ex) {
				// ignore errors at invalid positions (prevent ArgumentOutOfRangeException)
				if (ex.LineNumber >= 1 && ex.LineNumber <= doreplacedent.LineCount)
					firstErrorOffset = doreplacedent.GetOffset(ex.LineNumber, ex.LinePosition);
				else
					firstErrorOffset = 0;
			}
			foldMarkers.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
			return foldMarkers;
		}

19 Source : HtmlRichTextWriter.cs
with MIT License
from Abdesol

public override void EndSpan()
		{
			htmlWriter.Write(endTagStack.Pop());
		}

19 Source : RopeTextReader.cs
with MIT License
from Abdesol

void GoToNextNode()
		{
			if (stack.Count == 0) {
				currentNode = null;
			} else {
				indexInsideNode = 0;
				currentNode = stack.Pop();
				GoToLeftMostLeaf();
			}
		}

19 Source : BaseInputDeviceManager.cs
with Apache License 2.0
from abist-co-ltd

protected virtual IMixedRealityPointer[] RequestPointers(SupportedControllerType controllerType, Handedness controllingHand)
        {
            using (RequestPointersPerfMarker.Auto())
            {
                var returnPointers = new List<IMixedRealityPointer>();

                CleanActivePointers();

                for (int i = 0; i < pointerConfigurations.Length; i++)
                {
                    var option = pointerConfigurations[i].profile;
                    if (option.ControllerType.HasFlag(controllerType) && option.Handedness.HasFlag(controllingHand))
                    {
                        IMixedRealityPointer requestedPointer = null;

                        if (EnablePointerCache)
                        {
                            var pointerCache = pointerConfigurations[i].cache;
                            while (pointerCache.Count > 0)
                            {
                                var p = pointerCache.Pop();
                                var pointerComponent = p as MonoBehaviour;
                                if (!UnityObjectExtensions.IsNull(pointerComponent))
                                {
                                    pointerComponent.gameObject.SetActive(true);

                                    // We got pointer from cache, continue to next pointer option to review
                                    requestedPointer = p;
                                    break;
                                }
                            }
                        }

                        if (requestedPointer == null)
                        {
                            // We couldn't obtain a pointer from our cache, resort to creating a new one
                            requestedPointer = CreatePointer(in option);
                        }

                        if (requestedPointer != null)
                        {
                            // Track pointer for recycling
                            activePointersToConfig.Add(requestedPointer, (uint)i);

                            returnPointers.Add(requestedPointer);
                        }
                    }
                }

                return returnPointers.Count == 0 ? null : returnPointers.ToArray();
            }
        }

19 Source : BaseInputDeviceManager.cs
with Apache License 2.0
from abist-co-ltd

private void DestroyPointerCache()
        {
            for (int i = 0; i < pointerConfigurations.Length; i++)
            {
                while (pointerConfigurations[i].cache.Count > 0)
                {
                    var pointerComponent = pointerConfigurations[i].cache.Pop() as MonoBehaviour;
                    if (!UnityObjectExtensions.IsNull(pointerComponent))
                    {
                        GameObjectExtensions.DestroyGameObject(pointerComponent.gameObject);
                    }
                }
            }
        }

19 Source : AwaiterExtensions.cs
with Apache License 2.0
from abist-co-ltd

public IEnumerator Run()
            {
                while (true)
                {
                    var topWorker = processStack.Peek();

                    bool isDone;

                    try
                    {
                        isDone = !topWorker.MoveNext();
                    }
                    catch (Exception e)
                    {
                        // The IEnumerators we have in the process stack do not tell us the
                        // actual names of the coroutine methods but it does tell us the objects
                        // that the IEnumerators are replacedociated with, so we can at least try
                        // adding that to the exception output
                        var objectTrace = GenerateObjectTrace(processStack);
                        awaiter.Complete(default(T), objectTrace.Any() ? new Exception(GenerateObjectTraceMessage(objectTrace), e) : e);

                        yield break;
                    }

                    if (isDone)
                    {
                        processStack.Pop();

                        if (processStack.Count == 0)
                        {
                            awaiter.Complete((T)topWorker.Current, null);
                            yield break;
                        }
                    }

                    // We could just yield return nested IEnumerator's here but we choose to do
                    // our own handling here so that we can catch exceptions in nested coroutines
                    // instead of just top level coroutine
                    var item = topWorker.Current as IEnumerator;
                    if (item != null)
                    {
                        processStack.Push(item);
                    }
                    else
                    {
                        // Return the current value to the unity engine so it can handle things like
                        // WaitForSeconds, WaitToEndOfFrame, etc.
                        yield return topWorker.Current;
                    }
                }
            }

19 Source : OBJWriterUtility.cs
with Apache License 2.0
from abist-co-ltd

public static IEnumerator<string> CreateOBJFileContentAsync(GameObject target, bool includeChildren)
        {
            StringBuilder objBuffer = new StringBuilder();

            objBuffer.Append($"# {target.name}").AppendNewLine();
            var dt = DateTime.Now;
            objBuffer.Append($"# {dt.ToString(CultureInfo.InvariantCulture)}").AppendNewLine().AppendNewLine();

            Stack<Transform> processStack = new Stack<Transform>();
            processStack.Push(target.transform);

            // If including sub-meshes, need to track vertex indices in relation to entire file
            int startVertexIndex = 0;

            // DFS processing routine to add Mesh data to OBJ 
            while (processStack.Count != 0)
            {
                var current = processStack.Pop();

                MeshFilter meshFilter = current.GetComponent<MeshFilter>();
                if (meshFilter != null)
                {
                    CreateOBJDataForMesh(meshFilter, objBuffer, ref startVertexIndex);
                }

                if (includeChildren)
                {
                    for (int i = 0; i < current.childCount; i++)
                    {
                        processStack.Push(current.GetChild(i));
                    }
                }

                yield return null;
            }

            yield return objBuffer.ToString();
        }

19 Source : ONSPReflectionZone.cs
with MIT License
from absurd-joy

void PopCurrentMixerSnapshot()
	{
        ReflectionSnapshot snapshot = snapshotList.Pop();

		// Set the popped reflection values
        SetReflectionValues(ref snapshot);
	}

19 Source : OVRPlatformMenu.cs
with MIT License
from absurd-joy

private static bool RetreatOneLevel()
	{
		if (sceneStack.Count > 1)
		{
			string parentScene = sceneStack.Pop();
			UnityEngine.SceneManagement.SceneManager.LoadSceneAsync (parentScene);
			return false;
		}

		return true;
	}

19 Source : PropertyObserver.cs
with MIT License
from Accelerider

private static void Initialize(Linq.Expressions.Expression propertyExpression, Action action)
        {
            var propNameStack = new Stack<string>();
            while (propertyExpression is MemberExpression temp) // Gets the root of the property chain.
            {
                propertyExpression = temp.Expression;
                propNameStack.Push(temp.Member.Name); // Records the name of each property.
            }

            if (!(propertyExpression is ConstantExpression constantExpression))
                throw new NotSupportedException("Operation not supported for the given expression type. " +
                                                "Only MemberExpression and ConstantExpression are currently supported.");

            var propObserverNodeRoot = new PropertyObserverNode(propNameStack.Pop(), action);
            PropertyObserverNode previousNode = propObserverNodeRoot;
            foreach (var propName in propNameStack) // Create a node chain that corresponds to the property chain.
            {
                var currentNode = new PropertyObserverNode(propName, action);
                previousNode.Next = currentNode;
                previousNode = currentNode;
            }

            object propOwnerObject = constantExpression.Value;

            if (!(propOwnerObject is INotifyPropertyChanged inpcObject))
                throw new InvalidOperationException("Trying to subscribe PropertyChanged listener in object that " +
                                                    $"owns '{propObserverNodeRoot.PropertyName}' property, but the object does not implements INotifyPropertyChanged.");

            propObserverNodeRoot.SubscribeListenerFor(inpcObject);
        }

19 Source : FolderLocationBar.xaml.cs
with MIT License
from Accelerider

private static (ObservableCollection<ILazyTreeNode<INetDiskFile>> displayed, ObservableCollection<ILazyTreeNode<INetDiskFile>> folded) ClreplacedifyFolder(Stack<ILazyTreeNode<INetDiskFile>> folders)
        {
            ObservableCollection<ILazyTreeNode<INetDiskFile>> folded = null;
            int delta = folders.Count - MaxDisplayedFolderCount;
            if (delta > 0)
            {
                folded = new ObservableCollection<ILazyTreeNode<INetDiskFile>>();
                for (int i = 0; i < delta; i++)
                {
                    folded.Insert(0, folders.Pop());
                }
            }
            else
            {
                folders.Pop();
            }
            return (new ObservableCollection<ILazyTreeNode<INetDiskFile>>(folders), folded);
        }

19 Source : PropertyObserver.cs
with MIT License
from Accelerider

private void SubscribeListeners(Expression propertyExpression)
        {
            var propNameStack = new Stack<string>();
            while (propertyExpression is MemberExpression temp) // Gets the root of the property chain.
            {
                propertyExpression = temp.Expression;
                propNameStack.Push(temp.Member.Name); // Records the name of each property.
            }

            if (!(propertyExpression is ConstantExpression constantExpression))
                throw new NotSupportedException("Operation not supported for the given expression type. " +
                                                "Only MemberExpression and ConstantExpression are currently supported.");

            var propObserverNodeRoot = new PropertyObserverNode(propNameStack.Pop(), _action);
            PropertyObserverNode previousNode = propObserverNodeRoot;
            foreach (var propName in propNameStack) // Create a node chain that corresponds to the property chain.
            {
                var currentNode = new PropertyObserverNode(propName, _action);
                previousNode.Next = currentNode;
                previousNode = currentNode;
            }

            object propOwnerObject = constantExpression.Value;

            if (!(propOwnerObject is INotifyPropertyChanged inpcObject))
                throw new InvalidOperationException($"Trying to subscribe PropertyChanged listener in object that " +
                                                    $"owns '{propObserverNodeRoot.PropertyName}' property, " +
                                                    $"but the object does not implements INotifyPropertyChanged.");

            propObserverNodeRoot.SubscribeListenerFor(inpcObject);
        }

19 Source : ChessLogic.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void UndoMove(uint count)
        {
            while (History.Count > 0 && count > 0)
            {
                var move = History.Peek();

                // undo 'global' information
                Turn = Chess.InverseColor(move.Color);
                Castling = move.Castling;
                EnPreplacedantCoord = move.EnPreplacedantCoord;
                HalfMove = move.HalfMove;
                Move = move.Move;

                MovePiece(move.To, move.From);

                var flags = move.Flags;
                if (flags.HasFlag(ChessMoveFlag.Promotion))
                {
                    var piece = AddPiece(Turn, ChessPieceType.Pawn, move.To);
                    piece.Guid = move.Guid;
                }

                if (flags.HasFlag(ChessMoveFlag.Capture))
                {
                    var piece = AddPiece(Turn, move.Captured, move.To);
                    piece.Guid = move.CapturedGuid;
                }

                if (flags.HasFlag(ChessMoveFlag.EnPreplacedantCapture))
                {
                    var enPreplacedantFrom = new ChessPieceCoord(move.To);
                    enPreplacedantFrom.MoveOffset(0, move.Color == ChessColor.Black ? 1 : -1);

                    var piece = AddPiece(Turn, ChessPieceType.Pawn, enPreplacedantFrom);
                    piece.Guid = move.CapturedGuid;
                }

                if ((flags & (ChessMoveFlag.KingSideCastle | ChessMoveFlag.QueenSideCastle)) != 0)
                {
                    var castlingTo = new ChessPieceCoord(move.To);
                    var castlingFrom = new ChessPieceCoord(castlingTo);

                    if (flags.HasFlag(ChessMoveFlag.KingSideCastle))
                    {
                        castlingTo.MoveOffset(1, 0);
                        castlingFrom.MoveOffset(-1, 0);
                    }
                    if (flags.HasFlag(ChessMoveFlag.QueenSideCastle))
                    {
                        castlingTo.MoveOffset(-2, 0);
                        castlingFrom.MoveOffset(1, 0);
                    }

                    MovePiece(castlingTo, castlingFrom);
                }

                History.Pop();
                count--;
            }
        }

19 Source : IOUtil.cs
with MIT License
from actions

private static IEnumerable<FileSystemInfo> Enumerate(DirectoryInfo directory, CancellationTokenSource tokenSource)
        {
            ArgUtil.NotNull(directory, nameof(directory));
            ArgUtil.Equal(false, directory.Attributes.HasFlag(FileAttributes.ReparsePoint), nameof(directory.Attributes.HasFlag));

            // Push the directory onto the processing stack.
            var directories = new Stack<DirectoryInfo>(new[] { directory });
            while (directories.Count > 0)
            {
                // Pop the next directory.
                directory = directories.Pop();
                foreach (FileSystemInfo item in directory.GetFileSystemInfos())
                {
                    // Push non-reparse-point directories onto the processing stack.
                    directory = item as DirectoryInfo;
                    if (directory != null &&
                        !item.Attributes.HasFlag(FileAttributes.ReparsePoint))
                    {
                        directories.Push(directory);
                    }

                    // Then yield the directory. Otherwise there is a race condition when this method attempts to initialize
                    // the Attributes and the caller is deleting the reparse point in parallel (FileNotFoundException).
                    yield return item;
                }
            }
        }

19 Source : LexicalAnalyzer.cs
with MIT License
from actions

private Token CreateToken(
            TokenKind kind,
            String rawValue,
            Int32 index,
            Object parsedValue = null)
        {
            // Check whether the current token is legal based on the last token
            var legal = false;
            switch (kind)
            {
                case TokenKind.StartGroup:      // "(" logical grouping
                    // Is first or follows "," or "(" or "[" or a logical operator
                    legal = CheckLastToken(null, TokenKind.Separator, TokenKind.StartGroup, TokenKind.StartParameters, TokenKind.StartIndex, TokenKind.LogicalOperator);
                    break;
                case TokenKind.StartIndex:      // "["
                    // Follows ")", "]", "*", a property name, or a named-value
                    legal = CheckLastToken(TokenKind.EndGroup, TokenKind.EndParameters, TokenKind.EndIndex, TokenKind.Wildcard, TokenKind.PropertyName, TokenKind.NamedValue);
                    break;
                case TokenKind.StartParameters: // "(" function call
                    // Follows a function
                    legal = CheckLastToken(TokenKind.Function);
                    break;
                case TokenKind.EndGroup:        // ")" logical grouping
                    // Follows ")", "]", "*", a literal, a property name, or a named-value
                    legal = CheckLastToken(TokenKind.EndGroup, TokenKind.EndParameters, TokenKind.EndIndex, TokenKind.Wildcard, TokenKind.Null, TokenKind.Boolean, TokenKind.Number, TokenKind.String, TokenKind.PropertyName, TokenKind.NamedValue);
                    break;
                case TokenKind.EndIndex:        // "]"
                    // Follows ")", "]", "*", a literal, a property name, or a named-value
                    legal = CheckLastToken(TokenKind.EndGroup, TokenKind.EndParameters, TokenKind.EndIndex, TokenKind.Wildcard, TokenKind.Null, TokenKind.Boolean, TokenKind.Number, TokenKind.String, TokenKind.PropertyName, TokenKind.NamedValue);
                    break;
                case TokenKind.EndParameters:   // ")" function call
                    // Follows "(" function call, ")", "]", "*", a literal, a property name, or a named-value
                    legal = CheckLastToken(TokenKind.StartParameters, TokenKind.EndGroup, TokenKind.EndParameters, TokenKind.EndIndex, TokenKind.Wildcard, TokenKind.Null, TokenKind.Boolean, TokenKind.Number, TokenKind.String, TokenKind.PropertyName, TokenKind.NamedValue);
                    break;
                case TokenKind.Separator:       // ","
                    // Follows ")", "]", "*", a literal, a property name, or a named-value
                    legal = CheckLastToken(TokenKind.EndGroup, TokenKind.EndParameters, TokenKind.EndIndex, TokenKind.Wildcard, TokenKind.Null, TokenKind.Boolean, TokenKind.Number, TokenKind.String, TokenKind.PropertyName, TokenKind.NamedValue);
                    break;
                case TokenKind.Dereference:     // "."
                    // Follows ")", "]", "*", a property name, or a named-value
                    legal = CheckLastToken(TokenKind.EndGroup, TokenKind.EndParameters, TokenKind.EndIndex, TokenKind.Wildcard, TokenKind.PropertyName, TokenKind.NamedValue);
                    break;
                case TokenKind.Wildcard:        // "*"
                    // Follows "[" or "."
                    legal = CheckLastToken(TokenKind.StartIndex, TokenKind.Dereference);
                    break;
                case TokenKind.LogicalOperator: // "!", "==", etc
                    switch (rawValue)
                    {
                        case ExpressionConstants.Not:
                            // Is first or follows "," or "(" or "[" or a logical operator
                            legal = CheckLastToken(null, TokenKind.Separator, TokenKind.StartGroup, TokenKind.StartParameters, TokenKind.StartIndex, TokenKind.LogicalOperator);
                            break;
                        default:
                            // Follows ")", "]", "*", a literal, a property name, or a named-value
                            legal = CheckLastToken(TokenKind.EndGroup, TokenKind.EndParameters, TokenKind.EndIndex, TokenKind.Wildcard, TokenKind.Null, TokenKind.Boolean, TokenKind.Number, TokenKind.String, TokenKind.PropertyName, TokenKind.NamedValue);
                            break;
                    }
                    break;
                case TokenKind.Null:
                case TokenKind.Boolean:
                case TokenKind.Number:
                case TokenKind.String:
                    // Is first or follows "," or "[" or "(" or a logical operator (e.g. "!" or "==" etc)
                    legal = CheckLastToken(null, TokenKind.Separator, TokenKind.StartIndex, TokenKind.StartGroup, TokenKind.StartParameters, TokenKind.LogicalOperator);
                    break;
                case TokenKind.PropertyName:
                    // Follows "."
                    legal = CheckLastToken(TokenKind.Dereference);
                    break;
                case TokenKind.Function:
                    // Is first or follows "," or "[" or "(" or a logical operator (e.g. "!" or "==" etc)
                    legal = CheckLastToken(null, TokenKind.Separator, TokenKind.StartIndex, TokenKind.StartGroup, TokenKind.StartParameters, TokenKind.LogicalOperator);
                    break;
                case TokenKind.NamedValue:
                    // Is first or follows "," or "[" or "(" or a logical operator (e.g. "!" or "==" etc)
                    legal = CheckLastToken(null, TokenKind.Separator, TokenKind.StartIndex, TokenKind.StartGroup, TokenKind.StartParameters, TokenKind.LogicalOperator);
                    break;
            }

            // Illegal
            if (!legal)
            {
                return new Token(TokenKind.Unexpected, rawValue, index);
            }

            // Legal so far
            var token = new Token(kind, rawValue, index, parsedValue);

            switch (kind)
            {
                case TokenKind.StartGroup:      // "(" logical grouping
                case TokenKind.StartIndex:      // "["
                case TokenKind.StartParameters: // "(" function call
                    // Track start token
                    m_unclosedTokens.Push(token);
                    break;

                case TokenKind.EndGroup:        // ")" logical grouping
                    // Check inside logical grouping
                    if (m_unclosedTokens.FirstOrDefault()?.Kind != TokenKind.StartGroup)
                    {
                        return new Token(TokenKind.Unexpected, rawValue, index);
                    }

                    // Pop start token
                    m_unclosedTokens.Pop();
                    break;

                case TokenKind.EndIndex:        // "]"
                    // Check inside indexer
                    if (m_unclosedTokens.FirstOrDefault()?.Kind != TokenKind.StartIndex)
                    {
                        return new Token(TokenKind.Unexpected, rawValue, index);
                    }

                    // Pop start token
                    m_unclosedTokens.Pop();
                    break;

                case TokenKind.EndParameters:   // ")" function call
                    // Check inside function call
                    if (m_unclosedTokens.FirstOrDefault()?.Kind != TokenKind.StartParameters)
                    {
                        return new Token(TokenKind.Unexpected, rawValue, index);
                    }

                    // Pop start token
                    m_unclosedTokens.Pop();
                    break;

                case TokenKind.Separator:       // ","
                    // Check inside function call
                    if (m_unclosedTokens.FirstOrDefault()?.Kind != TokenKind.StartParameters)
                    {
                        return new Token(TokenKind.Unexpected, rawValue, index);
                    }
                    break;
            }

            return token;
        }

19 Source : ExpressionParser.cs
with MIT License
from actions

private static void FlushTopOperator(ParseContext context)
        {
            // Special handling for closing operators
            switch (context.Operators.Peek().Kind)
            {
                case TokenKind.EndIndex:        // "]"
                    FlushTopEndIndex(context);
                    return;

                case TokenKind.EndGroup:        // ")" logical grouping
                    FlushTopEndGroup(context);
                    return;

                case TokenKind.EndParameters:   // ")" function call
                    FlushTopEndParameters(context);
                    return;
            }

            // Pop the operator
            var @operator = context.Operators.Pop();

            // Create the node
            var node = (Container)@operator.ToNode();

            // Pop the operands, add to the node
            var operands = PopOperands(context, @operator.OperandCount);
            foreach (var operand in operands)
            {
                // Flatten nested And
                if (node is And)
                {
                    if (operand is And nestedAnd)
                    {
                        foreach (var nestedParameter in nestedAnd.Parameters)
                        {
                            node.AddParameter(nestedParameter);
                        }

                        continue;
                    }
                }
                // Flatten nested Or
                else if (node is Or)
                {
                    if (operand is Or nestedOr)
                    {
                        foreach (var nestedParameter in nestedOr.Parameters)
                        {
                            node.AddParameter(nestedParameter);
                        }

                        continue;
                    }
                }

                node.AddParameter(operand);
            }

            // Push the node to the operand stack
            context.Operands.Push(node);
        }

19 Source : ExpressionParser.cs
with MIT License
from actions

private static void FlushTopEndParameters(ParseContext context)
        {
            // Pop the operator
            var @operator = PopOperator(context, TokenKind.EndParameters);   // ")" function call

            // Sanity check top operator is the current token
            if (!Object.ReferenceEquals(@operator, context.Token))
            {
                throw new InvalidOperationException("Expected the operator to be the current token");
            }

            var function = default(Function);

            // No parameters
            if (context.LastToken.Kind == TokenKind.StartParameters)
            {
                // Node already exists on the operand stack
                function = (Function)context.Operands.Peek();
            }
            // Has parameters
            else
            {
                // Pop the operands
                var parameterCount = 1;
                while (context.Operators.Peek().Kind == TokenKind.Separator)
                {
                    parameterCount++;
                    context.Operators.Pop();
                }
                var functionOperands = PopOperands(context, parameterCount);
                
                // Node already exists on the operand stack
                function = (Function)context.Operands.Peek();

                // Add the operands to the node
                foreach (var operand in functionOperands)
                {
                    function.AddParameter(operand);
                }
            }

            // Pop the "(" operator too
            @operator = PopOperator(context, TokenKind.StartParameters);

            // Check min/max parameter count
            TryGetFunctionInfo(context, function.Name, out var functionInfo);
            if (functionInfo == null && context.AllowUnknownKeywords)
            {
                // Don't check min/max
            }
            else if (function.Parameters.Count < functionInfo.MinParameters)
            {
                throw new ParseException(ParseExceptionKind.TooFewParameters, token: @operator, expression: context.Expression);
            }
            else if (function.Parameters.Count > functionInfo.MaxParameters)
            {
                throw new ParseException(ParseExceptionKind.TooManyParameters, token: @operator, expression: context.Expression);
            }
        }

19 Source : ExpressionParser.cs
with MIT License
from actions

private static List<ExpressionNode> PopOperands(
            ParseContext context,
            Int32 count)
        {
            var result = new List<ExpressionNode>();
            while (count-- > 0)
            {
                result.Add(context.Operands.Pop());
            }

            result.Reverse();
            return result;
        }

19 Source : ExpressionParser.cs
with MIT License
from actions

private static Token PopOperator(
            ParseContext context,
            TokenKind expected)
        {
            var token = context.Operators.Pop();
            if (token.Kind != expected)
            {
                throw new NotSupportedException($"Expected operator '{expected}' to be popped. Actual '{token.Kind}'.");
            }
            return token;
        }

19 Source : IExpressionNodeExtensions.cs
with MIT License
from actions

public static Boolean[] CheckReferencesContext(
            this IExpressionNode tree,
            params String[] patterns)
        {
            var result = new Boolean[patterns.Length];

            var segmentedPatterns = default(Stack<IExpressionNode>[]);

            // Walk the tree
            var stack = new Stack<IExpressionNode>();
            stack.Push(tree);
            while (stack.Count > 0)
            {
                var node = stack.Pop();

                // Attempt to match a named-value or index operator.
                // Note, do not push children of the index operator.
                if (node is NamedValue || node is Sdk.Operators.Index)
                {
                    // Lazy initialize the pattern segments
                    if (segmentedPatterns is null)
                    {
                        segmentedPatterns = new Stack<IExpressionNode>[patterns.Length];
                        var parser = new ExpressionParser();
                        for (var i = 0; i < patterns.Length; i++)
                        {
                            var pattern = patterns[i];
                            var patternTree = parser.ValidateSyntax(pattern, null);
                            var patternSegments = GetMatchSegments(patternTree);
                            if (patternSegments.Count == 0)
                            {
                                throw new InvalidOperationException($"Invalid context-match-pattern '{pattern}'");
                            }
                            segmentedPatterns[i] = patternSegments;
                        }
                    }

                    // Match
                    Match(node, segmentedPatterns, result);
                }
                // Push children of any other container node.
                else if (node is Container container && container.Parameters.Count > 0)
                {
                    foreach (var child in container.Parameters)
                    {
                        stack.Push(child);
                    }
                }
            }

            return result;
        }

19 Source : ToJson.cs
with MIT License
from actions

protected sealed override Object EvaluateCore(
            EvaluationContext context,
            out ResultMemory resultMemory)
        {
            resultMemory = null;
            var result = new StringBuilder();
            var memory = new MemoryCounter(this, context.Options.MaxMemory);
            var current = Parameters[0].Evaluate(context);
            var ancestors = new Stack<ICollectionEnumerator>();

            do
            {
                // Descend as much as possible
                while (true)
                {
                    // Collection
                    if (current.TryGetCollectionInterface(out Object collection))
                    {
                        // Array
                        if (collection is IReadOnlyArray array)
                        {
                            if (array.Count > 0)
                            {
                                // Write array start
                                WriteArrayStart(result, memory, ancestors);

                                // Move to first item
                                var enumerator = new ArrayEnumerator(context, current, array);
                                enumerator.MoveNext();
                                ancestors.Push(enumerator);
                                current = enumerator.Current;
                            }
                            else
                            {
                                // Write empty array
                                WriteEmptyArray(result, memory, ancestors);
                                break;
                            }
                        }
                        // Mapping
                        else if (collection is IReadOnlyObject obj)
                        {
                            if (obj.Count > 0)
                            {
                                // Write mapping start
                                WriteMappingStart(result, memory, ancestors);

                                // Move to first pair
                                var enumerator = new ObjectEnumerator(context, current, obj);
                                enumerator.MoveNext();
                                ancestors.Push(enumerator);

                                // Write mapping key
                                WriteMappingKey(context, result, memory, enumerator.Current.Key, ancestors);

                                // Move to mapping value
                                current = enumerator.Current.Value;
                            }
                            else
                            {
                                // Write empty mapping
                                WriteEmptyMapping(result, memory, ancestors);
                                break;
                            }
                        }
                        else
                        {
                            throw new NotSupportedException($"Unexpected type '{collection?.GetType().FullName}'");
                        }
                    }
                    // Not a collection
                    else
                    {
                        // Write value
                        WriteValue(context, result, memory, current, ancestors);
                        break;
                    }
                }

                // Next sibling or ancestor sibling
                do
                {
                    if (ancestors.Count > 0)
                    {
                        var parent = ancestors.Peek();

                        // Parent array
                        if (parent is ArrayEnumerator arrayEnumerator)
                        {
                            // Move to next item
                            if (arrayEnumerator.MoveNext())
                            {
                                current = arrayEnumerator.Current;

                                break;
                            }
                            // Move to parent
                            else
                            {
                                ancestors.Pop();
                                current = arrayEnumerator.Array;

                                // Write array end
                                WriteArrayEnd(result, memory, ancestors);
                            }
                        }
                        // Parent mapping
                        else if (parent is ObjectEnumerator objectEnumerator)
                        {
                            // Move to next pair
                            if (objectEnumerator.MoveNext())
                            {
                                // Write mapping key
                                WriteMappingKey(context, result, memory, objectEnumerator.Current.Key, ancestors);

                                // Move to mapping value
                                current = objectEnumerator.Current.Value;

                                break;
                            }
                            // Move to parent
                            else
                            {
                                ancestors.Pop();
                                current = objectEnumerator.Object;

                                // Write mapping end
                                WriteMappingEnd(result, memory, ancestors);
                            }
                        }
                        else
                        {
                            throw new NotSupportedException($"Unexpected type '{parent?.GetType().FullName}'");
                        }
                    }
                    else
                    {
                        current = null;
                    }

                } while (current != null);

            } while (current != null);

            return result.ToString();
        }

19 Source : IExpressionNodeExtensions.cs
with MIT License
from actions

private static void Match(
            IExpressionNode node,
            Stack<IExpressionNode>[] patterns,
            Boolean[] result)
        {
            var nodeSegments = GetMatchSegments(node);

            if (nodeSegments.Count == 0)
            {
                return;
            }

            var nodeNamedValue = nodeSegments.Peek() as NamedValue;
            var originalNodeSegments = nodeSegments;

            for (var i = 0; i < patterns.Length; i++)
            {
                var patternSegments = patterns[i];
                var patternNamedValue = patternSegments.Peek() as NamedValue;

                // Compare the named-value
                if (String.Equals(nodeNamedValue.Name, patternNamedValue.Name, StringComparison.OrdinalIgnoreCase))
                {
                    // Clone the stacks before mutating
                    nodeSegments = new Stack<IExpressionNode>(originalNodeSegments.Reverse());
                    nodeSegments.Pop();
                    patternSegments = new Stack<IExpressionNode>(patternSegments.Reverse());
                    patternSegments.Pop();

                    // Walk the stacks
                    while (true)
                    {
                        // Every pattern segment was matched
                        if (patternSegments.Count == 0)
                        {
                            result[i] = true;
                            break;
                        }
                        // Every node segment was matched. Treat the pattern as matched. There is not
                        // enough information to determine whether the property is required; replacedume it is.
                        // For example, consider the pattern "github.event" and the expression "toJson(github)".
                        // In this example the function requires the full structure of the named-value.
                        else if (nodeSegments.Count == 0)
                        {
                            result[i] = true;
                            break;
                        }

                        var nodeSegment = nodeSegments.Pop();
                        var patternSegment = patternSegments.Pop();

                        // The behavior of a wildcard varies depending on whether the left operand
                        // is an array or an object. For simplicity, treat the pattern as matched.
                        if (nodeSegment is Wildcard)
                        {
                            result[i] = true;
                            break;
                        }
                        // Treat a wildcard pattern segment as matching any literal segment
                        else if (patternSegment is Wildcard)
                        {
                            continue;
                        }

                        // Convert literals to string and compare
                        var nodeLiteral = nodeSegment as Literal;
                        var nodeEvaluationResult = EvaluationResult.CreateIntermediateResult(null, nodeLiteral.Value);
                        var nodeString = nodeEvaluationResult.ConvertToString();
                        var patternLiteral = patternSegment as Literal;
                        var patternEvaluationResult = EvaluationResult.CreateIntermediateResult(null, patternLiteral.Value);
                        var patternString = patternEvaluationResult.ConvertToString();
                        if (String.Equals(nodeString, patternString, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        // Convert to number and compare
                        var nodeNumber = nodeEvaluationResult.ConvertToNumber();
                        if (!Double.IsNaN(nodeNumber) && nodeNumber >= 0d && nodeNumber <= (Double)Int32.MaxValue)
                        {
                            var patternNumber = patternEvaluationResult.ConvertToNumber();
                            if (!Double.IsNaN(patternNumber) && patternNumber >= 0 && patternNumber <= (Double)Int32.MaxValue)
                            {
                                nodeNumber = Math.Floor(nodeNumber);
                                patternNumber = Math.Floor(patternNumber);
                                if (nodeNumber == patternNumber)
                                {
                                    continue;
                                }
                            }
                        }

                        // Not matched
                        break;
                    }
                }
            }
        }

19 Source : ReCon.cs
with GNU Affero General Public License v3.0
from active-logic

public void Exit(bool reset = true){
            if(!forward && reset) foreach(var e in this) e.Reset();
            if(owner.Peek() != this){
                throw new InvOp(
                         "Exiting context not topmost in ReCon stack");
            }
            owner.Pop();
        }

19 Source : BqlLocalVariableTypeResolver.cs
with GNU General Public License v3.0
from Acumatica

private TypeSyntax GetTypeFromCandidates()
			{
				if (_methodBodyWalker.Candidates.Count == 0)
					return null;

				var (latestPotentialreplacedignmentStatement, replacedignedType) = _methodBodyWalker.Candidates.Pop();
				var (replacedysisSucceded, varAlwaysreplacedigned) = CheckCandidate(latestPotentialreplacedignmentStatement);

				if (!replacedysisSucceded || !varAlwaysreplacedigned || replacedignedType == null)
					return null;    //replacedysis failed or reacheable replacedignment with not always replacedigned variable or valid candidate with unresolvable type

				return replacedignedType;
			}

19 Source : XmlCommentsWalker.cs
with GNU General Public License v3.0
from Acumatica

public override void VisitClreplacedDeclaration(ClreplacedDeclarationSyntax clreplacedDeclaration)
		{
			INamedTypeSymbol typeSymbol = _syntaxContext.SemanticModel.GetDeclaredSymbol(clreplacedDeclaration, _syntaxContext.CancellationToken);
			bool isDacOrDacExtension = typeSymbol?.IsDacOrExtension(_pxContext) ?? false;
			replacedyzeTypeDeclarationForMissingXmlComments(clreplacedDeclaration, reportDiagnostic: isDacOrDacExtension, out bool checkChildNodes, typeSymbol);

			if (!checkChildNodes)
				return;
			
			try
			{
				_isInsideDacContextStack.Push(isDacOrDacExtension);
				base.VisitClreplacedDeclaration(clreplacedDeclaration);
			}
			finally
			{
				_isInsideDacContextStack.Pop();
			}
		}

19 Source : ArrayElemCountLocalVariableResolver.cs
with GNU General Public License v3.0
from Acumatica

private int? GetElementsCountFromCandidates()
			{
				if (_methodBodyWalker.Candidates.Count == 0)
					return null;

				var (lastPotentialreplacedignmentStatement, count) = _methodBodyWalker.Candidates.Pop();
				var (replacedysisSucceded, varAlwaysreplacedigned) = CheckCandidate(lastPotentialreplacedignmentStatement);

				if (!replacedysisSucceded || !varAlwaysreplacedigned || count == null)
					return null;    //replacedysis failed or reacheable replacedignment with not always replacedigned variable or valid candidate with unresolvable count

				return count;
			}

See More Examples