コード例 #1
0
        /// <summary>
        /// The "token_list" is assumed to be x [ ... ].
        /// </summary>
        void parse_slice(TokenList token_list)
        {
            // counter for right bracket detection
            int bracket_counter = 1; // number of left brackets so far

            int start_index = 2;

            for (int i = start_index; i < token_list.Count; i++)
            {
                // keep track of left brackets versus right brackets
                if (token_list[i].type == TokenType.Left_Bracket)
                {
                    bracket_counter++;
                }
                else if (token_list[i].type == TokenType.Right_Bracket)
                {
                    bracket_counter--;
                }

                // a colon, or the bracket_counter hitting zero, indicates a function argument
                if (token_list[i].type == TokenType.Colon || bracket_counter <= 0)
                {
                    // The slice notation has at most 3 arguments: start, end, step
                    if (arguments.Count >= 3)
                    {
                        throw new Exception("The slice notation can have at most 3 arguments: start, end, and step.");
                    }

                    // add token_list[start_index, i-1] to the list of arguments
                    if (i - start_index >= 1)
                    {
                        arguments.add_argument(token_list, start_index, i - 1);
                    }
                    else
                    {
                        // Handle the case where a default is being used, like x[:2]
                        arguments.add_null_argument();
                    }
                    start_index = i + 1;
                }

                // bracket_counter hitting zero indicates end of the function
                if (bracket_counter == 0)
                {
                    break;
                }
            }

            // The slice notation can have at most 3 arguments.
            if (arguments.Count > 3)
            {
                throw new Exception("The slice notation can have at most 3 arguments.");
            }
        }