Example #1
0
 public ParseEsc(char c, char code)
     :
     base(
         inp =>
 {
     var r = Prim.Character(c).Parse(inp);
     if (r.IsFaulted)
     {
         return(r);
     }
     else
     {
         var tuple = r.Value.First();
         return(ParserResult.Success <ParserChar>(
                    Tuple.Create <ParserChar, ImmutableList <ParserChar> >(
                        new ParserChar(
                            code,
                            tuple.Item1.Location
                            ),
                        tuple.Item2
                        ).Cons()
                    ));
     }
 }
         )
 { }
Example #2
0
        public void TestDigitList()
        {
            var p = from open in Prim.Character('[')
                    from d in Prim.Digit()
                    from ds in
                    Prim.Many(
                from comma in Prim.Character(',')
                from digit in Prim.Digit()
                select digit
                )
                    from close in Prim.Character(']')
                    select d.Cons(ds);

            var r = p.Parse("[1,2,3,4]").Value.Single();

            Assert.True(r.Item1.First().Value == '1');
            Assert.True(r.Item1.Skip(1).First().Value == '2');
            Assert.True(r.Item1.Skip(2).First().Value == '3');
            Assert.True(r.Item1.Skip(3).First().Value == '4');

            var r2 = p.Parse("[1,2,3,4");

            Assert.True(r2.IsFaulted);
            Assert.True(r2.Errors.First().Expected == "']'");
            Assert.True(r2.Errors.First().Input.IsEmpty);

            var r3 = p.Parse("[1,2,3,4*");

            Assert.True(r3.IsFaulted);
            Assert.True(r3.Errors.First().Expected == "']'");
            Assert.True(r3.Errors.First().Location.Line == 1);
            Assert.True(r3.Errors.First().Location.Column == 9);
        }
Example #3
0
        public void TestBetween()
        {
            var r = Prim.Between(Prim.Character('['), Prim.Character(']'), Prim.String("abc")).Parse("[abc]");

            Assert.True(!r.IsFaulted);
            Assert.True(r.Value.First().Item1.AsString() == "abc");
        }
Example #4
0
        public void TestMany()
        {
            var r = Prim.Many(Prim.Character('a')).Parse("aaabcde").Value.Single();

            Assert.True(r.Item1.AsString() == "aaa");
            Assert.True(r.Item2.AsString() == "bcde");
        }
Example #5
0
 public HaskellDef()
 {
     IdentLetter   = IdentLetter.Or(Prim.Character('#'));
     ReservedNames = Enumerable.Concat(
         ReservedNames,
         new string[] { "foreign", "import", "export", "primitive"
                        , "_ccall_", "_casm_"
                        , "forall" });
 }
Example #6
0
 public WsChrParser(char c)
     :
     base(
         inp => Prim.WhiteSpace()
         .And(Prim.Character(c))
         .Parse(inp)
         )
 {
 }
Example #7
0
 public CharEscape()
     :
     base(
         inp => (from c in Prim.Character('\\')
                 from ec in Tok.Chars.EscapeCode()
                 select ec)
         .Parse(inp)
         )
 {
 }
Example #8
0
 public EscapeGap()
     :
     base(
         inp => (from sp in Prim.Many1(Prim.Character(' '))
                 from ch in Prim.Character('\\')
                 select ch)
         .Fail("end of string gap")
         .Parse(inp)
         )
 {
 }
Example #9
0
 public JavaStyle()
 {
     CommentStart    = "/*";
     CommentEnd      = "*/";
     CommentLine     = "//";
     NestedComments  = true;
     IdentStart      = Prim.Letter();
     IdentLetter     = Prim.LetterOrDigit().Or(Prim.Character('_').Or(Prim.Character('\'')));
     ReservedOpNames = new string[0];
     ReservedNames   = new string[0];
     CaseSensitive   = true;
 }
