示例#1
0
        public Task TestUpgradeToRevocableSession()
        {
            IObjectState state = new MutableObjectState {
                ServerData = new Dictionary <string, object>()
                {
                    { "sessionToken", "llaKcolnu" }
                }
            };
            var mockController = new Mock <IParseSessionController>();

            mockController.Setup(obj => obj.UpgradeToRevocableSessionAsync(It.IsAny <string>(),
                                                                           It.IsAny <CancellationToken>())).Returns(Task.FromResult(state));

            var mockCurrentUserController = new Mock <IParseCurrentUserController>();

            ParseCorePlugins.Instance.SessionController     = mockController.Object;
            ParseCorePlugins.Instance.CurrentUserController = mockCurrentUserController.Object;

            CancellationTokenSource source = new CancellationTokenSource();

            return(ParseSession.UpgradeToRevocableSessionAsync("someSession", source.Token).ContinueWith(t => {
                Assert.False(t.IsFaulted);
                Assert.False(t.IsCanceled);
                mockController.Verify(obj => obj.UpgradeToRevocableSessionAsync(It.Is <string>(sessionToken => sessionToken == "someSession"),
                                                                                source.Token), Times.Exactly(1));

                Assert.AreEqual("llaKcolnu", t.Result);
            }));
        }
示例#2
0
        //
        // Factory method for producing an Expression object from a token stream.
        //
        // Returns a valid Expression if one could be parsed, otherwise returns null.
        //
        // Note that the parsed expression is content-less, i.e. we don't preserve
        // any details about it. This is intentional, since IntelliSense providers
        // don't need to care about the details of an expression (yet).
        //
        // As a consequence of this, we can safely ignore things (like the relative
        // precedences of operators) because the tokens will parse the same way for
        // all cases we care about supporting. Some things like unary operators are
        // handled specially in the helper functions, but these should be viewed as
        // supporting the general goal of not interpreting the expression.
        //
        internal static Expression Parse(ParseSession parser, int starttoken, out int consumedtokens)
        {
            int totaltokens = starttoken;

            consumedtokens = totaltokens;
            bool matchedstatement = false;

            if (!ParseExpressionTerm(parser, true, totaltokens, out totaltokens, out matchedstatement))
            {
                return(null);
            }

            if (matchedstatement && parser.CheckToken(totaltokens, ")"))
            {
            }
            else
            {
                while (ParseExpressionOperator(parser, totaltokens))
                {
                    ++totaltokens;
                    if (!ParseExpressionTerm(parser, false, totaltokens, out totaltokens, out matchedstatement))
                    {
                        return(null);
                    }
                }
            }

            consumedtokens = totaltokens;
            return(new Expression());
        }
        internal static ParsedObject <WeakAlias> Parse(ParseSession parser)
        {
            if (!parser.CheckToken(0, "alias"))
            {
                return(null);
            }

            var nametoken = parser.PeekToken(1);

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

            if (!parser.CheckToken(2, "="))
            {
                return(null);
            }

            parser.ConsumeTokens(4);
            var aliastype = new WeakAlias {
            };

            return(new ParsedObject <WeakAlias> {
                Name = nametoken, Object = aliastype
            });
        }
        //
        // Parse some code and add the data obtained to a Project.
        //
        private void AugmentProject(Project project, string filecontents)
        {
            project.RegisterSourceFile(FileFullPath, this);

            var lexer  = new LexSession(this, filecontents);
            var parser = new ParseSession(lexer);

            parser.AugmentProject(project);
        }
示例#5
0
        static void Test(string text)
        {
            var session     = new ParseSession(JsonParser.Start, compilerMessages: new ConsoleCompilerMessages());
            var source      = new SourceSnapshot(text);
            var parseResult = session.Parse(source);
            var parseTree   = parseResult.CreateParseTree();

            Console.WriteLine("Pretty print: " + parseTree);
        }
