﻿using Nitra.Internal.Recovery;
using Nemerle.Imperative;
using System;

namespace Nitra.Internal
{
  public sealed partial class ExtensibleRuleParser
  {
    public override Parse(mutable curTextPos : int, text : string, parseResult : ParseResult) : int
    {
      parseResult.ParseSession.CancellationToken.ThrowIfCancellationRequested();

      def startTextPos = curTextPos;
      curTextPos = ParsePrefix(curTextPos, text, parseResult);
      if (curTextPos >= 0)
      {
        when (IsDynamicExtensible)
        {
          def bestResult = BestPrefixRawTreeAtPos(startTextPos, parseResult);
          def ruleParser = PrefixRuleParser(bestResult, parseResult);
          parseResult.ParseSession.CurrentGrammar = ruleParser.GrammarChangeHandler(bestResult, startTextPos, curTextPos, parseResult, Grammar);
          return curTextPos;
        }
        mutable bestPos;
        do
        {
          bestPos = curTextPos;
          curTextPos = ParsePostfix(curTextPos, text, parseResult);
        }
        while (curTextPos > bestPos);
        bestPos;
      }
      else
        -1;
    }
  }
}
