public void Pop_NullString_ReturnsNullChar()
		{
			using (var scanner = new StringStream(null))
			{
				Assert.Equal('\0', scanner.Pop());
			}
		}
		public void Line_StartState_ReturnsNegOne()
		{
			using (var scanner = new StringStream(null))
			{
				Assert.Equal(0, scanner.Line);
			}
		}
		public void Index_StartState_ReturnsNegOne()
		{
			using (var scanner = new StringStream(null))
			{
				Assert.Equal(-1, scanner.Index);
			}
		}
Beispiel #4
0
        private static bool ParseDelimiter(StringStream stream, List<Token> tokens)
        {
            bool foundDelimiter = false;
            string peekedDelimiter = "";
            foreach (string del in delimiters)
            {
                peekedDelimiter = "";
                for (int i = 0; i < del.Length; ++i)
                    peekedDelimiter += stream.PeekAhead(i);

                if (peekedDelimiter == del)
                {
                    stream.Position += del.Length;
                    foundDelimiter = true;
                    break;
                }
            }

            if (foundDelimiter)
            {
                tokens.Add(new Token(TokenType.Delimiter, peekedDelimiter, filename, line));
                return true;
            }

            return false;
        }
Beispiel #5
0
 public IrcPacket(IrcClient irc, string prefix, string action, StringStream content, string origString)
     : base(action, new StringStream(content.Remainder))
 {
     this.irc = irc;
     this.prefix = prefix;
     this.origString = origString;
 }
 public void CanWriteIntoStringStreamAndConvertItBackToStringWithCustomEncoding()
 {
     var stream = new StringStream(Encoding.UTF32);
     var writer = new StreamWriter(stream, Encoding.UTF32);
     writer.Write("qweqwe");
     writer.Flush();
     stream.GetString().Should().Be("qweqwe");
     stream.GetString().Should().Be("qweqwe");
 }
Beispiel #7
0
        public void SendClientMessage( string msg )
        {
            byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes( msg );

            _input = new StringStream( "", "IP" );
            _parser = new IrcMsgParser( _input );

            _parser.MessageRecievedEvent += new MessageRecievedHandler( _parser_MessageRecievedEvent );
            _clientSocket.Client.Send( bytes );
        }
        public void CanWriteIntoStringStreamAndConvertItBackToString()
        {
            Encoding.UTF32.GetString(Encoding.UTF32.GetBytes("wtf")).Should().Be("wtf");

            var stream = new StringStream();
            var writer = new StreamWriter(stream);
            writer.Write("qweqwe");
            writer.Flush();
            stream.GetString().Should().Be("qweqwe");
            stream.GetString().Should().Be("qweqwe");
        }
Beispiel #9
0
        private static void Main()
        {
            var text = "lorem ipsum dolor sit amet";

            using (var stream = new StringStream(text))
            using (var reader = new StreamReader(stream))
            {
                var read = reader.ReadToEnd();

                Debug.Assert(text.Equals(read));
            }
        }
        public void ApplySatisfiesExtensionRequirementsWithoutMessageContext()
        {
            var transform = typeof(IdentityTransform);
            var arguments = XsltCache.Instance[transform].Arguments;

            arguments.GetExtensionObject(ExtensionObjectNamespaces.MessageContext).Should().BeNull();

            var stream = new StringStream("<?xml version='1.0' encoding='utf-16'?><root></root>");
            var sut    = new Transformer(new System.IO.Stream[] { stream });

            sut.Apply(transform);

            arguments.GetExtensionObject(ExtensionObjectNamespaces.MessageContext).Should().BeNull();
        }
        public void NotExpandable_WithInitialValue_SpecificEncoding(string data, Encoding encoding)
        {
            using (var stream = new StringStream(data, encoding))
            {
                Assert.That(stream.Encoding, Is.EqualTo(encoding));
                Assert.That(stream.ToString(), Is.EqualTo(data));

                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                Assert.That(stream.Encoding.GetString(bytes), Is.EqualTo(data));

                Assert.Throws <NotSupportedException>(() => stream.Capacity += 100);
            }
        }
        /// <summary>
        /// Removes the next char if it's a Command Prefix, and
        /// sets dbl = true, if it is double.
        /// </summary>
        public static bool ConsumeCommandPrefix(StringStream str, out bool dbl)
        {
            char c = str.PeekChar();

            if (IsCommandPrefix(c))
            {
                ++str.Position;
                dbl = str.ConsumeNext(c);
                return(true);
            }

            dbl = false;
            return(false);
        }
        public void GiveResultTest()
        {
            StringStream stringStream = new StringStream();

            char[] array = new char[5] {
                '\0', 'a', '\0', 'i', '\0'
            };
            stringStream.countVowel = new int[5] {
                0, 3, 1, 0, 2
            };

            var result = stringStream.GiveResult(array);

            Assert.AreEqual('i', result);
        }
        public void ZipUnzipSmallPayload()
        {
            const string content = "text";

            using (var clearStream = new StringStream(content))
                using (var compressedStream = new ZipOutputStream(clearStream, "entry-name"))
                    using (var uncompressedStream = new ZipInputStream(compressedStream))
                    {
                        uncompressedStream.GetNextEntry();
                        using (var reader = new StreamReader(uncompressedStream))
                        {
                            Assert.That(reader.ReadToEnd(), Is.EqualTo(content));
                        }
                    }
        }