Example #10
0
        public void LexemeTest()
        {
            var lex = from l in Tok.Lexeme <ParserChar>(Prim.Character('A'))
                      select l;

            var res = lex.Parse("A");

            Assert.True(!res.IsFaulted);

            res = lex.Parse("A   ");
            Assert.True(!res.IsFaulted);
        }
Example #11
0
 public HaskellStyle()
 {
     CommentStart    = "{-";
     CommentEnd      = "-}";
     CommentLine     = "--";
     NestedComments  = true;
     IdentStart      = Prim.Letter();
     IdentLetter     = Prim.LetterOrDigit().Or(Prim.Character('_').Or(Prim.Character('\'')));
     OpStart         = OpLetter = Prim.OneOf(":!#$%&*+./<=>?@\\^|-~");
     ReservedOpNames = new string[0];
     ReservedNames   = new string[0];
     CaseSensitive   = true;
 }
Example #12
0
 public StringEscape()
     :
     base(
         inp =>
         Prim.Character('\\')
         .And(
             new EscapeGap().And(Prim.Failure <ParserChar>(ParserError.Create("", inp)))
             .Or(new EscapeEmpty().And(Prim.Failure <ParserChar>(ParserError.Create("", inp))))
             .Or(Tok.Chars.EscapeCode())
             )
         .Parse(inp)
         )
 {
 }
Example #13
0
 public Expr()
     :
     base(
         inp => (from t in New.Term()
                 from e in
                 (from plus in Prim.Character('+')
                  from expr in New.Expr()
                  select expr)
                 | Prim.Return <int>(0)
                 select t + e)
         .Parse(inp)
         )
 {
 }
Example #14
0
 public Term()
     :
     base(
         inp => (from f in New.Factor()
                 from t in
                 (from mult in Prim.Character('*')
                  from term in New.Term()
                  select term)
                 | Prim.Return <int>(1)
                 select f *t)
         .Parse(inp)
         )
 {
 }
Example #15
0
        public Sign()
            :
            base(
                inp =>
        {
            var r = Prim.Character('-')
                    .Or(Prim.Character('+'))
                    .Parse(inp);

            return(r.IsFaulted
                        ? ParserResult.Success(Tuple.Create(new ParserChar('+'), inp).Cons())
                        : r);
        }
                )
        { }
Example #16
0
 public CharLiteral()
     :
     base(
         inp => Tok.Lexeme(
             Prim.Between(
                 Prim.Character('\''),
                 Prim.Character('\'').Fail("end of character"),
                 new CharacterChar()
                 ))
         .Select(ch => new CharLiteralToken(ch, inp.Head().Location))
         .Fail("character")
         .Parse(inp)
         )
 {
 }
Example #17
0
        public Factor()
            :
            base(
                inp => (from choice in
                        (from d in Prim.Digit()
                         select Int32.Parse(d.Value.ToString()))
                        | (from open in Prim.Character('(')
                           from expr in New.Expr()
                           from close in Prim.Character(')')
                           select expr)
                        select choice)
                .Parse(inp)

                )
        {
        }
Example #18
0
 public ZeroNumber()
     :
     base(
         inp => (from z in Prim.Character('0')
                 from y in Prim.Choice(
                     Tok.Numbers.Hexadecimal() as Parser <IntegerToken>,
                     Tok.Numbers.Octal() as Parser <IntegerToken>,
                     Tok.Numbers.Decimal() as Parser <IntegerToken>,
                     Prim.Return(new IntegerToken(0, SrcLoc.Null)) as Parser <IntegerToken>
                     )
                 select new IntegerToken(0, !inp.IsEmpty ? inp.Head().Location : SrcLoc.EndOfSource))
         .Fail("")
         .Parse(inp)
         )
 {
 }
Example #19
0
 public StringLiteral()
     :
     base(
         inp => (from l in Tok.Lexeme(
                     from str in Prim.Between(
                         Prim.Character('"'),
                         Prim.Character('"').Fail("end of string"),
                         Prim.Many(new StringChar())
                         )
                     select str
                     )
                 select new StringLiteralToken(l, inp.Head().Location)
                 )
         .Fail("literal string")
         .Parse(inp)
         )
 {
 }
