001/*
002 * Copyright (c) 2018 Chris K Wensel <chris@wensel.net>. All Rights Reserved.
003 *
004 * This Source Code Form is subject to the terms of the Mozilla Public
005 * License, v. 2.0. If a copy of the MPL was not distributed with this
006 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
007 */
008
009package heretical.parser.common;
010
011import java.util.ArrayList;
012import java.util.List;
013
014import heretical.parser.common.expression.Expression;
015import org.parboiled.errors.ErrorUtils;
016import org.parboiled.errors.ParseError;
017import org.parboiled.support.ParsingResult;
018
019/**
020 *
021 */
022public class Result<E extends Expression>
023  {
024  private final ParsingResult<E> result;
025  private final long parseDuration;
026
027  public Result( ParsingResult<E> result, long parseDuration )
028    {
029    this.result = result;
030    this.parseDuration = parseDuration;
031    }
032
033  public ParsingResult<E> getParsingResult()
034    {
035    return result;
036    }
037
038  public long getParseDuration()
039    {
040    return parseDuration;
041    }
042
043  public boolean matched()
044    {
045    return result.matched;
046    }
047
048  public boolean hasErrors()
049    {
050    return result.hasErrors();
051    }
052
053  public E getExpression()
054    {
055    return result.resultValue;
056    }
057
058  public int getNumErrors()
059    {
060    if( !result.hasErrors() )
061      return 0;
062
063    return result.parseErrors.size();
064    }
065
066  public int getErrorStartIndex( int index )
067    {
068    if( !result.hasErrors() )
069      throw new IllegalStateException( "has no errors" );
070
071    return result.parseErrors.get( index ).getStartIndex();
072    }
073
074  public int getErrorEndIndex( int index )
075    {
076    if( !result.hasErrors() )
077      throw new IllegalStateException( "has no errors" );
078
079    return result.parseErrors.get( index ).getEndIndex();
080    }
081
082  public List<String> getErrorMessages()
083    {
084    List<String> messages = new ArrayList<>();
085
086    for( ParseError parseError : result.parseErrors )
087      messages.add( parseError.getErrorMessage() );
088
089    return messages;
090    }
091
092  public String prettyPrintErrors()
093    {
094    return ErrorUtils.printParseErrors( result );
095    }
096  }