Beispiel #1
0
 public MyInputStream(char separator = ' ')
 {
     this.separator = separator;
     inputStream    = new Queue <string>();
 }
Beispiel #2
0
            string ParseString()
            {
                StringBuilder s = new StringBuilder();
                char c;

                // ditch opening quote
                json.Read();

                bool parsing = true;
                while (parsing)
                {

                    if (json.Peek() == -1)
                    {
                        parsing = false;
                        break;
                    }

                    c = NextChar;
                    switch (c)
                    {
                        case '"':
                            parsing = false;
                            break;
                        case '\\':
                            if (json.Peek() == -1)
                            {
                                parsing = false;
                                break;
                            }

                            c = NextChar;
                            switch (c)
                            {
                                case '"':
                                case '\\':
                                case '/':
                                    s.Append(c);
                                    break;
                                case 'b':
                                    s.Append('\b');
                                    break;
                                case 'f':
                                    s.Append('\f');
                                    break;
                                case 'n':
                                    s.Append('\n');
                                    break;
                                case 'r':
                                    s.Append('\r');
                                    break;
                                case 't':
                                    s.Append('\t');
                                    break;
                                case 'u':
                                    var hex = new char[4];

                                    for (int i = 0; i < 4; i++)
                                    {
                                        hex[i] = NextChar;
                                    }

                                    s.Append((char)Convert.ToInt32(new string(hex), 16));
                                    break;
                            }
                            break;
                        default:
                            s.Append(c);
                            break;
                    }
                }

                return s.ToString();
            }
Beispiel #3
0
        private void AddTerminalToLookupByFirstChar(TerminalLookupTable _lookup, Terminal term, char firstChar)
        {
            TerminalList currentList;

            if (!_lookup.TryGetValue(firstChar, out currentList))
            {
                //if list does not exist yet, create it
                currentList        = new TerminalList();
                _lookup[firstChar] = currentList;
            }
            //add terminal to the list
            if (!currentList.Contains(term))
            {
                currentList.Add(term);
            }
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((4 + 2 >= 42))
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();
            }
            else if (!(4 + 2 >= 42))
            {
                {}
            }
            else
            {
                {}
            }

            //flaw

            string query = "//user[@name='" + tainted_3 + "']";


            string      filename = "file.xml";
            XmlDocument document = new XmlDocument( );

            document.Load(filename);
            XmlTextWriter writer = new XmlTextWriter(Console.Out);

            writer.Formatting = Formatting.Indented;

            XmlNode node = document.SelectSingleNode(query);

            node.WriteTo(writer);

            writer.Close( );
        }
