View Javadoc
1   package de.fhdw.wtf.parser;
2   
3   import java.util.ArrayList;
4   import java.util.Collection;
5   
6   import de.fhdw.wtf.common.ast.Model;
7   import de.fhdw.wtf.common.exception.parser.AbstractParserException;
8   import de.fhdw.wtf.common.exception.parser.NoValidTokenStreamException;
9   import de.fhdw.wtf.common.stream.TokenStream;
10  
11  /**
12   * <h1>Parser</h1> The {@link Parser} transforms a given TokenStream of <i>WTF-Tokens</i> into an abstract syntax tree.
13   * See documentations for further information about the abstract syntax tree.
14   */
15  public final class Parser {
16  	
17  	/**
18  	 * TokenStream.
19  	 */
20  	private final TokenStream stream;
21  	
22  	/**
23  	 * Collection of exceptions.
24  	 */
25  	private final Collection<AbstractParserException> exceptions;
26  	
27  	/**
28  	 * Constructor for a Parser. <code>stream</code> is the TokenStream which will be parsed.
29  	 * 
30  	 * @param stream
31  	 *            tokenStream
32  	 */
33  	private Parser(final TokenStream stream) {
34  		this.stream = stream;
35  		this.exceptions = new ArrayList<>();
36  	}
37  	
38  	/**
39  	 * Factory Method for a {@link Parser}. <code>stream</code> is the TokenStream which will be parsed.
40  	 * 
41  	 * @param stream
42  	 *            tokenStream
43  	 * @return The {@link Parser}-Object.
44  	 */
45  	public static Parser create(final TokenStream stream) {
46  		return new Parser(stream);
47  	}
48  	
49  	/**
50  	 * Starts the parsing process. A Model will be returned which represents the root node of an abstract syntax tree.
51  	 * This tree will be the result of the processed stream.
52  	 * 
53  	 * @return The parsed Model
54  	 * @throws NoValidTokenStreamException
55  	 *             NoValidTokenStreamException
56  	 */
57  	public Model parse() throws NoValidTokenStreamException {
58  		final Model result = ModelParser.create(this.stream, this.exceptions).parse();
59  		if (this.exceptions.size() > 0) {
60  			throw NoValidTokenStreamException.create();
61  		}
62  		return result;
63  	}
64  	
65  	/**
66  	 * Returns all exceptions.
67  	 * 
68  	 * @return all exceptions
69  	 */
70  	public Collection<AbstractParserException> getExceptions() {
71  		return this.exceptions;
72  	}
73  }