Skip to content

Commit

Permalink
Implement parser for dimacs
Browse files Browse the repository at this point in the history
  • Loading branch information
paultristanwagner committed Oct 25, 2024
1 parent 4ec4bfb commit f1348e1
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package me.paultristanwagner.satchecking.parse;

import static me.paultristanwagner.satchecking.parse.TokenType.IDENTIFIER;
import static me.paultristanwagner.satchecking.parse.TokenType.INTEGER;

public class DimacsLexer extends Lexer {

public DimacsLexer(String input) {
super(input);

registerTokenTypes(IDENTIFIER, INTEGER);

initialize(input);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package me.paultristanwagner.satchecking.parse;

import me.paultristanwagner.satchecking.sat.CNF;
import me.paultristanwagner.satchecking.sat.Clause;
import me.paultristanwagner.satchecking.sat.Literal;

import java.util.ArrayList;
import java.util.List;

import static me.paultristanwagner.satchecking.parse.TokenType.IDENTIFIER;
import static me.paultristanwagner.satchecking.parse.TokenType.INTEGER;

public class DimacsParser implements Parser<CNF> {

@Override
public ParseResult<CNF> parseWithRemaining(String string) {
Lexer lexer = new DimacsLexer(string);

lexer.consume(IDENTIFIER);

lexer.consume(IDENTIFIER);

lexer.require(INTEGER);
int variableCount = Integer.parseInt(lexer.getLookahead().getValue());
lexer.consume(INTEGER);

lexer.require(INTEGER);
int clauseCount = Integer.parseInt(lexer.getLookahead().getValue());
lexer.consume(INTEGER);

List<Clause> clauses = new ArrayList<>();
for (int i = 0; i < clauseCount; ++i) {
List<Literal> literals = new ArrayList<>();

while (lexer.hasNextToken()) {
lexer.require(INTEGER);
int literalId = Integer.parseInt(lexer.getLookahead().getValue());
lexer.consume(INTEGER);

if (literalId == 0) {
break;
}

Literal literal;
if (literalId >= 0) {
literal = new Literal("l" + literalId);
} else {
literal = new Literal("l" + -literalId, true);
}

literals.add(literal);
}

clauses.add(new Clause(literals));
}

return new ParseResult<>(new CNF(clauses), lexer.getCursor(), lexer.getRemaining().isEmpty());
}
}

0 comments on commit f1348e1

Please sign in to comment.