Example #20
0
        public void TestSkipMany1()
        {
            var p = Prim.SkipMany1(Prim.Character('*'));

            var r = p.Parse("****hello, world");

            Assert.True(!r.IsFaulted);
            var after = r.Value.Head().Item2.AsString();

            Assert.True(after == "hello, world");

            r = p.Parse("*hello, world");
            Assert.True(!r.IsFaulted);
            after = r.Value.Head().Item2.AsString();
            Assert.True(after == "hello, world");

            r = p.Parse("hello, world");
            Assert.True(r.IsFaulted);
        }
Example #21
0
        private void BuildReplParser()
        {
            var ParserParameter = Prim.Many1(Prim.Choice(Prim.OneOf("_>"), Prim.LetterOrDigit()));

            var ParserQuery = from query in parser.TopLevelParser()
                              from _ in Prim.WhiteSpace()
                              select new QueryContainer(query) as ReplParseObject;

            var ParserREPLDirective = from _ in Prim.Character(':')
                                      from option in Prim.Many1(Prim.Choice(Prim.Character('/'), Prim.LetterOrDigit()))
                                      from __ in Prim.WhiteSpace()
                                      from parameters in Prim.SepBy(ParserParameter, Prim.WhiteSpace())
                                      from ___ in Prim.Character(';')
                                      from ____ in Prim.WhiteSpace()
                                      select new REPLDirectiveParsedObject(option.AsString(), parameters.AsStrings(), _.Location) as ReplParseObject;

            replParser = (from ts in Prim.Many1(
                              from lq in Prim.Choice(ParserQuery, ParserREPLDirective)
                              select lq
                              )
                          select ts)
                         .Fail("Expected query or command");
        }
Example #22
0
        public void TestChar()
        {
            var r = Prim.Character('X').Parse("X").Value.Single();

            Assert.True(r.Item1.Value == 'X');
        }
Example #23
0
        public void BuildLangParser()
        {
            var opChars = ";.,<>?/\\|\"':=+-_*&^%$£@!".AsEnumerable();

            Id = from w in Prim.WhiteSpace()
                 from c in Prim.Letter()
                 from cs in Prim.Many(Prim.LetterOrDigit())
                 select c.Cons(cs);

            Op = (from w in Prim.WhiteSpace()
                  from o in Prim.Satisfy(c => opChars.Contains(c), "an operator")
                  from os in Prim.Many(Prim.Satisfy(c => opChars.Contains(c), "an operator"))
                  select o.Cons(os))
                 .Fail("an operator");

            Ident = (from s in Id
                     where
                     s.IsNotEqualTo("let") &&
                     s.IsNotEqualTo("in")
                     select s)
                    .Fail("identifier");

            LetId = (from s in Id
                     where s.IsEqualTo("let")
                     select s)
                    .Fail("let");

            InId = (from s in Id
                    where s.IsEqualTo("in")
                    select s)
                   .Fail("'in'");

            Semi = (from s in Op
                    where s.IsEqualTo(";")
                    select s)
                   .Fail("';'");

            LambdaArrow = (from s in Op
                           where s.IsEqualTo("=>")
                           select s)
                          .Fail("a lambda arrow '=>'");

            Integer = (from w in Prim.WhiteSpace()
                       from d in Prim.Integer()
                       select new IntegerTerm(d) as Term)
                      .Fail("an integer");

            String = (from w in Prim.WhiteSpace()
                      from o in Prim.Character('"')
                      from cs in Prim.Many(Prim.Satisfy(c => c != '"'))
                      from c in Prim.Character('"')
                      select new StringTerm(cs) as Term)
                     .Fail("a string literal");

            Term1 = Integer
                    | String
                    | (from x in Ident
                       select new VarTerm(x) as Term)
                    | (from u1 in Lang.WsChr('(')
                       from t in Term
                       from u2 in Lang.WsChr(')')
                       select t)
                    .Fail("a term");

            Term = (from x in Ident
                    from arrow in LambdaArrow
                    from t in Term
                    select new LambdaTerm(x, t) as Term)
                   | (from lid in LetId
                      from x in Ident
                      from u1 in Lang.WsChr('=')
                      from t in Term
                      from s in Semi
                      from c in Term
                      select new LetTerm(x, t, c) as Term)
                   | (from t in Term1
                      from ts in Prim.Many(Term1)
                      select new AppTerm(t, ts) as Term)
                   .Fail("a term");

            Parser = from t in Term
                     from u in Lang.WsChr(';')
                     from w in Prim.WhiteSpace()
                     select t;
        }