Beispiel #15
0
        public void BatchTrackingContextIsEmptyIfInvalidBatchContent()
        {
            const string batchContent = @"<ns:BatchContent xmlns:ns=""urn:schemas.stateless.be:biztalk:batch:2012:12"">
  <ns:MessagingStepActivityIds />
  <ns:EnvelopeSpecName>Be.Stateless.BizTalk.Schemas.Xml.BatchControl+ReleaseBatches</ns:EnvelopeSpecName>
  <ns:Parts />
</BatchContent>";

            using (var stream = new StringStream(batchContent).AsMarkable())
            {
                var batchTrackingContext = ((IProbeBatchContentStream)stream.Probe()).BatchTrackingContext;
                Assert.That(batchTrackingContext.ProcessActivityId, Is.Null);
                Assert.That(batchTrackingContext.MessagingStepActivityIdList, Is.Null);
            }
        }
Beispiel #16
0
        public IParseResult TryConvertToTokenStream(string pattern, out ITokenStream tokenStream)
        {
            var inputStream = new StringStream(pattern);

            var parseResult = TryConvertToTokenStream(inputStream, out tokenStream);

            if (!parseResult.IsSuccess)
            {
                return(new FailureParseResult(parseResult.Position, parseResult.ErrorType));
            }

            tokenStream.Append(new EndOfStreamToken(pattern.Length));

            return(parseResult);
        }
        public void ZipUnzipSmallStringPayload()
        {
            const string content = "text";

            using (var clearStream = new StringStream(content))
                using (var compressedStream = new ZipOutputStream(clearStream, "entry-name"))
                    using (var decompressedStream = new ZipInputStream(compressedStream))
                    {
                        using (var reader = new StreamReader(decompressedStream))
                        {
                            var output = reader.ReadToEnd();
                            output.Should().Be(content);
                        }
                    }
        }
        protected override Task <Stream> OpenStreamAsync()
        {
            if (!manager.IsProviderEnabled(LocationManager.GpsProvider))
            {
                throw new InvalidOperationException("The GPS Location Provider is not enabled");
            }

            stream                = new StringStream();
            listener              = new Listener();
            listener.NmeaMessage += (s, e) => stream?.Append(e);
            bool success = manager.AddNmeaListener(listener);

            manager.RequestLocationUpdates(LocationManager.GpsProvider, 0, 0f, listener);
            return(Task.FromResult <Stream>(stream));
        }
Beispiel #19
0
        private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName)
        {
            foreach (var caHandle in GetCustomAttributes(token))
            {
                StringHandle namespaceName, typeName;
                if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) &&
                    StringStream.EqualsRaw(typeName, asciiTypeName) &&
                    StringStream.EqualsRaw(namespaceName, asciiNamespaceName))
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #20
0
        private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable)
        {
            InitializeProjectedTypes();

            int index = StringStream.BinarySearchRaw(s_projectedTypeNames, TypeRefTable.GetName(typeRef));

            if (index >= 0 && StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos[index].WinRTNamespace))
            {
                isIDisposable = s_projectionInfos[index].IsIDisposable;
                return(index);
            }

            isIDisposable = false;
            return(-1);
        }
Beispiel #21
0
            public override void Process(CmdTrigger <RealmServerCmdArgs> trigger)
            {
                StringStream      text           = trigger.Text;
                string            str            = text.NextModifiers();
                List <ItemRecord> itemRecordList = new List <ItemRecord>();
                uint cod   = 0;
                uint money = 0;

                if (str.Contains("i"))
                {
                    ItemTemplate template = ItemMgr.GetTemplate(trigger.Text.NextEnum(Asda2ItemId.None));
                    if (template == null)
                    {
                        trigger.Reply("Invalid ItemId.");
                        return;
                    }

                    ItemRecord record = ItemRecord.CreateRecord(template);
                    itemRecordList.Add(record);
                    record.SaveLater();
                }

                if (str.Contains("c"))
                {
                    cod = text.NextUInt();
                }
                string recipientName = trigger.Text.NextWord();

                if (recipientName.Length == 0)
                {
                    trigger.Reply("Could not send mail - Unknown Recipient: " + recipientName);
                }
                else
                {
                    string    subject   = trigger.Text.NextWord(",");
                    string    remainder = trigger.Text.Remainder;
                    MailError mailError = MailMgr.SendMail(recipientName, subject, remainder, MailStationary.GM,
                                                           itemRecordList, money, cod, trigger.Args.User);
                    if (mailError == MailError.OK)
                    {
                        trigger.Reply("Done.");
                    }
                    else
                    {
                        trigger.Reply("Could not send mail: " + mailError);
                    }
                }
            }
 public void SupportsXslTransformOfAggregatedXmlReaders()
 {
     using (var part1 = new StringStream(PART_1))
         using (var part2 = new StringStream(PART_2))
             using (var part3 = new StringStream(PART_3))
                 using (var composite = CompositeXmlReader.Create(new[] { XmlReader.Create(part1), XmlReader.Create(part2), XmlReader.Create(part3) }))
                 {
                     var xslTransformDescriptor = new XslCompiledTransformDescriptor(new XslCompiledTransformDescriptorBuilder(typeof(IdentityTransform)));
                     var builder = new StringBuilder();
                     using (var writer = XmlWriter.Create(builder))
                     {
                         xslTransformDescriptor.XslCompiledTransform.Transform(composite, xslTransformDescriptor.Arguments, writer !);
                     }
                     builder.GetReaderAtContent().ReadOuterXml().Should().Be(EXPECTED);
                 }
 }
        public void BatchTrackingContextOnlyHasProcessActivityId()
        {
            const string batchContent = @"<ns:BatchContent xmlns:ns=""urn:schemas.stateless.be:biztalk:batch:2012:12"">
  <ns:EnvelopeSpecName>Be.Stateless.BizTalk.Schemas.Xml.BatchControl+ReleaseBatches</ns:EnvelopeSpecName>
  <ns:Partition>partition</ns:Partition>
  <ns:ProcessActivityId>A800441B209E46A087A16833661590C2</ns:ProcessActivityId>
  <ns:Parts />
</BatchContent>";

            using (var stream = new StringStream(batchContent).AsMarkable())
            {
                var batchTrackingContext = stream.ProbeBatchContent().BatchTrackingContext;
                batchTrackingContext.ProcessActivityId.Should().Be("A800441B209E46A087A16833661590C2");
                batchTrackingContext.MessagingStepActivityIdList.Should().BeNull();
            }
        }