示例#6
0
 public void TestIsRevocableSessionToken()
 {
     Assert.True(ParseSession.IsRevocableSessionToken("r:session"));
     Assert.True(ParseSession.IsRevocableSessionToken("r:session:r:"));
     Assert.True(ParseSession.IsRevocableSessionToken("session:r:"));
     Assert.False(ParseSession.IsRevocableSessionToken("session:s:d:r"));
     Assert.False(ParseSession.IsRevocableSessionToken("s:ession:s:d:r"));
     Assert.False(ParseSession.IsRevocableSessionToken(""));
 }
        //
        // Helper routine for parsing an assignment statement.
        //
        // Returns true if an assignment was seen in the token stream, false
        // otherwise. A false return does not indicate a syntax error. Also
        // passes back the index of the next unexamined token.
        //
        // Assignments can have associated operations, such as "a += b".
        // They can also be "chained" as in "a = b = c". However these two
        // features may not be used in conjunction with one another.
        //
        internal static bool ParseAssignment(ParseSession parser, int starttoken, out int consumedtokens)
        {
            consumedtokens = starttoken;
            int totaltokens = starttoken;

            ++totaltokens;
            while (parser.CheckToken(totaltokens, "."))
            {
                totaltokens += 2;
            }

            if (!parser.CheckToken(totaltokens, "=") &&
                !parser.CheckToken(totaltokens, "+=") &&
                !parser.CheckToken(totaltokens, "-="))
            {
                return(false);
            }

            var assignmenttoken = parser.PeekToken(totaltokens);

            ++totaltokens;

            bool haschain = true;

            while (haschain)
            {
                while (parser.CheckToken(totaltokens + 1, "."))
                {
                    totaltokens += 2;
                }

                if (parser.CheckToken(totaltokens + 1, "="))
                {
                    if (assignmenttoken.Text != "=")
                    {
                        throw new SyntaxError("Chained assignments must all use the = assignment operator.", parser.PeekToken(totaltokens + 1));
                    }

                    ++totaltokens;
                }
                else
                {
                    haschain = false;
                }
            }

            var expr = Expression.Parse(parser, totaltokens, out totaltokens);

            if (expr == null)
            {
                return(false);
            }

            consumedtokens = totaltokens;
            return(true);
        }
示例#8
0
        public void TestGetSessionToken()
        {
            ParseSession session = ParseObjectExtensions.FromState <ParseSession>(new MutableObjectState {
                ServerData = new Dictionary <string, object>()
                {
                    { "sessionToken", "llaKcolnu" }
                }
            }, "_Session");

            Assert.IsNotNull(session);
            Assert.AreEqual("llaKcolnu", session.SessionToken);
        }
示例#9
0
        public void TestGetSessionToken()
        {
            ParseSession session = Client.GenerateObjectFromState <ParseSession>(new MutableObjectState {
                ServerData = new Dictionary <string, object>()
                {
                    ["sessionToken"] = "llaKcolnu"
                }
            }, "_Session");

            Assert.IsNotNull(session);
            Assert.AreEqual("llaKcolnu", session.SessionToken);
        }
示例#10
0
        public Task TestGetCurrentSessionWithNoCurrentUser()
        {
            var mockController            = new Mock <IParseSessionController>();
            var mockCurrentUserController = new Mock <IParseCurrentUserController>();

            ParseCorePlugins.Instance.SessionController     = mockController.Object;
            ParseCorePlugins.Instance.CurrentUserController = mockCurrentUserController.Object;

            return(ParseSession.GetCurrentSessionAsync().ContinueWith(t => {
                Assert.False(t.IsFaulted);
                Assert.False(t.IsCanceled);
                Assert.Null(t.Result);
            }));
        }
示例#11
0
        public Task TestRevoke()
        {
            var mockController = new Mock <IParseSessionController>();

            ParseCorePlugins.Instance.SessionController = mockController.Object;

            CancellationTokenSource source = new CancellationTokenSource();

            return(ParseSession.RevokeAsync("r:someSession", source.Token).ContinueWith(t => {
                Assert.False(t.IsFaulted);
                Assert.False(t.IsCanceled);
                mockController.Verify(obj => obj.RevokeAsync(It.Is <string>(sessionToken => sessionToken == "r:someSession"),
                                                             source.Token), Times.Exactly(1));
            }));
        }
