Skip to content

Add AND #22 #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Nov 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions src/main/antlr4/Cryptator.g4
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ import cryptator.tree.CryptaLeaf;

// Parser Rules

program : equation EOF{}; //additional token to simplify the passage in parameter
program : equations EOF{}; //additional token to simplify the passage in parameter

equation returns [ICryptaNode node]: //create a node of the tree corresponding to an equation and return this node
'(' equation ')' {$node=$equation.node;}
| left=expression COMPARATOR right=expression {$node=new CryptaNode($COMPARATOR.getText(), $left.node, $right.node);};
equations returns [ICryptaNode node] //create a node of conjuncts
: equation (AND*) {$node=$equation.node;}
| e1=equation (AND+) e2=equations (AND*) {$node=new CryptaNode($AND.getText(), $e1.node, $e2.node);};

equation returns [ICryptaNode node] //create a node of the tree corresponding to an equation and return this node
: '(' equation ')' {$node=$equation.node;}
| left=expression COMPARATOR right=expression {$node=new CryptaNode($COMPARATOR.getText(), $left.node, $right.node);};


expression returns [ICryptaNode node]: //create recursively the tree of expressions with priority and return the root of the tree
Expand Down Expand Up @@ -46,3 +50,4 @@ SYMBOL : [a-zA-Z0-9\u0080-\uFFFF] {};

WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ -> skip ;

AND : ';';
123 changes: 63 additions & 60 deletions src/main/java/cryptator/CryptaOperator.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,81 +8,84 @@
*/
package cryptator;

import java.math.BigInteger;
import java.util.function.BinaryOperator;

import org.chocosolver.solver.expression.discrete.arithmetic.ArExpression;
import org.chocosolver.solver.expression.discrete.relational.ReExpression;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.util.tools.VariableUtils;

import java.math.BigInteger;
import java.util.function.BinaryOperator;