Beispiel #24
0
        public void TestVogalInvalid()
        {
            StringStream stream    = new StringStream("aaaaaaaaa");
            FindVogal    findVogal = new FindVogal();
            char         resultado;

            try
            {
                resultado = findVogal.firstChar(stream);
            }
            catch (System.Exception)
            {
                resultado = ' ';
            }
            Assert.IsTrue(resultado == ' ');
        }
Beispiel #25
0
        private static bool HasCommandPrefix(StringStream text, IEnumerable <string> prefixes)
        {
            // check if any prefix matches
            var hasPrefix = prefixes.Iterate(prefix =>
            {
                if (text.String.StartsWith(prefix,
                                           StringComparison.CurrentCultureIgnoreCase))
                {
                    text.Skip(prefix.Length);
                    return(false);
                }
                return(true);
            });

            return(hasPrefix);
        }
Beispiel #26
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string DisconnectFromDatabase()
        {
            try
            {
                StringStream stringStream = new StringStream(pipeClient);
                string       sendProtocol = "DisconnectFromDatabase";
                stringStream.WriteStringToService(sendProtocol);

                messageFromService = stringStream.ReadStringFromService();
            }
            catch (Exception exceptionInDisconnectFromDB)
            {
                messageFromService = exceptionInDisconnectFromDB.Message;
            }
            return(messageFromService);
        }
Beispiel #27
0
        public void Parse(StringStream stream)
        {
            var cfg = ConfigFile;
            var globalSection = cfg.GlobalSection;
            ParseGlobalSection(ref stream, ref globalSection);

            while (!stream.IsAtEndOfStream)
            {
                stream.Skip(WhiteSpaceNewline);

                string sectionName;
                ConfigSection section;
                ParseSection(ref stream, out sectionName, out section);
                cfg[sectionName] = section;
            }
        }
Beispiel #28
0
        public void BatchDescriptorHasPartition()
        {
            const string batchContent = @"<ns:BatchContent xmlns:ns=""urn:schemas.stateless.be:biztalk:batch:2012:12"">
  <ns:EnvelopeSpecName>envelope-spec-name</ns:EnvelopeSpecName>
  <ns:Partition>p-one</ns:Partition>
  <ns:MessagingStepActivityIds>013684EE620E4A0BB6D6F7355B26D21B</ns:MessagingStepActivityIds>
  <ns:Parts />
</BatchContent>";

            using (var stream = new StringStream(batchContent).AsMarkable())
            {
                var batchDescriptor = ((IProbeBatchContentStream)stream.Probe()).BatchDescriptor;
                Assert.That(batchDescriptor.EnvelopeSpecName, Is.EqualTo("envelope-spec-name"));
                Assert.That(batchDescriptor.Partition, Is.EqualTo("p-one"));
            }
        }
        public void BatchDescriptorHasEnvironmentTag()
        {
            const string batchContent = @"<ns:BatchContent xmlns:ns=""urn:schemas.stateless.be:biztalk:batch:2012:12"">
  <ns:EnvelopeSpecName>envelope-spec-name</ns:EnvelopeSpecName>
  <ns:EnvironmentTag>environment-tag</ns:EnvironmentTag>
  <ns:MessagingStepActivityIds>013684EE620E4A0BB6D6F7355B26D21B</ns:MessagingStepActivityIds>
  <ns:Parts />
</BatchContent>";

            using (var stream = new StringStream(batchContent).AsMarkable())
            {
                var batchDescriptor = stream.ProbeBatchContent().BatchDescriptor;
                batchDescriptor.EnvelopeSpecName.Should().Be("envelope-spec-name");
                batchDescriptor.EnvironmentTag.Should().Be("environment-tag");
            }
        }
Beispiel #30
0
        public void Write_To_Stream()
        {
            //arrange
            var stream = new StringStream();

            var order  = new WalkDogOrder(new Dog("Santa's Little Helper", true, false), "Springfield", new DateTime(2017, 03, 17), 17.89);
            var writer = new WalkDogOrderStreamWriter();

            //act
            writer.Write(stream, order);

            //assert
            var content = stream.GetContent();

            content.Should().Be("Santa's Little Helper (small) in Springfield at 2017-03-17T00:00:00.0000000 for 17.89$");
        }