示例#12
0
文件: Program.cs 项目: rsdn/nitra
    static void Main(string[] args)
    {
      if (args.Length > 0)
        text = System.IO.File.ReadAllText(args[0]);

      var session = new ParseSession(JsonParser.Start, compilerMessages: new ConsoleCompilerMessages());
      var result = session.Parse(text);

      if (result.IsSuccess)
      {
        var parseTree = result.CreateParseTree();
        Console.WriteLine("Pretty print: " + parseTree);
        Console.WriteLine();
      }
    }
示例#13
0
        public Task TestGetCurrentSession()
        {
            MutableServiceHub hub = new MutableServiceHub {
            };
            ParseClient client    = new ParseClient(new ServerConnectionData {
                Test = true
            }, hub);

            IObjectState sessionState = new MutableObjectState
            {
                ServerData = new Dictionary <string, object>
                {
                    ["sessionToken"] = "newllaKcolnu"
                }
            };

            Mock <IParseSessionController> mockController = new Mock <IParseSessionController>();

            mockController.Setup(obj => obj.GetSessionAsync(It.IsAny <string>(), It.IsAny <IServiceHub>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(sessionState));

            IObjectState userState = new MutableObjectState
            {
                ServerData = new Dictionary <string, object>
                {
                    ["sessionToken"] = "llaKcolnu"
                }
            };

            ParseUser user = client.GenerateObjectFromState <ParseUser>(userState, "_User");

            Mock <IParseCurrentUserController> mockCurrentUserController = new Mock <IParseCurrentUserController>();

            mockCurrentUserController.Setup(obj => obj.GetAsync(It.IsAny <IServiceHub>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(user));

            hub.SessionController     = mockController.Object;
            hub.CurrentUserController = mockCurrentUserController.Object;

            return(client.GetCurrentSessionAsync().ContinueWith(task =>
            {
                Assert.IsFalse(task.IsFaulted);
                Assert.IsFalse(task.IsCanceled);

                mockController.Verify(obj => obj.GetSessionAsync(It.Is <string>(sessionToken => sessionToken == "llaKcolnu"), It.IsAny <IServiceHub>(), It.IsAny <CancellationToken>()), Times.Exactly(1));

                ParseSession session = task.Result;
                Assert.AreEqual("newllaKcolnu", session.SessionToken);
            }));
        }
示例#14
0
        internal static Variable Parse(ParseSession parser, int starttoken, out int consumedtokens, Origins origin)
        {
            consumedtokens = starttoken;

            if (parser.CheckToken(starttoken + 1, "."))
            {
                return(null);
            }

            var basetypename = parser.PeekToken(starttoken);

            int totaltokens = starttoken + 1;

            if (parser.CheckToken(totaltokens, "<"))
            {
                ++totaltokens;
                if (!parser.ParseTemplateArguments(totaltokens, basetypename, out totaltokens))
                {
                    return(null);
                }
            }

            var varname = parser.PeekToken(totaltokens);

            if (!parser.CheckToken(totaltokens + 1, "="))
            {
                return(null);
            }

            var type     = TypeSignatureInstantiated.Construct(parser, starttoken, totaltokens);
            var variable = new Variable {
                Name = varname, Origin = origin, Type = type
            };

            totaltokens += 2;

            Expression.Parse(parser, totaltokens, out totaltokens);
            while (parser.CheckToken(totaltokens, ","))
            {
                ++totaltokens;
                Expression.Parse(parser, totaltokens, out totaltokens);
            }

            consumedtokens = totaltokens;

            return(variable);
        }
        public Task TestGetCurrentSession()
        {
            IObjectState sessionState = new MutableObjectState
            {
                ServerData = new Dictionary <string, object>
                {
                    { "sessionToken", "newllaKcolnu" }
                }
            };
            var mockController = new Mock <IParseSessionController>();

            mockController.Setup(obj => obj.GetSessionAsync(It.IsAny <string>(),
                                                            It.IsAny <CancellationToken>())).Returns(Task.FromResult(sessionState));

            IObjectState userState = new MutableObjectState
            {
                ServerData = new Dictionary <string, object>()
                {
                    { "sessionToken", "llaKcolnu" }
                }
            };

            var user = ParseObjectExtensions.FromState <ParseUser>(userState, "_User");
            var mockCurrentUserController = new Mock <IParseCurrentUserController>();

            mockCurrentUserController.Setup(obj => obj.GetAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(user));
            ParseCorePlugins.Instance = new ParseCorePlugins
            {
                SessionController     = mockController.Object,
                CurrentUserController = mockCurrentUserController.Object,
            };
            ParseObject.RegisterSubclass <ParseSession>();

            return(ParseSession.GetCurrentSessionAsync()
                   .ContinueWith(t =>
            {
                Assert.False(t.IsFaulted);
                Assert.False(t.IsCanceled);
                mockController.Verify(obj => obj.GetSessionAsync(
                                          It.Is <string>(sessionToken => sessionToken == "llaKcolnu"),
                                          It.IsAny <CancellationToken>()), Times.Exactly(1));

                var session = t.Result;
                Assert.AreEqual("newllaKcolnu", session.SessionToken);
            }));
        }
示例#16
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                text = System.IO.File.ReadAllText(args[0]);
            }

            var session = new ParseSession(JsonParser.Start, compilerMessages: new ConsoleCompilerMessages());
            var result  = session.Parse(text);

            if (result.IsSuccess)
            {
                var parseTree = result.CreateParseTree();
                Console.WriteLine("Pretty print: " + parseTree);
                Console.WriteLine();
            }
        }