Beispiel #5
0
    public Level()
    {
        Random random = new Random(100);

        //==========================================================================================
        // Create the player:
        //==========================================================================================
        Creatures.Add(new Creature
        {
            Speed = 240,
            Appearance = MakeTileSpan(new TileIndex(0, 8), new TileIndex(1, 0), 4),
        });

        //==========================================================================================
        // Parse map data:
        //==========================================================================================
        string[] raw = RawMapData.Split('\n').Select(x => x.Trim()).Where(x => x.Length > 0).ToArray();
        MapWidth = raw[0].Length;
        MapHeight = raw.Length;
        Walls = new TileIndex[MapWidth, MapHeight];
        Obstacles = new bool[MapWidth, MapHeight];
        for (int row = 0; row < MapHeight; row++)
        {
            for (int column = 0; column < MapWidth; column++)
            {
                //==========================================================================================
                // Choose tile variations for the static map terrain:
                //==========================================================================================
                char c = raw[row][column];
                char left = (column > 0) ? raw[row][column - 1] : '.';
                char right = (column < MapWidth - 1) ? raw[row][column + 1] : '.';
                char above = (row > 0) ? raw[row - 1][column] : '.';
                char below = (row < MapHeight - 1) ? raw[row + 1][column] : '.';

                TileIndex[] tiles;
                bool obstacle = false;
                if (c == '.')
                {
                    tiles = MakeTileSpan(new TileIndex(0, 0));
                }
                else if (c == 'W')
                {
                    // Outer corners:
                    if (below == 'W' && right == 'W' && above == '.') tiles = MakeTileSpan(new TileIndex(0, 1));
                    else if (below == 'W' && left == 'W' && above == '.') tiles = MakeTileSpan(new TileIndex(5, 1));
                    else if (above == 'W' && right == 'W' && below == '.') tiles = MakeTileSpan(new TileIndex(0, 5));
                    else if (above == 'W' && left == 'W' && below == '.') tiles = MakeTileSpan(new TileIndex(5, 5));
                    // Inside corners:
                    else if (below == 'W' && right == 'W' && above != '.') tiles = MakeTileSpan(new TileIndex(8, 1));
                    else if (below == 'W' && left == 'W' && above != '.') tiles = MakeTileSpan(new TileIndex(11, 1));
                    // Horizontal walls:
                    else if (above == '.' || (above == 'W' && (left == 'W' || right == 'W'))) tiles = MakeTileSpan(new TileIndex(1, 1), new TileIndex(1, 0), 4);
                    else if (below == '.') tiles = MakeTileSpan(new TileIndex(1, 5), new TileIndex(1, 0), 4);
                    // Vertical walls:
                    else if (left == '.') tiles = MakeTileSpan(new TileIndex(0, 2), new TileIndex(0, 1), 3);
                    else if (right == '.') tiles = MakeTileSpan(new TileIndex(5, 2), new TileIndex(0, 1), 3);
                    else tiles = MakeTileSpan(new TileIndex(2, 0));

                    obstacle = true;
                }
                else
                {
                    // All other entities are implicitly on a floor tile.
                    tiles = MakeTileSpan(new TileIndex(4, 0), new TileIndex(1, 0), 12);
                }
                Walls[column, row] = Choose(random, tiles);

                Vector2 here = new Vector2(column, row) * Assets.CellSize;

                //==========================================================================================
                // Spawn creatures and props:
                //==========================================================================================
                if (c == '@')
                {
                    Player.Position = here;
                }
                else if (c == 'P')
                {
                    // Priest NPC:
                    Creatures.Add(new Creature
                    {
                        Speed = 200,
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(0, 9), new TileIndex(1, 0), 4),
                        Facing = TextureMirror.Horizontal,
                        Conversation = new[]
                        {
                            "Expedition Leader\n\n\"Phew!\"",
                            "Expedition Leader\n\n\"We nearly didn't make it\n out of that level!\"",
                            "Expedition Leader\n\n\"Now, quickly, the exit is\n just ahead.\"",
                            "Expedition Leader\n\n\"Go!\"",
                        },
                        Thought = Thought.WaitToJoin,
                        FollowDistanceMin = 80,
                        FollowDistanceMax = float.MaxValue,
                    });
                }
                else if (c == 'S')
                {
                    // Skeleton:
                    Creatures.Add(new Creature
                    {
                        Speed = 40,
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(0, 5), new TileIndex(1, 0), 4),
                        Facing = TextureMirror.Horizontal,
                        CanKill = true,
                        Thought = Thought.Follow,
                        FollowDistanceMin = 0,
                        FollowDistanceMax = 300,
                    });
                }
                else if (c == 'F')
                {
                    // Flaming skull:
                    Creatures.Add(new Creature
                    {
                        Speed = 210,
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(0, 7), new TileIndex(1, 0), 4),
                        Facing = TextureMirror.Horizontal,
                        CanKill = true,
                        Thought = Thought.Follow,
                        FollowDistanceMin = 0,
                        FollowDistanceMax = 260,
                    });
                }
                else if (c == 'L')
                {
                    // Ladder:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(3, 0)),
                        IsFlat = true,
                    });
                    obstacle = true;
                }
                else if (c == 'B')
                {
                    // Big crate:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(3, 3)),
                    });
                    obstacle = true;
                }
                else if (c == 'b')
                {
                    // Small crate:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(2, 3)),
                    });
                    obstacle = true;
                }
                else if (c == 'f')
                {
                    // Wall torch:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(3, 4)),
                    });
                }
                else if (c == 'C')
                {
                    // Large cobweb:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(4, 1)),
                    });
                }
                else if (c == 'c')
                {
                    // Small cobweb:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(5, 1)),
                    });
                }
                else if (c == 'r')
                {
                    // Bones:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(7, 2)),
                        IsFlat = true,
                    });
                }
                else if (c == 'T')
                {
                    // Treasure:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(4, 3)),
                    });
                    obstacle = true;
                }
                else if (c == 'h')
                {
                    // Health potion:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(9, 3)),
                    });
                }
                else if (c == 'm')
                {
                    // Mana potion:
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(7, 3)),
                    });
                }
                else if (c == 'D')
                {
                    // Door (left):
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(0, 0)),
                        CanWin = true,
                    });
                    obstacle = true;
                }
                else if (c == 'O')
                {
                    // Door (right):
                    Creatures.Add(new Creature
                    {
                        Position = here,
                        Appearance = MakeTileSpan(new TileIndex(1, 0)),
                        CanWin = true,
                    });
                    obstacle = true;
                }

                Obstacles[column, row] = obstacle;
            }
        }

        Engine.PlayMusic(Assets.LevelMusic, looping: true);
    }