Beispiel #31
0
        private static List <Token> ParseStream(StringStream stream)
        {
            List <Token> tokens = new List <Token>();

            Line = 1;

            while (!stream.IsEndOfStream)
            {
                SkipWhitespace(stream);

                if (SkipComment(stream))
                {
                    continue;
                }

                if (ParseString(stream, tokens))
                {
                    continue;
                }

                if (ParseWord(stream, tokens))
                {
                    continue;
                }

                if (ParseNumber(stream, tokens))
                {
                    continue;
                }

                if (ParseDelimiter(stream, tokens))
                {
                    continue;
                }

                if (stream.IsEndOfStream)
                {
                    break;
                }

                throw new LexerException("Unexpected token '{0}' on line {1}.", stream.Read(), Line);
            }

            tokens.Add(new Token(TokenType.EndOfStream, Filename, Line));

            return(tokens);
        }
 public void TransformMultipleStreamsDiscardsXmlDeclarations()
 {
     using (var stream1 = new StringStream("<?xml version='1.0' encoding='utf-16'?><root><one/></root>"))
         using (var stream2 = new StringStream("<?xml version='1.0' encoding='utf-16'?><root><two/></root>"))
             using (var stream6 = new StringStream("<?xml version='1.0' encoding='utf-16'?><root><six/></root>"))
                 using (var stream = new Stream[] { stream1, stream2, stream6 }.Transform().Apply(typeof(IdentityTransform)))
                     using (var reader = XmlReader.Create(stream))
                     {
                         reader.MoveToContent();
                         reader.ReadOuterXml().Should().Be(
                             "<agg:Root xmlns:agg=\"http://schemas.microsoft.com/BizTalk/2003/aggschema\">"
                             + "<agg:InputMessagePart_0><root><one /></root></agg:InputMessagePart_0>"
                             + "<agg:InputMessagePart_1><root><two /></root></agg:InputMessagePart_1>"
                             + "<agg:InputMessagePart_2><root><six /></root></agg:InputMessagePart_2>"
                             + "</agg:Root>");
                     }
 }
        public void ContentIsMultipart()
        {
            using (var dataStream = new StringStream(XML_BODY))
            {
                MessageMock.Object.BodyPart.Data = dataStream;

                var sut = new MultipartFormDataContentEncoder();
                sut.Execute(PipelineContextMock.Object, MessageMock.Object);

                MessageMock.Object.BodyPart.ContentType.Should().MatchRegex(MULTIPART_FORM_DATA_BOUNDARY_PATTERN);
                using (var reader = new StreamReader(MessageMock.Object.BodyPart.Data))
                {
                    var content = reader.ReadToEnd();
                    content.Should().MatchRegex("^(\\-\\-" + BOUNDARY_PATTERN + ")\r\nContent\\-Disposition: form\\-data\r\n[\\w\\W]+\r\n\\1\\-\\-\r\n$");
                }
            }
        }
Beispiel #34
0
        /// <summary>
        /// Returns the SubCommand, following the given set of aliases through the SubCommand structure.
        /// </summary>
        public void GetSubCommands(StringStream cmdString, List <BaseCommand <C> > list)
        {
            var str  = cmdString.NextWord();
            var cmds = m_subCommandSet.Where(comd => comd.Aliases.Where(alias => alias.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) > -1).Count() > 0);

            if (cmdString.HasNext && cmds.Count() == 1)
            {
                cmds.First().GetSubCommands(cmdString, list);
            }
            else
            {
                foreach (var cmd in cmds)
                {
                    list.Add(cmd);
                }
            }
        }
Beispiel #35
0
        protected override void SetBuffer()
        {
            this.BufferText = this.Buffer.CurrentSnapshot.GetText();
            var currentBuffer = new StringStream(this.BufferText);

            Lexer.SetStream(currentBuffer);

            /* *
             * Reset the timer on the reparse to ensure that
             * it doesn't repeat frequently.
             * */
            if (ParserEnabled && !CurrentlyParsing)
            {
                this.delayedReparseTimer.Stop();
                this.delayedReparseTimer.Start();
            }
        }
        public void ZipUnzipLargePayloadUsingTinyBuffer()
        {
            // computing content beforehand is much more faster that using a ReplicatingReadStream
            var content = Enumerable.Range(0, 1024)
                          .Select(i => Guid.NewGuid().ToString())
                          .Aggregate(string.Empty, (k, v) => k + v);

            using (var clearStream = new StringStream(content))
                using (var compressedStream = new ZipOutputStream(clearStream, "entry-name", 16))
                    using (var uncompressedStream = new ZipInputStream(compressedStream))
                    {
                        uncompressedStream.GetNextEntry();
                        using (var reader = new StreamReader(uncompressedStream))
                        {
                            Assert.That(reader.ReadToEnd(), Is.EqualTo(content));
                        }
                    }
        }
        public void ApplySatisfiesExtensionRequirementsWithMessageContext()
        {
            var contextMock = new Mock <IBaseMessageContext>();
            var transform   = typeof(CompoundContextMapTransform);
            var arguments   = XsltCache.Instance[transform].Arguments;

            arguments.GetExtensionObject(BaseMessageContextFunctions.TARGET_NAMESPACE).Should().BeNull();

            var stream = new StringStream("<?xml version='1.0' encoding='utf-16'?><root></root>");
            var sut    = new Transformer(new Stream[] { stream });

            sut.ExtendWith(contextMock.Object).Apply(transform);

            arguments.GetExtensionObject(BaseMessageContextFunctions.TARGET_NAMESPACE).Should().BeNull();

            contextMock.Verify(c => c.Read(BizTalkFactoryProperties.EnvironmentTag.Name, BizTalkFactoryProperties.EnvironmentTag.Namespace), Times.Once());
            contextMock.Verify(c => c.Read(BtsProperties.Operation.Name, BtsProperties.Operation.Namespace), Times.Once());
        }
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!asyncClient1.Active)
            {
                return;
            }

            string s = e.KeyChar.ToString();

            if (e.KeyChar == '\r')
            {
                s = "\r\n";
            }

            using (StringStream str = new StringStream(s)) {
                asyncClient1.WriteData(str);
            }
        }
