Esempio n. 1
0
        public static bool Scan(this IDfaSimulation dfa, int[] input, out int action)
        {
            int state          = dfa.Start;
            int?acceptingState = null;

            foreach (var item in input)
            {
                if (!dfa.TryNext(state, item, out state))
                {
                    break;
                }

                if (dfa.IsAccepting(state))
                {
                    acceptingState = state;
                }
            }

            if (!acceptingState.HasValue)
            {
                action = -1;
                return(false);
            }

            var optAction = dfa.GetAction(acceptingState.Value);

            action = optAction.GetValueOrDefault(-1);
            return(true);
        }
        public IReceiver <Msg> Accept(IReceiver <Msg> visitor)
        {
            int start = 0, pos = 0;

            int length = text.Length;

            while (pos != length)
            {
                int state          = dfa.Start;
                int?acceptingState = null;

                // Find longest token
                for (; pos != length; ++pos)
                {
                    int item = text[pos];

                    if (!dfa.TryNext(state, item, out state))
                    {
                        break;
                    }

                    if (dfa.IsAccepting(state))
                    {
                        acceptingState = state;
                    }
                }

                // Fail
                if (!acceptingState.HasValue)
                {
                    throw new Exception("Unexpected character at pos " + pos);
                }

                int action      = dfa.GetAction(acceptingState.Value) ?? -1;
                int tokenLength = pos - start;

                var production = descriptor.Matchers[action];
                if (production.Outcome != null)
                {
                    TokenFactoryDelegate tokenFactory = tokenFactories[action];

                    // Emit next token
                    visitor = visitor.Next(
                        new Msg(
                            production.Outcome.Index,
                            tokenFactory(text.Substring(start, tokenLength)),
                            new Loc(Loc.MemoryString, start, pos)));
                }

                start = pos;
            }

            return(visitor.Done());
        }