/**
* @see https://en.wikipedia.org/wiki/Relational_operator
*/
public enum CryptaOperator {
ADD("+", (a, b) -> a.add(b), (a, b) -> a.add(b)),
SUB("-", (a, b) -> a.subtract(b), (a, b) -> a.sub(b)),
MUL("*", (a, b) -> a.multiply(b), (a, b) -> a.mul(b)),
DIV("//", (a, b) -> a.divide(b), (a, b) -> a.div(b)),
FDIV("/", (a, b) -> fdiv(a, b), (a, b) -> fdiv(a, b)),
MOD("%", (a, b) -> a.mod(b), (a, b) -> a.mod(b)),
POW("^", (a, b) -> a.pow(b.intValue()), (a, b) -> a.pow(b)),
ID("", (a, b) -> BigInteger.ZERO, (a, b) -> null),
EQ("=", (a, b) -> toBigInt(a.compareTo(b) == 0), (a, b) -> a.eq(b)),
NE("!=", (a, b) -> toBigInt(a.compareTo(b) != 0), (a, b) -> a.ne(b)),
LT("<", (a, b) -> toBigInt(a.compareTo(b) < 0), (a, b) -> a.lt(b)),
GT(">", (a, b) -> toBigInt(a.compareTo(b) > 0), (a, b) -> a.gt(b)),
LE("<=", (a, b) -> toBigInt(a.compareTo(b) <= 0), (a, b) -> a.le(b)),
GE(">=", (a, b) -> toBigInt(a.compareTo(b) >= 0), (a, b) -> a.ge(b));
ADD("+", (a, b) -> a.add(b), (a, b) -> a.add(b)),
SUB("-", (a, b) -> a.subtract(b), (a, b) -> a.sub(b)),
MUL("*", (a, b) -> a.multiply(b), (a, b) -> a.mul(b)),
DIV("//", (a, b) -> a.divide(b), (a, b) -> a.div(b)),
FDIV("/", (a, b) -> fdiv(a, b), (a, b) -> fdiv(a, b)),
MOD("%", (a, b) -> a.mod(b), (a, b) -> a.mod(b)),
POW("^", (a, b) -> a.pow(b.intValue()), (a, b) -> a.pow(b)),
ID("", (a, b) -> BigInteger.ZERO, (a, b) -> null),
EQ("=", (a, b) -> toBigInt(a.compareTo(b) == 0), (a, b) -> a.eq(b)),
NE("!=", (a, b) -> toBigInt(a.compareTo(b) != 0), (a, b) -> a.ne(b)),
LT("<", (a, b) -> toBigInt(a.compareTo(b) < 0), (a, b) -> a.lt(b)),
GT(">", (a, b) -> toBigInt(a.compareTo(b) > 0), (a, b) -> a.gt(b)),
LE("<=", (a, b) -> toBigInt(a.compareTo(b) <= 0), (a, b) -> a.le(b)),
GE(">=", (a, b) -> toBigInt(a.compareTo(b) >= 0), (a, b) -> a.ge(b)),

AND(";", (a, b) -> toBigInt(!a.equals(BigInteger.ZERO) && !b.equals(BigInteger.ZERO)), (a, b) -> ((ReExpression) a).and((ReExpression) b));

public final String token;

public final BinaryOperator<BigInteger> function;

public final String token;
public final BinaryOperator<ArExpression> expression;

public final BinaryOperator<BigInteger> function;
CryptaOperator(String token, BinaryOperator<BigInteger> function, BinaryOperator<ArExpression> expression) {
this.token = token;
this.function = function;
this.expression = expression;
}

public final BinaryOperator<ArExpression> expression;
public static CryptaOperator valueOfToken(String token) {
if (token == null) return null;
for (CryptaOperator operator : CryptaOperator.values()) {
if (token.equals(operator.getToken())) return operator;
}
throw new IllegalArgumentException("Unknown token: " + token);
}

private CryptaOperator(String token, BinaryOperator<BigInteger> function, BinaryOperator<ArExpression> expression) {
this.token = token;
this.function = function;
this.expression = expression;
}
private static final BigInteger toBigInt(boolean b) {
return b ? BigInteger.ONE : BigInteger.ZERO;
}

public final String getToken() {
return token;
}
private static final BigInteger fdiv(BigInteger a, BigInteger b) {
final BigInteger[] r = a.divideAndRemainder(b);
if (r[1].equals(BigInteger.ZERO)) return r[0];
else throw new ArithmeticException("The remainder of the division is non-zero.");
}

public final BinaryOperator<BigInteger> getFunction() {
return function;
}
private static final ArExpression fdiv(ArExpression a, ArExpression b) {
final IntVar va = a.intVar();
final IntVar vb = b.intVar();
final int[] bounds = VariableUtils.boundsForDivision(va, vb);
final IntVar q = a.getModel().intVar(bounds[0], bounds[1]);
// Post auxiliary constraint to emulate floor division.
q.mul(b).eq(a).post();
return q;
}

public final BinaryOperator<ArExpression> getExpression() {
return expression;
}
public final String getToken() {
return token;
}

public static CryptaOperator valueOfToken(String token) {
if(token == null) return null;
for(CryptaOperator operator : CryptaOperator.values()) {
if(token.equals(operator.getToken())) return operator;
}
throw new IllegalArgumentException("Unknown token: " + token);
}

private static final BigInteger toBigInt(boolean b) {
return b ? BigInteger.ONE : BigInteger.ZERO;
}
public final BinaryOperator<BigInteger> getFunction() {
return function;
}

private static final BigInteger fdiv(BigInteger a, BigInteger b) {
final BigInteger[] r = a.divideAndRemainder(b);
if(r[1].equals(BigInteger.ZERO)) return r[0];
else throw new ArithmeticException("The remainder of the division is non-zero.");
}

private static final ArExpression fdiv(ArExpression a, ArExpression b) {
final IntVar va = a.intVar();
final IntVar vb = b.intVar();
final int[] bounds = VariableUtils.boundsForDivision(va, vb);
final IntVar q = a.getModel().intVar(bounds[0], bounds[1]);
// Post auxiliary constraint to emulate floor division.
q.mul(b).eq(a).post();
return q;
}
public final BinaryOperator<ArExpression> getExpression() {
return expression;
}
}
11 changes: 5 additions & 6 deletions src/main/java/cryptator/parser/CryptaParserWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,16 @@
package cryptator.parser;