示例#17
0
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);
            var auth = new OAuth2Authenticator(
                clientId: "1790522011216423",                                                 // your OAuth2 client id
                scope: "email",                                                               // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: new Uri("https://www.facebook.com/v2.8/dialog/oauth"),          // the auth URL for the service
                redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")); // the redirect URL for the service

            auth.Completed += async(sender, eventArgs) =>
            {
                count++;
                // We presented the UI, so it's up to us to dimiss it on iOS.
                //App.SuccessfulLoginAction.Invoke();

                if (eventArgs.IsAuthenticated)
                {
                    DismissViewController(true, null);
                    var accessToken = eventArgs.Account.Properties["access_token"].ToString();
                    var expiresIn   = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
                    var expireDate  = DateTime.Now + TimeSpan.FromSeconds(expiresIn);

                    var request  = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender"), null, eventArgs.Account);
                    var response = await request.GetResponseAsync();

                    var obj = JObject.Parse(response.GetResponseText());
                    var id  = obj["id"].ToString().Replace("\"", "");
                    await ParseFacebookUtils.LogInAsync(id, accessToken, expireDate);

                    var session = await ParseSession.GetCurrentSessionAsync();

                    var token = session.SessionToken;
                    App.SuccessfulLoginAction.Invoke();
                    App.SuccessFacebookLogin(token, obj);
                }
                else
                {
                    // The user cancelled
                }
            };
            if (count <= 1)
            {
                PresentViewController(auth.GetUI(), true, null);
            }
        }
示例#18
0
        public IParseResult Run([NotNull] string code, [CanBeNull] string gold = null, int completionStartPos = -1, string completionPrefix = null, RecoveryAlgorithm recoveryAlgorithm = RecoveryAlgorithm.Smart)
        {
            var source = new SourceSnapshot(code);

            if (Language.StartRule == null)
            {
                return(null);
            }

            try
            {
                var parseSession = new ParseSession(Language.StartRule,
                                                    compositeGrammar:   Language.CompositeGrammar,
                                                    completionPrefix:   completionPrefix,
                                                    completionStartPos: completionStartPos,
                                                    parseToEndOfString: true,
                                                    dynamicExtensions:  DynamicExtensions,
                                                    statistics:         Statistics);
                switch (recoveryAlgorithm)
                {
                case RecoveryAlgorithm.Smart: parseSession.OnRecovery = ParseSession.SmartRecovery; break;

                case RecoveryAlgorithm.Panic: parseSession.OnRecovery = ParseSession.PanicRecovery; break;

                case RecoveryAlgorithm.FirstError: parseSession.OnRecovery = ParseSession.FirsrErrorRecovery; break;
                }
                var parseResult = parseSession.Parse(source);
                this.Exception = null;
                return(parseResult);
            }
            catch (Exception ex)
            {
                this.Exception = ex;
                return(null);
            }
        }
