new tests with lexer and parser

This commit is contained in:
ChUrl
2020-12-07 23:34:09 +01:00
parent 081ef492d6
commit 0c89e5b3dc

View File

@ -1,19 +1,26 @@
package parser;
import lexer.StupsLexer;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.Lexer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import parser.grammar.Grammar;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -23,6 +30,24 @@ class LL1ParserTest {
private static ILL1ParsingTable table0;
private static ILL1ParsingTable table1;
private Lexer initLexer(String program) {
try {
Path path = Paths.get(this.getClass().getClassLoader().getResource("examplePrograms/" + program).toURI());
String programCode = Files.readString(path, StandardCharsets.US_ASCII);
return new StupsLexer(CharStreams.fromString(programCode));
} catch (Exception ignore) {
ignore.printStackTrace();
}
return null;
}
private List<String> getSymbols(Lexer lex) {
return lex.getAllTokens().stream()
.map(tok -> lex.getVocabulary().getSymbolicName(tok.getType()))
.collect(Collectors.toUnmodifiableList());
}
@BeforeAll
static void setUp() {
table0 = initTable0();
@ -190,4 +215,27 @@ class LL1ParserTest {
assertThatThrownBy(() -> parser.parse(Arrays.asList(token1))).isInstanceOf(MyParseException.class);
}
@Test
void testDanglingElse() throws URISyntaxException, IOException {
Path path = Paths.get(this.getClass().getClassLoader().getResource("exampleGrammars/DanglingElse.grammar").toURI());
LL1Parser parser = LL1Parser.fromGrammar(path);
// String[] token1 = {"if", "expr", "then", "other"};
// String[] token2 = {"if", "expr", "then", "other", "else", "other"};
// assertThat(parser.parse(Arrays.asList(token1))).isTrue();
// assertThat(parser.parse(Arrays.asList(token2))).isTrue();
}
@Test
void testGrammarEmptyMain() throws URISyntaxException, IOException {
Path path = Paths.get(this.getClass().getClassLoader().getResource("exampleGrammars/Grammar.grammar").toURI());
LL1Parser parser = LL1Parser.fromGrammar(path);
Lexer lex = this.initLexer("EmptyMain.stups");
List<String> token = this.getSymbols(lex);
assertThat(parser.parse(token)).isTrue();
}
}