﻿// Copyright 2012 Fan Shi
// 
// This file is part of the VBF project.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;

namespace VBF.Compilers.Scanners
{
    public class Lexer
    {
        private List<TokenInfo> m_tokens;
        internal Lexer(Lexicon lexicon, int index) : this(lexicon, index, null) { }

        internal Lexer(Lexicon lexicon, int index, Lexer baseLexer)
        {
            Children = new List<Lexer>();
            Lexicon = lexicon;
            BaseLexer = baseLexer;
            m_tokens = new List<TokenInfo>();
            Index = index;

            if (baseLexer == null)
            {
                Level = 0;
            }
            else
            {
                Level = baseLexer.Level + 1;
                baseLexer.Children.Add(this);
            }
        }

        public Lexicon Lexicon { get; private set; }
        public Lexer BaseLexer { get; private set; }
        public int Index { get; private set; }
        internal int Level { get; private set; }
        internal List<Lexer> Children { get; private set; }

        public Token DefineToken(RegularExpression regex, string description)
        {
            CodeContract.RequiresArgumentNotNull(regex, "regex");

            int indexInState = m_tokens.Count;

            TokenInfo token = Lexicon.AddToken(regex, this, indexInState, description);
            m_tokens.Add(token);

            return token.Tag;
        }

        public Token DefineToken(RegularExpression regex)
        {
            return DefineToken(regex, null);
        }

        public Lexer CreateSubLexer()
        {
            return Lexicon.DefineLexer(this);
        }

    }
}