Beispiel #6
0
 private static bool CharEqual(char ch1, char ch2, bool isCaseSensitive)
 {
     return(isCaseSensitive ? ch1 == ch2 : Char.ToLower(ch1) == Char.ToLower(ch2));
 }
	void FormatText(ref string _targetString, string _source)
	{
		if (formatting == false || wordWrapWidth == 0 || _fontInst.texelSize == Vector2.zero)
		{
			_targetString = _source;
			return;
		}

		float lineWidth = _fontInst.texelSize.x * wordWrapWidth;

		System.Text.StringBuilder target = new System.Text.StringBuilder(_source.Length);
		float widthSoFar = 0.0f;
		float wordStart = 0.0f;
		int targetWordStartIndex = -1;
		int fmtWordStartIndex = -1;
		bool ignoreNextCharacter = false;
		for (int i = 0; i < _source.Length; ++i)
		{
			char idx = _source[i];
			tk2dFontChar chr;

			bool inlineHatChar = (idx == '^');
			
			if (_fontInst.useDictionary)
			{
				if (!_fontInst.charDict.ContainsKey(idx)) idx = (char)0;
				chr = _fontInst.charDict[idx];
			}
			else
			{
				if (idx >= _fontInst.chars.Length) idx = (char)0; // should be space
				chr = _fontInst.chars[idx];
			}

			if (inlineHatChar) idx = '^';

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

			if (data.inlineStyling && idx == '^' && i + 1 < _source.Length) {
				if (_source[i + 1] == '^') {
					ignoreNextCharacter = true;
					target.Append('^'); // add the second hat that we'll skip
				} else {
					int cmdLength = GetInlineStyleCommandLength(_source[i + 1]);
					int skipLength = 1 + cmdLength; // The ^ plus the command
					for (int j = 0; j < skipLength; ++j) {
						if (i + j < _source.Length) {
							target.Append(_source[i + j]);
						}
					}
					i += skipLength - 1;
					continue;
				}
			}

			if (idx == '\n') 
			{
				widthSoFar = 0.0f;
				wordStart = 0.0f;
				targetWordStartIndex = target.Length;
				fmtWordStartIndex = i;
			}
			else if (idx == ' '/* || idx == '.' || idx == ',' || idx == ':' || idx == ';' || idx == '!'*/)
			{
				/*if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth)
				{
					target.Append('\n');
					widthSoFar = chr.advance * data.scale.x;
				}
				else
				{*/
					widthSoFar += (chr.advance + data.spacing) * data.scale.x;
				//}

				wordStart = widthSoFar;
				targetWordStartIndex = target.Length;
				fmtWordStartIndex = i;
			}
			else
			{
				if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth)
				{
					// If the last word started after the start of the line
					if (wordStart > 0.0f)
					{
						wordStart = 0.0f;
						widthSoFar = 0.0f;
						// rewind
						target.Remove(targetWordStartIndex + 1, target.Length - targetWordStartIndex - 1);
						target.Append('\n');
						i = fmtWordStartIndex;
						continue; // don't add this character
					}
					else
					{
						target.Append('\n');
						widthSoFar = (chr.advance + data.spacing) * data.scale.x;
					}
				}
				else
				{
					widthSoFar += (chr.advance + data.spacing) * data.scale.x;
				}
			}
			
			target.Append(idx);
		}
		_targetString = target.ToString();
	}
 public void Process()
 {
     char[] input = new char[] { '1', '3', '5', '6', ',', '4', '9', '7', '3', ',', '2', '3', ',', '7', '7', ',', '2', '2', ',', '9', '9', ',', '1' };
     Evaluate(input);
 }
		public IParameterDataProvider HandleParameterCompletion (MonoDevelop.Ide.Gui.Document realDocument, CodeCompletionContext completionContext, DocumentInfo info, LocalDocumentInfo localInfo, char completionChar)
		{
			CodeCompletionContext ccc;
			using (var completion = CreateCompletion (realDocument, info, localInfo, out ccc)) {
				return completion.HandleParameterCompletion (completionContext, completionChar);
			}
		}
		public ICompletionDataList HandleCompletion (MonoDevelop.Ide.Gui.Document realDocument, CodeCompletionContext completionContext, DocumentInfo info, LocalDocumentInfo localInfo, char currentChar, ref int triggerWordLength)
		{
			CodeCompletionContext ccc;
			using (var completion = CreateCompletion (realDocument, info, localInfo, out ccc)) {
				return completion.HandleCodeCompletion (completionContext, currentChar, ref triggerWordLength);
			}
		}
Beispiel #11
0
        private static string ean13(char c, char type)
        {
            switch (type)
            {
            case 'A':
            {
                switch (c)
                {
                case '0': return("0001101");

                case '1': return("0011001");

                case '2': return("0010011");

                case '3': return("0111101");

                case '4': return("0100011");

                case '5': return("0110001");

                case '6': return("0101111");

                case '7': return("0111011");

                case '8': return("0110111");

                case '9': return("0001011");

                default: return("Error!");
                }
            }

            case 'B':
            {
                switch (c)
                {
                case '0': return("0100111");

                case '1': return("0110011");

                case '2': return("0011011");

                case '3': return("0100001");

                case '4': return("0011101");

                case '5': return("0111001");

                case '6': return("0000101");

                case '7': return("0010001");

                case '8': return("0001001");

                case '9': return("0010111");

                default: return("Error!");
                }
            }

            case 'C':
            {
                switch (c)
                {
                case '0': return("1110010");

                case '1': return("1100110");

                case '2': return("1101100");

                case '3': return("1000010");

                case '4': return("1011100");

                case '5': return("1001110");

                case '6': return("1010000");

                case '7': return("1000100");

                case '8': return("1001000");

                case '9': return("1110100");

                default: return("Error!");
                }
            }

            default: return("Error!");
            }
        }
