Example #1
0
        /// <summary>
        /// Разбивает строку на базовые языковые единицы (токены).
        /// </summary>
        /// <param name="str">Исходная строка.</param>
        /// <returns>Список токенов для парсинга.</returns>
        public static TokenList Lex(string code)
        {
            fullCode = code;
            TokenList tokens = new TokenList();

            currentCharIndex = 0;

            while (currentCharIndex < code.Length)
            {
                char ch = GetCurrentChar();

                if (ch == '\n')
                {
                    tokens.Add(new Token(TokenType.NextLine, "\n"));
                    currentLineIndex++;
                }

                if (char.IsWhiteSpace(ch) || char.IsControl(ch))
                {
                    currentCharIndex++;
                    continue;
                }

                if (char.IsDigit(ch))
                {
                    tokens.Add(TokenType.Number, ReadNumber());
                }
                else if (GetOperatorType(ch) != TokenType.UndefinedOperator)
                {
                    string op = ReadOperator();

                    tokens.Add(GetOperatorType(op), op);
                }
                else if (char.IsLetter(ch))
                {
                    string id = ReadId();
                    if (Keywords.IsKeyword(id))
                    {
                        tokens.Add(TokenType.Keyword, id);
                    }
                    else
                    {
                        tokens.Add(TokenType.Id, id);
                    }
                }
                else if (ch == '"')
                {
                    tokens.Add(TokenType.String, ReadString('"'));
                }
                else if (ch == '\'')
                {
                    tokens.Add(TokenType.String, ReadString('\''));
                }
                else
                {
                    tokens.Add(GetOperatorType(ch), ch);
                }
                GetNextChar();
            }

            return(tokens);
        }