Exemple #1
0
        public UnitReader(
            IProcessMemoryReader reader,
            GameMemoryTable memory,
            IStringReader stringReader,
            ISkillReader skillReader
            )
        {
            this.reader       = reader;
            this.stringReader = stringReader;
            this.skillReader  = skillReader;

            cachedItemData     = new Dictionary <IntPtr, D2ItemData>();
            cachedDescriptions = new Dictionary <int, D2ItemDescription>();

            globals          = reader.Read <D2GlobalData>(reader.ReadAddress32(memory.GlobalData));
            lowQualityTable  = reader.Read <D2SafeArray>(memory.LowQualityItems);
            descriptionTable = reader.Read <D2SafeArray>(memory.ItemDescriptions);
            magicModifiers   = reader.Read <ModifierTable>(memory.MagicModifierTable);
            rareModifiers    = reader.Read <ModifierTable>(memory.RareModifierTable);
            if (globals != null)
            {
                opNestings = reader.ReadArray <ushort>(globals.OpStatNesting, (int)globals.OpStatNestingCount);

                if (ItemStatCost == null && !globals.ItemStatCost.IsNull)
                {
                    ItemStatCost = reader.ReadArray <D2ItemStatCost>(globals.ItemStatCost, (int)globals.ItemStatCostCount);
                }
            }
        }
Exemple #2
0
 private IEnumerable <ChangeSet> ParseCommits(IStringReader reader)
 {
     while (!reader.Done)
     {
         yield return(ParseCommit(reader));
     }
 }
        public string GetString(IStringReader stringReader)
        {
            var lineValues = new List <string>();

            foreach (var instruction in Instructions)
            {
                // Get all jumps pointing to the current instruction
                var viableJumps = Jumps.Where(x => x.Instruction == instruction);

                // Add jump labels
                lineValues.AddRange(viableJumps.Select(x => x.GetString() + ":"));

                // Add instruction
                lineValues.Add("\t" + instruction.GetString(stringReader));
            }

            // Add jumps at end of function
            var endJumps = Jumps.Where(x => !Instructions.Contains(x.Instruction));

            lineValues.AddRange(endJumps.Select(x => x.GetString() + ":"));

            // Prepare other strings
            var lines      = string.Join(Environment.NewLine, lineValues);
            var parameters = string.Join(", ", Enumerable.Range(0, ParameterCount).Select(x => $"$p{x}"));
            var unknowns   = string.Join(',', Unknowns);

            // Build final function
            var functionParts  = new[] { $"{Name}<{unknowns}>({parameters})" };
            var functionParts2 = !lines.Any() ? new[] { "{", "}" } : new[] { "{", lines, "}" };

            return(string.Join(Environment.NewLine, functionParts.Concat(functionParts2)));
        }
Exemple #4
0
        public ReadResults Parse(IStringReader reader, DispatcherResources resources, out Message result)
        {
            result = default;
            string message = reader.GetRemaining();
            Dictionary <int, EntitySelector> selectors = new Dictionary <int, EntitySelector>();

            while (reader.CanRead())
            {
                if (reader.Peek() == '@')
                {
                    if (reader.CanRead(2) && "parse".Contains(reader.Peek(1)))
                    {
                        int         start       = reader.GetCursor();
                        ReadResults readResults = new EntitySelectorParser(reader, resources, UseBedrock).Parse(out EntitySelector entitySelector);
                        if (!readResults.Successful)
                        {
                            return(readResults);
                        }
                        selectors.Add(start, entitySelector);
                    }
                    else
                    {
                        reader.Skip(2);
                    }
                    continue;
                }
                reader.Skip();
            }

            result = new Message(message, selectors);
            return(ReadResults.Success());
        }