Beispiel #39
0
        public void TokenizedStreamTest()
        {
            // 任意のパーサを繰り返し適用した結果をソースストリームとして利用可能にします。
            // 字句解析等の前段処理を可能にします。

            // 空白に挟まれた文字列を1要素として返すパーサ。
            var token = Many1(LetterOrDigit()).Between(Spaces()).AsString();

            var source = "The quick brown fox jumps over the lazy dog";

            using var stream    = StringStream.Create(source);
            using var tokenized = ParsecState.Tokenize(stream, token);

            // 任意のトークンにマッチし、その長さを返すパーサ。
            var parser = Many(Any <string>().Map(x => x.Length));

            parser.Parse(tokenized).WillSucceed(value => value.Is(source.Split(' ').Select(x => x.Length)));
        }
        public void ZipUnzipLargePayloadUsingTinyBuffer()
        {
            // computing content beforehand is much faster than using a ReplicatingReadStream
            var content = Enumerable.Range(0, 1024)
                          .Select(_ => Guid.NewGuid().ToString())
                          .Aggregate(string.Empty, (k, v) => k + v);

            using (var clearStream = new StringStream(content))
                using (var compressedStream = new ZipOutputStream(clearStream, "entry-name", 16))
                    using (var decompressedStream = new ZipInputStream(compressedStream))
                    {
                        using (var reader = new StreamReader(decompressedStream))
                        {
                            var output = reader.ReadToEnd();
                            output.Should().Be(content);
                        }
                    }
        }
 public StringStream ReadEnabledLine()
 {
     string line = null;
     StringStream st = null;
     while (true)
     {
         line = reader.ReadLine();
         lineNo++;
         if (line == null)
             return null;
         if (line.Length == 0)
             continue;
         st = new StringStream(line);
         if (st.EOS)
             continue;
         return st;
     }
 }
Beispiel #42
0
 public void Parse(string serializedConfigFile)
 {
     var stream = new StringStream(serializedConfigFile);
     Parse(stream);
 }
Beispiel #43
0
        private void ParseSectionHeader(ref StringStream stream,
            out string ref_sectionName)
        {
            // Skip prefix character
            stream.Read();
            ref_sectionName = string.Empty;

            while (true)
            {
                if (stream.IsAtEndOfStream)
                {
                    break;
                }
                if (stream.PeekUnchecked() == SectionSuffix)
                {
                    // Read the suffix character
                    stream.Read();
                    break;
                }
                ref_sectionName += (char)stream.Read();
            }
        }
Beispiel #44
0
        private void ParseSectionBody(ref StringStream stream,
            ref ConfigSection ref_section)
        {
            stream.Skip(WhiteSpaceNewline);
            while (true)
            {
                stream.Skip(WhiteSpace);
                if (stream.IsAtEndOfStream)
                {
                    break;
                }

                var currentChar = stream.PeekUnchecked();

                if (currentChar == SectionPrefix)
                {
                    break;
                }

                if (currentChar == CommentPrefix)
                {
                    string comment;
                    ParseComment(ref stream, out comment);
                    if (!string.IsNullOrEmpty(ref_section.Comment))
                    {
                        comment = Environment.NewLine + comment;
                    }
                    ref_section.Comment += comment;
                    continue;
                }

                string optionName;
                ConfigOption option;
                ParseOption(ref stream, out optionName, out option);
                ref_section[optionName] = option;
            }
        }
Beispiel #45
0
 private void ParseSection(ref StringStream stream,
     out string out_sectionName,
     out ConfigSection out_section)
 {
     out_section = new ConfigSection();
     ParseSectionHeader(ref stream, out out_sectionName);
     ParseSectionBody(ref stream, ref out_section);
 }
Beispiel #46
0
        private static List<Token> ParseStream(StringStream stream)
        {
            List<Token> tokens = new List<Token>();
            line = 1;

            while (!stream.IsEndOfStream)
            {
                SkipWhitespace(stream);

                if (SkipComment(stream))
                    continue;

                if (ParseString(stream, tokens))
                    continue;

                if (ParseWord(stream, tokens))
                    continue;

                if (ParseNumber(stream, tokens))
                    continue;

                if (ParseDelimiter(stream, tokens))
                    continue;

                if (stream.IsEndOfStream)
                    break;

                throw new Exception("Unexpected token \"" + stream.Read() + "\" on line " + line);
            }

            tokens.Add(new Token(TokenType.EndOfStream, filename, line));

            return tokens;
        }