示例#19
0
        internal static ParsedObject <SumType> Parse(ParseSession parser)
        {
            int totaltokens = 0;

            if (!parser.CheckToken(0, "type"))
            {
                return(null);
            }

            Token sumtypename = parser.PeekToken(1);

            if (sumtypename == null || string.IsNullOrEmpty(sumtypename.Text))
            {
                return(null);
            }

            if (parser.CheckToken(2, "<"))
            {
                if (!parser.ParseTemplateParameters(3, sumtypename, out totaltokens))
                {
                    return(null);
                }

                if (!parser.CheckToken(totaltokens, ":"))
                {
                    return(null);
                }
            }
            else if (!parser.CheckToken(2, ":"))
            {
                return(null);
            }
            else if (!parser.CheckToken(4, "|"))
            {
                return(null);
            }
            else
            {
                totaltokens = 2;
            }

            do
            {
                ++totaltokens;

                if (parser.CheckToken(totaltokens + 1, "<"))
                {
                    var token = parser.PeekToken(totaltokens);
                    if (token == null)
                    {
                        return(null);
                    }

                    if (!parser.ParseTemplateArguments(totaltokens + 2, token, out totaltokens))
                    {
                        return(null);
                    }
                }
                else
                {
                    ++totaltokens;
                }
            } while (parser.CheckToken(totaltokens, "|"));

            // Success! Consume everything and return the constructed result
            parser.ConsumeTokens(totaltokens);
            var sumtype = new SumType {
            };

            return(new ParsedObject <SumType> {
                Name = sumtypename, Object = sumtype
            });
        }
        //
        // Helper routine for parsing a code entity from a token stream.
        //
        // This terminology is mostly legacy from an older implementation of Epoch.
        // An entity is really just a branch/flow-control construct such as a loop
        // or an if/else statement. Typically there is an expression which controls
        // execution and an associated code block.
        //
        internal static bool ParseEntity(ParseSession parser, LexicalScope parentscope, int starttoken, out int consumedtokens)
        {
            consumedtokens = starttoken;
            int totaltokens = starttoken;

            if (parser.CheckToken(totaltokens, "if"))
            {
                if (!parser.CheckToken(totaltokens + 1, "("))
                {
                    return(false);
                }

                totaltokens += 2;

                var expr = Expression.Parse(parser, totaltokens, out totaltokens);
                if (expr == null)
                {
                    throw new SyntaxError("if() statement must be supplied with a valid Boolean-typed expression", parser.ReversePeekToken());
                }

                while (parser.CheckToken(totaltokens, ")"))
                {
                    ++totaltokens;
                }

                if (!parser.CheckToken(totaltokens, "{"))
                {
                    throw new SyntaxError("if() statement must be followed by a code block surrounded in braces { }", parser.PeekToken(totaltokens));
                }

                ++totaltokens;
                LexicalScope.Parse(parser, parentscope, totaltokens, out totaltokens);

                while (parser.CheckToken(totaltokens, "elseif"))
                {
                    totaltokens += 2;
                    var condexpr = Expression.Parse(parser, totaltokens, out totaltokens);
                    if (condexpr == null)
                    {
                        throw new SyntaxError("elseif() statement must be supplied with a valid Boolean-typed expression", parser.ReversePeekToken());
                    }

                    while (parser.CheckToken(totaltokens, ")"))
                    {
                        ++totaltokens;
                    }

                    if (!parser.CheckToken(totaltokens, "{"))
                    {
                        throw new SyntaxError("elseif() statement must be followed by a code block surrounded in braces { }", parser.PeekToken(totaltokens));
                    }

                    ++totaltokens;
                    LexicalScope.Parse(parser, parentscope, totaltokens, out totaltokens);
                }

                if (parser.CheckToken(totaltokens, "else"))
                {
                    ++totaltokens;
                    if (!parser.CheckToken(totaltokens, "{"))
                    {
                        throw new SyntaxError("else statement must be followed by a code block surrounded in braces { }", parser.PeekToken(totaltokens));
                    }

                    ++totaltokens;
                    LexicalScope.Parse(parser, parentscope, totaltokens, out totaltokens);
                }

                consumedtokens = totaltokens;
                return(true);
            }
            else if (parser.CheckToken(totaltokens, "while"))
            {
                if (!parser.CheckToken(totaltokens + 1, "("))
                {
                    throw new SyntaxError("while() statement must be supplied with a valid Boolean-typed expression", parser.ReversePeekToken());
                }

                totaltokens += 2;

                while (parser.CheckToken(totaltokens, ")"))
                {
                    ++totaltokens;
                }

                var expr = Expression.Parse(parser, totaltokens, out totaltokens);
                ++totaltokens;

                if (!parser.CheckToken(totaltokens, "{"))
                {
                    throw new SyntaxError("while() statement must be followed by a code block surrounded in braces { }", parser.PeekToken(totaltokens));
                }

                ++totaltokens;
                LexicalScope.Parse(parser, parentscope, totaltokens, out totaltokens);

                consumedtokens = totaltokens;
                return(true);
            }

            return(false);
        }
 public static Task <string> UpgradeToRevocableSessionAsync(string sessionToken, CancellationToken cancellationToken)
 {
     return(ParseSession.UpgradeToRevocableSessionAsync(sessionToken, cancellationToken));
 }
