aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/shedlang/compiler/parser/ParserStringLiteralTests.java
blob: 21c6a2ca5102d3aef99c4a4612a653491b4cdd4c (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
package org.shedlang.compiler.parser;

import org.junit.jupiter.api.Test;
import org.shedlang.compiler.parser.errors.UnrecognisedEscapeSequenceError;
import org.shedlang.compiler.sources.FileFragmentSource;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.shedlang.compiler.ast.untyped.UntypedNodeMatchers.isUntypedStringLiteralNode;
import static org.shedlang.compiler.parser.ParserTesting.parseString;
import static org.zwobble.precisely.AssertThat.assertThat;
import static org.zwobble.precisely.Matchers.*;

public class ParserStringLiteralTests {
    @Test
    public void canParseEmptyString() {
        var source = "\"\"";

        var node = parseString(source, Parser::parseTopLevelExpression);

        assertThat(node, isUntypedStringLiteralNode(""));
    }

    @Test
    public void canParseStringWithUnescapedCharacters() {
        var source = "\"abc 123 XYZ\"";

        var node = parseString(source, Parser::parseTopLevelExpression);

        assertThat(node, isUntypedStringLiteralNode("abc 123 XYZ"));
    }

    @Test
    public void canParseStringWithEscapedCharacters() {
        var source = "\"\\n\\r\\t\\\\\\\"\"";

        var node = parseString(source, Parser::parseTopLevelExpression);

        assertThat(node, isUntypedStringLiteralNode("\n\r\t\\\""));
    }

    @Test
    public void whenStringHasUnrecognisedEscapeSequenceThenExceptionIsThrown() {
        var source = "\"a\\ab\"";

        var error = assertThrows(
            UnrecognisedEscapeSequenceError.class,
            () -> parseString(source, Parser::parseTopLevelExpression)
        );

        assertThat(error.getMessage(), equalTo("Unrecognised escape sequence: \\a"));
        assertThat(error.source(), instanceOf(FileFragmentSource.class, allOf(
            has("characterIndexStart", x -> x.sourceRange().start().characterIndex(), equalTo(2)),
            has("characterIndexEnd", x -> x.sourceRange().end().characterIndex(), equalTo(4))
        )));
    }
}