import cryptator.specs.ICryptaNode;
import cryptator.specs.ICryptaParser;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;

import cryptator.specs.ICryptaNode;
import cryptator.specs.ICryptaParser;

public class CryptaParserWrapper implements ICryptaParser {

@Override
public ICryptaNode parse(final String cryptarithm) throws CryptaParserException {
@Override
public ICryptaNode parse(final String cryptarithm) throws CryptaParserException {
final CharStream input = CharStreams.fromString(cryptarithm);
final CryptatorLexer lexer = new CryptatorLexer(input);
lexer.removeErrorListeners();
Expand All @@ -30,7 +29,7 @@ public ICryptaNode parse(final String cryptarithm) throws CryptaParserException
parser.removeErrorListeners();
parser.addErrorListener(ThrowingErrorListener.INSTANCE);
cryptator.parser.CryptatorParser.ProgramContext ctx = parser.program();
return ctx.equation().node;
return ctx.equations().node;
}

}
22 changes: 14 additions & 8 deletions src/main/java/cryptator/solver/CryptaBignumModeler.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
package cryptator.solver;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

import org.chocosolver.solver.Model;
import org.chocosolver.solver.expression.discrete.arithmetic.ArExpression;
import org.chocosolver.solver.expression.discrete.relational.ReExpression;
import org.chocosolver.solver.variables.IntVar;

import cryptator.CryptaOperator;
Expand Down Expand Up @@ -73,7 +75,7 @@ private final ArExpression[] applyADD(ArExpression[] a, ArExpression[] b) {
c[i] = b[i];
}
return c;
}
}

class BignumArExpression {

Expand All @@ -86,7 +88,6 @@ public BignumArExpression(ArExpression[] a, int n, String suffix) {
digits = model.intVarArray("D" + suffix, n, 0, config.getArithmeticBase()-1);
// TODO improve the bound ?
carries = model.intVarArray("C"+ suffix, n, 0, IntVar.MAX_INT_BOUND / config.getArithmeticBase());
// TODO Is it better to use scalar or an expression ?
postScalar(
new IntVar[] {carries[0], digits[0], a[0].intVar()},
new int[] {config.getArithmeticBase(), 1, -1}
Expand Down Expand Up @@ -121,27 +122,32 @@ private final void applyEQ(ArExpression[] a, ArExpression[] b) {
a1.digits[i].eq(b1.digits[i]).decompose().post();
}
a1.carries[n-1].eq(b1.carries[n-1]).decompose().post();
}

}

@Override
public void accept(ICryptaNode node, int numNode) {
super.accept(node, numNode);
if(node.isLeaf()) {
if(node.isLeaf()) {
stack.push(makeWordVars(node.getWord()));
} else {
} else if (!node.getOperator().equals(CryptaOperator.AND)) {
final ArExpression[] b = stack.pop();
final ArExpression[] a = stack.pop();
switch (node.getOperator()) {
case ADD:
stack.push(applyADD(a, b));
break;
case EQ:
case EQ:
applyEQ(a, b);
if(!stack.isEmpty()) throw new IllegalStateException("Stack is not empty after accepting a relational operator.");
break;
default:
break;
}
// Should never be in the default case, this exception is
// a program break in order to recall to modify the switch if
// a new operator in BigNum is added.
// Example case : we remove the MUL operator in computeUnsupportedBignumOperator
throw new IllegalStateException("Bignum operator is not yet implemented");
}
}
}

Expand Down
Loading