示例#22
0
        //
        // Helper function to extract an operator from a token stream.
        //
        // Returns true if successful, false if no valid operator was
        // detected. Does not directly consume tokens; assume exactly
        // one token can be popped if true is returned.
        //
        // Note that this function will return false if a terminating
        // token (closing parens, etc.) is seen; this should not be
        // taken to indicate a syntax error.
        //
        private static bool ParseExpressionOperator(ParseSession parser, int starttoken)
        {
            var token = parser.PeekToken(starttoken);

            if (token == null)
            {
                return(false);
            }

            string op = token.Text;

            if (op == ")")
            {
                return(false);
            }

            if (op == ",")
            {
                return(false);
            }

            if (op == "")
            {
                return(false);
            }

            if (op.Length > 2)
            {
                return(false);
            }

            if (op == ".")
            {
                return(true);
            }
            else if (op == "+")
            {
                return(true);
            }
            else if (op == "-")
            {
                return(true);
            }
            else if (op == "*")
            {
                return(true);
            }
            else if (op == "/")
            {
                return(true);
            }
            else if (op == "==")
            {
                return(true);
            }
            else if (op == "!=")
            {
                return(true);
            }
            else if (op == ";")
            {
                return(true);
            }
            else if (op == ">")
            {
                return(true);
            }
            else if (op == "<")
            {
                return(true);
            }
            else if (op == "&")
            {
                return(true);
            }
            else if (op == "&&")
            {
                return(true);
            }

            return(false);
        }
示例#23
0
    public IParseResult Run([NotNull] string code, [CanBeNull] string gold = null, int completionStartPos = -1, string completionPrefix = null, RecoveryAlgorithm recoveryAlgorithm = RecoveryAlgorithm.Smart)
    {
      var source = new SourceSnapshot(code);

      if (Language.StartRule == null)
        return null;

      try
      {
        var parseSession = new ParseSession(Language.StartRule,
          compositeGrammar:   Language.CompositeGrammar,
          completionPrefix:   completionPrefix,
          completionStartPos: completionStartPos,
          parseToEndOfString: true,
          dynamicExtensions:  DynamicExtensions,
          statistics:         Statistics);
        switch (recoveryAlgorithm)
        {
          case RecoveryAlgorithm.Smart: parseSession.OnRecovery = ParseSession.SmartRecovery; break;
          case RecoveryAlgorithm.Panic: parseSession.OnRecovery = ParseSession.PanicRecovery; break;
          case RecoveryAlgorithm.FirstError: parseSession.OnRecovery = ParseSession.FirsrErrorRecovery; break;
        }
        var parseResult = parseSession.Parse(source);
        this.Exception = null;
        return parseResult;
      }
      catch (Exception ex)
      {
        this.Exception = ex;
        return null;
      }
    }
