Browse Source

Ajout méthode vérification expression Lisp

Arthur Brandao 6 years ago
parent
commit
a571a5f446
1 changed files with 51 additions and 1 deletions
  1. 51 1
      src/migl/lisp/LispImpl.java

+ 51 - 1
src/migl/lisp/LispImpl.java

@@ -2,6 +2,8 @@ package migl.lisp;
 
 import java.math.BigInteger;
 import java.util.Stack;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import migl.util.ConsList;
 import migl.util.ConsListFactory;
@@ -10,6 +12,11 @@ public class LispImpl implements Lisp {
 
 	@Override
 	public Object parse(String expr) throws LispError {
+		//Analyse l'expression
+		if(!this.verify(expr)) {
+			throw new LispError("Invalid Format");
+		}
+		//Explose l'expression
 		Stack<String> explode = this.explode(expr);
 		//Analyse le type d'expression
 		String val = explode.remove(0);
@@ -29,13 +36,56 @@ public class LispImpl implements Lisp {
 		return new BigInteger("3"); //ToDo juste pour passer le test ReplTest
 	}
 	
+	private boolean verify(String expr) {
+		expr = expr.trim();
+		//Pas vide
+		if(expr.length() == 0) {
+			return false;
+		}
+		//Liste ou element
+		if(expr.charAt(0) == '(') {
+			return this.verifyList(expr);
+		}
+		System.out.println("Ici");
+		return this.verifyElement(expr);
+	}
+	
+	private boolean verifyList(String expr) {
+		Pattern p = Pattern.compile("\\(([ |\t]*[A-Za-z0-9\\.\\+\\-<>=\\/\\*]+[ |\t]*)+\\)");
+		Matcher m = p.matcher(expr);
+		//Si pas de correspondance
+		if(!m.find()) {
+			return false;
+		} 
+		//Si toute la chaine
+		else if(m.end() - m.start() == expr.length()) {
+			return true;
+		} 
+		//Si commence au debut mais finit avant la fin il y a alors des elements hors de la liste
+		else if(m.start() == 0) {
+			return false;
+		} 
+		//Si il y a une liste dans la liste
+		else {
+			StringBuilder builder = new StringBuilder();
+			builder.append(expr.substring(0, m.start())).append("list").append(expr.substring(m.end()));
+			return this.verifyList(builder.toString());
+		}
+	}
+	
+	private boolean verifyElement(String expr) {
+		Pattern p = Pattern.compile("[ |\t]*[A-Za-z0-9\\.\\+\\-<>=\\/\\*]+[ |\t]*");
+		Matcher m = p.matcher(expr);
+		return m.find();
+	}
+	
 	/**
 	 * Découpe un string pour l'analyse Lisp
 	 * @param expr L'expression à analyser
 	 * @return L'expression découper
 	 */
 	private Stack<String> explode(String expr) {
-		String[] tmp = expr.split("[ |\t]");
+		String[] tmp = expr.trim().split("[ |\t]");
 		Stack<String> result = new Stack<>();
 		for(String str : tmp) {
 			char[] charArray = str.toCharArray();