PageRenderTime 22ms CodeModel.GetById 14ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/src/org/ooc/frontend/parser/MatchParser.java

http://github.com/nddrylliog/ooc
Java | 73 lines | 57 code | 15 blank | 1 comment | 12 complexity | 022195398022a6e7702f5a90eb9b4ca9 MD5 | raw file
 1package org.ooc.frontend.parser;
 2
 3import org.ooc.frontend.model.Case;
 4import org.ooc.frontend.model.Expression;
 5import org.ooc.frontend.model.Match;
 6import org.ooc.frontend.model.Module;
 7import org.ooc.frontend.model.tokens.Token;
 8import org.ooc.frontend.model.tokens.TokenReader;
 9import org.ooc.frontend.model.tokens.Token.TokenType;
10import org.ubi.CompilationFailedError;
11import org.ubi.SourceReader;
12
13public class MatchParser {
14
15	public static Match parse(Module module, SourceReader sReader, TokenReader reader) {
16		
17		Token startToken = reader.peek();
18		if(startToken.type != TokenType.MATCH_KW) return null;
19		reader.skip();
20
21		Expression expr = ExpressionParser.parse(module, sReader, reader, true);
22		
23		reader.skipWhitespace();
24		if(reader.peek().type != TokenType.OPEN_BRACK) {
25			throw new CompilationFailedError(sReader.getLocation(reader.peek()), "Expected a '{' after match.");
26		}
27		reader.skip();
28		
29		Match match = new Match(expr, startToken);
30		
31		while(true) {
32			
33			reader.skipWhitespace();
34			
35			Token token = reader.peek();
36			if(token.type == TokenType.CLOS_BRACK) {
37				reader.skip();
38				break;
39			}
40			boolean isFallthrough = false;
41			if(token.type == TokenType.FALLTHR_KW) {
42				isFallthrough = true;
43				reader.skip();
44				reader.skipWhitespace();
45				token = reader.peek();
46			}
47			if(token.type == TokenType.CASE_KW) {
48				reader.skip();
49				Expression caseExpr = ExpressionParser.parse(module, sReader, reader, true);
50				reader.skipWhitespace();
51				if(reader.peek().type != TokenType.DOUBLE_ARROW) {
52					throw new CompilationFailedError(sReader.getLocation(token), "Unexpected token "+reader.peek()
53							+" Expected a '=>' after a case.");
54				}
55				reader.skip();
56				Case case1 = new Case(caseExpr, match, isFallthrough, token);
57				while(LineParser.fill(module, sReader, reader, case1.getBody())) {
58					// well, continue as long as we can find lines
59				}
60				match.getCases().add(case1);
61				continue;
62			}
63			
64			throw new CompilationFailedError(sReader.getLocation(token), "Unexpected token "+token
65					+" Expected either a '}' or a case.");
66			
67		}
68		
69		return match;
70		
71	}
72	
73}