示例#24
0
文件: Json-1.cs 项目: rsdn/nitra
 static void Test(string text)
 {
   var session     = new ParseSession(JsonParser.Start, compilerMessages: new ConsoleCompilerMessages());
   var source      = new SourceSnapshot(text);
   var parseResult = session.Parse(source);
   var parseTree   = parseResult.CreateParseTree();
   Console.WriteLine("Pretty print: " + parseTree);
 }
 public static Task RevokeAsync(string sessionToken, CancellationToken cancellationToken) => ParseSession.RevokeAsync(sessionToken, cancellationToken);
 public static Task RevokeAsync(string sessionToken, CancellationToken cancellationToken)
 {
     return(ParseSession.RevokeAsync(sessionToken, cancellationToken));
 }
示例#27
0
        //
        // Helper function to extract an expression term from a token stream.
        //
        // Returns true if a term was found, and passes out the index of the
        // next token to examine. No tokens should be popped if this helper
        // returns false.
        //
        // Note that in cases where a terminating token is present, such as
        // a closing parenthesis or a comma, this will return false; however
        // this does not indicate a syntax error.
        //
        private static bool ParseExpressionTerm(ParseSession parser, bool atstart, int starttoken, out int consumedtokens, out bool matchedstatement)
        {
            matchedstatement = false;
            int totaltokens = starttoken;

            consumedtokens = totaltokens;

            if (parser.PeekToken(totaltokens) == null)
            {
                return(false);
            }

            if (parser.CheckToken(totaltokens, ")"))
            {
                return(false);
            }

            if (parser.CheckToken(totaltokens, ","))
            {
                return(false);
            }

            if (parser.CheckToken(totaltokens, "("))
            {
                ++totaltokens;
                if (Parse(parser, totaltokens, out totaltokens) != null)
                {
                    ++totaltokens;
                    consumedtokens = totaltokens;
                    return(true);
                }

                return(false);
            }

            if (parser.CheckToken(totaltokens, "!"))
            {
                ++totaltokens;
                var ret = ParseExpressionTerm(parser, atstart, totaltokens, out totaltokens, out matchedstatement);

                if (matchedstatement && parser.CheckToken(totaltokens, ")"))
                {
                    ++totaltokens;
                }

                consumedtokens = totaltokens;

                return(ret);
            }

            // The following check is a tiny optimization. Instead of trying to parse
            // a statement first and then eventually giving up, we first try checking
            // for common literals. This makes code with literals parse a fractional,
            // almost insignificant amount faster. It's actually a relic from the way
            // the compiler implements this logic. Maybe it makes sense to remove it,
            // and aim for simplicity over ideal efficiency. Profiling data is so far
            // insufficient to decide for sure, so this stays in the interim.
            if (parser.CheckToken(totaltokens, "false") || parser.CheckToken(totaltokens, "true") || parser.CheckToken(totaltokens, "0") || parser.CheckToken(totaltokens, "0.0"))
            {
                ++totaltokens;
            }
            else if (parser.ParsePreopStatement(totaltokens, out totaltokens))
            {
                consumedtokens = totaltokens;
                return(true);
            }
            else if (parser.ParseStatement(totaltokens, out totaltokens))
            {
                matchedstatement = true;
                consumedtokens   = totaltokens;
                return(true);
            }
            else
            {
                ++totaltokens;
            }

            consumedtokens = totaltokens;
            return(true);
        }