summaryrefslogtreecommitdiff
path: root/src/test/java/no/eliashaugsbakk/kompilator/parsing/ParserTest.java
blob: 133e9a661a165a3629eb05eec04586e575829e0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package no.eliashaugsbakk.kompilator.parsing;

import static no.eliashaugsbakk.kompilator.tokenization.TokenType.KEYWORD;
import static no.eliashaugsbakk.kompilator.tokenization.TokenType.LPAREN;
import static no.eliashaugsbakk.kompilator.tokenization.TokenType.RPAREN;
import static no.eliashaugsbakk.kompilator.tokenization.TokenType.SEMICOLON;
import static no.eliashaugsbakk.kompilator.tokenization.TokenType.STRING;
import static org.junit.jupiter.api.Assertions.*;

import java.util.List;
import no.eliashaugsbakk.kompilator.parsing.node.Program;
import no.eliashaugsbakk.kompilator.parsing.node.expression.FunctionCall;
import no.eliashaugsbakk.kompilator.parsing.node.expression.StringLiteral;
import no.eliashaugsbakk.kompilator.parsing.node.statement.ExpressionStatement;
import no.eliashaugsbakk.kompilator.tokenization.Token;
import org.junit.jupiter.api.Test;

class ParserTest {

  @Test
  void validSyntaxBuildsCorrectTree() throws ParserException {
    List<Token> tokens = List.of(
        new Token(KEYWORD, "print", 1, 0),
        new Token(LPAREN, "(", 1, 5),
        new Token(STRING, "Hello", 1, 6),
        new Token(RPAREN, ")", 1, 13),
        new Token(SEMICOLON, ";", 1, 14)
    );

    AST ast = new Parser(tokens).parse();

    // Verify tree structure
    assertNotNull(ast.root);
    assertInstanceOf(Program.class, ast.root);
    Program program = (Program) ast.root;
    assertEquals(1, program.statements.size());

    ExpressionStatement stmt = (ExpressionStatement) program.statements.getFirst();
    assertInstanceOf(FunctionCall.class, stmt.expression);

    FunctionCall call = (FunctionCall) stmt.expression;
    assertEquals("print", call.functionName);
    assertEquals(1, call.arguments.size());
    assertEquals("Hello", ((StringLiteral) call.arguments.getFirst()).value);
  }

  @Test
  void missingSemicolonThrows() {
    List<Token> tokens = List.of(
        new Token(KEYWORD, "print", 1, 0),
        new Token(LPAREN, "(", 1, 5),
        new Token(STRING, "Hello", 1, 6),
        new Token(RPAREN, ")", 1, 13)
    );

    assertThrows(ParserException.class, () -> new Parser(tokens).parse());
  }

  @Test
  void missingParenthesisThrows() {
    List<Token> tokens = List.of(
        new Token(KEYWORD, "print", 1, 0),
        new Token(STRING, "Hello", 1, 5),
        new Token(RPAREN, ")", 1, 12),
        new Token(SEMICOLON, ";", 1, 13)
    );

    assertThrows(ParserException.class, () -> new Parser(tokens).parse());
  }
}