Beispiel #47
0
        private static bool ParseNumber(StringStream stream, List<Token> tokens)
        {
            if (char.IsDigit(stream.Peek()) || (stream.Peek() == '-' && char.IsDigit(stream.PeekAhead(1))))
            {
                string number = "";
                if (stream.Peek() == '-')
                    number += stream.Read();

                if (stream.Peek() == '0' && stream.PeekAhead(1) == 'x')
                {
                    stream.Position += 2;

                    while (!stream.IsEndOfStream && char.IsLetterOrDigit(stream.Peek()))
                        number += stream.Read();

                    ulong result;
                    try
                    {
                        result = ulong.Parse(number, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                    }
                    catch (OverflowException)
                    {
                        throw new Exception("Number is larger than 64bits on line " + line);
                    }
                    catch (Exception)
                    {
                        throw new Exception("Invalid number on line " + line);
                    }

                    number = result.ToString("G");
                }
                else
                {
                    while (!stream.IsEndOfStream && (char.IsDigit(stream.Peek()) || stream.Peek() == '.'))
                        number += stream.Read();
                }

                tokens.Add(new Token(TokenType.Number, number, filename, line));
                return true;
            }

            return false;
        }
Beispiel #48
0
		public static bool Parse(string str, Type type, ref object obj)
		{
			if (type.IsArray)
			{
				var reader = new StringStream(str);
				// iterate over string twice:
				// first get the count
				var count = 0;
				while (reader.HasNext)
				{
					string value;
					count++;
					if (!reader.NextString(out value))
					{
						// no more terminator
						break;
					}
				}

				// start again
				reader.Position = 0;

				// then fill the array
				var elemType = type.GetElementType();
				var arr = Array.CreateInstance(elemType, count);
				for (var i = 0; i < count; i++)
				{
					object value = null;
					string strVal;
					reader.NextString(out strVal);

					if (ParseSingleValue(strVal, elemType, ref value))
					{
						arr.SetValue(value, i);
					}
					else
					{
						return false;
					}
				}
				obj = arr;
				return true;
			}
			else
			{
				return ParseSingleValue(str, type, ref obj);
			}
		}
Beispiel #49
0
 public void PressEnterKey(bool mesSkip, string str, ScriptPosition pos)
 {
     if ((state == ConsoleState.Running) || (state == ConsoleState.Initializing) || (state == ConsoleState.WaitKeyWithTimerF))
         return;
     else if ((state == ConsoleState.Quit))
     {
         window.Close();
         return;
     }
     else if (state == ConsoleState.Error)
     {
         if (str == "openFileWithDebug" && pos != null)
         {
             ProcessStartInfo pInfo = new ProcessStartInfo();
             pInfo.FileName = Config.TextEditor;
             string fname = pos.Filename.ToUpper();
             if (fname.EndsWith(".CSV"))
             {
                 if (fname.Contains(Program.CsvDir.ToUpper()))
                     fname = fname.Replace(Program.CsvDir.ToUpper(), "");
                 fname = Program.CsvDir + fname;
             }
             else
             {
                 //解析モードの場合は見ているファイルがERB\の下にあるとは限らないかつフルパスを持っているのでこの補正はしなくてよい
                 if (!Program.AnalysisMode)
                 {
                     if (fname.Contains(Program.ErbDir.ToUpper()))
                         fname = fname.Replace(Program.ErbDir.ToUpper(), "");
                     fname = Program.ErbDir + fname;
                 }
             }
             if (Config.EditorArg != "" && Config.EditorArg != null)
                 pInfo.Arguments = Config.EditorArg + pos.LineNo.ToString() + " \"" + fname + "\"";
             else
                 pInfo.Arguments = fname;
             try
             {
                 System.Diagnostics.Process.Start(pInfo);
             }
             catch (System.ComponentModel.Win32Exception)
             {
                 System.Media.SystemSounds.Hand.Play();
                 PrintError("エディタを開くことができませんでした");
                 forceUpdateGeneration();
             }
             return;
         }
         else
         {
             window.Close();
             return;
         }
     }
     else if (state == ConsoleState.WaitKeyWithTimer)
         stopTimer();
     if (str.StartsWith("@") && !IsWaintingOnePhrase)
     {
         doSystemCommand(str);
         return;
     }
     if (((state == ConsoleState.WaitInteger) || (state == ConsoleState.WaitIntegerWithTimer) || (state == ConsoleState.WaitOneIntegerWithTimer) || (state == ConsoleState.WaitOneInteger) || (state == ConsoleState.WaitSystemInteger)
         || (state == ConsoleState.WaitString) || (state == ConsoleState.WaitStringWithTimer) || (state == ConsoleState.WaitOneStringWithTimer) || (state == ConsoleState.WaitOneString))
         && str.Contains("("))
     {
         StringStream st = new StringStream(str);
         str = parseInput(st, false);
     }
     string[] text = str.Split(spliter, StringSplitOptions.None);
     inProcess = (text.Length > 1);
     //右クリックでのスキップ時のみtrueになる
     inMouseSkip = mesSkip;
     for (int i = 0; i < text.Length; i++)
     {
         string inputs = text[i];
         if (inputs.IndexOf("\\e") >= 0)
         {
             inputs = inputs.Replace("\\e", "");//\eの除去
             mesSkip = true;
             //マクロによるスキップの方を優先
             if (inMouseSkip)
                 inMouseSkip = false;
         }
         if (IsWaintingOnePhrase && inputs.Length > 1)
             inputs = inputs.Remove(1);
         if (state == ConsoleState.WaitKeyWithTimer || state == ConsoleState.WaitKeyWithTimerF)
             stopTimer();
         //強制待ちWAITは入力を受け付けないので次に回す必要がある。
         if (state != ConsoleState.WaitKeyWithTimerF)
             callEmueraProgram(inputs);
         else
         {
             i--;
             callEmueraProgram("");
         }
         if (mesSkip)
         {
             while ((state == ConsoleState.WaitKey && !isForceWait) || state == ConsoleState.WaitKeyWithTimer || state == ConsoleState.WaitKeyWithTimerF || state == ConsoleState.WaitAnyKey)
             {
                 if (state == ConsoleState.WaitKeyWithTimer || state == ConsoleState.WaitKeyWithTimerF)
                     stopTimer();
                 callEmueraProgram("");
             }
         }
         mesSkip = false;
         inMouseSkip = false;
         isForceWait = false;
         if (state == ConsoleState.Error || state == ConsoleState.Quit)
             break;
         //マクロループ時は待ち処理が起こらないのでここでシステムキューを捌く
         Application.DoEvents();
     }
     RefreshStrings(true);
     inProcess = false;
 }
Beispiel #50
0
        string parseInput(StringStream st, bool isNest)
        {
            StringBuilder sb = new StringBuilder(20);
            StringBuilder num = new StringBuilder(20);
            int res = 0;
            while (!st.EOS && (!isNest || st.Current != ')'))
            {
                if (st.Current == '(')
                {
                    st.ShiftNext();
                    string tstr = parseInput(st, true);

                    if (!st.EOS)
                    {
                        st.ShiftNext();
                        if (st.Current == '*')
                        {
                            st.ShiftNext();
                            while (char.IsNumber(st.Current))
                            {
                                num.Append(st.Current);
                                st.ShiftNext();
                            }
                            if (num.ToString() != "" && num.ToString() != null)
                            {
                                int.TryParse(num.ToString(), out res);
                                for (int i = 0; i < res; i++)
                                    sb.Append(tstr);
                                num.Remove(0, num.Length);
                            }
                        }
                        else
                            sb.Append(tstr);
                        continue;
                    }
                    else
                    {
                        sb.Append(tstr);
                        break;
                    }
                }
                else if (st.Current == '\\')
                {
                    st.ShiftNext();
                    switch (st.Current)
                    {
                        case 'n':
                            sb.Append('\n');
                            break;
                        case 'r':
                            sb.Append('\r');
                            break;
                        case 'e':
                            sb.Append("\\e");
                            break;
                        case '\n':
                            break;
                        default:
                            sb.Append(st.Current);
                            break;
                    }
                }
                else
                    sb.Append(st.Current);
                st.ShiftNext();
            }
            return sb.ToString();
        }
Beispiel #51
0
        private static string ParseEscapeSequences(string value)
        {
            StringStream ss = new StringStream(value);
            string parsedValue = "";

            while (!ss.IsEndOfStream)
            {
                // Read non-escaping characters
                if (ss.Peek() != '\\')
                {
                    parsedValue += ss.Read();
                    continue;
                }

                // Skip backslash
                ss.Read();

                switch (ss.Read())
                {
                    case 'a':
                        parsedValue += '\a';
                        continue;

                    case 'b':
                        parsedValue += '\b';
                        continue;

                    case 'f':
                        parsedValue += '\f';
                        continue;

                    case 'n':
                        parsedValue += '\n';
                        continue;

                    case 'r':
                        parsedValue += '\r';
                        continue;

                    case 't':
                        parsedValue += '\t';
                        continue;

                    case 'v':
                        parsedValue += '\v';
                        continue;

                    case '\'':
                        parsedValue += '\'';
                        continue;

                    case '\"':
                        parsedValue += '\"';
                        continue;

                    case '\\':
                        parsedValue += '\\';
                        continue;

                    case 'x':
                        {
                            string hexString = new string(new[] { ss.Read(), ss.Read() });
                            parsedValue += (char)Convert.ToInt32(hexString, 16);
                            continue;
                        }

                    case 'u':
                    case 'U':
                        throw new NotImplementedException();
                }

                throw new Exception("Bad escape sequence.");
            }

            return parsedValue;
        }
            public PRINT_Instruction(string name)
            {
                //PRINT(|V|S|FORM|FORMS)(|K)(|D)(|L|W) コレと
                //PRINTSINGLE(|V|S|FORM|FORMS)(|K)(|D) コレと
                //PRINT(|FORM)(C|LC)(|K)(|D) コレ
                //PRINTDATA(|K)(|D)(|L|W) ←は別クラス
                flag = IS_PRINT;
                StringStream st = new StringStream(name);
                st.Jump(5);//PRINT
                if (st.CurrentEqualTo("SINGLE"))
                {
                    flag |= PRINT_SINGLE | EXTENDED;
                    st.Jump(6);
                }

                if (st.CurrentEqualTo("V"))
                {
                    ArgBuilder = ArgumentParser.GetArgumentBuilder(FunctionArgType.SP_PRINTV);
                    isPrintV = true;
                    st.Jump(1);
                }
                else if (st.CurrentEqualTo("S"))
                {
                    ArgBuilder = ArgumentParser.GetArgumentBuilder(FunctionArgType.STR_EXPRESSION);
                    st.Jump(1);
                }
                else if (st.CurrentEqualTo("FORMS"))
                {
                    ArgBuilder = ArgumentParser.GetArgumentBuilder(FunctionArgType.STR_EXPRESSION);
                    isForms = true;
                    st.Jump(5);
                }
                else if (st.CurrentEqualTo("FORM"))
                {
                    ArgBuilder = ArgumentParser.GetArgumentBuilder(FunctionArgType.FORM_STR_NULLABLE);
                    st.Jump(4);
                }
                else
                {
                    ArgBuilder = ArgumentParser.GetArgumentBuilder(FunctionArgType.STR_NULLABLE);
                }
                if (st.CurrentEqualTo("LC"))
                {
                    flag |= EXTENDED;
                    isLC = true;
                    st.Jump(2);
                }
                else if (st.CurrentEqualTo("C"))
                {
                    if (name == "PRINTFORMC")
                        flag |= EXTENDED;
                    isC = true;
                    st.Jump(1);
                }
                if (st.CurrentEqualTo("K"))
                {
                    flag |= ISPRINTKFUNC | EXTENDED;
                    st.Jump(1);
                }
                if (st.CurrentEqualTo("D"))
                {
                    flag |= ISPRINTDFUNC | EXTENDED;
                    st.Jump(1);
                }
                if (st.CurrentEqualTo("L"))
                {
                    flag |= PRINT_NEWLINE;
                    flag |= METHOD_SAFE;
                    st.Jump(1);
                }
                else if (st.CurrentEqualTo("W"))
                {
                    flag |= PRINT_NEWLINE | PRINT_WAITINPUT;
                    st.Jump(1);
                }
                else
                {
                    flag |= METHOD_SAFE;
                }
                if ((ArgBuilder == null) || (!st.EOS))
                    throw new ExeEE("PRINT異常");
            }
Beispiel #53
0
        private void ParseComment(ref StringStream stream,
            out string out_comment)
        {
            // Skip initial prefix character
            stream.Read();

            out_comment = stream.ReadLine();
        }
Beispiel #54
0
        private static bool SkipComment(StringStream stream)
        {
            // Skip single line comments
            if (stream.Peek() == '/' && stream.PeekAhead(1) == '/')
            {
                while (!stream.IsEndOfStream && stream.Peek() != StringStream.NewLine)
                    stream.Read();

                return true;
            }

            // Skip multi line comments
            if (stream.Peek() == '/' && stream.PeekAhead(1) == '*')
            {
                while (!stream.IsEndOfStream && !(stream.Peek() == '*' && stream.PeekAhead(1) == '/'))
                {
                    if (stream.Read() == StringStream.NewLine)
                        ++line;
                }

                stream.Position += 2;
                return true;
            }

            return false;
        }
 public override void DoInstruction(ExpressionMediator exm, InstructionLine func, ProcessState state)
 {
     //int termnum = 0;
     //foreach (IOperandTerm term in ((ExpressionArrayArgument)func.Argument).TermList)
     //{
     //    string arg = term.GetStrValue(exm);
     //    StringStream aSt = new StringStream(arg);
     //    WordCollection wc = LexicalAnalyzer.Analyse(aSt, LexEndWith.EoL, false, false);
     //    exm.VEvaluator.SetResultX((ExpressionParser.ReduceIntegerTerm(wc, TermEndWith.EoL).GetIntValue(exm)), termnum);
     //    termnum++;
     //}
     //state.Return(exm.VEvaluator.RESULT);
     //if (state.ScriptEnd)
     //    return;
     //int termnum = 0;
     StringStream aSt = new StringStream(((ExpressionArgument)func.Argument).Term.GetStrValue(exm));
     List<long> termList = new List<long>();
     while (!aSt.EOS)
     {
         WordCollection wc = LexicalAnalyzer.Analyse(aSt, LexEndWith.Comma, false, false);
         //exm.VEvaluator.SetResultX(ExpressionParser.ReduceIntegerTerm(wc, TermEndWith.EoL).GetIntValue(exm), termnum++);
         termList.Add(ExpressionParser.ReduceIntegerTerm(wc, TermEndWith.EoL).GetIntValue(exm));
         aSt.ShiftNext();
         LexicalAnalyzer.SkipHalfSpace(aSt);
         //termnum++;
     }
     if (termList.Count == 0)
         termList.Add(0);
     exm.VEvaluator.SetResultX(termList);
     state.Return(exm.VEvaluator.RESULT);
     if (state.ScriptEnd)
         return;
 }
Beispiel #56
0
 private static void SkipWhitespace(StringStream stream)
 {
     while (!stream.IsEndOfStream && char.IsWhiteSpace(stream.Peek()))
     {
         // Read new lines
         if (stream.Read() == StringStream.NewLine)
             ++line;
     }
 }
Beispiel #57
0
 private void ParseGlobalSection(ref StringStream stream,
     ref ConfigSection out_section)
 {
     ParseSectionBody(ref stream, ref out_section);
 }
Beispiel #58
0
        private void ParseOption(ref StringStream stream,
            out string out_optionName,
            out ConfigOption out_option)
        {
            var splitChars = new char[]{ KeyValueSeparator };
            var line = stream.ReadLine();
            var lineParts = line.Split(splitChars, 2);
            if (lineParts.Length != 2)
            {
                throw new InvalidDataException("The config file contains an invalid option-line.");
            }

            out_optionName = lineParts[0].Trim();
            out_option = ConfigOption.Create(lineParts[1].Trim());
        }
Beispiel #59
0
        private static bool ParseWord(StringStream stream, List<Token> tokens)
        {
            if (char.IsLetter(stream.Peek()) || stream.Peek() == '_')
            {
                string word = "";

                while (!stream.IsEndOfStream && (char.IsLetterOrDigit(stream.Peek()) || stream.Peek() == '_'))
                    word += stream.Read();

                switch (word)
                {
                    case "true":
                        tokens.Add(new Token(TokenType.Number, "1", filename, line));
                        break;

                    case "false":
                        tokens.Add(new Token(TokenType.Number, "0", filename, line));
                        break;

                    default:
                        tokens.Add(new Token(TokenType.Word, word, filename, line));
                        break;
                }

                return true;
            }

            return false;
        }
Beispiel #60
0
        private static bool ParseString(StringStream stream, List<Token> tokens)
        {
            if (stream.Peek() != '\"')
                return false;

            uint startLine = line;
            string value = "";

            while (stream.Peek() == '\"')
            {
                char ch;

                ++stream.Position;
                while ((ch = stream.Read()) != '\"')
                {
                    if (stream.IsEndOfStream)
                        throw new Exception("Unterminated string on line " + startLine);

                    if (ch == StringStream.NewLine)
                        ++line;

                    value += ch;
                }

                SkipWhitespace(stream);
            }

            tokens.Add(new Token(TokenType.String, ParseEscapeSequences(value), filename, startLine));

            return true;
        }