Example #24
0
        public void BuildScrapeQLParser()
        {
            var def        = new ScrapeQLDef();
            var lexer      = Tok.MakeTokenParser <Term>(def);
            var reserved   = lexer.Reserved;
            var identifier = lexer.Identifier;
            var strings    = lexer.StringLiteral;

            var ParserComma = from _ in Prim.WhiteSpace()
                              from c in Prim.Character(',')
                              from __ in Prim.WhiteSpace()
                              select c;

            var ParserRegularExpression = (from b in Prim.Character('\\')
                                           from r in Prim.Character('r')
                                           from re in strings
                                           select new RegularExpression(re.Value.AsString()))
                                          .Fail("Regex");

            var ParserListLiteralStringToken = (from strs in Prim.SepBy(
                                                    strings,
                                                    ParserComma
                                                    )
                                                select strs);

            var ParserListIdentifierToken = (from strs in Prim.SepBy(
                                                 identifier,
                                                 ParserComma
                                                 )
                                             select strs);

            /*ParserKeyPair = (from left in ParserString
             *         from c in Prim.Character(':')
             *         from right in ParserString
             *         select Tuple.Create(left, right))
             *         .Fail("tuple");
             *
             * ParserDictionary = (from ps in Prim.SepBy1(ParserKeyPair, Prim.Character(','))
             *                 select ps)
             *                 .Fail("dictionary");*/

            var ParserLoadQuery = from _ in reserved("LOAD")
                                  from sources in ParserListLiteralStringToken
                                  from __ in reserved("AS")
                                  from aliases in ParserListIdentifierToken
                                  select new LoadQuery(aliases, sources, _.Location) as Query;

            var ParserWriteQuery = from _ in reserved("WRITE")
                                   from alias in identifier
                                   from __ in reserved("TO")
                                   from src in strings
                                   select new WriteQuery(alias, src, _.Location) as Query;

            var ParserStringSelector = from s in strings select new SelectorString(s, s.Location) as Selector;

            var ParserAttributeSelector = from src in identifier
                                          from xpath in Prim.Between(Prim.Character('['), Prim.Character(']'), strings)
                                          select new AttributeSelector(src, xpath, src.Location) as Selector;

            var Conditional = from sq in reserved("TO")
                              select sq; //TODO: Conditions

            var ParserWhereExpression = from _ in reserved("WHERE")
                                        from clauses in Prim.Many1(Conditional)
                                        select new WhereExpression() as Term; //TODO: Return enumarable conditions

            var ParserSelectQuery = from _ in reserved("SELECT")
                                    from selector in Prim.Choice(ParserStringSelector, ParserAttributeSelector)
                                    from __ in reserved("AS")
                                    from alias in identifier
                                    from ___ in reserved("FROM")
                                    from src in identifier
                                    from whereClasuses in Prim.Try(ParserWhereExpression)
                                    select new SelectQuery(selector, alias, src, _.Location) as Query;



            TopLevel = Prim.Choice(ParserLoadQuery, ParserSelectQuery, ParserWriteQuery);

            TopLevelMany = from ts in Prim.Many1(
                from lq in TopLevel
                select lq
                )
                           select ts;
        }