Beispiel #12
0
    public Expr ProcessOperand(object operand, FunctionBlock block, bool isInsideBoolean = false)
    {
        Expr                     returnExpr  = new Expr();
        StringBuilder            exprBuilder = new StringBuilder();
        bool                     hasSign     = false;
        DeclareVariableStatement resultVar   = new DeclareVariableStatement();

        resultVar.IsHidden = true;
        int insertResultIndex = block.Statements.Count;

        block.Statements.Add("");
        char signChar = ' ';

        if (operand is ExprAtom)
        {
            if ((operand as ExprAtom).Op == ExprAtom.UnaryOp.Inverse)
            {
                signChar = '!';
            }
            else if ((operand as ExprAtom).Op == ExprAtom.UnaryOp.Not)
            {
                signChar = '-';
            }
            operand = (operand as ExprAtom).Content;
        }

        BindingFlags any = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public;

        if (operand is Scope)
        {
            //bool exprIsResultVar = false;
            var  scope           = (operand as Scope).Parts;
            bool contextVariable = true;
            var  contextVar      = block.FindStatement <DeclareVariableStatement> (v => v.Name == scope [0] as string);
            if (contextVariable = (contextVar == null))
            {
                contextVar = block.FindStatement <DeclareVariableStatement> (v => v.IsContext);
            }
            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogWarningFormat("S_CTX {0} {1}", contextVar, operand);
            }
            string contextName = null;           //!contextVariable ? "root" : contextVar.Name;
            Type   contextType = null;           //!contextVariable ? typeof(GameObject) : contextVar.Type;
            if (contextVar == null)
            {
                contextName = block.DefaultScope;
                contextType = typeof(GameObject);
            }
            else
            {
                contextName = contextVar.Name;
                contextType = contextVar.Type;
            }

            exprBuilder.Append(contextName).Append(".");
            bool          firstTimeList = true;
            FunctionBlock curBlock      = block;
            for (int i = contextVariable ? 0 : 1; i < scope.Count; i++)
            {
                if (ScriptEngine.AnalyzeDebug)
                {
                    Debug.LogWarningFormat("scope part {0} {1} {2}", scope [i], contextType.IsGenericType, contextType.IsGenericType ? (contextType.GetGenericTypeDefinition() == typeof(List <>)).ToString() : "");
                }
                if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    if (firstTimeList)
                    {
                        CleanUpContextes.Push(resultVar);
                        resultVar.IsTemp = true;
                        resultVar.Name   = "result" + DeclareVariableStatement.VariableId++;
                        block.Statements [insertResultIndex] = resultVar;
                        resultVar.IsHidden = false;
                        resultVar.IsResult = true;

                        //resultList.Type = contextType;
                        //exprIsResultVar = true;
                        firstTimeList = false;
                    }
                    Debug.Log("scope list " + scope [i]);
                    DeclareVariableStatement declVar = new DeclareVariableStatement();
                    CleanUpContextes.Push(declVar);
                    declVar.IsTemp = true;
                    declVar.Name   = "list" + DeclareVariableStatement.VariableId++;
                    declVar.Type   = contextType;
                    if (exprBuilder [exprBuilder.Length - 1] == '.')
                    {
                        exprBuilder.Length -= 1;
                    }
                    if (hasSign)
                    {
                        declVar.InitExpression = exprBuilder.ToString(1, exprBuilder.Length - 1);
                        exprBuilder.Length     = 1;
                        //exprBuilder.Append (declVar.Name).Append ('.');
                    }
                    else
                    {
                        declVar.InitExpression = exprBuilder.ToString();
                        exprBuilder.Length     = 0;
                        //exprBuilder.Append (declVar.Name).Append ('.');
                    }
                    curBlock.Statements.Add(declVar);
                    ForStatement forStatement = new ForStatement();
                    forStatement.RepeatBlock = new FunctionBlock(block, block.Method, block.Type);
                    var repeatContext = new DeclareVariableStatement();
                    repeatContext.IsTemp = true;
                    CleanUpContextes.Push(repeatContext);
                    forStatement.RepeatBlock.Statements.Add(repeatContext);
                    curBlock.Statements.Add(forStatement);
                    curBlock = forStatement.RepeatBlock;
                    var iterName = "i" + DeclareVariableStatement.VariableId++;
                    forStatement.InsideExpr = String.Format(@"int {0} = 0; {0} < {1}.Count; {0}++", iterName, declVar.Name);

                    contextType                  = contextType.GetGenericArguments() [0];
                    repeatContext.Name           = "SubContext" + DeclareVariableStatement.VariableId++;
                    repeatContext.Type           = contextType;
                    repeatContext.IsContext      = true;
                    repeatContext.InitExpression = String.Format(@"{0}[{1}]", declVar.Name, iterName);
                }
                bool isFunc = false;
                if (scope [i] is FunctionCall || scope [i] is string)
                {
//					var callOp = ProcessOperand (scope [i], block);
                    Expression[] callArgs = defaultArgsList;
                    string       callName = null;
                    var          call     = scope [i] as FunctionCall;
                    if (call != null)
                    {
                        callName = call.Name;
                        callArgs = call.Args;
                    }
                    else
                    {
                        callName = scope [i] as string;
                    }
                    if (scopeInterpreters.ContainsKey(callName))
                    {
                        var    interpreter = scopeInterpreters [callName];
                        string outExpr     = null;
                        interpreter.Interpret(callArgs, curBlock, contextType, exprBuilder.ToString(), out outExpr, out curBlock, out contextType, i == scope.Count - 1);
                        if (hasSign)
                        {
                            exprBuilder.Length = 1;
                            exprBuilder.Append(outExpr).Append('.');
                        }
                        else
                        {
                            exprBuilder.Length = 0;
                            exprBuilder.Append(outExpr).Append('.');
                        }
                        isFunc = true;
                    }
                    else
                    {
                        var methodName = NameTranslator.CSharpNameFromScript(callName);
                        var method     = contextType.GetMethod(methodName);
                        if (i == 0 && method == null)
                        {
                            var otherContext = block.FindStatement <DeclareVariableStatement> (v => (v.IsContext || v.IsArg) && (method = v.Type.GetMethod(methodName, any)) != null);
                            if (otherContext != null)
                            {
                                exprBuilder.Length = hasSign ? 1 : 0;
                                if (ScriptEngine.AnalyzeDebug)
                                {
                                    Debug.LogWarning("OTHER CONTEXT" + otherContext.DebugString());
                                }
                                exprBuilder.Append(otherContext.Name).Append('.');
                                contextType = otherContext.Type;
                            }
                            else
                            {
                                if (ScriptEngine.AnalyzeDebug)
                                {
                                    Debug.LogWarning("Can't find context for method " + methodName);
                                }
                                block.FindStatement <DeclareVariableStatement> (v => {
                                    if (ScriptEngine.AnalyzeDebug)
                                    {
                                        Debug.LogFormat("{0} {1} {3}                  ||||{2}", v.Name, v.Type, IfStatement.AntiMergeValue++, v.IsContext || v.IsArg);
                                    }
                                    return(false);
                                });
                            }
                        }
                        if (method == null)
                        {
                            if (ScriptEngine.AnalyzeDebug)
                            {
                                Debug.LogFormat("Can't find {0} in {1}", NameTranslator.CSharpNameFromScript(callName), contextType);
                            }
                        }
                        else
                        {
                            exprBuilder.Append(method.Name).Append("(");
                            var argsDef = method.GetParameters();
                            if (callArgs != null)
                            {
                                for (int j = 0; j < callArgs.Length; j++)
                                {
                                    if (argsDef [j].ParameterType.IsSubclassOf(typeof(Delegate)))
                                    {
                                        exprBuilder.Append(InterpretClosure(callArgs [j], curBlock, argsDef [j].ParameterType).ExprString).Append(",");
                                    }
                                    else
                                    {
                                        exprBuilder.Append(InterpretExpression(callArgs [j], curBlock).ExprString).Append(",");
                                    }
                                }
                                if (callArgs.Length > 0)
                                {
                                    exprBuilder.Length -= 1;
                                }
                            }

                            exprBuilder.Append(")");
                            contextType = method.ReturnType;


                            var declVar = new DeclareVariableStatement();
                            CleanUpContextes.Push(declVar);
                            declVar.IsTemp    = true;
                            declVar.Name      = "prop" + DeclareVariableStatement.VariableId++;
                            declVar.IsContext = true;
                            if (exprBuilder.Length > 0 && exprBuilder [exprBuilder.Length - 1] == '.')
                            {
                                exprBuilder.Length -= 1;
                            }
                            if (hasSign)
                            {
                                declVar.InitExpression = exprBuilder.ToString(1, exprBuilder.Length - 1);
                                exprBuilder.Length     = 1;
                                exprBuilder.Append(declVar.Name).Append('.');
                            }
                            else
                            {
                                declVar.InitExpression = exprBuilder.ToString();
                                exprBuilder.Length     = 0;
                                exprBuilder.Append(declVar.Name).Append('.');
                            }
                            declVar.Type = contextType;
                            curBlock.Statements.Add(declVar);
                            if (contextType.IsClass)
                            {
                                IfStatement ifSt = new IfStatement();
                                ifSt.CheckExpression = String.Format("{0} != null", declVar.Name);
                                ifSt.TrueBlock       = new FunctionBlock(curBlock);
                                curBlock.Statements.Add(ifSt);
                                curBlock = ifSt.TrueBlock;
                            }
                            isFunc = true;
                        }
                    }
                }
                if (!isFunc)
                {
                    var propName = NameTranslator.CSharpNameFromScript(scope [i] as string);

                    var prop = contextType.GetProperty(propName);

                    if (i == 0 && prop == null)
                    {
                        var customVar = block.FindStatement <DeclareVariableStatement> (v => v.Name == scope [i] as string);
                        if (customVar == null)
                        {
                            var otherContext = block.FindStatement <DeclareVariableStatement> (v => {
                                //Debug.LogWarning (v.Type);
                                //Debug.Log (v.IsContext || v.IsArg);
                                //var props = v.Type.GetProperties (any);
                                //foreach (var allProp in props)
                                //	Debug.Log (allProp.Name);
                                return((v.IsContext || v.IsArg) && (prop = v.Type.GetProperty(propName, any)) != null);
                            });
                            if (otherContext != null)
                            {
                                exprBuilder.Length = hasSign ? 1 : 0;

                                exprBuilder.Append(otherContext.Name).Append('.');
                                contextType = otherContext.Type;
                                if (contextType.IsClass && !prop.GetGetMethod().IsStatic)
                                {
                                    IfStatement ifSt = new IfStatement();
                                    ifSt.CheckExpression = String.Format("{0} != null", otherContext.Name);
                                    ifSt.TrueBlock       = new FunctionBlock(curBlock);
                                    curBlock.Statements.Add(ifSt);
                                    curBlock = ifSt.TrueBlock;
                                }
                            }
                            else
                            if (ScriptEngine.AnalyzeDebug)
                            {
                                Debug.LogWarning("Can't find context for property " + propName);
                            }
                        }
                        else
                        {
                            exprBuilder.Length = hasSign ? 1 : 0;
                            exprBuilder.Append(customVar.Name).Append('.');
                            contextType = customVar.Type;
                            if (contextType.IsClass && !prop.GetGetMethod().IsStatic)
                            {
                                IfStatement ifSt = new IfStatement();
                                ifSt.CheckExpression = String.Format("{0} != null", customVar.Name);
                                ifSt.TrueBlock       = new FunctionBlock(curBlock);
                                curBlock.Statements.Add(ifSt);
                                curBlock = ifSt.TrueBlock;
                            }
                        }
                    }
                    if (ScriptEngine.AnalyzeDebug)
                    {
                        Debug.LogWarning(prop);
                    }
                    if (prop == null && components.ContainsKey(scope [i] as string))
                    {
                        var    type           = components [scope [i] as string];
                        string storedFromName = null;
                        if (hasSign)
                        {
                            storedFromName = exprBuilder.ToString(1, exprBuilder.Length - 1);
                        }
                        else
                        {
                            storedFromName = exprBuilder.ToString();
                        }
                        if (ScriptEngine.AnalyzeDebug)
                        {
                            Debug.LogWarning("Component found " + type);
                        }
                        var storedVar = curBlock.FindStatement <DeclareVariableStatement> (v => v.Type == type && v.storedOf != null && storedFromName == v.storedOf);

                        contextType = type;
                        if (storedVar == null)
                        {
                            storedVar = new DeclareVariableStatement();
                            CleanUpContextes.Push(storedVar);
                            storedVar.IsTemp    = true;
                            storedVar.IsContext = true;
                            curBlock.Statements.Add(storedVar);                             //block.FindStatement<DeclareVariableStatement> (v => !v.IsContext && v.Type == type);
                            storedVar.Name = "StoredVariable" + DeclareVariableStatement.VariableId++;
                            storedVar.Type = type;

                            storedVar.storedOf = hasSign ? exprBuilder.ToString(1, exprBuilder.Length) : exprBuilder.ToString(0, exprBuilder.Length);
                            exprBuilder.Append(String.Format("GetComponent(typeof({0})))", type));
                            exprBuilder.Insert(0, String.Format("(({0})", type));
                            if (hasSign)
                            {
                                storedVar.InitExpression = exprBuilder.ToString(1, exprBuilder.Length - 1);
                                exprBuilder.Length       = 1;
                                exprBuilder.Append(storedVar.Name).Append('.');
                            }
                            else
                            {
                                storedVar.InitExpression = exprBuilder.ToString();
                                exprBuilder.Length       = 0;
                                exprBuilder.Append(storedVar.Name).Append('.');
                            }
                        }
                        if (hasSign)
                        {
                            exprBuilder.Length = 1;
                            exprBuilder.Append(storedVar.Name).Append('.');
                        }
                        else
                        {
                            exprBuilder.Length = 0;
                            exprBuilder.Append(storedVar.Name).Append('.');
                        }

                        if (contextType.IsClass)
                        {
                            IfStatement ifSt = new IfStatement();
                            ifSt.CheckExpression = String.Format("{0} != null", storedVar.Name);
                            ifSt.TrueBlock       = new FunctionBlock(curBlock);
                            curBlock.Statements.Add(ifSt);
                            curBlock = ifSt.TrueBlock;
                        }
                    }
                    else if (scopeInterpreters.ContainsKey(scope [i] as string))
                    {
                        var    interpreter = scopeInterpreters [scope [i] as string];
                        string outExpr     = null;
                        interpreter.Interpret(null, curBlock, contextType, exprBuilder.ToString(), out outExpr, out curBlock, out contextType, i == scope.Count - 1);
                        if (hasSign)
                        {
                            exprBuilder.Length = 1;
                            exprBuilder.Append(outExpr).Append('.');
                        }
                        else
                        {
                            exprBuilder.Length = 0;
                            exprBuilder.Append(outExpr).Append('.');
                        }
                    }
                    else if (prop == null && scope.Count == 1)
                    {
                        if (ScriptEngine.AnalyzeDebug)
                        {
                            Debug.LogWarningFormat("Can't find {0} in {1}, interpreting as a string", propName, contextType);
                        }
                        contextType        = typeof(string);
                        exprBuilder.Length = 0;
                        exprBuilder.Append("\"").Append(scope [i]).Append("\"");
                        break;
                    }
                    else if (prop == null)
                    {
                        Debug.LogWarningFormat("Can't find {0} in {1}", propName, contextType);
                        break;
                    }
                    else
                    {
                        contextType = prop.PropertyType;
                        exprBuilder.Append(propName).Append('.');
                        var declVar = new DeclareVariableStatement();
                        CleanUpContextes.Push(declVar);
                        declVar.IsTemp    = true;
                        declVar.IsContext = true;
                        declVar.Name      = "prop" + DeclareVariableStatement.VariableId++;
                        if (exprBuilder.Length > 0 && exprBuilder [exprBuilder.Length - 1] == '.')
                        {
                            exprBuilder.Length -= 1;
                        }
                        if (hasSign)
                        {
                            declVar.InitExpression = exprBuilder.ToString(1, exprBuilder.Length - 1);
                            exprBuilder.Length     = 1;
                            exprBuilder.Append(declVar.Name).Append('.');
                        }
                        else
                        {
                            declVar.InitExpression = exprBuilder.ToString();
                            exprBuilder.Length     = 0;
                            exprBuilder.Append(declVar.Name).Append('.');
                        }
                        declVar.Type = contextType;
                        curBlock.Statements.Add(declVar);
                        if (contextType.IsClass)
                        {
                            IfStatement ifSt = new IfStatement();
                            ifSt.CheckExpression = String.Format("{0} != null", declVar.Name);
                            ifSt.TrueBlock       = new FunctionBlock(curBlock);
                            curBlock.Statements.Add(ifSt);
                            curBlock = ifSt.TrueBlock;
                        }
                    }
                }
            }
            returnExpr.Type = contextType;
            var res = resultVar;
            if (!res.IsHidden)
            {
                var list   = curBlock.FindStatement <DeclareVariableStatement> (v => v.Type != null && v.Type.IsGenericType && v.Type.GetGenericTypeDefinition() == typeof(List <>));
                var lasVar = curBlock.FindStatement <DeclareVariableStatement> (v => v.IsContext);
                if (list != null && !firstTimeList)
                {
                    curBlock.Statements.Add(String.Format(@"{0}.Add({1});", res.Name, lasVar.Name));
                    res.Type           = typeof(List <>).MakeGenericType(lasVar.Type);
                    res.InitExpression = String.Format("new {0}();", TypeName.NameOf(res.Type));
                }
                else
                {
                    res.Type = lasVar.Type;
                    curBlock.Statements.Add(String.Format(@"{0} = {1};", res.Name, lasVar.Name));
                }
                if (hasSign)
                {
                    exprBuilder.Length = 1;
                    exprBuilder.Append(res.Name).Append('.');
                }
                else
                {
                    exprBuilder.Length = 0;
                    exprBuilder.Append(res.Name).Append('.');
                }

                returnExpr.Type = res.Type;
            }

            if (!res.IsHidden && res.Type != null)
            {
                var resType = res.Type;
                res.IsResult = false;
                Debug.Log(isInsideBoolean);
                if (isInsideBoolean && resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    exprBuilder.Append(String.Format(" != null ? {0}.Count : 0", exprBuilder));
                }
            }
            if (exprBuilder.Length > 0 && exprBuilder [exprBuilder.Length - 1] == '.')
            {
                exprBuilder.Length -= 1;
            }
            if (res.IsHidden)
            {
                resultVar.Name                       = "OperandVar" + DeclareVariableStatement.VariableId++;
                resultVar.Type                       = contextType;
                resultVar.InitExpression             = string.Format("default({0})", TypeName.NameOf(contextType));
                resultVar.IsHidden                   = false;
                block.Statements [insertResultIndex] = resultVar;
                curBlock.Statements.Add(String.Format("{0} = {1};", resultVar.Name, exprBuilder));
                exprBuilder.Length = hasSign ? 1 : 0;
                var resType = res.Type;
                if (isInsideBoolean && resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    exprBuilder.Append(String.Format("{0} != null ? {0}.Count : 0", resultVar.Name));
                }
                else
                {
                    exprBuilder.Append(resultVar.Name);
                }
            }
        }
        else if (operand is FunctionCall)
        {
//			var call = operand as FunctionCall;
//			for (int i = 0; i < call.Args.Length; i++)
//			{
//
//			}
        }
        else if (operand is Expression)
        {
            var ex = InterpretExpression(operand as Expression, block, false, isInsideBoolean);
            exprBuilder.Append(ex.ExprString);
            returnExpr.Type = ex.Type;
        }
        else
        {
            returnExpr.Type = operand.GetType();
            if (operand is bool)
            {
                exprBuilder.Append((bool)operand ? "true" : "false");
            }
            else
            {
                exprBuilder.Append(operand);
            }
            if (operand is float)
            {
                exprBuilder.Append('f');
            }
        }
        string head = String.Format("{0}(", signChar);

        exprBuilder.Insert(0, head).Append(')');
        returnExpr.ExprString = exprBuilder.ToString();
        return(returnExpr);
    }