Exemple #5
0
        public ReadResults Parse(IStringReader reader, DispatcherResources resources, out NbtPath result)
        {
            result = default;

            int  start  = reader.GetCursor();
            bool isRoot = true;

            ReadResults readResults;

            while (!reader.AtEndOfArgument())
            {
                readResults = ParseNode(reader, isRoot);
                if (!readResults.Successful)
                {
                    return(readResults);
                }

                isRoot = false;
                if (!reader.CanRead())
                {
                    continue;
                }
                char c = reader.Peek();
                if (c == ' ' || c == '[' || c == '{')
                {
                    continue;
                }
                readResults = reader.Expect('.');
                if (!readResults.Successful)
                {
                    return(readResults);
                }
            }
            result = new NbtPath(reader.GetString()[start..reader.GetCursor()]);
Exemple #6
0
            public static DiffRange Parse(IStringReader reader)
            {
                var range = new DiffRange();

                reader.Skip("@@");
                reader.SkipWhitespace();
                reader.Skip('-');
                range.LeftFrom = reader.ReadInt();
                if (reader.Skip(','))
                {
                    range.LeftTo = range.LeftFrom + reader.ReadInt();
                }
                else
                {
                    range.LeftTo = range.LeftFrom;
                }
                reader.SkipWhitespace();
                reader.Skip('+');
                range.RightFrom = reader.ReadInt();
                if (reader.Skip(','))
                {
                    range.RightTo = range.RightFrom + reader.ReadInt();
                }
                else
                {
                    range.RightTo = range.RightFrom;
                }
                reader.SkipWhitespace();
                reader.Skip("@@");
                return(range);
            }
Exemple #7
0
        public ReadResults Parse(IStringReader reader, DispatcherResources resources, out Team result)
        {
            ReadResults readResults = reader.ReadUnquotedString(out string team);

            result = new Team(team);
            return(readResults);
        }
        public ReadResults Handle(EntitySelectorParser parser, DispatcherResources resources, string name, int start, bool useBedrock)
        {
            IStringReader reader  = parser.GetReader();
            bool          negated = false;

            if (AllowInverse)
            {
                negated = parser.ShouldInvertValue();
            }

            ReadResults readResults = Option switch
            {
                Option.SetLimit => SetLimit(parser, reader),
                Option.SetExecutor => SetExecutor(parser, reader, negated, name, start, resources, useBedrock),
                Option.Advancements => ReadAdvancements(parser, reader),
                Option.Scores => ReadScores(parser, reader),
                Option.Gamemode => ReadGamemode(parser, reader, resources),
                Option.Sort => ReadSort(parser, reader, name, start, resources),
                _ => CheckComponents(parser, reader, resources)
            };

            if (readResults.Successful)
            {
                parser.Apply(name, negated);
            }
            return(readResults);
        }
        public SkillReader(IProcessMemoryReader reader, GameMemoryTable memory)
        {
            this.reader = reader;

            globals      = reader.Read <D2GlobalData>(reader.ReadAddress32(memory.GlobalData, AddressingMode.Relative));
            stringReader = new StringReader(reader, memory);
        }
        public ReadResults Parse(IStringReader reader, DispatcherResources resources, out Time result)
        {
            result = default;
            ReadResults readResults = reader.ReadFloat(out float time);

            if (!readResults.Successful)
            {
                return(readResults);
            }

            if (time < 0.0f)
            {
                return(ReadResults.Failure(CommandError.InvalidTickCount()));
            }

            if (!reader.AtEndOfArgument())
            {
                if (resources.TimeScalars.TryGetScalar(reader.Peek(), out int scalar))
                {
                    time *= scalar;
                    reader.Skip();
                }
                else
                {
                    return(ReadResults.Failure(CommandError.InvalidTimeUnit().WithContext(reader)));
                }
            }

            result = new Time((int)time);
            return(ReadResults.Success());
        }
Exemple #11
0
 public ItemParser(IStringReader stringReader, DispatcherResources resources, bool forTesting, bool useBedrock)
 {
     StringReader = stringReader;
     Resources    = resources;
     ForTesting   = forTesting;
     UseBedrock   = useBedrock;
 }
        private static ReadResults ReadSort(EntitySelectorParser parser, IStringReader reader, string originalName, int previousStart, DispatcherResources resources)
        {
            if (parser.IsSorted())
            {
                reader.SetCursor(previousStart);
                return(ReadResults.Failure(CommandError.InapplicableOption(originalName).WithContext(reader)));
            }

            int         start       = reader.GetCursor();
            ReadResults readResults = reader.ReadUnquotedString(out string sort);

            if (!readResults.Successful)
            {
                return(readResults);
            }

            if (resources.Sorts.Contains(sort))
            {
                parser.AddArgument(new ParsedArgument <Literal>(new Literal(sort), false));
                return(ReadResults.Success());
            }
            else
            {
                reader.SetCursor(start);
                return(ReadResults.Failure(CommandError.UnknownSort(sort).WithContext(reader)));
            }
        }
        internal static void ParseSummary(IStringReader reader, ChangeSetDetail detail)
        {
            reader.SkipWhitespace();

            while (!reader.Done)
            {
                string line = reader.ReadLine();

                if (ParserHelpers.IsSingleNewLine(line))
                {
                    break;
                }
                else if (line.Contains('\t'))
                {
                    // n	n	path
                    string[] parts = line.Split('\t');
                    int      insertions;
                    Int32.TryParse(parts[0], out insertions);
                    int deletions;
                    Int32.TryParse(parts[1], out deletions);
                    string path = parts[2].TrimEnd();

                    detail.Files[path] = new FileInfo {
                        Insertions = insertions,
                        Deletions  = deletions,
                        Binary     = parts[0] == "-" && parts[1] == "-"
                    };
                }
                else
                {
                    // n files changed, n insertions(+), n deletions(-)
                    ParserHelpers.ParseSummaryFooter(line, detail);
                }
            }
        }
Exemple #14
0
        public ReadResults Parse(IStringReader reader, DispatcherResources resources, out EntitySelector result)
        {
            int start = reader.GetCursor();
            EntitySelectorParser entitySelectorParser = new EntitySelectorParser(reader, resources, UseBedrock);
            ReadResults          readResults          = entitySelectorParser.Parse(out result);

            if (!readResults.Successful)
            {
                return(readResults);
            }

            if (result.MaxResults > 1 && SingleEntity)
            {
                reader.SetCursor(start);
                if (PlayersOnly)
                {
                    return(ReadResults.Failure(CommandError.SelectorTooManyPlayers().WithContext(reader)));
                }
                else
                {
                    return(ReadResults.Failure(CommandError.SelectorTooManyEntities().WithContext(reader)));
                }
            }
            if (result.IncludesEntities && PlayersOnly && !result.IsSelf)
            {
                reader.SetCursor(start);
                return(ReadResults.Failure(CommandError.SelectorPlayersOnly().WithContext(reader)));
            }

            return(ReadResults.Success());
        }
 public EntitySelectorParser(IStringReader reader, DispatcherResources resources, bool useBedrock)
 {
     Reader     = reader;
     Start      = reader.GetCursor();
     Resources  = resources;
     UseBedrock = useBedrock;
 }
Exemple #16
0
        internal ChangeSetDetail PopulateDetails(string id, ChangeSetDetail detail)
        {
            var summaryCommand = new DiffCommand
            {
                SummaryOnly = true
            };

            if (!String.IsNullOrEmpty(id))
            {
                summaryCommand.ChangeIntroducedByRevision = id;
            }

            IStringReader summaryReader = Repository.Diff(summaryCommand).AsReader();

            ParseSummary(summaryReader, detail);

            var diffCommand = new DiffCommand
            {
                UseGitDiffFormat = true,
            };

            if (!String.IsNullOrEmpty(id))
            {
                diffCommand.ChangeIntroducedByRevision = id;
            }

            var diffReader = Repository.Diff(diffCommand).AsReader();

            GitExeRepository.ParseDiffAndPopulate(diffReader, detail);

            return(detail);
        }
        public ReadResults Parse(IStringReader reader, DispatcherResources resources, out Objective result)
        {
            result = default;
            ReadResults readResults;
            string      objective;

            if (UseBedrock)
            {
                readResults = reader.ReadString(out objective);
            }
            else
            {
                readResults = reader.ReadUnquotedString(out objective);
            }

            if (!readResults.Successful)
            {
                return(readResults);
            }
            if (objective.Length > 16)
            {
                return(ReadResults.Failure(CommandError.ObjectiveNameTooLong()));
            }
            result = new Objective(objective);
            return(ReadResults.Success());
        }
Exemple #18
0
        public ItemInfo(
            Item item,
            D2Unit owner,
            UnitReader unitReader,
            IStringReader stringReader,
            IInventoryReader inventoryReader
            )
        {
            Class        = item.Unit.eClass;
            ItemName     = unitReader.GetFullItemName(item);
            ItemBaseName = BaseItemName(item, unitReader);
            QualityColor = QualityColorDefault(item);
            Properties   = unitReader.GetMagicalStrings(item, owner, inventoryReader);
            Location     = item.ItemData.BodyLoc;

            // Backward compatibility for D2ID:
            // TODO: add Slug/Image/EnglishBaseName or something like that, D2ID currently uses ItemName/BaseItem for
            // displaying images, which doesnt work for languages other than english, so BaseItem will be
            // the english version, to show at least some item. also Quality is set to "YELLOW" in case of
            // unique and set, if game is not english, so that D2ID falls back to the
            // BaseItem img and shows the "unique" / "set" name above the BaseItem
            if (stringReader.Language == Language.English)
            {
                BaseItem = ItemBaseName;
                Quality  = QualityColor;
            }
            else
            {
                BaseItem = BaseItemNameFallback(item, unitReader);
                Quality  = QualityColorFallback(item);
            }
        }
Exemple #19
0
        public override ReadResults Parse(IStringReader reader, CommandContext builder, DispatcherResources resources)
        {
            int start = reader.GetCursor();
            int end   = Parse(reader);

            if (end > -1)
            {
                ParsedArgument <Literal> parsed = new ParsedArgument <Literal>(new Literal(reader.GetString()[start..end]), builder.InRoot);
 public ReadResults Parse(IStringReader reader, DispatcherResources resources, out ICoordinates result)
 {
     if (reader.CanRead() && reader.Peek() == '^')
     {
         return(new LocalCoordinatesParser(reader, UseBedrock).Parse(out result));
     }
     return(new WorldCoordinatesParser(reader, UseBedrock).ParseDouble(out result));
 }
Exemple #21
0
        public string GetString(IStringReader stringReader)
        {
            var args            = string.Join(", ", Arguments.Select(x => x.GetString(InstructionType, stringReader)));
            var subName         = RoutineMap.ContainsKey(InstructionType) ? RoutineMap[InstructionType] : $"sub{InstructionType}";
            var returnParameter = Parameter.Parse(ReturnParameter);

            return($"{returnParameter.ParameterName} = {subName}({args})");
        }
 private static void VerifyInitialState(IStringReader reader)
 {
     Assert.IsNotNull(reader);
     Assert.AreEqual(char.MinValue, reader.CurrentChar);
     Assert.IsFalse(reader.IsEof);
     Assert.IsFalse(reader.IsEmpty);
     Assert.AreEqual(0, reader.Line);
     Assert.AreEqual(-1, reader.LineOffset);
 }
 private static void VerifyEmptyReadingByLines(IStringReader reader)
 {
     Assert.IsNotNull(reader);
     Assert.IsTrue(reader.IsEmpty);
     Assert.AreEqual(null, reader.ReadLine());
     Assert.AreEqual(0, reader.Line);
     Assert.AreEqual(-1, reader.LineOffset);
     Assert.AreEqual(char.MinValue, reader.CurrentChar);
 }
Exemple #24
0
        public static ReadResults TryRead(IStringReader stringReader, out ResourceLocation result)
        {
            int start = stringReader.GetCursor();

            while (stringReader.CanRead() && IsAllowedInResourceLocation(stringReader.Peek()))
            {
                stringReader.Skip();
            }
            string input = stringReader.GetString()[start..stringReader.GetCursor()];
        public ReadResults Parse(IStringReader reader, DispatcherResources resources, out UUID result)
        {
            int start = reader.GetCursor();

            while (reader.CanRead() && IsUuidPart(reader.Peek()))
            {
                reader.Skip();
            }
            string uuid = reader.GetString()[start..reader.GetCursor()];
 private static void VerifyInitialState(IStringReader reader)
 {
     Assert.IsNotNull(reader);
     Assert.AreEqual(char.MinValue, reader.CurrentChar);
     Assert.IsFalse(reader.IsEof);
     Assert.IsFalse(reader.IsEmpty);
     Assert.AreEqual(0, reader.Line);
     Assert.AreEqual(-1, reader.LineOffset);
 }
Exemple #27
0
        /// <summary>
        /// Sets the new input for processing.
        /// </summary>
        public void SetSource(string input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            _input = StringHelper.CreateReader(input);
        }
        private static void VerifyReadingSimpleText(IStringReader reader)
        {
            Assert.IsNotNull(reader);

            // read first line:
            var c = reader.ReadNext();

            Assert.AreEqual('a', c);
            Assert.AreEqual('a', reader.CurrentChar);
            Assert.AreEqual(0, reader.Line);
            Assert.AreEqual(0, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\r', c);
            Assert.AreEqual(0, reader.Line);
            Assert.AreEqual(1, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\n', c);
            Assert.AreEqual('\n', reader.CurrentChar);
            Assert.AreEqual(0, reader.Line);
            Assert.AreEqual(2, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('b', c);
            Assert.AreEqual('b', reader.CurrentChar);
            Assert.AreEqual(1, reader.Line);
            Assert.AreEqual(0, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\r', c);
            Assert.AreEqual('\r', reader.CurrentChar);
            Assert.AreEqual(1, reader.Line);
            Assert.AreEqual(1, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\n', c);
            Assert.AreEqual('\n', reader.CurrentChar);
            Assert.AreEqual(1, reader.Line);
            Assert.AreEqual(2, reader.LineOffset);
            Assert.IsFalse(reader.IsEof);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\0', c);
            Assert.AreEqual('\0', reader.CurrentChar);
            Assert.AreEqual(2, reader.Line);
            Assert.AreEqual(-1, reader.LineOffset);
            Assert.IsTrue(reader.IsEof);
            Assert.IsFalse(reader.IsEmpty);
        }
        public BlockParser(IStringReader stringReader, bool forTesting, DispatcherResources resources, bool useBedrock)
        {
            StringReader = stringReader;
            ForTesting   = forTesting;
            Resources    = resources;
            UseBedrock   = useBedrock;

            Block = null;
            IsTag = false;
        }
        void CreateReaders()
        {
            stringReader = new StringReader(reader, memory);
            skillReader  = new SkillReader(reader, memory);

            // note: readers need to be recreated everytime before read.. at least unitReader
            // unitReader fails sometimes... if this is not done .. why? not sure yet ~_~
            unitReader      = new UnitReader(reader, memory, stringReader, skillReader);
            inventoryReader = new InventoryReader(reader, unitReader);
        }
        public ReadResults Parse(IStringReader reader, DispatcherResources resources, out StructureRotation result)
        {
            result = default;
            int start = reader.GetCursor();

            while (reader.CanRead() && IsUnquotedStringPart(reader.Peek()))
            {
                reader.Skip();
            }
            string structureRotation = reader.GetString()[start..reader.GetCursor()];
Exemple #32
0
        internal static void ParseSummary(IStringReader reader, ChangeSetDetail detail)
        {
            reader.SkipWhitespace();

            while (!reader.Done)
            {
                string line = reader.ReadLine();

                if (ParserHelpers.IsSingleNewLine(line))
                {
                    break;
                }
                else if (line.Contains('\t'))
                {
                    // n	n	path
                    string[] parts = line.Split('\t');
                    int insertions;
                    Int32.TryParse(parts[0], out insertions);
                    int deletions;
                    Int32.TryParse(parts[1], out deletions);
                    string path = parts[2].TrimEnd();

                    detail.Files[path] = new FileInfo
                    {
                        Insertions = insertions,
                        Deletions = deletions,
                        Binary = parts[0] == "-" && parts[1] == "-"
                    };
                }
                else
                {
                    // n files changed, n insertions(+), n deletions(-)
                    ParserHelpers.ParseSummaryFooter(line, detail);
                }
            }
        }
        internal static StringHelperStatusCode ReadCommentChars(IStringReader reader, bool multiline)
        {
            if (multiline)
            {
                char previousChar;
                char currentChar = '\0';
                do
                {
                    previousChar = currentChar;
                    currentChar = reader.ReadNext();

                    if (reader.IsEof)
                        return StringHelperStatusCode.UnexpectedEoF;

                    if (previousChar == '*' && currentChar == '/')
                        return StringHelperStatusCode.Success;
                }
                while (true);
            }
            else
            {
                do
                {
                    var currentChar = reader.ReadNext();

                    if (reader.IsEof)
                        return StringHelperStatusCode.UnexpectedEoF;

                    if (currentChar == '\r' || currentChar == '\n')
                        return StringHelperStatusCode.Success;
                }
                while (true);
            }
        }
 /// <summary>
 /// Reads from the current input stream all the whitespaces.
 /// </summary>
 internal static StringHelperStatusCode ReadWhiteChars(IStringReader reader)
 {
     int count;
     return ReadWhiteChars(reader, out count);
 }
        private static int Parse(IStringReader input, object o, string startTag, string endTag, Callback onText, Callback onMarker)
        {
            if (input == null)
                throw new ArgumentNullException("input");
            if (string.IsNullOrEmpty(startTag))
                throw new ArgumentNullException("startTag");
            if (string.IsNullOrEmpty(endTag))
                throw new ArgumentNullException("endTag");
            if (onText == null && onMarker == null)
                throw new ArgumentNullException("onText");

            if (input.IsEmpty)
                return 0;

            string line;
            string substring;
            int processingStart;
            int startIndex;
            int endIndex;
            int result = 0;
            StringBuilder text = new StringBuilder();
            StringBuilder content = new StringBuilder();
            bool insideTag = false;
            bool continueProcessing;


            while ((line = input.ReadLine()) != null)
            {
                processingStart = 0;

                do
                {
                    // is there any tag in current line:
                    startIndex = insideTag ? -1 : line.IndexOf(startTag, processingStart, StringComparison.Ordinal);
                    continueProcessing = false;

                    if (startIndex < 0)
                    {
                        if (insideTag)
                        {
                            endIndex = line.IndexOf(endTag, processingStart, StringComparison.Ordinal);

                            if (endIndex < 0)
                            {
                                // add content of the tag
                                content.Append(processingStart > 0 ? line.Substring(processingStart) : line).Append("\r\n");
                            }
                            else
                            {
                                // was there any text before
                                if (text.Length > 0)
                                {
                                    if (onText != null)
                                        onText(o, text.ToString());
#if NET_2_COMPATIBLE || SILVERLIGHT
                                    text.Remove(0, text.Length);
#else
                                    text.Clear();
#endif
                                }

                                // append beginning as a tag
                                if (content.Length > 0)
                                {
                                    substring = content.Append(line.Substring(processingStart, endIndex - processingStart)).ToString();
#if NET_2_COMPATIBLE || SILVERLIGHT
                                    content.Remove(0, content.Length);
#else
                                    content.Clear();
#endif
                                }
                                else
                                {
                                    substring = line.Substring(processingStart, endIndex - processingStart);
                                }

                                if (onMarker != null)
                                    onMarker(o, substring);

                                result++;
                                insideTag = false;
                                continueProcessing = true;
                                processingStart = endIndex + endTag.Length;
                            }
                        }
                        else
                        {
                            // add the whole line into the buffer, so we minimize the number of notifications
                            text.Append(processingStart > 0 ? line.Substring(processingStart) : line);

                            if (!input.IsEof)
                                text.Append("\r\n");
                        }
                    }
                    else
                    {
                        // text before tag
                        if (startIndex > processingStart || text.Length > 0)
                        {
                            if (text.Length > 0)
                            {
                                substring = text.Append(line.Substring(processingStart, startIndex - processingStart)).ToString();
#if NET_2_COMPATIBLE || SILVERLIGHT
                                text.Remove(0, text.Length);
#else
                                text.Clear();
#endif
                            }
                            else
                                substring = line.Substring(processingStart, startIndex - processingStart);

                            if (onText != null)
                                onText(o, substring);
                        }

                        // tag:
                        endIndex = line.IndexOf(endTag, startIndex + startTag.Length, StringComparison.Ordinal);
                        if (endIndex < 0)
                        {
                            // add rest of the line as the content of the tag
                            content.Append(line.Substring(startIndex + startTag.Length)).Append("\r\n");
                            insideTag = true;
                        }
                        else
                        {
                            if (content.Length > 0)
                            {
                                substring = content.Append(line.Substring(startIndex + startTag.Length, endIndex - startIndex - endTag.Length)).ToString();
#if NET_2_COMPATIBLE || SILVERLIGHT
                                content.Remove(0, content.Length);
#else
                                content.Clear();
#endif
                            }
                            else
                            {
                                substring = line.Substring(startIndex + startTag.Length, endIndex - startIndex - endTag.Length);
                            }

                            if (onMarker != null)
                                onMarker(o, substring);

                            result++;
                            insideTag = false;
                            continueProcessing = true;
                            processingStart = endIndex + endTag.Length;
                        }
                    }
                } while (continueProcessing);
            }

            if (insideTag || content.Length > 0)
                throw new FormatException(string.Concat("Unclosed tag with content: '", content, "'"));

            if (onText != null && text.Length > 0)
                onText(o, text.ToString());

            return result;
        }
 private static void VerifyEmptyReadingByLines(IStringReader reader)
 {
     Assert.IsNotNull(reader);
     Assert.IsTrue(reader.IsEmpty);
     Assert.AreEqual(null, reader.ReadLine());
     Assert.AreEqual(0, reader.Line);
     Assert.AreEqual(-1, reader.LineOffset);
     Assert.AreEqual(char.MinValue, reader.CurrentChar);
 }
Exemple #37
0
 public static DiffRange Parse(IStringReader reader)
 {
     var range = new DiffRange();
     reader.Skip("@@");
     reader.SkipWhitespace();
     reader.Skip('-');
     range.LeftFrom = reader.ReadInt();
     if (reader.Skip(','))
     {
         range.LeftTo = range.LeftFrom + reader.ReadInt();
     }
     else
     {
         range.LeftTo = range.LeftFrom;
     }
     reader.SkipWhitespace();
     reader.Skip('+');
     range.RightFrom = reader.ReadInt();
     if (reader.Skip(','))
     {
         range.RightTo = range.RightFrom + reader.ReadInt();
     }
     else
     {
         range.RightTo = range.RightFrom;
     }
     reader.SkipWhitespace();
     reader.Skip("@@");
     return range;
 }
Exemple #38
0
        private static ChangeSetDetail ParseShow(IStringReader reader, bool includeChangeSet = true)
        {
            ChangeSetDetail detail = null;
            if (includeChangeSet)
            {
                detail = ParseCommitAndSummary(reader);
            }
            else
            {
                detail = new ChangeSetDetail();
                ParseSummary(reader, detail);
            }

            ParseDiffAndPopulate(reader, detail);

            return detail;
        }
        /// <summary>
        /// Reads from the current input stream all the whitespaces.
        /// </summary>
        internal static StringHelperStatusCode ReadWhiteChars(IStringReader reader, out int count)
        {
            count = 0;

            do
            {
                char currentChar = reader.ReadNext();

                if (reader.IsEof)
                    return StringHelperStatusCode.UnexpectedEoF;

                if (!char.IsWhiteSpace(currentChar))
                    break;

                count++;
            }
            while (true);

            return StringHelperStatusCode.Success;
        }
        /// <summary>
        /// Reads characters that might be a number and copies them to given output.
        /// </summary>
        internal static StringHelperStatusCode ReadIntegerNumberChars(IStringReader reader, StringBuilder output)
        {
            do
            {
                var currentChar = reader.ReadNext();

                if (char.IsDigit(currentChar) || currentChar == '-' || currentChar == '+')
                {
                    output.Append(currentChar);
                }
                else
                    break;
            }
            while (true);

            return StringHelperStatusCode.Success;
        }
Exemple #41
0
        internal static void ParseSummary(IStringReader reader, ChangeSetDetail detail)
        {
            while (!reader.Done)
            {
                string line = reader.ReadLine();
                if (line.Contains('|'))
                {
                    string[] parts = line.Split('|');
                    string path = parts[0].Trim();

                    // TODO: Figure out a way to get this information
                    detail.Files[path] = new FileInfo();
                }
                else
                {
                    // n files changed, n insertions(+), n deletions(-)
                    ParserHelpers.ParseSummaryFooter(line, detail);
                }
            }
        }
        /// <summary>
        /// Reads the string from given input stream.
        /// </summary>
        internal static StringHelperStatusCode ReadStringChars(IStringReader reader, StringBuilder output, StringBuilder escapedUnicodeNumberBuffer, bool errorOnNewLine, out int lastLine, out int lastOffset)
        {
            bool escape = false;
            bool unicodeNumber = false;

            if (escapedUnicodeNumberBuffer == null)
                escapedUnicodeNumberBuffer = new StringBuilder();

            lastLine = reader.Line;
            lastOffset = reader.LineOffset;

            do
            {
                if (!unicodeNumber)
                {
                    lastLine = reader.Line;
                    lastOffset = reader.LineOffset;
                }

                var currentChar = reader.ReadNext();

                // verify if not an invalid character was found in text:
                if (reader.IsEof)
                    return StringHelperStatusCode.UnexpectedEoF;
                if (errorOnNewLine && (currentChar == '\r' || currentChar == '\n'))
                    return StringHelperStatusCode.UnexpectedNewLine;

                if (unicodeNumber)
                {
                    StringHelperStatusCode result = ReadStringUnicodeCharacter(currentChar, output, escapedUnicodeNumberBuffer, out unicodeNumber);

                    // if parsing Unicode character failed, immediatelly stop!
                    if (result != StringHelperStatusCode.Success)
                        return result;

                    continue;
                }

                if (currentChar == '\\' && !escape)
                {
                    escape = true;
                }
                else
                {
                    if (escape)
                    {
                        switch (currentChar)
                        {
                            case 'n':
                                output.Append('\n');
                                break;
                            case 'r':
                                output.Append('\r');
                                break;
                            case 't':
                                output.Append('\t');
                                break;
                            case '/':
                                output.Append('/');
                                break;
                            case '\\':
                                output.Append('\\');
                                break;
                            case 'f':
                                output.Append('\f');
                                break;
                            case 'U':
                            case 'u':
                                unicodeNumber = true;
                                break;
                            case '"':
                                output.Append('"');
                                break;
                            case '\'':
                                output.Append('\'');
                                break;
                            default:
                                return StringHelperStatusCode.UnknownEscapedChar;
                        }

                        escape = false;
                    }
                    else
                    {
                        if (currentChar == '"')
                            break;

                        output.Append(currentChar);
                    }
                }
            }
            while (true);

            // as the string might finish with a Unicode character...
            if (unicodeNumber)
                return AddUnicodeChar(output, escapedUnicodeNumberBuffer, false);

            return StringHelperStatusCode.Success;
        }
        /// <summary>
        /// Reads the keyword definition chars from given input.
        /// </summary>
        internal static StringHelperStatusCode ReadKeywordChars(IStringReader reader, StringBuilder output)
        {
            do
            {
                var currentChar = reader.ReadNext();

                if (char.IsLetter(currentChar))
                {
                    output.Append(currentChar);
                }
                else
                    break;
            }
            while (true);

            return StringHelperStatusCode.Success;
        }
Exemple #44
0
 internal static void PopulateStatus(IStringReader reader, ChangeSetDetail detail)
 {
     while (!reader.Done)
     {
         string line = reader.ReadLine();
         // Status lines contain tabs
         if (!line.Contains("\t"))
         {
             continue;
         }
         var lineReader = line.AsReader();
         string status = lineReader.ReadUntilWhitespace();
         lineReader.SkipWhitespace();
         string name = lineReader.ReadToEnd().TrimEnd();
         lineReader.SkipWhitespace();
         FileInfo file;
         if (detail.Files.TryGetValue(name, out file))
         {
             file.Status = ConvertStatus(status);
         }
     }
 }
Exemple #45
0
        internal static ChangeSet ParseCommit(IStringReader reader)
        {
            // commit hash
            reader.ReadUntilWhitespace();
            reader.SkipWhitespace();
            string id = reader.ReadUntilWhitespace();

            // Merges will have (from hash) so we're skipping that
            reader.ReadLine();

            string author = null;
            string email = null;
            string date = null;

            while (!reader.Done)
            {
                string line = reader.ReadLine();

                if (ParserHelpers.IsSingleNewLine(line))
                {
                    break;
                }

                var subReader = line.AsReader();
                string key = subReader.ReadUntil(':');
                // Skip :
                subReader.Skip();
                subReader.SkipWhitespace();
                string value = subReader.ReadToEnd().Trim();

                if (key.Equals("Author", StringComparison.OrdinalIgnoreCase))
                {
                    // Author <email>
                    var authorReader = value.AsReader();
                    author = authorReader.ReadUntil('<').Trim();
                    authorReader.Skip();
                    email = authorReader.ReadUntil('>');
                }
                else if (key.Equals("Date", StringComparison.OrdinalIgnoreCase))
                {
                    date = value;
                }
            }

            var messageBuilder = new StringBuilder();
            while (!reader.Done)
            {
                string line = reader.ReadLine();

                if (ParserHelpers.IsSingleNewLine(line))
                {
                    break;
                }
                messageBuilder.Append(line);
            }

            string message = messageBuilder.ToString();
            return new ChangeSet(id, author, email, message, DateTimeOffset.ParseExact(date, "ddd MMM d HH:mm:ss yyyy zzz", CultureInfo.InvariantCulture));
        }
Exemple #46
0
        private static FileDiff ParseDiffHeader(IStringReader reader, ChangeSetDetail merge)
        {
            string fileName = ParseFileName(reader.ReadLine());
            bool binary = false;

            while (!reader.Done)
            {
                string line = reader.ReadLine();
                if (line.StartsWith("@@", StringComparison.Ordinal))
                {
                    reader.PutBack(line.Length);
                    break;
                }
                else if (line.StartsWith("GIT binary patch", StringComparison.Ordinal))
                {
                    binary = true;
                }
            }

            if (binary)
            {
                // Skip binary files
                reader.ReadToEnd();
            }

            var diff = new FileDiff(fileName)
            {
                Binary = binary
            };

            // Skip files from merged changesets
            if (merge != null && merge.Files.ContainsKey(fileName))
            {
                return null;
            }

            return diff;
        }
Exemple #47
0
        internal static ChangeSetDetail ParseCommitAndSummary(IStringReader reader)
        {
            // Parse the changeset
            ChangeSet changeSet = ParseCommit(reader);

            var detail = new ChangeSetDetail(changeSet);

            ParseSummary(reader, detail);

            return detail;
        }
Exemple #48
0
 private IEnumerable<ChangeSet> ParseCommits(IStringReader reader)
 {
     while (!reader.Done)
     {
         yield return ParseCommit(reader);
     }
 }
Exemple #49
0
        /// <summary>
        /// Sets the new input for processing.
        /// </summary>
        public void SetSource(string input)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            _input = StringHelper.CreateReader(input);
        }
 public object Deserialize(IStringReader reader)
 {
     return xmlSerializer.Deserialize(reader.ToStringReader());
 }
Exemple #51
0
        internal static void ParseDiffAndPopulate(IStringReader reader, ChangeSetDetail detail)
        {
            foreach (var diff in ParseDiff(reader))
            {
                FileInfo stats;
                if (!detail.Files.TryGetValue(diff.FileName, out stats))
                {
                    stats = new FileInfo();
                    detail.Files.Add(diff.FileName, stats);
                }

                // Set the binary flag if any of the files are binary
                bool binary = diff.Binary || stats.Binary;
                stats.Binary = binary;
                diff.Binary = binary;

                foreach (var line in diff.Lines)
                {
                    stats.DiffLines.Add(line);
                }
            }
        }
        private static void VerifyReadingByLines(IStringReader reader)
        {
            var line = reader.ReadLine();
            Assert.IsNotNull(reader);
            Assert.AreEqual(string.Empty, line);
            Assert.AreEqual('\n', reader.CurrentChar);
            Assert.AreEqual(0, reader.Line);
            Assert.AreEqual(0, reader.LineOffset);

            line = reader.ReadLine();
            Assert.AreEqual(string.Empty, line);
            Assert.AreEqual('\n', reader.CurrentChar);
            Assert.AreEqual(1, reader.Line);
            Assert.AreEqual(1, reader.LineOffset);
        }
Exemple #53
0
        internal static FileDiff ParseDiffChunk(IStringReader reader, ref ChangeSetDetail merge)
        {
            var diff = ParseDiffHeader(reader, merge);

            if (diff == null)
            {
                return null;
            }

            // Current diff range
            DiffRange currentRange = null;
            int? leftCounter = null;
            int? rightCounter = null;

            // Parse the file diff
            while (!reader.Done)
            {
                int? currentLeft = null;
                int? currentRight = null;
                string line = reader.ReadLine();

                if (line.Equals(@"\ No newline at end of file", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                bool isDiffRange = line.StartsWith("@@", StringComparison.Ordinal);
                ChangeType? changeType = null;

                if (line.StartsWith("+", StringComparison.Ordinal))
                {
                    changeType = ChangeType.Added;
                    currentRight = ++rightCounter;
                    currentLeft = null;
                }
                else if (line.StartsWith("-", StringComparison.Ordinal))
                {
                    changeType = ChangeType.Deleted;
                    currentLeft = ++leftCounter;
                    currentRight = null;
                }
                else if (IsCommitHeader(line))
                {
                    reader.PutBack(line.Length);
                    merge = ParseCommitAndSummary(reader);
                }
                else
                {
                    if (!isDiffRange)
                    {
                        currentLeft = ++leftCounter;
                        currentRight = ++rightCounter;
                    }
                    changeType = ChangeType.None;
                }

                if (changeType != null)
                {
                    var lineDiff = new LineDiff(changeType.Value, line);
                    if (!isDiffRange)
                    {
                        lineDiff.LeftLine = currentLeft;
                        lineDiff.RightLine = currentRight;
                    }

                    diff.Lines.Add(lineDiff);
                }

                if (isDiffRange)
                {
                    // Parse the new diff range
                    currentRange = DiffRange.Parse(line.AsReader());
                    leftCounter = currentRange.LeftFrom - 1;
                    rightCounter = currentRange.RightFrom - 1;
                }
            }

            return diff;
        }
        private static void VerifyReadingSimpleText(IStringReader reader)
        {
            Assert.IsNotNull(reader);

            // read first line:
            var c = reader.ReadNext();
            Assert.AreEqual('a', c);
            Assert.AreEqual('a', reader.CurrentChar);
            Assert.AreEqual(0, reader.Line);
            Assert.AreEqual(0, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\r', c);
            Assert.AreEqual(0, reader.Line);
            Assert.AreEqual(1, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\n', c);
            Assert.AreEqual('\n', reader.CurrentChar);
            Assert.AreEqual(0, reader.Line);
            Assert.AreEqual(2, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('b', c);
            Assert.AreEqual('b', reader.CurrentChar);
            Assert.AreEqual(1, reader.Line);
            Assert.AreEqual(0, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\r', c);
            Assert.AreEqual('\r', reader.CurrentChar);
            Assert.AreEqual(1, reader.Line);
            Assert.AreEqual(1, reader.LineOffset);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\n', c);
            Assert.AreEqual('\n', reader.CurrentChar);
            Assert.AreEqual(1, reader.Line);
            Assert.AreEqual(2, reader.LineOffset);
            Assert.IsFalse(reader.IsEof);
            Assert.IsFalse(reader.IsEmpty);

            c = reader.ReadNext();
            Assert.AreEqual('\0', c);
            Assert.AreEqual('\0', reader.CurrentChar);
            Assert.AreEqual(2, reader.Line);
            Assert.AreEqual(-1, reader.LineOffset);
            Assert.IsTrue(reader.IsEof);
            Assert.IsFalse(reader.IsEmpty);
        }
Exemple #55
0
        internal static IEnumerable<FileStatus> ParseStatus(IStringReader reader)
        {
            reader.SkipWhitespace();

            while (!reader.Done)
            {
                var subReader = reader.ReadLine().AsReader();
                string status = subReader.ReadUntilWhitespace().Trim();
                string path = subReader.ReadLine().Trim();
                yield return new FileStatus(path, ConvertStatus(status));
                reader.SkipWhitespace();
            }
        }
Exemple #56
0
        internal static IEnumerable<FileDiff> ParseDiff(IStringReader reader)
        {
            var builder = new StringBuilder();

            // If this was a merge change set then we'll parse the details out of the
            // first diff
            ChangeSetDetail merge = null;

            do
            {
                string line = reader.ReadLine();

                // If we see a new diff header then process the previous diff if any
                if ((reader.Done || IsDiffHeader(line)) && builder.Length > 0)
                {
                    if (reader.Done)
                    {
                        builder.Append(line);
                    }
                    string diffChunk = builder.ToString();
                    FileDiff diff = ParseDiffChunk(diffChunk.AsReader(), ref merge);

                    if (diff != null)
                    {
                        yield return diff;
                    }

                    builder.Clear();
                }

                if (!reader.Done)
                {
                    builder.Append(line);
                }
            } while (!reader.Done);
        }
Exemple #57
0
        /// <summary>
        /// Returns reader to the original state.
        /// </summary>
        private void Reset(IStringReader input, bool returnJSonObject)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            _input = input;
            _tokens = new Stack<JSonReaderTokenInfo>();
            _getTokenFromStack = false;
            if (returnJSonObject)
                _factory = new JSonObjectFactory();
            else
                _factory = new FclObjectFactory();
        }