Beispiel #13
0
        /// <summary>
        /// Attempts to parse an email address e.g. "*****@*****.**".
        /// </summary>
        /// <param name="markdown"> The markdown text. </param>
        /// <param name="minStart"> The minimum start position to return. </param>
        /// <param name="tripPos"> The location of the at character. </param>
        /// <param name="maxEnd"> The location to stop parsing. </param>
        /// <returns> A parsed URL, or <c>null</c> if this is not a URL. </returns>
        internal static InlineParseResult ParseEmailAddress(string markdown, int minStart, int tripPos, int maxEnd)
        {
            // Search backwards until we find a character which is not a letter, digit, or one of
            // these characters: '+', '-', '_', '.'.
            // Note: it is intended that this code match the reddit.com markdown parser; there are
            // many characters which are legal in email addresses but which aren't picked up by
            // reddit (for example: '$' and '!').

            // Special characters as per https://en.wikipedia.org/wiki/Email_address#Local-part allowed
            char[] allowedchars = new char[] { '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~' };

            int start = tripPos;
            while (start > minStart)
            {
                char c = markdown[start - 1];
                if ((c < 'a' || c > 'z') &&
                    (c < 'A' || c > 'Z') &&
                    (c < '0' || c > '9') &&
                    !allowedchars.Contains(c))
                {
                    break;
                }

                start--;
            }

            // There must be at least one character before the '@'.
            if (start == tripPos)
            {
                return null;
            }

            // Search forwards until we find a character which is not a letter, digit, or one of
            // these characters: '-', '_'.
            // Note: it is intended that this code match the reddit.com markdown parser;
            // technically underscores ('_') aren't allowed in a host name.
            int dotIndex = tripPos + 1;
            while (dotIndex < maxEnd)
            {
                char c = markdown[dotIndex];
                if ((c < 'a' || c > 'z') &&
                    (c < 'A' || c > 'Z') &&
                    (c < '0' || c > '9') &&
                    c != '-' && c != '_')
                {
                    break;
                }

                dotIndex++;
            }

            // We are expecting a dot.
            if (dotIndex == maxEnd || markdown[dotIndex] != '.')
            {
                return null;
            }

            // Search forwards until we find a character which is not a letter, digit, or one of
            // these characters: '.', '-', '_'.
            // Note: it is intended that this code match the reddit.com markdown parser;
            // technically underscores ('_') aren't allowed in a host name.
            int end = dotIndex + 1;
            while (end < maxEnd)
            {
                char c = markdown[end];
                if ((c < 'a' || c > 'z') &&
                    (c < 'A' || c > 'Z') &&
                    (c < '0' || c > '9') &&
                    c != '.' && c != '-' && c != '_')
                {
                    break;
                }

                end++;
            }

            // There must be at least one character after the dot.
            if (end == dotIndex + 1)
            {
                return null;
            }

            // We found an email address!
            var emailAddress = markdown.Substring(start, end - start);
            return new InlineParseResult(new HyperlinkInline { Url = "mailto:" + emailAddress, Text = emailAddress, LinkType = HyperlinkType.Email }, start, end);
        }