diff --git a/Median3Entiers.lir b/Median3Entiers.lir new file mode 100644 index 0000000..39c9af1 --- /dev/null +++ b/Median3Entiers.lir @@ -0,0 +1,37 @@ +10 affiche "Bienvenue dans le programme Median3Entiers.lir" +20 affiche +30 affiche "Entrez le premier entier : " +40 entre premier +50 affiche "Entrez le deuxième entier : " +60 entre deuxieme +70 affiche "Entrez le troisième entier : " +80 entre troisieme +90 procedure 1000 +100 affiche "Median( " +110 affiche premier +120 affiche ", " +130 affiche deuxieme +140 affiche ", " +150 affiche troisieme +160 affiche ") = " +170 affiche median +180 affiche +250 stop + +1000 si premier <= deuxieme vaen 1100 +1010 si deuxieme <= troisieme vaen 1200 +1020 vaen 1520 + +1100 si deuxieme <= troisieme vaen 1520 +1110 si premier <= troisieme vaen 1540 +1120 vaen 1500 + +1200 si premier <= troisieme vaen 1500 +1220 vaen 1540 + +1500 var median = premier +1510 vaen 1550 +1520 var median = deuxieme +1530 vaen 1550 +1540 var median = troisieme +1550 retour \ No newline at end of file diff --git a/demo.lir b/demo.lir new file mode 100644 index 0000000..0c64a91 --- /dev/null +++ b/demo.lir @@ -0,0 +1,13 @@ +10 affiche "Entre ton nom : " +20 entre $nom +30 affiche "Bienvenue "+$nom +35 affiche +40 var an=2021 +50 affiche "Quelle est ton année de naissance ? " +60 entre naissance +65 si naissance > an vaen 50 +70 affiche "Tu as autour de " +80 affiche an-naissance +90 affiche "ans " +100 affiche +200 stop \ No newline at end of file diff --git a/etatCivil.lir b/etatCivil.lir new file mode 100644 index 0000000..363473d --- /dev/null +++ b/etatCivil.lir @@ -0,0 +1,28 @@ +10 affiche "Bienvenue dans le programme" +20 affiche +30 var instant = 2021 +40 procedure 500 +50 var $message = "Vous êtes " + $prenom +60 var $message = $message + " " +65 var $message = $message + $nom +70 affiche $message +80 affiche +90 affiche "age : " +100 affiche age +110 affiche " ans" +120 vaen 150 +124 affiche +125 affiche "erreur vaen si affiché" +150 affiche +200 affiche "Merci d'avoir utilisé ce programme !" +400 stop +500 affiche "Saisissez votre nom : " +510 entre $nom +520 affiche "Saisissez votre prénom : " +530 entre $prenom +540 affiche "Saisissez votre année de naissance (entier) : " +550 entre naissance +560 procedure 1000 +570 retour +1000 var age = instant - naissance +1010 retour diff --git a/factorielle.lir b/factorielle.lir new file mode 100644 index 0000000..07f530f --- /dev/null +++ b/factorielle.lir @@ -0,0 +1,35 @@ +10 affiche "Bienvenue dans le programme factorielle.lir !" +20 affiche +30 affiche "Entrez un entier : " +40 entre entier +45 procedure 500 +50 procedure 1000 +60 affiche entier +70 affiche "! = " +80 affiche factorielle +90 affiche +200 stop + +500 si entier >= 0 vaen 600 +510 affiche "n! est définie sur l'ensemble des entiers naturels" +520 stop +600 retour + +1000 var factorielle = 1 +1010 var entierCourant = 2 +1011 var ancienFactorielle = factorielle +1012 var test = factorielle +1015 si entierCourant > entier vaen 1100 +1016 si ancienFactorielle <> test vaen 1060 +1017 var ancienFactorielle = factorielle +1020 var factorielle = factorielle * entierCourant +1025 var test = factorielle / entierCourant +1030 var entierCourant = entierCourant + 1 +1040 vaen 1015 +1050 vaen 1100 +1060 affiche "dépassement de la capacité des entiers pour " +1070 affiche entier +1080 affiche "!" +1090 affiche +1095 stop +1100 retour \ No newline at end of file diff --git a/prototype/interpreteurLIR.jar b/prototype/interpreteurLIR.jar new file mode 100644 index 0000000..8f3cede Binary files /dev/null and b/prototype/interpreteurLIR.jar differ diff --git a/prototype/lanceInterpreteurLIR.bat b/prototype/lanceInterpreteurLIR.bat new file mode 100644 index 0000000..46d9782 --- /dev/null +++ b/prototype/lanceInterpreteurLIR.bat @@ -0,0 +1,2 @@ +java -jar interpreteurLIR.jar +cmd /k java -jar interpreteurLIR.jar \ No newline at end of file diff --git a/src/interpreteurlir/Analyseur.java b/src/interpreteurlir/Analyseur.java index fb2c05b..6b7921b 100644 --- a/src/interpreteurlir/Analyseur.java +++ b/src/interpreteurlir/Analyseur.java @@ -1,5 +1,5 @@ /** - * Analyseur.java 9 mai 2021 + * Analyseur.java 9 mai 2021 * IUT Rodez info1 2020-2021, pas de copyright, aucun droit */ package interpreteurlir; @@ -143,6 +143,10 @@ public class Analyseur { .getConstructor(classeArg, classeContexte) .newInstance(arguments, contexteGlobal); feedback(cmd.executer()); + if (motCle.equals("lance") + || (motCle.equals("affiche") && !arguments.isBlank())) { + System.out.println(); + } } catch ( InvocationTargetException | IllegalAccessException | InstantiationException | NoSuchMethodException | InterpreteurException | ExecutionException lancee) { @@ -213,14 +217,14 @@ public class Analyseur { * Recherche l'instruction correspondant au mot clé. * - * @param aTester + * @param aTester chaîne à tester * @return true si le prédicat est vérifié * false sinon */ @@ -77,17 +77,15 @@ implements Comparable { public static boolean isAlphanumerique(String aTester) { int index; for (index = 0 ; - index < aTester.length() - && Character.isLetterOrDigit(aTester.charAt(index)) ; - index++) - ; // Corps vide + index < aTester.length() + && Character.isLetterOrDigit(aTester.charAt(index)) ; + index++) + ; /* empty body */ - return index >= aTester.length(); + return index >= aTester.length(); } - /** - * @return la valeur de nom - */ + /** @return la valeur de nom */ public String getNom() { return nom; } diff --git a/src/interpreteurlir/donnees/IdentificateurChaine.java b/src/interpreteurlir/donnees/IdentificateurChaine.java index 0277202..2d535fd 100644 --- a/src/interpreteurlir/donnees/IdentificateurChaine.java +++ b/src/interpreteurlir/donnees/IdentificateurChaine.java @@ -39,7 +39,7 @@ public class IdentificateurChaine extends Identificateur { * @return true si l'identificateur est bien un identificateur d'entier * false sinon */ - private static boolean isIdentificateurChaine(String identificateur) { + public static boolean isIdentificateurChaine(String identificateur) { return identificateur.length() >= 2 && identificateur.charAt(0) == '$' diff --git a/src/interpreteurlir/donnees/IdentificateurEntier.java b/src/interpreteurlir/donnees/IdentificateurEntier.java index e3e273d..41b8b47 100644 --- a/src/interpreteurlir/donnees/IdentificateurEntier.java +++ b/src/interpreteurlir/donnees/IdentificateurEntier.java @@ -21,10 +21,10 @@ import interpreteurlir.InterpreteurException; public class IdentificateurEntier extends Identificateur { /** - * Instantiation de cet identificateur d'entier avec le nom spécififié + * Instantiation de cet identificateur d'entier avec le nom spécifié * en argument. Lève une exception si l'identificateur n'est pas * valide. - * @param identificateur a instancier + * @param identificateur à instancier * @throws InterpreteurException si l'identificateur est invalide */ public IdentificateurEntier(String identificateur) { @@ -49,7 +49,7 @@ public class IdentificateurEntier extends Identificateur { * @return true si l'identificateur est bien un identificateur d'entier * false sinon */ - private static boolean isIdentificateurEntier(String aTester) { + public static boolean isIdentificateurEntier(String aTester) { return aTester.length() <= 25 && Character.isLetter(aTester.charAt(0)) && isAlphanumerique(aTester.substring(1)); } diff --git a/src/interpreteurlir/donnees/Variable.java b/src/interpreteurlir/donnees/Variable.java index 7216469..6541870 100644 --- a/src/interpreteurlir/donnees/Variable.java +++ b/src/interpreteurlir/donnees/Variable.java @@ -65,7 +65,7 @@ public class Variable extends Object implements Comparable { /** * Modifie la valeur de cette variable - * @param nouvelleValeur + * @param nouvelleValeur valeur à affecter à cette variable */ public void setValeur(Litteral nouvelleValeur) { if (isVariable(identificateur, nouvelleValeur)) { @@ -86,6 +86,10 @@ public class Variable extends Object implements Comparable { return identificateur.toString() + " = " + valeur.toString(); } + /* + * non javadoc + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ public int compareTo(Variable aComparer) { return identificateur.compareTo(aComparer.identificateur); } diff --git a/src/interpreteurlir/donnees/litteraux/Booleen.java b/src/interpreteurlir/donnees/litteraux/Booleen.java new file mode 100644 index 0000000..bc83855 --- /dev/null +++ b/src/interpreteurlir/donnees/litteraux/Booleen.java @@ -0,0 +1,48 @@ +/** + * Booleen.java 21 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.donnees.litteraux; + +import interpreteurlir.InterpreteurException; + +/** + * Constante littérale de type booléen + * + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heia Dexter + * @author Lucas Vabre + */ +public class Booleen extends Litteral { + + /** + * Initialise ce booléen + * @param unBooleen valeur du booléen à construire + * @throws InterpreteurException si la condition n'est pas un + * + */ + public Booleen(Boolean unBooleen) { + super(); + valeur = unBooleen; + } + + /* non javadoc + * @see interpreteurlir.donnees.litteraux.Litteral#getValeur() + */ + @Override + public Boolean getValeur() { + return (Boolean) super.valeur; + } + + /* non javadoc + * @deprecated + * @see Litteral#compareTo(Litteral) + */ + @Override + public int compareTo(Litteral autre) { + return (Boolean)this.valeur == (Boolean)autre.valeur ? 0 : 1; // égalité + } + +} diff --git a/src/interpreteurlir/donnees/litteraux/Chaine.java b/src/interpreteurlir/donnees/litteraux/Chaine.java index bca64e4..0813c68 100644 --- a/src/interpreteurlir/donnees/litteraux/Chaine.java +++ b/src/interpreteurlir/donnees/litteraux/Chaine.java @@ -21,11 +21,11 @@ public class Chaine extends Litteral { /** Erreur chaîne trop longue */ private static final String ERREUR_LG_MAX = - "Longueur maximale d'une chaîne dépassée"; + "longueur maximale d'une chaîne dépassée"; /** Erreur constante littéral chaîne invalide */ private static final String ERREUR_INVALIDE = - "syntaxe incorrecte pour une constante de type chaîne : "; + " n'est pas une constante de type chaîne"; /** * initialise cette chaîne avec une valeur par défaut. @@ -35,22 +35,33 @@ public class Chaine extends Litteral { } /** - * Initialise une chaîne avec la séquence de caractères passée en argument. - * @param uneValeur + * Initialise une chaîne avec la séquence + * de caractères passée en argument. + * @param uneValeur valeur de la chaine à construire (entre guillemets) */ public Chaine(String uneValeur) { uneValeur = uneValeur.trim(); - if (!uneValeur.startsWith("\"") || !uneValeur.endsWith("\"")) { - throw new InterpreteurException(ERREUR_INVALIDE - + uneValeur); - } - - uneValeur = uneValeur.substring(1, uneValeur.length() - 1); - - if (uneValeur.length() > LG_MAX_CHAINE) - throw new InterpreteurException(ERREUR_LG_MAX); - - valeur = uneValeur; + if (!isChaine(uneValeur)) { + throw new InterpreteurException(uneValeur + ERREUR_INVALIDE); + } + + uneValeur = uneValeur.substring(1, uneValeur.length() - 1); + + if (uneValeur.length() > LG_MAX_CHAINE) + throw new InterpreteurException(ERREUR_LG_MAX); + + valeur = uneValeur; + } + + /** + * Prédicat de validité d'une constante littérale de type chaîne. + * @param uneValeur valeur aTester + * @return true si uneValeur est une chaîne sinon false + */ + public static boolean isChaine(String uneValeur) { + uneValeur = uneValeur.trim(); + return uneValeur.length() >= 2 + && uneValeur.startsWith("\"") && uneValeur.endsWith("\""); } /** @@ -61,16 +72,15 @@ public class Chaine extends Litteral { * @return une nouvelle Chaîne. */ public static Chaine concatener(Chaine a, Chaine b) { - - return new Chaine("\"" + a.valeur + b.valeur + "\""); + return new Chaine("\"" + a.valeur + b.valeur + "\""); } /* non javadoc - * @see interpreteurlir.donnees.litteraux.Litteral#compareTo(interpreteurlir.donnees.litteraux.Litteral) + * @see Litteral#compareTo(Litteral) */ @Override public int compareTo(Litteral autre) { - return this.valeur.toString().compareTo(autre.valeur.toString()); + return valeur.toString().compareTo(autre.valeur.toString()); } /* non javadoc diff --git a/src/interpreteurlir/donnees/litteraux/Entier.java b/src/interpreteurlir/donnees/litteraux/Entier.java index f5fe21d..d726ad0 100644 --- a/src/interpreteurlir/donnees/litteraux/Entier.java +++ b/src/interpreteurlir/donnees/litteraux/Entier.java @@ -17,73 +17,46 @@ import interpreteurlir.InterpreteurException; * @author Lucas Vabre */ public class Entier extends Litteral { - - private static final int LONG_CH_MAX = 11; - - /** Valeur entière minimale */ - public static int VALEUR_MIN = Integer.MIN_VALUE; - - /** Valeur entière minimale */ - public static int VALEUR_MAX = Integer.MAX_VALUE; /** * Initialisation de cet entier avec une valeur passée en argument - * @param unEntier - * @throws InterpreteurException lorsque entier n'est pas un Entier + * @param unEntier valeur de l'entier à construire */ - @SuppressWarnings("boxing") public Entier(int unEntier) { - if (! isEntier(unEntier)) { - throw new InterpreteurException("Erreur. " + unEntier - + " n'est pas un entier. "); - } super.valeur = unEntier; } /** * Initialisation de cet entier avec une valeur passée en argument - * @param uneValeur + * @param uneValeur chaîne contenant l'entier à construire */ public Entier(String uneValeur) { if (!isEntier(uneValeur)) { throw new InterpreteurException(uneValeur - + " n'est pas un nombre entier. "); + + " n'est pas un nombre entier"); } valeur = Integer.valueOf(uneValeur); } - private static boolean isEntier(String uneValeur) { - if (uneValeur != null && !uneValeur.isBlank() - && uneValeur.length() <= LONG_CH_MAX - && (isChiffre(uneValeur.charAt(0)) - || uneValeur.length() > 1 && (uneValeur.charAt(0) == '-' - || uneValeur.charAt(0) == '+'))) { - int i; - for (i = 1; i < uneValeur.length() && isChiffre(uneValeur.charAt(i)); - i++) - ; /* corps vide */ - if ((uneValeur.startsWith("+214748364") - || uneValeur.startsWith("214748364")) - && uneValeur.charAt(uneValeur.length() - 1) > '7' - || uneValeur.startsWith("-214748364") - && uneValeur.charAt(uneValeur.length() - 1) > '8' - ) - return false; - - return i >= uneValeur.length(); + /** + * Prédicat de validité d'une chaîne en tant que nombre entier signé + * @param uneValeur la chaîne à tester + * @return true si uneValeur est un entier sinon false + */ + public static boolean isEntier(String uneValeur) { + if (uneValeur == null) { + return false; } - return false; - } - - private static boolean isChiffre(char caractere) { - return '0' <= caractere && caractere <= '9'; - } - - private static boolean isEntier(int entier) { - return VALEUR_MIN <= entier && entier <= VALEUR_MAX; + try { + Integer.valueOf(uneValeur.trim()); + } catch (NumberFormatException lancee) { + return false; + } + + return true; } /* non javadoc @@ -101,10 +74,10 @@ public class Entier extends Litteral { /** * Compare cet entier à un autre entier - * @param autre - * @return une valeur < 0 lorsque autre > cet entier - * une valeur > 0 lorsque autre < cet entier - * une valeur = 0 lorsque autre et cet entier sont égaux + * @param autre entier avec lequel this est comparé + * @return une {@code valeur < 0} lorsque {@code autre > cet entier} + * une {@code valeur > 0} lorsque {@code autre < cet entier} + * une {@code valeur = 0} lorsque autre et cet entier sont égaux */ public int compareTo(Entier autre) { return ((Integer) valeur).compareTo(autre.getValeur()); @@ -151,7 +124,7 @@ public class Entier extends Litteral { */ public static Entier quotient(Entier premier, Entier second) { if (second.compareTo(new Entier (0)) == 0) { - throw new ExecutionException("Erreur. Division par 0. "); + throw new ExecutionException("division par 0"); } return new Entier((int) premier.getValeur() / (int) second.getValeur()); } @@ -165,8 +138,16 @@ public class Entier extends Litteral { */ public static Entier reste(Entier premier, Entier second) { if (second.compareTo(new Entier (0)) == 0) { - throw new ExecutionException("Erreur. Division par 0. "); + throw new ExecutionException("division par 0"); } return new Entier((int) premier.getValeur() % (int) second.getValeur()); } + + /* non javadoc + * @see Litteral#compareTo(Litteral) + */ + @Override + public int compareTo(Litteral autre) { + return ((Integer)valeur).compareTo((Integer)autre.valeur); + } } diff --git a/src/interpreteurlir/donnees/litteraux/Litteral.java b/src/interpreteurlir/donnees/litteraux/Litteral.java index 953915e..fd54e2a 100644 --- a/src/interpreteurlir/donnees/litteraux/Litteral.java +++ b/src/interpreteurlir/donnees/litteraux/Litteral.java @@ -13,7 +13,7 @@ package interpreteurlir.donnees.litteraux; * @author Heïa Dexter * @author Lucas Vabre */ -public class Litteral implements Comparable { +public abstract class Litteral implements Comparable { /** valeur de ce littéral */ protected Object valeur; @@ -27,9 +27,9 @@ public class Litteral implements Comparable { /** * Initialise cette valeur avec un objet argument. - * @param valeur + * @param valeur valeur du littéral à construire */ - public Litteral(Object valeur) { // TODO public >>> protected + public Litteral(Object valeur) { super(); this.valeur = valeur; } @@ -53,11 +53,5 @@ public class Litteral implements Comparable { * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override - public int compareTo(Litteral autre) { - - if (autre.valeur.getClass() == this.valeur.getClass()) - return 0; - - return this.valeur.hashCode() - autre.valeur.hashCode(); - } + public abstract int compareTo(Litteral autre); } \ No newline at end of file diff --git a/src/interpreteurlir/donnees/litteraux/tests/TestBooleen.java b/src/interpreteurlir/donnees/litteraux/tests/TestBooleen.java new file mode 100644 index 0000000..60ed3ab --- /dev/null +++ b/src/interpreteurlir/donnees/litteraux/tests/TestBooleen.java @@ -0,0 +1,50 @@ +/** + * TestBooleen.java 21 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.donnees.litteraux.tests; + +import interpreteurlir.donnees.litteraux.Booleen; +import static info1.outils.glg.Assertions.*; + +/** + * Tests unitaires des méthodes de la classe Booleen + * + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heia Dexter + * @author Lucas Vabre + */ +public class TestBooleen { + + private static final Booleen[] FIXTURE = { + new Booleen(false), + new Booleen(true), + new Booleen(1<2), + new Booleen(1>=2), + new Booleen("bob".equals("bob")), + new Booleen(Character.isDigit('a')), + new Booleen(!Double.isNaN(1/0.0)), + }; + + /** + * Tests unitaire de {@link Booleen#getValeur()} + */ + public void testGetValeur() { + final Boolean[] ATTENDUS = { + false, + true, + true, + false, + true, + false, + true + }; + System.out.println("\tExécution du test de getValeur"); + for (int i = 0 ; i < ATTENDUS.length ; i++) { + assertTrue(ATTENDUS[i].compareTo(FIXTURE[i].getValeur()) + == 0); + } + } +} diff --git a/src/interpreteurlir/donnees/litteraux/tests/TestChaine.java b/src/interpreteurlir/donnees/litteraux/tests/TestChaine.java index f7f4966..2aeee55 100644 --- a/src/interpreteurlir/donnees/litteraux/tests/TestChaine.java +++ b/src/interpreteurlir/donnees/litteraux/tests/TestChaine.java @@ -10,7 +10,8 @@ import interpreteurlir.donnees.litteraux.Chaine; import static info1.outils.glg.Assertions.*; /** - * Tests unitaires de Chaine + * Tests unitaires de la classe Chaine + * * @author Nicolas Caminade * @author Sylvan Courtiol * @author Pierre Debas @@ -18,134 +19,118 @@ import static info1.outils.glg.Assertions.*; * @author Lucas Vabre */ public class TestChaine { - - - /** test de Chaine(String) */ - public static void testChaine() { - - final String[] VALIDE = { - "\"arztyehjklmpoijhghnbghjklmpoiuytrf" + - "ghjnklmpoiuytrezaqsdfghnjklmpjbfrtyu\"", - "\"\"","\"coucou \"", - "\"" + 42 + "\"" - }; - - final String INVALIDE = - "arztyehjklmpoijhghnbghjklmpoiuytrf" + - "yeryghjnklmpoiuytrezaqsdfghnjklmpjbfrtyu"; - System.out.println("test de Chaine(String)"); - - for (String aTester : VALIDE) - new Chaine(aTester); - - try { - new Chaine(INVALIDE); - throw new RuntimeException("Instanciation interdite"); - } catch (InterpreteurException lancee) { - System.out.println("Revoi d'exception OK\nfin du test"); - } - } - - /** test de compareTo */ - public static void testCompareTo() { - final Chaine[][] EGALITES = { - {new Chaine("\"coucou\""), new Chaine("\"coucou\"")}, - {new Chaine("\" \""), new Chaine("\" \"")}, - {new Chaine("\"\""), new Chaine()} - }; - - final Chaine[][] DIFFERENCES = { - {new Chaine("\"coucou\""), new Chaine("\"camomille\"")}, - {new Chaine("\"tarentule\""), new Chaine("\"coucou\"")}, - {new Chaine("\"coucou\""), new Chaine("\" \"")}, - {new Chaine("\"coucou\""), new Chaine()}, - {new Chaine("\" \""), new Chaine()} - }; - - System.out.println("test de compareTo(Chaine)\nAvec égalités"); - - for (Chaine[] couple : EGALITES) { - - try { - assert couple[0].compareTo(couple[1]) == 0; - } catch (AssertionError lancee) { - System.err.println("Echec du test"); - } - - } - - System.out.println("Avec des inégalités"); - for (Chaine[] couple : DIFFERENCES) { - try { - assert couple[0].compareTo(couple[1]) > 0; - } catch (AssertionError lancee) { - System.err.println("Echec du test"); - } - } - System.out.println("fin du test"); - - } - - /** test de toString */ - public static void testToString() { - final Chaine[] A_AFFICHER = { - new Chaine(), new Chaine("\" \""), - new Chaine("\"coucou\""), - new Chaine("\" coucou \""), - new Chaine("\"coucou monsieur\"") - }; - - final String[] AFFICHAGE_GUILLEMETS = { - "\"\"", "\" \"", "\"coucou\"", "\" coucou \"", - "\"coucou monsieur\"" - }; - - System.out.println("test de toString"); - for (int i = 0 ; i < A_AFFICHER.length ; i++) { - - try { - assert A_AFFICHER[i].toString().equals(AFFICHAGE_GUILLEMETS[i]); - } catch (AssertionError lancee) { - System.err.println("Echec du test a l'indice " + i); - } - } - System.out.println("==>test terminé\n"); - } - - /** - * Tests unitaires de concaténer - */ - public void testConcatener() { - final Chaine[] ATTENDU = { - new Chaine(), - new Chaine("\"Bonjour le monde ! \""), - new Chaine("\" \""), - new Chaine("\"3,1415\""), - }; - - final Chaine[][] A_CONCATENER = { - {new Chaine(), new Chaine("\"\"")}, - {new Chaine("\"Bonjour \""), new Chaine("\"le monde ! \"")}, - {new Chaine("\"\""), new Chaine("\" \"")}, - {new Chaine("\"3,\""), new Chaine("\"1415\"")}, - }; - - System.out.println("\tExécution du test de concaténer"); - for (int numTest = 0 ; numTest < ATTENDU.length ; numTest++ ) { - assertTrue(ATTENDU[numTest].compareTo(Chaine.concatener( - A_CONCATENER[numTest][0], A_CONCATENER[numTest][1])) - == 0); - } - } - - /** - * Lancement des tests - * @param args non utilisés - */ - public static void main(String[] args) { - testChaine(); - testCompareTo(); - testToString(); - } -} + + /** Test unitaire de {@link Chaine#Chaine(String)} */ + public static void testChaine() { + + final String[] VALIDE = { + "\"arztyehjklmpoijhghnbghjklmpoiuytrf" + + "ghjnklmpoiuytrezaqsdfghnjklmpjbfrtyu\"", + "\"\"", + "\"coucou \"", + "\"" + 42 + "\"" + }; + + final String INVALIDE = + "arztyehjklmpoijhghnbghjklmpoiuytrf" + + "yeryghjnklmpoiuytrezaqsdfghnjklmpjbfrtyu"; + + System.out.println("\tExécution du test de Chaine(String)"); + + for(String aTester : VALIDE) { + try { + new Chaine(aTester); + } catch (InterpreteurException lancee) { + echec(); + } + } + + try { + new Chaine(INVALIDE); + echec(); + } catch (InterpreteurException lancee) { + // Test OK + } + } + + /** Test unitaire de {@link Chaine#compareTo(Litteral)} */ + public static void testCompareTo() { + final Chaine[][] EGALITES = { + { new Chaine("\"coucou\""), new Chaine("\"coucou\"") }, + { new Chaine("\" \""), new Chaine("\" \"") }, + { new Chaine("\"\""), new Chaine() } + }; + + final Chaine[][] DIFFERENCES = { + { new Chaine("\"coucou\""), new Chaine("\"camomille\"") }, + { new Chaine("\"tarentule\""), new Chaine("\"coucou\"") }, + { new Chaine("\"coucou\""), new Chaine("\" \"") }, + { new Chaine("\"coucou\""), new Chaine() }, + { new Chaine("\" \""), new Chaine() } + }; + + System.out.println("\tExécution du test de compareTo(Chaine)\n" + + "\tAvec égalités"); + + for (Chaine[] couple : EGALITES) { + assertEquivalence(couple[0].compareTo(couple[1]), 0); + } + + System.out.println("\tAvec des inégalités"); + for (Chaine[] couple : DIFFERENCES) { + assertTrue(couple[0].compareTo(couple[1]) > 0); + } + } + + /** Test unitaire de {@link Chaine#toString()} */ + public static void testToString() { + final Chaine[] A_AFFICHER = { + new Chaine(), + new Chaine("\" \""), + new Chaine("\"coucou\""), + new Chaine("\" coucou \""), + new Chaine("\"coucou monsieur\"") + }; + + final String[] AFFICHAGE_GUILLEMETS = { + "\"\"", + "\" \"", + "\"coucou\"", + "\" coucou \"", + "\"coucou monsieur\"" + }; + + System.out.println("\tExécution du test de toString"); + for (int i = 0 ; i < A_AFFICHER.length ; i++) { + assertTrue(AFFICHAGE_GUILLEMETS[i] + .equals(A_AFFICHER[i].toString())); + } + } + + /** + * Tests unitaires de concaténer + */ + public static void testConcatener() { + final Chaine[] ATTENDU = { + new Chaine(), + new Chaine("\"Bonjour le monde ! \""), + new Chaine("\" \""), + new Chaine("\"3,1415\""), + }; + + final Chaine[][] A_CONCATENER = { + { new Chaine(), new Chaine("\"\"") }, + { new Chaine("\"Bonjour \""), new Chaine("\"le monde ! \"") }, + { new Chaine("\"\""), new Chaine("\" \"") }, + { new Chaine("\"3,\""), new Chaine("\"1415\"") }, + }; + + System.out.println("\tExécution du test de concaténer"); + for (int numTest = 0 ; numTest < ATTENDU.length ; numTest++ ) { + assertTrue(ATTENDU[numTest].compareTo( + Chaine.concatener(A_CONCATENER[numTest][0], + A_CONCATENER[numTest][1])) == 0); + } + } +} \ No newline at end of file diff --git a/src/interpreteurlir/donnees/litteraux/tests/TestEntier.java b/src/interpreteurlir/donnees/litteraux/tests/TestEntier.java index bc1ca7f..db064fc 100644 --- a/src/interpreteurlir/donnees/litteraux/tests/TestEntier.java +++ b/src/interpreteurlir/donnees/litteraux/tests/TestEntier.java @@ -40,22 +40,6 @@ public class TestEntier { new Entier(179892), }; - /** Jeu d'entiers correctement instanciés */ - private final Entier[] ENTIERS_STRING = { - - new Entier("1"), - new Entier("-4587"), - new Entier("-569"), - new Entier("-3"), - new Entier("0"), - new Entier("2"), - new Entier("78"), - new Entier("781"), - new Entier("179892"), - new Entier("-2147483648"), - new Entier("2147483647"), - }; - /** Jeu d'integers correspondants */ private static final int[] INT_VALIDES = { MIN_VALUE, @@ -94,6 +78,7 @@ public class TestEntier { "+", }; + System.out.println("\tExécution du test de Entier(String)"); for (int i = 0; i < INVALIDES.length; i++) { try { new Entier(INVALIDES[i]); @@ -108,6 +93,7 @@ public class TestEntier { * Test unitaire de la méthode toString() */ public void testToString() { + System.out.println("\tExécution du test de Entier(String)"); for (int i = 0; i < INT_VALIDES.length; i ++) { assertTrue(ENTIERS_INT[i].toString() .compareTo(Integer.toString(INT_VALIDES[i])) == 0); @@ -115,12 +101,12 @@ public class TestEntier { } /** - * Test unitaire de la méthode toCompareTo() + * Test unitaire de la méthode compareTo() */ public void testCompareTo() { final Entier REF_MIN = new Entier(MIN_VALUE); final Entier REF_MAX = new Entier(MAX_VALUE); - + System.out.println("\tExécution du test de compareTo()"); for (int i = 2; i < ENTIERS_INT.length; i++) { assertTrue(REF_MIN.compareTo(ENTIERS_INT[i]) < 0); assertTrue(REF_MAX.compareTo(ENTIERS_INT[i]) > 0); @@ -149,14 +135,14 @@ public class TestEntier { 781, 179892, }; - + System.out.println("\tExécution du test de getValeur()"); for (int i = 0; i < ENTIERS_INT.length; i++) { assertTrue(ENTIERS_INT[i].getValeur().compareTo(ATTENDUS[i]) == 0); } } /** - * Test unitaire de la méthode somme() + * Test unitaire de la méthode somme(Entier, Entier) */ public void testSomme() { final Entier[] ATTENDUS = { @@ -172,7 +158,7 @@ public class TestEntier { new Entier(1562), new Entier(359784), }; - + System.out.println("\tExécution du test de somme(Entier, Entier)"); for (int i = 0; i < ENTIERS_INT.length; i++) { assertTrue(somme(ENTIERS_INT[i], ENTIERS_INT[i]) .compareTo(ATTENDUS[i]) == 0); @@ -184,7 +170,7 @@ public class TestEntier { */ public void testSoustrait() { Entier zero = new Entier(0); - + System.out.println("\tExécution du test de soustrait(Entier, Entier)"); for (int i = 0; i < ENTIERS_INT.length; i++) { assertTrue(soustrait(ENTIERS_INT[i], ENTIERS_INT[i]) .compareTo(zero) == 0); @@ -208,7 +194,7 @@ public class TestEntier { new Entier(781 * 781), new Entier(179892 * 179892), }; - + System.out.println("\tExécution du test de multiplie(Entier, Entier)"); for (int i = 0; i < ENTIERS_INT.length; i++) { assertTrue(multiplie(ENTIERS_INT[i], ENTIERS_INT[i]) .compareTo(ATTENDUS[i]) == 0); @@ -234,7 +220,7 @@ public class TestEntier { new Entier(390), new Entier(89946) }; - + System.out.println("\tExécution du test de quotient(Entier, Entier)"); for (int i = 0; i < ENTIERS_INT.length; i++) { assertTrue(quotient(ENTIERS_INT[i], DIVISEUR) .compareTo(ATTENDUS[i]) == 0); @@ -246,7 +232,8 @@ public class TestEntier { */ public void testQuotientParZero() { final Entier DIVISEUR = new Entier(0); - + System.out.println("\tExécution du test de " + + "quotient(Entier, Entier) par 0"); for (int i = 0; i < ENTIERS_INT.length; i++) { try { quotient(ENTIERS_INT[i], DIVISEUR); @@ -276,7 +263,7 @@ public class TestEntier { new Entier(1), new Entier(0) }; - + System.out.println("\tExécution du test de reste(Entier, Entier)"); for (int i = 0; i < ENTIERS_INT.length; i++) { assertTrue(reste(ENTIERS_INT[i], DIVISEUR) .compareTo(ATTENDUS[i]) == 0); @@ -288,7 +275,8 @@ public class TestEntier { */ public void testResteParZero() { final Entier DIVISEUR = new Entier(0); - + System.out.println("\tExécution du test de " + + "reste(Entier, Entier) par 0"); for (int i = 0; i < ENTIERS_INT.length; i++) { try { reste(ENTIERS_INT[i], DIVISEUR); diff --git a/src/interpreteurlir/donnees/litteraux/tests/TestLitteraux.java b/src/interpreteurlir/donnees/litteraux/tests/TestLitteraux.java index d045778..fd12a00 100644 --- a/src/interpreteurlir/donnees/litteraux/tests/TestLitteraux.java +++ b/src/interpreteurlir/donnees/litteraux/tests/TestLitteraux.java @@ -1,171 +1,172 @@ -/** - * TestLitteraux.java 7 mai 2021 - * IUT info1 2020-2021, pas de copyright, aucun droit - */ -package interpreteurlir.donnees.litteraux.tests; - -import interpreteurlir.donnees.litteraux.Litteral; - -/** - * Test unitaires des constantes littérales de l'interpréteurlir - * @author Nicolas Caminade - * @author Sylvan Courtiol - * @author Pierre Debas - * @author Heïa Dexter - * @author Lucas Vabre - */ -public class TestLitteraux { - - /** Jeux de littéraux pour test. */ - private static final Litteral[] VALIDES = { - /* Caractères */ - new Litteral('a'), - new Litteral('!'), - new Litteral('\"'), - new Litteral('1'), - new Litteral('\t'), - /* Chaînes */ - new Litteral("ceci est une chaine"), - new Litteral("bonjour"), - new Litteral(" bonjour "), - new Litteral(""), - new Litteral(" "), - /* Entier */ - new Litteral(123), - new Litteral(-123), - new Litteral(0), - new Litteral(Integer.MAX_VALUE), - /* Double */ - new Litteral(14.258), - new Litteral(-14.128), - new Litteral(0.0), - new Litteral(Double.NaN), - new Litteral(Double.NEGATIVE_INFINITY), - new Litteral(Double.MAX_VALUE), - new Litteral(Double.MIN_VALUE), - new Litteral(Double.MIN_NORMAL), - /* Boolean */ - new Litteral(true), - new Litteral(false), - new Litteral(3 >= 4), - new Litteral(true), - new Litteral(true), - new Litteral(true) - }; - - /** test de getValeur */ - public static void testGetValeur() { - - final Object[] VALEURS_ATTENDUES = { - 'a', '!', '\"', '1', '\t' ,"ceci est une chaîne", "bonjour", - " bonjour ", "", " ", 123, -123, 0, 2147483647, 14.258, -14.128, - 0.0, Double.NaN, Double.NEGATIVE_INFINITY, Double.MAX_VALUE, - Double.MIN_VALUE, Double.MIN_NORMAL, true, false, false, true, true, - true - }; - - System.out.println("test de getValeur\n"); - - for (int i = 0 ; i < VALIDES.length ; i++) { - - try { - assert (VALIDES[i].getValeur().equals(VALEURS_ATTENDUES[i])); - } catch (AssertionError lancee) { - System.err.println("Echec du test a l'indice " + i); - } - } - System.out.println("==>test terminé\n"); - } - - /** test de toString */ - public static void testToString() { - - final String[] STRING_ATTENDUE = { - "a", "!", "\"", "1", "\t", "ceci est une chaîne", "bonjour", - " bonjour ", "", " ", "123", "-123", "0", "2147483647", "14.258", - "-14.128", "0.0", "NaN", "-Infinity", "1.7976931348623157E308", - "4.9E-324", "2.2250738585072014E-308", "true", "false", "false", - "true", "true", "true" - }; - - System.out.println("test de toString\n"); - - for (int i = 0 ; i < VALIDES.length ; i++ ) { - - try { - assert (VALIDES[i].toString().equals(STRING_ATTENDUE[i])); - } catch (AssertionError lancee) { - System.err.println("Echec du test a l'indice " + i); - } - } - System.out.println("==>test terminé\n"); - } - - /** test de compareTo */ - public static void testCompareTo() { - - final Litteral[] MEMES_TYPES = { - new Litteral('a'), - new Litteral('!'), - new Litteral('\"'), - new Litteral('Z'), - new Litteral('s'), - new Litteral("bonjour"), - new Litteral("bonjour"), - new Litteral("arar"), - new Litteral("zarar za "), - new Litteral("CAFE_BABE"), - new Litteral(123), - new Litteral(123), - new Litteral(0), - new Litteral(-123), - new Litteral(Double.MAX_VALUE), - new Litteral(Double.NaN), - new Litteral(12.3), - new Litteral(Double.NaN), - new Litteral(45.7), - new Litteral(-12.6), - new Litteral(0.0), - new Litteral(Double.MIN_NORMAL), - new Litteral(false), - new Litteral(false), - new Litteral(true), - new Litteral(true), - new Litteral(true), - new Litteral(true) - }; - - System.out.println("test de compareTo\nAvec des types identiques"); - - for (int i = 0 ; i < VALIDES.length ; i++ ) { - - try { - assert (VALIDES[i].compareTo(MEMES_TYPES[i]) == 0); - } catch (AssertionError lancee) { - System.err.println("Echec du test a l'indice " + i); - } - } - System.out.println("Avec des types différents"); - - for (int i = 0 ; i < VALIDES.length ; i++ ) { - - try { - assert (VALIDES[i].compareTo(MEMES_TYPES[MEMES_TYPES.length - - (i + 1)]) != 0); - } catch (AssertionError lancee) { - System.err.println("Echec du test a l'indice " + i); - } - } - System.out.println("==>test terminé\n"); - } - - /** - * Lancement des test - * @param args non utilisé - */ - public static void main(String[] args) { - testGetValeur(); - testToString(); - testCompareTo(); - } -} \ No newline at end of file +// Classe testée passé en abstract +///** +// * TestLitteraux.java 7 mai 2021 +// * IUT info1 2020-2021, pas de copyright, aucun droit +// */ +//package interpreteurlir.donnees.litteraux.tests; +// +//import interpreteurlir.donnees.litteraux.Litteral; +// +///** +// * Test unitaires des constantes littérales de l'interpréteurlir +// * @author Nicolas Caminade +// * @author Sylvan Courtiol +// * @author Pierre Debas +// * @author Heïa Dexter +// * @author Lucas Vabre +// */ +//public class TestLitteraux { +// +// /** Jeux de littéraux pour test. */ +// private static final Litteral[] VALIDES = { +// /* Caractères */ +// new Litteral('a'), +// new Litteral('!'), +// new Litteral('\"'), +// new Litteral('1'), +// new Litteral('\t'), +// /* Chaînes */ +// new Litteral("ceci est une chaine"), +// new Litteral("bonjour"), +// new Litteral(" bonjour "), +// new Litteral(""), +// new Litteral(" "), +// /* Entier */ +// new Litteral(123), +// new Litteral(-123), +// new Litteral(0), +// new Litteral(Integer.MAX_VALUE), +// /* Double */ +// new Litteral(14.258), +// new Litteral(-14.128), +// new Litteral(0.0), +// new Litteral(Double.NaN), +// new Litteral(Double.NEGATIVE_INFINITY), +// new Litteral(Double.MAX_VALUE), +// new Litteral(Double.MIN_VALUE), +// new Litteral(Double.MIN_NORMAL), +// /* Boolean */ +// new Litteral(true), +// new Litteral(false), +// new Litteral(3 >= 4), +// new Litteral(true), +// new Litteral(true), +// new Litteral(true) +// }; +// +// /** test de getValeur */ +// public static void testGetValeur() { +// +// final Object[] VALEURS_ATTENDUES = { +// 'a', '!', '\"', '1', '\t' ,"ceci est une chaîne", "bonjour", +// " bonjour ", "", " ", 123, -123, 0, 2147483647, 14.258, -14.128, +// 0.0, Double.NaN, Double.NEGATIVE_INFINITY, Double.MAX_VALUE, +// Double.MIN_VALUE, Double.MIN_NORMAL, true, false, false, true, true, +// true +// }; +// +// System.out.println("test de getValeur\n"); +// +// for (int i = 0 ; i < VALIDES.length ; i++) { +// +// try { +// assert (VALIDES[i].getValeur().equals(VALEURS_ATTENDUES[i])); +// } catch (AssertionError lancee) { +// System.err.println("Echec du test a l'indice " + i); +// } +// } +// System.out.println("==>test terminé\n"); +// } +// +// /** test de toString */ +// public static void testToString() { +// +// final String[] STRING_ATTENDUE = { +// "a", "!", "\"", "1", "\t", "ceci est une chaîne", "bonjour", +// " bonjour ", "", " ", "123", "-123", "0", "2147483647", "14.258", +// "-14.128", "0.0", "NaN", "-Infinity", "1.7976931348623157E308", +// "4.9E-324", "2.2250738585072014E-308", "true", "false", "false", +// "true", "true", "true" +// }; +// +// System.out.println("test de toString\n"); +// +// for (int i = 0 ; i < VALIDES.length ; i++ ) { +// +// try { +// assert (VALIDES[i].toString().equals(STRING_ATTENDUE[i])); +// } catch (AssertionError lancee) { +// System.err.println("Echec du test a l'indice " + i); +// } +// } +// System.out.println("==>test terminé\n"); +// } +// +// /** test de compareTo */ +// public static void testCompareTo() { +// +// final Litteral[] MEMES_TYPES = { +// new Litteral('a'), +// new Litteral('!'), +// new Litteral('\"'), +// new Litteral('Z'), +// new Litteral('s'), +// new Litteral("bonjour"), +// new Litteral("bonjour"), +// new Litteral("arar"), +// new Litteral("zarar za "), +// new Litteral("CAFE_BABE"), +// new Litteral(123), +// new Litteral(123), +// new Litteral(0), +// new Litteral(-123), +// new Litteral(Double.MAX_VALUE), +// new Litteral(Double.NaN), +// new Litteral(12.3), +// new Litteral(Double.NaN), +// new Litteral(45.7), +// new Litteral(-12.6), +// new Litteral(0.0), +// new Litteral(Double.MIN_NORMAL), +// new Litteral(false), +// new Litteral(false), +// new Litteral(true), +// new Litteral(true), +// new Litteral(true), +// new Litteral(true) +// }; +// +// System.out.println("test de compareTo\nAvec des types identiques"); +// +// for (int i = 0 ; i < VALIDES.length ; i++ ) { +// +// try { +// assert (VALIDES[i].compareTo(MEMES_TYPES[i]) == 0); +// } catch (AssertionError lancee) { +// System.err.println("Echec du test a l'indice " + i); +// } +// } +// System.out.println("Avec des types différents"); +// +// for (int i = 0 ; i < VALIDES.length ; i++ ) { +// +// try { +// assert (VALIDES[i].compareTo(MEMES_TYPES[MEMES_TYPES.length +// - (i + 1)]) != 0); +// } catch (AssertionError lancee) { +// System.err.println("Echec du test a l'indice " + i); +// } +// } +// System.out.println("==>test terminé\n"); +// } +// +// /** +// * Lancement des test +// * @param args non utilisé +// */ +// public static void main(String[] args) { +// testGetValeur(); +// testToString(); +// testCompareTo(); +// } +//} \ No newline at end of file diff --git a/src/interpreteurlir/donnees/tests/TestIdentificateur.java b/src/interpreteurlir/donnees/tests/TestIdentificateur.java index 0d42314..e288928 100644 --- a/src/interpreteurlir/donnees/tests/TestIdentificateur.java +++ b/src/interpreteurlir/donnees/tests/TestIdentificateur.java @@ -1,115 +1,118 @@ -/** - * TestIdentificateur.java 8 mai 2021 - * IUT-Rodez info1 2020-2021, pas de droits, pas de copyrights - */ -package interpreteurlir.donnees.tests; +// Classe testée passé en abstract -import static info1.outils.glg.Assertions.*; +///** +// * TestIdentificateur.java 8 mai 2021 +// * IUT-Rodez info1 2020-2021, pas de droits, pas de copyrights +// */ +//package interpreteurlir.donnees.tests; +// +//import static info1.outils.glg.Assertions.*; +// +//import interpreteurlir.InterpreteurException; +//import interpreteurlir.donnees.Identificateur; +// +///** +// * Test de la classe donnees.Identificateur +// * @author Nicolas Caminade +// * @author Sylvan Courtiol +// * @author Pierre Debas +// * @author Heia Dexter +// * @author Lucas Vabre +// */ +//public class TestIdentificateur { +// +// /** Jeu d'identificateurs correctement instanciés */ +// public static final Identificateur[] FIXTURE = { +// new Identificateur("b"), +// new Identificateur("A"), +// new Identificateur("zalpha"), +// new Identificateur("Alpha"), +// new Identificateur("Alpha5"), +// new Identificateur("jeSuisUnTresLongIdentifi"), +// new Identificateur("$b"), +// new Identificateur("z"), +// new Identificateur("$zalpha"), +// new Identificateur("$Alpha"), +// new Identificateur("$Alpha5"), +// new Identificateur("$jeSuisUnTresLongIdentifi") +// +// }; +// +// /** +// * Test de Identificateur(String identificateur) +// */ +// public static void testIdentificateurString() { +// final String[] INVALIDE = { +// null, +// "", +// +// // Fait au maximum 25 caractères +// "$jeSuisUnTresLongIdentificateur", // 30 char +// "$jeSuisUnTresLongIdentifica", +// +// // Espaces +// "id 3a", +// "$id 3a", +// " ", +// "$ ", +// +// // caractères d'échapements +// "\t", +// "\n", +// "$\t", +// "$\n", +// +// // , cas particulier +// "$" +// }; +// +// for(int noJeu = 0 ; noJeu < INVALIDE.length ; noJeu++) { +// try { +// new Identificateur(INVALIDE[noJeu]); +// echec(); +// } catch (InterpreteurException lancee) { +// // Test OK +// } +// } +// } +// +// /** +// * Test de compareTo(Identificateur aComparer) +// */ +// public static void testCompareTo() { +// final Identificateur REF_MIN = new Identificateur("$AAAAAAAAAAAAAAAAAAAAAAAA"); +// final Identificateur REF_MAX = new Identificateur("zzzzzzzzzzzzzzzzzzzzzzzz"); +// +// for(int noJeu = 0; noJeu < FIXTURE.length; noJeu++) { +// assertTrue(FIXTURE[noJeu].compareTo(REF_MIN) >= 0); +// assertTrue(FIXTURE[noJeu].compareTo(REF_MAX) <= 0); +// assertTrue(FIXTURE[noJeu].compareTo(FIXTURE[noJeu]) == 0); +// } +// } +// +// /** +// * Tests unitaires de toString +// */ +// public static void testToString() { +// final String[] CHAINES_VALIDES = { +// "b", +// "A", +// "zalpha", +// "Alpha", +// "Alpha5", +// "jeSuisUnTresLongIdentifi", +// "$b", +// "z", +// "$zalpha", +// "$Alpha", +// "$Alpha5", +// "$jeSuisUnTresLongIdentifi" +// }; +// +// for (int noJeu = 0 ; noJeu < CHAINES_VALIDES.length ; noJeu++) { +// assertEquivalence(CHAINES_VALIDES[noJeu], +// FIXTURE[noJeu].toString()); +// } +// } +//} -import interpreteurlir.InterpreteurException; -import interpreteurlir.donnees.Identificateur; - -/** - * Test de la classe donnees.Identificateur - * @author Nicolas Caminade - * @author Sylvan Courtiol - * @author Pierre Debas - * @author Heia Dexter - * @author Lucas Vabre - */ -public class TestIdentificateur { - - /** Jeu d'identificateurs correctement instanciés */ - public static final Identificateur[] FIXTURE = { - new Identificateur("b"), - new Identificateur("A"), - new Identificateur("zalpha"), - new Identificateur("Alpha"), - new Identificateur("Alpha5"), - new Identificateur("jeSuisUnTresLongIdentifi"), - new Identificateur("$b"), - new Identificateur("z"), - new Identificateur("$zalpha"), - new Identificateur("$Alpha"), - new Identificateur("$Alpha5"), - new Identificateur("$jeSuisUnTresLongIdentifi") - - }; - - /** - * Test de Identificateur(String identificateur) - */ - public static void testIdentificateurString() { - final String[] INVALIDE = { - null, - "", - - // Fait au maximum 25 caractères - "$jeSuisUnTresLongIdentificateur", // 30 char - "$jeSuisUnTresLongIdentifica", - - // Espaces - "id 3a", - "$id 3a", - " ", - "$ ", - - // caractères d'échapements - "\t", - "\n", - "$\t", - "$\n", - - // , cas particulier - "$" - }; - - for(int noJeu = 0 ; noJeu < INVALIDE.length ; noJeu++) { - try { - new Identificateur(INVALIDE[noJeu]); - echec(); - } catch (InterpreteurException lancee) { - // Test OK - } - } - } - - /** - * Test de compareTo(Identificateur aComparer) - */ - public static void testCompareTo() { - final Identificateur REF_MIN = new Identificateur("$AAAAAAAAAAAAAAAAAAAAAAAA"); - final Identificateur REF_MAX = new Identificateur("zzzzzzzzzzzzzzzzzzzzzzzz"); - - for(int noJeu = 0; noJeu < FIXTURE.length; noJeu++) { - assertTrue(FIXTURE[noJeu].compareTo(REF_MIN) >= 0); - assertTrue(FIXTURE[noJeu].compareTo(REF_MAX) <= 0); - assertTrue(FIXTURE[noJeu].compareTo(FIXTURE[noJeu]) == 0); - } - } - - /** - * Tests unitaires de toString - */ - public static void testToString() { - final String[] CHAINES_VALIDES = { - "b", - "A", - "zalpha", - "Alpha", - "Alpha5", - "jeSuisUnTresLongIdentifi", - "$b", - "z", - "$zalpha", - "$Alpha", - "$Alpha5", - "$jeSuisUnTresLongIdentifi" - }; - - for (int noJeu = 0 ; noJeu < CHAINES_VALIDES.length ; noJeu++) { - assertEquivalence(CHAINES_VALIDES[noJeu], - FIXTURE[noJeu].toString()); - } - } -} diff --git a/src/interpreteurlir/donnees/tests/TestIdentificateurChaine.java b/src/interpreteurlir/donnees/tests/TestIdentificateurChaine.java index f507c16..16dcfdf 100644 --- a/src/interpreteurlir/donnees/tests/TestIdentificateurChaine.java +++ b/src/interpreteurlir/donnees/tests/TestIdentificateurChaine.java @@ -31,11 +31,11 @@ public class TestIdentificateurChaine { }; /** - * Tests unitaires du constructeur IdentificateurEntier(String identificateur) + * Tests unitaires du constructeur + * IdentificateurEntier(String identificateur) */ public static void testIdentificateurChaineString() { final String[] INVALIDE = { - null, "", // Commence par une lettre @@ -62,7 +62,8 @@ public class TestIdentificateurChaine { "$", "$1" }; - + System.out.println("\tExécution du test de " + + "IdentificateurEntier(String identificateur)"); for(int noJeu = 0; noJeu < INVALIDE.length ; noJeu++) { try { new IdentificateurChaine(INVALIDE[noJeu]); @@ -87,6 +88,7 @@ public class TestIdentificateurChaine { "$jeSuisUnTresLongIdentifi" }; + System.out.println("\tExécution du test de getNom()"); for (int noJeu = 0 ; noJeu < NOM_VALIDES.length ; noJeu++) { assertEquivalence(NOM_VALIDES[noJeu], FIXTURE[noJeu].getNom()); } diff --git a/src/interpreteurlir/donnees/tests/TestVariable.java b/src/interpreteurlir/donnees/tests/TestVariable.java index ff3e91a..66a8ae6 100644 --- a/src/interpreteurlir/donnees/tests/TestVariable.java +++ b/src/interpreteurlir/donnees/tests/TestVariable.java @@ -63,36 +63,24 @@ public class TestVariable { new Chaine("\"titi\n\"") }; -// /** Jeu d'entiers valides */ -// private static final Entier[] VALEUR_ENTIER = { -// // TODO: jeu d'entiers valide -// }; - /** Jeu de variables chaîne valides*/ - private static Variable[] fixtureChaine = new Variable[ID_CHAINE.length]; - - /* Jeu de variables entières valides*/ - //private static Variable[] fixtureEntier= new Variable[ID_ENTIER.length]; + private static Variable[] fixtureChaine = new Variable[ID_CHAINE.length]; private static void fixtureReload() { for (int i = 0; i < ID_CHAINE.length; i++) { fixtureChaine[i] = new Variable(ID_CHAINE[i], VALEURS_CHAINE[i]); } - - //TODO reload fixtureEntier } /** * Test unitaire du constructeur Variable(Identificateur, Littéral) */ public static void testVariableIdentificateurChaineLitteral() { - + System.out.println("\tExécution du test de " + + "Variable(Identificateur, Littéral)"); for (int noJeu = 0; noJeu < VALEURS_CHAINE.length; noJeu++) { try { - //new Variable(ID_CHAINE[noJeu], VALEURS_CHAINE[noJeu]); // bouchon new Variable(ID_ENTIER[noJeu], VALEURS_CHAINE[noJeu]); - // TODO tester avec la classe Entier - // new Variable(ID_CHAINE[noJeu], VALEURS_ENTIER[noJeu]); echec(); } catch (InterpreteurException lancee) { // test OK @@ -106,32 +94,21 @@ public class TestVariable { public static void testGetIdentificateurChaine() { fixtureReload(); + System.out.println("\tExécution du test de getIdentificateur()"); + for (int i = 0; i < VALEURS_CHAINE.length; i++ ) { assertTrue(ID_CHAINE[i].compareTo(fixtureChaine[i] .getIdentificateur()) == 0); } } - /** - * Test unitaire de getIdentificateur() d'une variable entière - */ - public static void testGetIdentificateurEntier() { -// fixtureReload(); -// -// for (int i = 0; i < VALEURS_Entier.length; i++ ) { -// assertTrue(ID_ENTIER[i].compareTo(fixtureEntier[i] -// .getIdentificateur()) == 0); -// } - - echec(); - } - /** * Test unitaire de getValeur() d'une variable chaîne */ public static void testGetValeurChaine() { fixtureReload(); + System.out.println("\tExécution du test de getValeur()"); for (int i = 0; i < VALEURS_CHAINE.length; i++ ) { assertTrue(VALEURS_CHAINE[i] .compareTo(fixtureChaine[i].getValeur()) == 0); @@ -153,6 +130,7 @@ public class TestVariable { new Chaine("\"-5 + 962\"") }; + System.out.println("\tExécution du test de setValeur()"); for (int i = 0; i < NOUVELLE_CHAINE.length; i++) { fixtureChaine[i].setValeur(NOUVELLE_CHAINE[i]); assertTrue(NOUVELLE_CHAINE[i] @@ -178,7 +156,7 @@ public class TestVariable { "$MichelSardou = \"tata\t\"", "$PhilippePoutou2022 = \"titi\n\"" }; - + System.out.println("\tExécution du test de toString()"); for (int noJeu = 0; noJeu < fixtureChaine.length; noJeu++ ) { assertEquivalence(fixtureChaine[noJeu].toString(), ATTENDUS[noJeu]); @@ -199,12 +177,12 @@ public class TestVariable { = new Variable(new IdentificateurChaine("$z"), new Chaine("\"Max\"")); + System.out.println("\tExécution du test de compareTo"); for(int noJeu = 0; noJeu < fixtureChaine.length; noJeu++) { assertTrue(fixtureChaine[noJeu].compareTo(REF_MIN) > 0); assertTrue(fixtureChaine[noJeu].compareTo(REF_MAX) < 0); assertTrue(fixtureChaine[noJeu].compareTo(fixtureChaine[noJeu]) == 0); } - // TODO Faire le même test pour les variables contenant des entiers } } diff --git a/src/interpreteurlir/expressions/Expression.java b/src/interpreteurlir/expressions/Expression.java index 70b97dc..fc14f23 100644 --- a/src/interpreteurlir/expressions/Expression.java +++ b/src/interpreteurlir/expressions/Expression.java @@ -19,7 +19,7 @@ import interpreteurlir.donnees.litteraux.Litteral; * @author Heïa Dexter * @author Lucas Vabre */ -public class Expression { +public abstract class Expression { /** Index de l'operande gauche */ protected static final int INDEX_OPERANDE_G = 0; @@ -29,6 +29,12 @@ public class Expression { /** Index de de l'identificateur pour l'affectation */ protected static final int INDEX_AFFECTATION = 2; + + /** Index du premier symbole de l'opérateur */ + protected static final int INDEX_OPERATEUR_G = 0; + + /** Index du second symbole de l'opérateur */ + protected static final int INDEX_OPERATEUR_D = 1; /** Contexte global pour accéder aux données. */ protected static Contexte contexteGlobal; @@ -39,6 +45,12 @@ public class Expression { /** Littéraux opérandes de cette expression */ protected Litteral[] litterauxOperandes; + /** + * Opérateur de cette expression potentiellement + * composé de plusieurs symboles + */ + protected char[] operateur; + /** * Initialise une expression par défaut avec les liens nécessaires à * son calcul. @@ -48,6 +60,10 @@ public class Expression { final int NB_IDENTIFICATEUR = 3; final int NB_LITTERAL = 2; + operateur = new char[2]; + operateur[INDEX_OPERATEUR_G] = '\u0000'; + operateur[INDEX_OPERATEUR_D] = '\u0000'; + identificateursOperandes = new Identificateur[NB_IDENTIFICATEUR]; litterauxOperandes = new Litteral[NB_LITTERAL]; } @@ -77,20 +93,28 @@ public class Expression { Identificateur affect = identificateursOperandes[INDEX_AFFECTATION]; resultat.append(affect == null ? "" : (affect.toString() + " = ")); - Identificateur gaucheId = identificateursOperandes[INDEX_OPERANDE_G]; - Litteral gaucheLitteral = litterauxOperandes[INDEX_OPERANDE_G]; - resultat.append(gaucheId != null ? gaucheId.toString() - : gaucheLitteral.toString()); + if (litterauxOperandes[INDEX_OPERANDE_G] != null) { + resultat.append(litterauxOperandes[INDEX_OPERANDE_G]); + } else { + resultat.append(identificateursOperandes[INDEX_OPERANDE_G]); + } + resultat.append(" "); - Identificateur droiteId = identificateursOperandes[INDEX_OPERANDE_D]; - Litteral droiteLitteral = litterauxOperandes[INDEX_OPERANDE_D]; - if (droiteId != null || droiteLitteral != null) { - resultat.append(" + "); - resultat.append(droiteId != null ? droiteId.toString() - : droiteLitteral.toString()); + if (operateur[INDEX_OPERATEUR_G] != '\u0000') { + resultat.append(operateur[INDEX_OPERATEUR_G]); + } + if (operateur[INDEX_OPERATEUR_D] != '\u0000') { + resultat.append(operateur[INDEX_OPERATEUR_D]); } - return resultat.toString(); + resultat.append(" "); + if (litterauxOperandes[INDEX_OPERANDE_D] != null) { + resultat.append(litterauxOperandes[INDEX_OPERANDE_D]); + } else if (identificateursOperandes[INDEX_OPERANDE_D] != null) { + resultat.append(identificateursOperandes[INDEX_OPERANDE_D]); + } + + return resultat.toString().trim(); } /** @@ -129,4 +153,26 @@ public class Expression { return new ExpressionEntier(aTraiter); } } + + /** + * Détermine l'index du caractère en dehors des constantes littérales + * @param aTraiter chaîne à traiter + * @param caractere opérateur à chercher hors guillemet + * @return index dans à traiter du plus sinon -1 si aucun plus + */ + public static int detecterCaractere(String aTraiter, char caractere) { + char[] aTester = aTraiter.toCharArray(); + int indexPlus; + int nbGuillemet = 0; + for (indexPlus = 0 ; + indexPlus < aTester.length + && (aTester[indexPlus] != caractere || nbGuillemet % 2 != 0) ; + indexPlus++) { + + if (aTester[indexPlus] == '"') { + nbGuillemet++; + } + } + return indexPlus >= aTester.length ? -1 : indexPlus; + } } diff --git a/src/interpreteurlir/expressions/ExpressionBooleenne.java b/src/interpreteurlir/expressions/ExpressionBooleenne.java new file mode 100644 index 0000000..bc329ee --- /dev/null +++ b/src/interpreteurlir/expressions/ExpressionBooleenne.java @@ -0,0 +1,287 @@ +/** + * ExpressionBooleenne.java 21 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.expressions; + +import static interpreteurlir.donnees.IdentificateurChaine + .isIdentificateurChaine; +import static interpreteurlir.donnees.IdentificateurEntier + .isIdentificateurEntier; +import static interpreteurlir.donnees.litteraux.Entier.isEntier; +import static interpreteurlir.donnees.litteraux.Chaine.isChaine; + +import interpreteurlir.InterpreteurException; +import interpreteurlir.donnees.IdentificateurChaine; +import interpreteurlir.donnees.IdentificateurEntier; +import interpreteurlir.donnees.litteraux.*; + +/** + * Expression de type Booleen qui peut être évaluée. + *

+ * Syntaxe d'une expression logique : opérande1 oprel opérande2 + *

+ * Les expressions logiques concerneront donc toujours deux opérandes + * séparés par un opérateur relationnel (notation infixe). Un opérande + * est soit une constante, soit un identificateur. + *

+ * L'’opérateur relationnel oprel est un symbole parmi : {@code = <> < <= > >=} + * + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heïa Dexter + * @author Lucas Vabre + */ +public class ExpressionBooleenne extends Expression { + + /** Liste des opérateurs relationnels utilisés */ + private static char[] OPERATEURS = { '<', '>', '=' }; + + private static final String ERREUR_ARGUMENT = "une expression ne peut être " + + "vide"; + private static final String ERREUR_SYNTAXE = + "usage \n" + + "avec oprel comme opérateur relationnel " + + "un des symboles suivants : <> < <= > >=" + + "et comme opérandes des constantes, " + + "ou alors des identificateurs"; + private static final String ERREUR_TYPE = "opérande invalide " + + "ou type incompatible"; + private static final String ERREUR_OPERATEUR = "opérateur inconnu"; + + + /** + * Initialise une expression de type Booleen avec les liens + * nécessaires à son calcul. + * + * @param texteExpression l'expression booléenne lue sous forme + * de chaîne + * @throws InterpreteurException si l'expression est vide ou les + * types des opérandes sont incompatibles + * ou si l'opérande droit est manquant + */ + public ExpressionBooleenne(String texteExpression) { + super(); + + String gauche; + String droite; + String aTraiter; + + if (texteExpression == null || texteExpression.isBlank()) { + throw new InterpreteurException(ERREUR_ARGUMENT); + } + + aTraiter = texteExpression.trim(); + + int[] indexOperateurs = affecterOperateur(aTraiter, + detecterOperateurs(aTraiter)); + + if (indexOperateurs[INDEX_OPERATEUR_D] > aTraiter.length() - 2 + || indexOperateurs[INDEX_OPERATEUR_G] <= 0) { + throw new InterpreteurException(aTraiter + ERREUR_SYNTAXE); + } + + gauche = aTraiter.substring(0, indexOperateurs[INDEX_OPERATEUR_G]) + .trim(); + droite = aTraiter.substring(indexOperateurs[INDEX_OPERATEUR_D] + 1) + .trim(); + + if (!isMemeType(gauche, droite)) { + throw new InterpreteurException(ERREUR_TYPE); + } + + initialiserOperande(gauche, INDEX_OPERANDE_G); + initialiserOperande(droite, INDEX_OPERANDE_D); + } + + /** + * Affecte les symboles de l'opérateur à partir des index de indexOperateur + * correspondant à des caractères dans aTraiter. + * @param aTraiter chaîne contenant les opérateurs + * @param indexOperateurs index des symboles de l'opérateur. + * @return tableau d'index avec l'index de début de l'opérateur en indice 0 + * et l'index de la fin de l'opérateur en indice 1. + * Les index peuvent être égaux. + * @throws InterpreteurException si les symboles de l'opérateur ne + * se suivent pas dans aTraiter + * + */ + private int[] affecterOperateur(String aTraiter, int[] indexOperateurs) { + operateur[INDEX_OPERATEUR_G] = indexOperateurs[INDEX_OPERATEUR_G] <= 0 + ? '\u0000' + : aTraiter.charAt(indexOperateurs[INDEX_OPERATEUR_G]); + operateur[INDEX_OPERATEUR_D] = indexOperateurs[INDEX_OPERATEUR_D] <= 0 + ? '\u0000' + : aTraiter.charAt(indexOperateurs[INDEX_OPERATEUR_D]); + + if (indexOperateurs[INDEX_OPERATEUR_G] <= 0) { + indexOperateurs[INDEX_OPERATEUR_G] = + indexOperateurs[INDEX_OPERATEUR_D]; + + } else if (indexOperateurs[INDEX_OPERATEUR_D] <= 0) { + indexOperateurs[INDEX_OPERATEUR_D] = + indexOperateurs[INDEX_OPERATEUR_G]; + } + + if (indexOperateurs[INDEX_OPERATEUR_D] + - indexOperateurs[INDEX_OPERATEUR_G] > 1 + || !isOperateurValide()) { + throw new InterpreteurException(ERREUR_OPERATEUR); + } + return indexOperateurs; + } + + /** + * Prédicat de validité de concordance des symboles + * de l'opérateur à faire un opérateur valide + * @return true si opérateur formé par les symboles est valide, false sinon + */ + private boolean isOperateurValide() { + + final String[] OPERATEUR_VALIDE = { + "<", ">", "<=", ">=", "=", "<>" + }; + + String aTester = ""; + if (operateur[INDEX_OPERATEUR_G] != '\u0000') { + aTester = aTester + operateur[INDEX_OPERATEUR_G]; + } + if (operateur[INDEX_OPERATEUR_D] != '\u0000') { + aTester = aTester + operateur[INDEX_OPERATEUR_D]; + } + + int index; + for (index = 0 ; + index < OPERATEUR_VALIDE.length + && !OPERATEUR_VALIDE[index].equals(aTester); + index++) + ; /* empty body */ + return index < OPERATEUR_VALIDE.length; + } + + /** + * Prédicat de validité de compatibilité + * entre les opérandes gauche et droite + * @param gauche opérande gauche + * @param droit opérande droit + * @return true si deux opérandes sont de même type + * sinon false + */ + private static boolean isMemeType(String gauche, String droit) { + return ( (isIdentificateurEntier(gauche) || isEntier(gauche)) + && (isIdentificateurEntier(droit) || isEntier(droit))) + || + ( (isIdentificateurChaine(gauche) || isChaine(gauche))) + && (isIdentificateurChaine(droit) || isChaine(droit)); + + } + + + /** + * Détecte les opérateurs d'une expression logique + * @param aTraiter chaine dont on cherche les opérateurs + * @return les indexes de début et de fin du premier et unique + * opérateur trouvé + * @throws InterpreteurException s'il l'opérateur est invalide + * ou inexistant + */ + private static int[] detecterOperateurs(String aTraiter) { + int[] index = new int[2]; + char charCourant; + index[INDEX_OPERATEUR_G] = -1; + index[INDEX_OPERATEUR_D] = -1; + int nbGuillemet = 0; + + for (int i = 0 ; i < aTraiter.length() - 1 ; i++) { + charCourant = aTraiter.charAt(i); + + if (charCourant == '"') { + nbGuillemet++; + } + + if (index[INDEX_OPERATEUR_G] < 0 && (nbGuillemet & 1) == 0 + && ( charCourant == OPERATEURS[0] + || charCourant == OPERATEURS[1])) { + index[INDEX_OPERATEUR_G] = i; + } else if ((nbGuillemet & 1) == 0 + && (charCourant == OPERATEURS[1] + || charCourant == OPERATEURS[2])) { + index[INDEX_OPERATEUR_D] = i; + } + } + + if (index[INDEX_OPERATEUR_G] == index[INDEX_OPERATEUR_D]) { + throw new InterpreteurException(ERREUR_OPERATEUR); + } + + return index; + } + + /** + * Initialise l'opérande à sa place dans l'Expression. + * @param operande + * @param index + * @throws IllegalArgumentException si index invalide + */ + private void initialiserOperande(String operande, int index) { + if (INDEX_OPERANDE_G != index && INDEX_OPERANDE_D != index) { + throw new IllegalArgumentException("index invalide"); + } + + if (isIdentificateurEntier(operande)) { + identificateursOperandes[index] = + new IdentificateurEntier(operande); + } else if (isIdentificateurChaine(operande)) { + identificateursOperandes[index] = + new IdentificateurChaine(operande); + } else if (isChaine(operande)) { + litterauxOperandes[index] = new Chaine(operande); + } else { + litterauxOperandes[index] = new Entier(operande); + } + } + + + /* non javadoc + * @see interpreteurlir.expressions.Expression#calculer() + */ + @Override + public Booleen calculer() { + Litteral gauche = litterauxOperandes[INDEX_OPERANDE_G] != null + ? litterauxOperandes[INDEX_OPERANDE_G] + : contexteGlobal.lireValeurVariable( + identificateursOperandes[INDEX_OPERANDE_G]); + Litteral droite = litterauxOperandes[INDEX_OPERANDE_D] != null + ? litterauxOperandes[INDEX_OPERANDE_D] + : contexteGlobal.lireValeurVariable( + identificateursOperandes[INDEX_OPERANDE_D]); + + return new Booleen(calculAvecOperateur(gauche, droite)); + } + + /** + * Calcule la valeur de l'expression selon l'opérateur + * à partir de l'opérande gauche et droite + * Les opérande doivent être du même type. + * @param gauche opérande gauche + * @param droite opérande droite + * @return true si expression true sinon false + */ + private boolean calculAvecOperateur(Litteral gauche, Litteral droite) { + boolean resultat = false; + if (operateur[INDEX_OPERATEUR_G] == OPERATEURS[0]) { + resultat = gauche.compareTo(droite) < 0; + } else if (operateur[INDEX_OPERATEUR_G] == OPERATEURS[1]) { + resultat = gauche.compareTo(droite) > 0; + } + + if (operateur[INDEX_OPERATEUR_D] == OPERATEURS[1]) { + resultat = resultat || gauche.compareTo(droite) > 0; + } else if (operateur[INDEX_OPERATEUR_D] == OPERATEURS[2]) { + resultat = resultat || gauche.compareTo(droite) == 0; + } + + return resultat; + } +} \ No newline at end of file diff --git a/src/interpreteurlir/expressions/ExpressionChaine.java b/src/interpreteurlir/expressions/ExpressionChaine.java index 9825882..f9c6f94 100644 --- a/src/interpreteurlir/expressions/ExpressionChaine.java +++ b/src/interpreteurlir/expressions/ExpressionChaine.java @@ -19,8 +19,11 @@ import interpreteurlir.donnees.litteraux.Chaine; */ public class ExpressionChaine extends Expression { + /** Opérateur possible pour ce type d'expression */ + private static final char OPERATEUR = '+'; + /** - * Initalise une expression de type Chaine + * Initialise une expression de type Chaine * avec les liens nécessaires à son calcul. * @param texteExpression texte suivant la syntaxe d'une expression * @throws InterpreteurException si texteExpression n'est pas valide @@ -50,39 +53,18 @@ public class ExpressionChaine extends Expression { } /* Traitement du nombre d'opérande */ - int indexPlus = indexOperateur(aTraiter, '+'); + int indexPlus = detecterCaractere(aTraiter, '+'); gauche = aTraiter; if (indexPlus > -1) { gauche = aTraiter.substring(0, indexPlus); droite = aTraiter.substring(indexPlus + 1, aTraiter.length()); + operateur[INDEX_OPERANDE_G] = OPERATEUR; initialiserOperande(droite, INDEX_OPERANDE_D); } initialiserOperande(gauche, INDEX_OPERANDE_G); } - /** - * Détermine l'index de l'opérateur en dehors des constantes littérales - * @param aTraiter chaîne à traiter - * @param operateur opérateur à chercher hors guillemet - * @return index dans à traiter du plus sinon -1 si aucun plus - */ - public static int indexOperateur(String aTraiter, char operateur) { - char[] aTester = aTraiter.toCharArray(); - int indexPlus; - int nbGuillemet = 0; - for (indexPlus = 0 ; - indexPlus < aTester.length - && (aTester[indexPlus] != operateur || nbGuillemet % 2 != 0) ; - indexPlus++) { - - if (aTester[indexPlus] == '"') { - nbGuillemet++; - } - } - return indexPlus >= aTester.length ? -1 : indexPlus; - } - /** * Initialise l'opérande à sa place dans l'expression. * @param operande représentation texte de l'opérande @@ -95,7 +77,7 @@ public class ExpressionChaine extends Expression { throw new IllegalArgumentException("index invalide"); } - if (operandeEstLitteral(operande)) { + if (Chaine.isChaine(operande)) { litterauxOperandes[index] = new Chaine(operande); } else { identificateursOperandes[index] = @@ -103,14 +85,6 @@ public class ExpressionChaine extends Expression { } } - /** - * Détermine le genre de l'opérande (Chaine ou IdentificateurChaine). - * @param operande représentation texte de l'opérande - * @return true si operande est du genre Litteral sinon false - */ - private static boolean operandeEstLitteral(String operande) { - return operande.trim().startsWith("\""); - } /* non javadoc * @see interpreteurlir.expressions.Expression#calculer() @@ -149,6 +123,6 @@ public class ExpressionChaine extends Expression { } return valeur; - } + } } diff --git a/src/interpreteurlir/expressions/ExpressionEntier.java b/src/interpreteurlir/expressions/ExpressionEntier.java index 98ca19b..cbcdeeb 100644 --- a/src/interpreteurlir/expressions/ExpressionEntier.java +++ b/src/interpreteurlir/expressions/ExpressionEntier.java @@ -7,11 +7,8 @@ package interpreteurlir.expressions; import interpreteurlir.ExecutionException; import interpreteurlir.InterpreteurException; import interpreteurlir.donnees.Identificateur; -import interpreteurlir.donnees.IdentificateurChaine; import interpreteurlir.donnees.IdentificateurEntier; -import interpreteurlir.donnees.litteraux.Chaine; import interpreteurlir.donnees.litteraux.Entier; -import interpreteurlir.donnees.litteraux.Litteral; /** * Expression de type Entier qui peut être calculer. @@ -32,12 +29,11 @@ public class ExpressionEntier extends Expression { /** Erreur opérande attendue */ private static final String OPERANDE_D_MANQUANT = - " : opérande droit attendu"; + " attend un opérande droit"; - private char operateur; /** - * Initalise une expression de type Entier avec les liens nécessaires à son + * Initialise une expression de type Entier avec les liens nécessaires à son * calcule. * @param texteExpression texte suivant la syntaxe d'une expression * @throws InterpreteurException si texteExpression n'est pas valide @@ -49,8 +45,9 @@ public class ExpressionEntier extends Expression { String droite; String aTraiter; - if (texteExpression == null || texteExpression.isBlank()) + if (texteExpression == null || texteExpression.isBlank()) { throw new InterpreteurException(ERREUR_VIDE); + } aTraiter = texteExpression.trim(); @@ -58,7 +55,8 @@ public class ExpressionEntier extends Expression { int indexEgal = aTraiter.indexOf('='); if (indexEgal > 0) { identificateursOperandes[INDEX_AFFECTATION] = - new IdentificateurEntier(aTraiter.substring(0, indexEgal).trim()); + new IdentificateurEntier(aTraiter.substring(0, indexEgal) + .trim()); aTraiter = aTraiter.substring(indexEgal + 1).trim(); } @@ -67,11 +65,12 @@ public class ExpressionEntier extends Expression { int indexOperateur = detecterOperateur(aTraiter); gauche = aTraiter.trim(); if (indexOperateur > 0) { - operateur = aTraiter.charAt(indexOperateur); + operateur[INDEX_OPERATEUR_G] = aTraiter.charAt(indexOperateur); gauche = aTraiter.substring(0, indexOperateur).trim(); - if (aTraiter.length() - 1 <= indexOperateur) + if (aTraiter.length() - 1 <= indexOperateur) { throw new ExecutionException(aTraiter + OPERANDE_D_MANQUANT); + } droite = aTraiter.substring(indexOperateur + 1).trim(); initialiserOperande(droite, INDEX_OPERANDE_D); @@ -88,9 +87,11 @@ public class ExpressionEntier extends Expression { */ private static int detecterOperateur(String expression) { for (int i = 1 ; i < expression.length() ; i++) { - for (char operateur : OPERATEURS) - if (operateur == expression.charAt(i)) + for (char operateur : OPERATEURS) { + if (operateur == expression.charAt(i)) { return i; + } + } } return -1; @@ -98,15 +99,15 @@ public class ExpressionEntier extends Expression { /** * Initialise l'opérande à sa place dans l'expression. - * @param droite - * @param indexOperandeD + * @param operande opérande à initialiser + * @param index de l'opérande */ private void initialiserOperande(String operande, int index) { if (INDEX_OPERANDE_G != index && INDEX_OPERANDE_D != index) { throw new IllegalArgumentException("index invalide"); } - if (operandeEstLitteral(operande)) { + if (Entier.isEntier(operande)) { litterauxOperandes[index] = new Entier(operande); } else { identificateursOperandes[index] = @@ -115,17 +116,6 @@ public class ExpressionEntier extends Expression { } - /** - * Détermine si l'opérande est un littéral de type entier - * @param operande à tester - * @return true si l'operande commence par +, - ou un chiffre, - * false dans le cas contraire. - */ - private static boolean operandeEstLitteral(String operande) { - char aTester = operande.charAt(0); - return Character.isDigit(aTester) || aTester == '-' || aTester == '+'; - } - /* non javadoc * @see interpreteurlir.expressions.Expression#calculer() */ @@ -154,7 +144,7 @@ public class ExpressionEntier extends Expression { /* Calcul de la valeur */ valeur = operandeD == null ? operandeG - : switch (operateur) { + : switch (operateur[INDEX_OPERATEUR_G]) { case '+' -> Entier.somme(operandeG, operandeD); case '-' -> Entier.soustrait(operandeG, operandeD); case '*' -> Entier.multiplie(operandeG, operandeD); @@ -172,30 +162,4 @@ public class ExpressionEntier extends Expression { return valeur; } - /* - * Non - javadoc - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder resultat = new StringBuilder(""); - - Identificateur affect = identificateursOperandes[INDEX_AFFECTATION]; - resultat.append(affect == null ? "" : (affect.toString() + " = ")); - - Identificateur gaucheId = identificateursOperandes[INDEX_OPERANDE_G]; - Litteral gaucheLitteral = litterauxOperandes[INDEX_OPERANDE_G]; - resultat.append(gaucheId != null ? gaucheId.toString() - : gaucheLitteral.toString()); - - Identificateur droiteId = identificateursOperandes[INDEX_OPERANDE_D]; - Litteral droiteLitteral = litterauxOperandes[INDEX_OPERANDE_D]; - if (droiteId != null || droiteLitteral != null) { - resultat.append(" " + operateur + " "); - resultat.append(droiteId != null ? droiteId.toString() - : droiteLitteral.toString()); - } - - return resultat.toString(); - } } \ No newline at end of file diff --git a/src/interpreteurlir/expressions/tests/TestExpression.java b/src/interpreteurlir/expressions/tests/TestExpression.java index 81027c0..9d464be 100644 --- a/src/interpreteurlir/expressions/tests/TestExpression.java +++ b/src/interpreteurlir/expressions/tests/TestExpression.java @@ -21,23 +21,6 @@ import interpreteurlir.Contexte; */ public class TestExpression { - /** Jeu d'essai d'expression typée */ - private Expression[] fixture = { - new ExpressionChaine("$chaine = \"texte\""), - new ExpressionChaine("$chaine=\"tata\""), - new ExpressionChaine(" $tata \t "), - new ExpressionChaine("\"une chaine de texte\""), - new ExpressionChaine("$chaine= \"toto\"+\"titi\""), - new ExpressionChaine("$chaine= $toto +\"titi\""), - new ExpressionChaine("$chaine= \"toto\"+ $titi"), - new ExpressionChaine("$chaine=$toto +$titi"), - new ExpressionChaine(" \"toto\"+\"titi\""), - new ExpressionChaine("$toto +\"titi\""), - new ExpressionChaine("\"toto\"+ $titi"), - new ExpressionChaine("$toto + $titi"), - // TODO expression entière - }; - /** * Tests unitaires de {@link Expression#referencerContexte(Contexte)} */ @@ -58,32 +41,6 @@ public class TestExpression { } } - /** - * Tests unitaires de {@link Expression#toString()} - */ - public void testToString() { - final String[] chaineAttendue = { - "$chaine = \"texte\"", - "$chaine = \"tata\"", - "$tata", - "\"une chaine de texte\"", - "$chaine = \"toto\" + \"titi\"", - "$chaine = $toto + \"titi\"", - "$chaine = \"toto\" + $titi", - "$chaine = $toto + $titi", - "\"toto\" + \"titi\"", - "$toto + \"titi\"", - "\"toto\" + $titi", - "$toto + $titi" - }; - - System.out.println("\tExécution du test de Expression#toString()"); - for (int numTest = 0 ; numTest < chaineAttendue.length ; numTest++) { - assertEquivalence(chaineAttendue[numTest], - fixture[numTest].toString()); - } - } - /** * Tests unitaires de {@link Expression#determinerTypeExpression(String)} */ diff --git a/src/interpreteurlir/expressions/tests/TestExpressionBooleenne.java b/src/interpreteurlir/expressions/tests/TestExpressionBooleenne.java new file mode 100644 index 0000000..c5aea0d --- /dev/null +++ b/src/interpreteurlir/expressions/tests/TestExpressionBooleenne.java @@ -0,0 +1,467 @@ +/** + * TestExpressionBooleenne.java 21 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.expressions.tests; + +import interpreteurlir.Contexte; +import interpreteurlir.InterpreteurException; +import interpreteurlir.donnees.IdentificateurChaine; +import interpreteurlir.donnees.IdentificateurEntier; +import interpreteurlir.donnees.litteraux.Chaine; +import interpreteurlir.donnees.litteraux.Entier; +import interpreteurlir.expressions.Expression; +import interpreteurlir.expressions.ExpressionBooleenne; +import static info1.outils.glg.Assertions.*; + +/** + * Tests unitaires des méthodes de la classe ExpressionBooleenne + * + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heia Dexter + * @author Lucas Vabre + */ +public class TestExpressionBooleenne { + + private final ExpressionBooleenne[] FIXTURE_LITTERALE = { + /* Expression logique sur des Entiers AVEC ESPACES */ + new ExpressionBooleenne("1 = 1"), // true + new ExpressionBooleenne("1 = 2"), // false + new ExpressionBooleenne("1 < 2"), + new ExpressionBooleenne("1 < 1"), + new ExpressionBooleenne("1 <> 2"), + new ExpressionBooleenne("1 <> 1"), + new ExpressionBooleenne("1 <= 1"), + new ExpressionBooleenne("1 <= 5"), + new ExpressionBooleenne("1 > -3"), + new ExpressionBooleenne("1 > 56"), + new ExpressionBooleenne("1 >= 1"), + new ExpressionBooleenne("1 >= 45"), + /* Expression logique sur des Entiers SANS ESPACES */ + new ExpressionBooleenne("1=1"), + new ExpressionBooleenne("1=2"), + new ExpressionBooleenne("1<2"), + new ExpressionBooleenne("1<1"), + new ExpressionBooleenne("1<>2"), + new ExpressionBooleenne("1<>1"), + new ExpressionBooleenne("1<=1"), + new ExpressionBooleenne("1<=5"), + new ExpressionBooleenne("1>-3"), + new ExpressionBooleenne("1>56"), + new ExpressionBooleenne("1>=1"), + new ExpressionBooleenne("1>=45"), + /* Expression logique sur des Entiers MOITIE ESPACES */ + new ExpressionBooleenne(" 1=1"), + new ExpressionBooleenne("1=2 "), + new ExpressionBooleenne("1 <2"), + new ExpressionBooleenne("1< 1"), + new ExpressionBooleenne("1 <>2"), + new ExpressionBooleenne("1<> 1"), + new ExpressionBooleenne(" 1<=1 "), + new ExpressionBooleenne("1 <= 5"), + new ExpressionBooleenne(" 1 > -3 "), + new ExpressionBooleenne("1>56\t"), + new ExpressionBooleenne(" 1 >= 1 "), + new ExpressionBooleenne(" 1 >= 45 "), + + /* Expression logique sur des Chaines AVEC ESPACES */ + new ExpressionBooleenne("\"TATA\" = \"TATA\""), + new ExpressionBooleenne("\"TATA\" = \"TITI\""), + new ExpressionBooleenne("\"TATA\" < \"TITI\""), + new ExpressionBooleenne("\"TOTO\" < \"TITI\""), + new ExpressionBooleenne("\"TOTO\" <> \"TATA\""), + new ExpressionBooleenne("\"TATA\" <> \"TATA\""), + new ExpressionBooleenne("\"TATA\" <= \"TATA\""), + new ExpressionBooleenne("\"TITI\" <= \"TATA\""), + new ExpressionBooleenne("\"TATA\" > \"FOO BAR\""), + new ExpressionBooleenne("\"FOO BAR\" > \"TATA\""), + new ExpressionBooleenne("\"TATA\" >= \"TATA\""), + new ExpressionBooleenne("\"FOO BAR\" >= \"TATA\""), + /* Expression logique sur des Chaines SANS ESPACES */ + new ExpressionBooleenne("\"TATA\"=\"TATA\""), + new ExpressionBooleenne("\"TATA\"=\"TITI\""), + new ExpressionBooleenne("\"TATA\"<\"TITI\""), + new ExpressionBooleenne("\"TOTO\"<\"TITI\""), + new ExpressionBooleenne("\"TOTO\"<>\"TATA\""), + new ExpressionBooleenne("\"TATA\"<>\"TATA\""), + new ExpressionBooleenne("\"TATA\"<=\"TATA\""), + new ExpressionBooleenne("\"TITI\"<=\"TATA\""), + new ExpressionBooleenne("\"TATA\">\"FOO BAR\""), + new ExpressionBooleenne("\"FOO BAR\">\"TATA\""), + new ExpressionBooleenne("\"TATA\">=\"TATA\""), + new ExpressionBooleenne("\"FOO BAR\">=\"TATA\""), + /* Expression logique sur des Chaines MOITIE ESPACES */ + new ExpressionBooleenne(" \"TATA\" = \"TATA\""), + new ExpressionBooleenne("\"TATA\" = \"TITI\""), + new ExpressionBooleenne("\"TATA\" < \"TITI\""), + new ExpressionBooleenne("\"TOTO\" < \"TITI\" "), + new ExpressionBooleenne(" \"TOTO\"<> \"TATA\" "), + new ExpressionBooleenne("\"TATA\" <> \"TATA\" "), + new ExpressionBooleenne(" \"TATA\" <=\"TATA\""), + new ExpressionBooleenne("\"TITI\" <= \"TATA\""), + new ExpressionBooleenne(" \"TATA\" > \"FOO BAR\""), + new ExpressionBooleenne(" \"FOO BAR \" > \"TATA\""), + new ExpressionBooleenne("\"TATA\" >= \"TATA\""), + new ExpressionBooleenne(" \"FOO BAR\" >= \"TATA\""), + /* Expression logique sur des Chaines AVEC OPERATEURS */ + new ExpressionBooleenne("\"FOO BAR\"<>\"TATA=TOTO\""), + new ExpressionBooleenne("\"FOO BAR=FLEMME\">\"TOTO\""), + new ExpressionBooleenne("\"FOO BAR > FLEMME\"=\"TOTO\""), + new ExpressionBooleenne("\"FOO BAR<>FLEMME\">\"TOTO\""), + + }; + + private final ExpressionBooleenne[] FIXTURE_ID = { + /* Expression logique sur des IdEntier et Entiers */ + new ExpressionBooleenne("marcel <= 10"), // true + new ExpressionBooleenne("marcel > j34n"), // false + new ExpressionBooleenne("2 = pi3rr3"), + new ExpressionBooleenne("j34n = pi3rr3"), + /* Expression logique sur des IdChaine et Chaines */ + new ExpressionBooleenne("$sanchis < $barrios"), + new ExpressionBooleenne("$servieres > \"Windows\""), + new ExpressionBooleenne("$barrios <> $servieres"), + new ExpressionBooleenne("\"coucou\" = $barrios"), + }; + + /** + * Tests unitaire de {@link ExpressionBooleenne#ExpressionBooleenne(String)} + */ + public void testExpressionBooleenne() { + + final String[] INVALIDES = { + /* Pas d'opérateur */ + "", + "2 5", + "\"John Doe\"", + "\"Foo bar\" $serpillere", + "entier -20", + /* Opérateurs invalides */ + "-89 + 67", + "-8979 % 7", + "35 * 12", + "89 / 12", + "65 - 74", + "\"Foo bar\" + $serpillere", + "ab >> cd", + /* Expressions logiques avec opérateurs invalides */ + "78 < = 45", + "entier > = 56", + "\"Foo bar\" < > $serpillere", + "$coucou >< $dollarchaine", + "78 => 45", + "32 =< 61", + "32 == 61", + /* Plus de 2 opérandes et 1 opérateur */ + "65 <> 45 = 45", + "entier > 85 && 45 = 12", + "entier <= 85 || 45 <> 12", + /* Caractères entre les opérandes et l'opérateur */ + "\"Foo bar\" . > $serpillere", + "\"Foo bar\" < _ $serpillere", + "\"Foo bar\" + $balai > serpillere", + /* opérande manquant */ + ">= entier", + "entier =", + "<>", + /* Incompatibilité entre types d'opérandes */ + "\"Foo bar\" > serpillere", + "serpillere <> \"Foo bar\"", + "15 > $coucou", + "\"coucou\" <> 45", + "$coucou = entier" + }; + + System.out.println("\tExécution du test de ExpressionBooleenne()"); + + for (String aTester : INVALIDES) { + try { + new ExpressionBooleenne(aTester); + echec(); + } catch (InterpreteurException lancee) { + // Test OK + } + } + + try { + /* Expression logique sur des Entiers AVEC ESPACES */ + new ExpressionBooleenne("1 = 1"); // true + new ExpressionBooleenne("1 = 2"); // false + new ExpressionBooleenne("1 < 2"); + new ExpressionBooleenne("1 < 1"); + new ExpressionBooleenne("1 <> 2"); + new ExpressionBooleenne("1 <> 1"); + new ExpressionBooleenne("1 <= 1"); + new ExpressionBooleenne("1 <= 5"); + new ExpressionBooleenne("1 > -3"); + new ExpressionBooleenne("1 > 56"); + new ExpressionBooleenne("1 >= 1"); + new ExpressionBooleenne("1 >= 45"); + /* Expression logique sur des Entiers SANS ESPACES */ + new ExpressionBooleenne("1=1"); + new ExpressionBooleenne("1=2"); + new ExpressionBooleenne("1<2"); + new ExpressionBooleenne("1<1"); + new ExpressionBooleenne("1<>2"); + new ExpressionBooleenne("1<>1"); + new ExpressionBooleenne("1<=1"); + new ExpressionBooleenne("1<=5"); + new ExpressionBooleenne("1>-3"); + new ExpressionBooleenne("1>56"); + new ExpressionBooleenne("1>=1"); + new ExpressionBooleenne("1>=45"); + /* Expression logique sur des Entiers MOITIE ESPACES */ + new ExpressionBooleenne(" 1=1"); + new ExpressionBooleenne("1=2 "); + new ExpressionBooleenne("1 <2"); + new ExpressionBooleenne("1< 1"); + new ExpressionBooleenne("1 <>2"); + new ExpressionBooleenne("1<> 1"); + new ExpressionBooleenne(" 1<=1 "); + new ExpressionBooleenne("1 <= 5"); + new ExpressionBooleenne(" 1 > -3 "); + new ExpressionBooleenne("1>56\t"); + new ExpressionBooleenne(" 1 >= 1 "); + new ExpressionBooleenne(" 1 >= 45 "); + + /* Expression logique sur des Chaines AVEC ESPACES */ + new ExpressionBooleenne("\"TATA\" = \"TATA\""); + new ExpressionBooleenne("\"TATA\" = \"TITI\""); + new ExpressionBooleenne("\"TATA\" < \"TITI\""); + new ExpressionBooleenne("\"TOTO\" < \"TITI\""); + new ExpressionBooleenne("\"TOTO\" <> \"TATA\""); + new ExpressionBooleenne("\"TATA\" <> \"TATA\""); + new ExpressionBooleenne("\"TATA\"<=\"TATA\""); + new ExpressionBooleenne("\"TITI\" <= \"TATA\""); + new ExpressionBooleenne("\"TATA\" > \"FOO BAR\""); + new ExpressionBooleenne("\"FOO BAR\" > \"TATA\""); + new ExpressionBooleenne("\"TATA\" >= \"TATA\""); + new ExpressionBooleenne("\"FOO BAR\" >= \"TATA\""); + /* Expression logique sur des Chaines SANS ESPACES */ + new ExpressionBooleenne("\"TATA\"=\"TATA\""); + new ExpressionBooleenne("\"TATA\"=\"TITI\""); + new ExpressionBooleenne("\"TATA\"<\"TITI\""); + new ExpressionBooleenne("\"TOTO\"<\"TITI\""); + new ExpressionBooleenne("\"TOTO\"<>\"TATA\""); + new ExpressionBooleenne("\"TATA\"<>\"TATA\""); + new ExpressionBooleenne("\"TATA\"<=\"TATA\""); + new ExpressionBooleenne("\"TITI\"<=\"TATA\""); + new ExpressionBooleenne("\"TATA\">\"FOO BAR\""); + new ExpressionBooleenne("\"FOO BAR\">\"TATA\""); + new ExpressionBooleenne("\"TATA\">=\"TATA\""); + new ExpressionBooleenne("\"FOO BAR\">=\"TATA\""); + /* Expression logique sur des Chaines MOITIE ESPACES */ + new ExpressionBooleenne(" \"TATA\" = \"TATA\""); + new ExpressionBooleenne("\"TATA\" = \"TITI\""); + new ExpressionBooleenne("\"TATA\" < \"TITI\""); + new ExpressionBooleenne("\"TOTO\" < \"TITI\" "); + new ExpressionBooleenne(" \"TOTO\"<> \"TATA\" "); + new ExpressionBooleenne("\"TATA\" <> \"TATA\" "); + new ExpressionBooleenne(" \"TATA\" <=\"TATA\""); + new ExpressionBooleenne("\"TITI\" <= \"TATA\""); + new ExpressionBooleenne(" \"TATA\" > \"FOO BAR\""); + new ExpressionBooleenne(" \"FOO BAR \" > \"TATA\""); + new ExpressionBooleenne("\"TATA\" >= \"TATA\""); + new ExpressionBooleenne(" \"FOO BAR\" >= \"TATA\""); + /* Expression logique sur des Chaines AVEC OPERATEURS */ + new ExpressionBooleenne("\"FOO BAR\"<>\"TATA=TOTO\""); + new ExpressionBooleenne("\"FOO BAR=FLEMME\">\"TOTO\""); + new ExpressionBooleenne("\"FOO BAR > FLEMME\"=\"TOTO\""); + new ExpressionBooleenne("\"FOO BAR<>FLEMME\">\"TOTO\""); + + /* Expression logique sur des IdEntier et Entiers */ + new ExpressionBooleenne("marcel <= 10"); // true + new ExpressionBooleenne("marcel > j34n"); // false + new ExpressionBooleenne("2 = pi3rr3"); + new ExpressionBooleenne("j34n = pi3rr3"); + /* Expression logique sur des IdChaine et Chaines */ + new ExpressionBooleenne("$sanchis < $barrios"); + new ExpressionBooleenne("$servieres > \"Windows\""); + new ExpressionBooleenne("$barrios <> $servieres"); + new ExpressionBooleenne("\"coucou\" = $barrios"); + } catch (InterpreteurException lancee) { + echec(); + } + } + + /** + * Tests unitaire de {@link ExpressionBooleenne#calculer()} + */ + public void testCalculer() { + + final Boolean[] VALEUR_ATTENDU_ID = { + true, false, true, false, true, false, true, false + }; + + + Contexte contexteGlobal = new Contexte(); + contexteGlobal.ajouterVariable(new IdentificateurEntier("marcel"), + new Entier(0)); + contexteGlobal.ajouterVariable(new IdentificateurEntier("j34n"), + new Entier(1)); + contexteGlobal.ajouterVariable(new IdentificateurEntier("pi3rr3"), + new Entier(2)); + contexteGlobal.ajouterVariable(new IdentificateurChaine("$sanchis"), + new Chaine("\"coucou\"")); + contexteGlobal.ajouterVariable(new IdentificateurChaine("$barrios"), + new Chaine("\"java\"")); + contexteGlobal.ajouterVariable(new IdentificateurChaine("$servieres"), + new Chaine("\"WinDesign\"")); + Expression.referencerContexte(contexteGlobal); + + System.out.println("\tExécution du test de Calculer()"); + for (int numTest = 0 ; numTest < VALEUR_ATTENDU_ID.length ; numTest++) { + assertEquivalence(VALEUR_ATTENDU_ID[numTest], + FIXTURE_ID[numTest].calculer().getValeur()); + } + + final ExpressionBooleenne[] A_TESTER = { + new ExpressionBooleenne("1=1"), + new ExpressionBooleenne("1=2"), + new ExpressionBooleenne("1<2"), + new ExpressionBooleenne("1<1"), + new ExpressionBooleenne("1<>2"), + new ExpressionBooleenne("1<>1"), + new ExpressionBooleenne("1<=1"), + new ExpressionBooleenne("1<=5"), + new ExpressionBooleenne("1>-3"), + new ExpressionBooleenne("1>56"), + new ExpressionBooleenne("1>=1"), + new ExpressionBooleenne("1>=45"), + new ExpressionBooleenne("\"TATA\" = \"TATA\""), + new ExpressionBooleenne("\"TATA\" = \"TITI\""), + new ExpressionBooleenne("\"TATA\" < \"TITI\""), + new ExpressionBooleenne("\"TOTO\" < \"TITI\""), + new ExpressionBooleenne("\"TOTO\" <> \"TATA\""), + new ExpressionBooleenne("\"TATA\" <> \"TATA\""), + new ExpressionBooleenne("\"TATA\"<=\"TATA\""), + new ExpressionBooleenne("\"TITI\" <= \"TATA\""), + new ExpressionBooleenne("\"TATA\" > \"FOO BAR\""), + new ExpressionBooleenne("\"FOO BAR\" > \"TATA\""), + new ExpressionBooleenne("\"TATA\" >= \"TATA\""), + new ExpressionBooleenne("\"FOO BAR\" >= \"TATA\""), + }; + + final Boolean[] VALEUR_ATTENDU_L = { + true, false, true, false, true, false, + true, true, true, false, true, false, + + true, false, true, false, true, false, + true, false, true, false, true, false + }; + + for (int numTest = 0 ; numTest < A_TESTER.length ; numTest++) { + assertEquivalence(VALEUR_ATTENDU_L[numTest], + A_TESTER[numTest].calculer().getValeur()); + } + } + + /** + * Tests unitaire de {@link ExpressionBooleenne#toString()} + */ + public void testToString() { + System.out.println("\tExécution du test de toString()"); + + final String[] ATTENDU_L = { + "1 = 1", + "1 = 2", + "1 < 2", + "1 < 1", + "1 <> 2", + "1 <> 1", + "1 <= 1", + "1 <= 5", + "1 > -3", + "1 > 56", + "1 >= 1", + "1 >= 45", + "1 = 1", + "1 = 2", + "1 < 2", + "1 < 1", + "1 <> 2", + "1 <> 1", + "1 <= 1", + "1 <= 5", + "1 > -3", + "1 > 56", + "1 >= 1", + "1 >= 45", + "1 = 1", + "1 = 2", + "1 < 2", + "1 < 1", + "1 <> 2", + "1 <> 1", + "1 <= 1", + "1 <= 5", + "1 > -3", + "1 > 56", + "1 >= 1", + "1 >= 45", + "\"TATA\" = \"TATA\"", + "\"TATA\" = \"TITI\"", + "\"TATA\" < \"TITI\"", + "\"TOTO\" < \"TITI\"", + "\"TOTO\" <> \"TATA\"", + "\"TATA\" <> \"TATA\"", + "\"TATA\" <= \"TATA\"", + "\"TITI\" <= \"TATA\"", + "\"TATA\" > \"FOO BAR\"", + "\"FOO BAR\" > \"TATA\"", + "\"TATA\" >= \"TATA\"", + "\"FOO BAR\" >= \"TATA\"", + "\"TATA\" = \"TATA\"", + "\"TATA\" = \"TITI\"", + "\"TATA\" < \"TITI\"", + "\"TOTO\" < \"TITI\"", + "\"TOTO\" <> \"TATA\"", + "\"TATA\" <> \"TATA\"", + "\"TATA\" <= \"TATA\"", + "\"TITI\" <= \"TATA\"", + "\"TATA\" > \"FOO BAR\"", + "\"FOO BAR\" > \"TATA\"", + "\"TATA\" >= \"TATA\"", + "\"FOO BAR\" >= \"TATA\"", + "\"TATA\" = \"TATA\"", + "\"TATA\" = \"TITI\"", + "\"TATA\" < \"TITI\"", + "\"TOTO\" < \"TITI\"", + "\"TOTO\" <> \"TATA\"", + "\"TATA\" <> \"TATA\"", + "\"TATA\" <= \"TATA\"", + "\"TITI\" <= \"TATA\"", + "\"TATA\" > \"FOO BAR\"", + "\"FOO BAR \" > \"TATA\"", + "\"TATA\" >= \"TATA\"", + "\"FOO BAR\" >= \"TATA\"", + "\"FOO BAR\" <> \"TATA=TOTO\"", + "\"FOO BAR=FLEMME\" > \"TOTO\"", + "\"FOO BAR > FLEMME\" = \"TOTO\"", + "\"FOO BAR<>FLEMME\" > \"TOTO\"", + }; + + for (int numTest = 0 ; numTest < ATTENDU_L.length ; numTest++) { + assertEquivalence(ATTENDU_L[numTest], + FIXTURE_LITTERALE[numTest].toString()); + } + + final String[] ATTENDU_I = { + "marcel <= 10", + "marcel > j34n", + "2 = pi3rr3", + "j34n = pi3rr3", + "$sanchis < $barrios", + "$servieres > \"Windows\"", + "$barrios <> $servieres", + "\"coucou\" = $barrios", + }; + + for (int numTest = 0 ; numTest < ATTENDU_I.length ; numTest++) { + assertEquivalence(ATTENDU_I[numTest], + FIXTURE_ID[numTest].toString()); + } + } +} \ No newline at end of file diff --git a/src/interpreteurlir/expressions/tests/TestExpressionChaine.java b/src/interpreteurlir/expressions/tests/TestExpressionChaine.java index 08d0788..439f90c 100644 --- a/src/interpreteurlir/expressions/tests/TestExpressionChaine.java +++ b/src/interpreteurlir/expressions/tests/TestExpressionChaine.java @@ -141,4 +141,33 @@ public class TestExpressionChaine { } } + + /** + * Tests unitaires de {@link ExpressionChaine#toString()} + */ + public void testToString() { + final String[] chaineAttendue = { + "$chaine = \"texte\"", + "$chaine = \"tata\"", + "$tata", + "\"une chaine de texte\"", + "$chaine = \"toto\" + \"titi\"", + "$chaine = $toto + \"titi\"", + "$chaine = \"toto\" + $titi", + "$chaine = $toto + $titi", + "\"toto\" + \"titi\"", + "$toto + \"titi\"", + "\"toto\" + $titi", + "$toto + $titi", + "\"ab=bc\"", + "$chaine = \"ab+cd\" + $toto", + }; + + System.out.println("\tExécution du test de " + + "ExpressionChaine#toString()"); + for (int numTest = 0 ; numTest < chaineAttendue.length ; numTest++) { + assertEquivalence(chaineAttendue[numTest], + fixture[numTest].toString()); + } + } } diff --git a/src/interpreteurlir/expressions/tests/TestExpressionEntier.java b/src/interpreteurlir/expressions/tests/TestExpressionEntier.java index dbf5937..8c5ff81 100644 --- a/src/interpreteurlir/expressions/tests/TestExpressionEntier.java +++ b/src/interpreteurlir/expressions/tests/TestExpressionEntier.java @@ -9,10 +9,7 @@ import static info1.outils.glg.Assertions.*; import interpreteurlir.Contexte; import interpreteurlir.ExecutionException; import interpreteurlir.InterpreteurException; -import interpreteurlir.donnees.Identificateur; -import interpreteurlir.donnees.IdentificateurChaine; import interpreteurlir.donnees.IdentificateurEntier; -import interpreteurlir.donnees.litteraux.Chaine; import interpreteurlir.donnees.litteraux.Entier; import interpreteurlir.expressions.Expression; import interpreteurlir.expressions.ExpressionEntier; @@ -67,7 +64,8 @@ public class TestExpressionEntier { "divisionRatee = 5 /", "ratee=*7", }; - + System.out.println("\tExécution du test de " + + "ExpressionEntier#ExpressionEntier(String)"); for (String invalide : INVALIDES) { try { new ExpressionEntier(invalide); @@ -99,6 +97,9 @@ public class TestExpressionEntier { new Entier(0) // Bouchon }; + System.out.println("\tExécution du test de " + + "ExpressionEntier#calculer()"); + /* Exception levée si contexte non référencé */ try { FIXTURE[0].calculer(); @@ -153,6 +154,9 @@ public class TestExpressionEntier { "modulo = 12 % 0" }; + System.out.println("\tExécution du test de " + + "ExpressionEntier#toString()"); + for (int i = 0 ; i < FIXTURE.length ; i++) { assertTrue(FIXTURE[i].toString().equals(ATTENDUES[i])); } diff --git a/src/interpreteurlir/motscles/Commande.java b/src/interpreteurlir/motscles/Commande.java index 4cfa3a1..ac74d4c 100644 --- a/src/interpreteurlir/motscles/Commande.java +++ b/src/interpreteurlir/motscles/Commande.java @@ -19,7 +19,7 @@ import interpreteurlir.programmes.Programme; * @author Heïa Dexter * @author Lucas Vabre */ -public class Commande { +public abstract class Commande { /** référence du programme global */ protected static Programme programmeGlobal; @@ -52,10 +52,7 @@ public class Commande { * @return true si la commande affiche un feedback directement sur la sortie * standard, sinon false */ - public boolean executer() { - // pas de comportement pour une Commande générale - return false; // pas de feedback - } + public abstract boolean executer(); /** * Référence le programme pour accéder et modifier le programme chargé. diff --git a/src/interpreteurlir/motscles/CommandeCharge.java b/src/interpreteurlir/motscles/CommandeCharge.java new file mode 100644 index 0000000..1086a2d --- /dev/null +++ b/src/interpreteurlir/motscles/CommandeCharge.java @@ -0,0 +1,167 @@ +/** + * CommandeCharge.java 21 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.motscles; + +import interpreteurlir.Contexte; +import interpreteurlir.ExecutionException; +import interpreteurlir.InterpreteurException; +import interpreteurlir.motscles.instructions.Instruction; +import interpreteurlir.programmes.Etiquette; +import interpreteurlir.Analyseur; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; + +/** + * Charge les lignes de programme dans le fichier texte indiqué en argument + * + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heia Dexter + * @author Lucas Vabre + */ +public class CommandeCharge extends Commande{ + + /** Chemin du fichier dans lequel sera le programme chargé */ + private String cheminFichier; + + /** + * Initialise la commande Charge a partir de ses argument et + * de son contexte passé en paramètre. + * @param arguments Chemin du fichier dans lequel sera le programme chargé + * @param contexte Contexte du programme + * @throws InterpreteurException Si l'argument est null, vide, + * contient uniquement des espaces ou + * ne se termine pas par ".lir". + */ + public CommandeCharge(String arguments, Contexte contexte ) { + super(arguments, contexte); + + final String extension = ".lir"; + + if (arguments == null + || arguments.isEmpty() + || arguments.isBlank() + || !arguments.trim().endsWith(extension)) { + + throw new InterpreteurException("\t" + arguments + + " n'est pas un chemin valide"); + } + + this.cheminFichier = arguments.trim(); + } + + /** + * Charge le programme contenu dans le fichier de this + * @return false car elle n'affiche aucun feedback directement + * @throws InterpreteurException Si le fichier a charger n'as pas été trouvé + */ + public boolean executer() { + + programmeGlobal.raz(); + + /* Chemin du fichier */ + String nomFichier = new File(cheminFichier).getAbsolutePath(); + + /* Fichier logique en entrée */ + BufferedReader entree; + + entree = null; + try { + entree = new BufferedReader( + new InputStreamReader( + new FileInputStream(nomFichier))); + analyserFichier(entree); + entree.close(); + } catch (IOException e) { + throw new InterpreteurException(nomFichier + " est introuvable"); + } + + return false; + } + + /** + * Analyse chaque ligne de l'entrée et les ajoute dans programme global + * @param entree Tampon du fichier à lire + * @throws IOException Problème de lecture du fichier + */ + private void analyserFichier(BufferedReader entree) throws IOException { + + /* Index de la ligne découpée */ + final int ETIQUETTE = 0; + final int MOT_CLE = 1; + final int ARGUMENT = 2; + + String ligneLue; + int numLigne = 0; + + do { + ligneLue = entree.readLine(); + if (ligneLue != null && !ligneLue.isBlank()) { + numLigne++; + + String[] decoupage = splitter(ligneLue); + + Class aAjouter; + try { + aAjouter = Analyseur + .rechercheInstruction(decoupage[MOT_CLE]); + + Class classeArg = String.class; + Class classeContexte = Contexte.class; + Instruction inst = (Instruction)aAjouter + .getConstructor(classeArg, classeContexte) + .newInstance(decoupage[ARGUMENT], contexte); + + Etiquette etiquette = new Etiquette(decoupage[ETIQUETTE]); + + programmeGlobal.ajouterLigne(etiquette, inst); + } catch (InvocationTargetException| IllegalAccessException + |InstantiationException | NoSuchMethodException + |InterpreteurException | ExecutionException lancee) { + programmeGlobal.raz(); + throw new InterpreteurException(ligneLue + " => ligne " + + numLigne); + } + } + } while (ligneLue != null); + } + + /** + * Sépare la ligne en etiquette/mot clé/argument + * @param ligneLue + * @return Tableau comportant en : + *

  • indice 1 : l'étiquette
  • + *
  • indice 2 : mot clé
  • + *
  • indice 3 : argument
+ * @throws InterpreteurException Si la ligne ne contient pas les 2 éléments: + *
  • Etiquette
  • + *
  • Mot clé
+ */ + private static String[] splitter(String ligneLue) { + /* Sépare l'étiquette, la commande et l'argument */ + String[] ligne = ligneLue.split(" ", 3); + + if (ligne.length < 2) { + programmeGlobal.raz(); + throw new InterpreteurException(ligneLue + " n'est pas " + + "une ligne valide"); + } + + String[] decoupage = new String[3]; + + /* Ajouter la ligne dans le contexte */ + decoupage[0] = ligne[0]; + decoupage[1] = ligne[1]; + decoupage[2] = ligne.length >= 3 ? ligne[2] : ""; + + return decoupage; + } +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/CommandeDebut.java b/src/interpreteurlir/motscles/CommandeDebut.java index 90fa70c..657e854 100644 --- a/src/interpreteurlir/motscles/CommandeDebut.java +++ b/src/interpreteurlir/motscles/CommandeDebut.java @@ -39,7 +39,6 @@ public class CommandeDebut extends Commande { } } - /** * Commande d'exécution de la commande. * Efface le contexte. @@ -52,4 +51,4 @@ public class CommandeDebut extends Commande { return false; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/CommandeEfface.java b/src/interpreteurlir/motscles/CommandeEfface.java index 4c8274e..78f5802 100644 --- a/src/interpreteurlir/motscles/CommandeEfface.java +++ b/src/interpreteurlir/motscles/CommandeEfface.java @@ -21,7 +21,7 @@ public class CommandeEfface extends Commande { /** Erreur nombre incorrect d'arguments */ private static final String ERREUR_NB_ARGS = - "nombre d'arguments incorrect. Syntaxe attendue ==> :"; + "usage efface <étiquette_début>:<étiquette_fin>"; /** Plage de suppression des lignes de code */ private Etiquette[] plageSuppression; @@ -31,7 +31,7 @@ public class CommandeEfface extends Commande { * contexte passés en paramètres. Modifie le programme global référencé * par l'analyseur. * @param arguments lignes à effacer (tout le programme si vide) - * @param contexte + * @param contexte référence du contexte global */ public CommandeEfface(String arguments, Contexte contexte) { super(arguments, contexte); diff --git a/src/interpreteurlir/motscles/CommandeFin.java b/src/interpreteurlir/motscles/CommandeFin.java index 0f33707..146d697 100644 --- a/src/interpreteurlir/motscles/CommandeFin.java +++ b/src/interpreteurlir/motscles/CommandeFin.java @@ -35,7 +35,6 @@ public class CommandeFin extends Commande { throw new InterpreteurException(ERREUR_ARGUMENTS); } } - /** * Commande d'exécution de la commande. @@ -51,4 +50,4 @@ public class CommandeFin extends Commande { System.exit(0); return true; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/CommandeLance.java b/src/interpreteurlir/motscles/CommandeLance.java index 5531e8d..a6e4628 100644 --- a/src/interpreteurlir/motscles/CommandeLance.java +++ b/src/interpreteurlir/motscles/CommandeLance.java @@ -6,7 +6,6 @@ package interpreteurlir.motscles; import interpreteurlir.Contexte; import interpreteurlir.InterpreteurException; -import interpreteurlir.programmes.Programme; import interpreteurlir.programmes.Etiquette; /** @@ -25,8 +24,8 @@ public class CommandeLance extends Commande { /** * Initialise la commande lance avec ses arguments et le contexte - * @param arguments - * @param contexte + * @param arguments vide ou étiquette de lancement + * @param contexte référence du contexte global * @throws InterpreteurException en cas d'erreur de syntaxe à * la création d'une étiquette */ @@ -67,4 +66,4 @@ public class CommandeLance extends Commande { return true; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/CommandeListe.java b/src/interpreteurlir/motscles/CommandeListe.java index 6747953..8e6db8d 100644 --- a/src/interpreteurlir/motscles/CommandeListe.java +++ b/src/interpreteurlir/motscles/CommandeListe.java @@ -28,8 +28,8 @@ public class CommandeListe extends Commande { /** * Initialise la commande liste avec ses arguments et le contexte * - * @param arguments - * @param contexte + * @param arguments arguments vide ou contenant les étiquettes à afficher + * @param contexte référence du contexte global * @throws InterpreteurException en cas d'erreur de syntaxe lors * de l'instanciation des étiquettes */ @@ -39,10 +39,10 @@ public class CommandeListe extends Commande { final int ARGS_DEBUT = 0; final int ARGS_FIN = 1; - final String ERREUR_INTERVALLE = "usage :" - + " avec " - + " < " - + " "; + final String ERREUR_INTERVALLE = "usage liste <étiquette_début>:" + + "<étiquette_fin> avec " + + "<étiquette_début> <= " + + "<étiquette_fin> "; if (arguments.isBlank()) { debut = new Etiquette(VALEUR_ETIQUETTE_MIN); @@ -75,16 +75,16 @@ public class CommandeListe extends Commande { * dans la classe {@link Commande} */ public boolean executer() { - final String ERREUR = "erreur exécution"; if (programmeGlobal == null) { throw new RuntimeException(ERREUR); } + if (debut != null || fin != null) { System.out.print(programmeGlobal.listeBornee(debut, fin)); } return true; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/CommandeSauve.java b/src/interpreteurlir/motscles/CommandeSauve.java new file mode 100644 index 0000000..3c5542b --- /dev/null +++ b/src/interpreteurlir/motscles/CommandeSauve.java @@ -0,0 +1,86 @@ +/** + * CommandeSauve.java 21 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.motscles; + +import java.io.PrintStream; + +import interpreteurlir.Contexte; +import interpreteurlir.ExecutionException; +import interpreteurlir.InterpreteurException; +import interpreteurlir.programmes.Programme; + +/** + * Commande sauve prenant en argument le chemin du fichier + * (avec une extension .lir) dans lequel est enregistré le programme chargé. + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heia Dexter + * @author Lucas Vabre + */ +public class CommandeSauve extends Commande { + + /** chemin du fichier d'extension .lir pour la sauvegarde */ + private String cheminFichier; + + /** + * Initialise une commande sauve avec un chemin de fichier .lir passé en + * argument. + * @param arguments chemin du fichier dans lequel + * la sauvegarde sera effectuée + * @param contexte référence du contexte global + * @throws InterpreteurException si le chemin du fichier n'a pas + * l'extension .lir + * ou si arguments est chaîne blanche + */ + public CommandeSauve(String arguments, Contexte contexte) { + super(arguments, contexte); + + final String EXTENSION = ".lir"; + final String USAGE = "usage sauve .lir"; + + arguments = arguments.trim(); + + if (arguments.isBlank() || !arguments.endsWith(EXTENSION)) { + throw new InterpreteurException(USAGE); + } + // else + + cheminFichier = arguments; + } + + /** + * Commande d'exécution de la commande. + * Sauvegarde le programme référencé dans la classe Commande + * dans le fichier de cette CommandeSauve. + * @return false car aucun feedback afficher directement + * @throws ExecutionException si l'enregistrement est impossible + * @throws RuntimeException si aucun programme référencé dans la classe + * Commande avec la méthode + * {@link Commande#referencerProgramme(Programme)} + */ + @Override + public boolean executer() { + final String MSG_ERREUR = "impossible de sauvegarder le programme " + + "dans le fichier (le chemin est peut-être invalide)"; + + if (programmeGlobal == null) { + throw new RuntimeException("Programme non référencé dans Commande"); + } + + PrintStream aEcrire = null; + + try { + aEcrire = new PrintStream(cheminFichier); + aEcrire.print(programmeGlobal.toString()); + aEcrire.close(); + } catch (Exception lancee) { + throw new ExecutionException(MSG_ERREUR); + } + + return false; + } + +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/instructions/Instruction.java b/src/interpreteurlir/motscles/instructions/Instruction.java index 787aaaf..33d6850 100644 --- a/src/interpreteurlir/motscles/instructions/Instruction.java +++ b/src/interpreteurlir/motscles/instructions/Instruction.java @@ -17,10 +17,7 @@ import interpreteurlir.motscles.Commande; * @author Heïa Dexter * @author Lucas Vabre */ -public class Instruction extends Commande { - - /** Contexte d'exécution de cette instruction */ - protected Contexte contexteGlobal; +public abstract class Instruction extends Commande { /** Expression qui sera exécutée par la commande */ protected Expression aExecuter; @@ -41,16 +38,12 @@ public class Instruction extends Commande { * @see interpreteurlir.motscles.Commande#executer() */ @Override - public boolean executer() { - return super.executer(); - } + public abstract boolean executer(); /* * Non - javadoc * @see java.lang.Object#toString() */ @Override - public String toString() { - return getClass().getSimpleName() + " " + aExecuter; - } + public abstract String toString(); } diff --git a/src/interpreteurlir/motscles/instructions/InstructionAffiche.java b/src/interpreteurlir/motscles/instructions/InstructionAffiche.java index 56aa71e..e4a752e 100644 --- a/src/interpreteurlir/motscles/instructions/InstructionAffiche.java +++ b/src/interpreteurlir/motscles/instructions/InstructionAffiche.java @@ -7,7 +7,6 @@ package interpreteurlir.motscles.instructions; import interpreteurlir.Contexte; import interpreteurlir.InterpreteurException; import interpreteurlir.expressions.Expression; -import interpreteurlir.expressions.ExpressionChaine; /** * Affiche sur la sortie standard une expression passée en argument. Cette @@ -21,8 +20,9 @@ import interpreteurlir.expressions.ExpressionChaine; */ public class InstructionAffiche extends Instruction { - /** Erreur d'affectation illegale */ - private static final String AFFECTATION_ILLEGALE = "affectation illegale"; + /** Erreur d'affectation illégale */ + private static final String AFFECTATION_ILLEGALE = + "affectation impossible avec la commande affiche"; /** * Initialise cette InstructionAffiche à partir de son contexte global @@ -37,8 +37,9 @@ public class InstructionAffiche extends Instruction { public InstructionAffiche(String arguments, Contexte contexte) { super(arguments, contexte); - if (ExpressionChaine.indexOperateur(arguments, '=') >= 0) + if (Expression.detecterCaractere(arguments, '=') >= 0) { throw new InterpreteurException(AFFECTATION_ILLEGALE); + } aExecuter = arguments.isBlank() ? null @@ -70,5 +71,4 @@ public class InstructionAffiche extends Instruction { : " " + aExecuter.toString()); } - -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/instructions/InstructionEntre.java b/src/interpreteurlir/motscles/instructions/InstructionEntre.java index 50f0c8e..b9905b6 100644 --- a/src/interpreteurlir/motscles/instructions/InstructionEntre.java +++ b/src/interpreteurlir/motscles/instructions/InstructionEntre.java @@ -44,7 +44,7 @@ public class InstructionEntre extends Instruction { */ public InstructionEntre(String arguments, Contexte contexte) { super(arguments, contexte); - final String ERREUR_ARG = "Entre attend un identificateur en argument"; + final String ERREUR_ARG = "usage entre "; if (arguments.isBlank()) { throw new InterpreteurException(ERREUR_ARG); @@ -68,8 +68,10 @@ public class InstructionEntre extends Instruction { */ public boolean executer() { - final String MESSAGE_ERREUR_TYPE = "Le type saisi ne correspond" - + " pas au type demandé"; + final String MESSAGE_ERREUR_TYPE = "type saisi " + + "et type demandé incompatibles"; + + @SuppressWarnings("resource") // ne pas fermer sinon crash Scanner entree = new Scanner(System.in); String valeurSaisie = entree.nextLine(); @@ -84,6 +86,7 @@ public class InstructionEntre extends Instruction { } catch (InterpreteurException lancee) { throw new ExecutionException(MESSAGE_ERREUR_TYPE); } + return false; } @@ -94,4 +97,4 @@ public class InstructionEntre extends Instruction { public String toString() { return "entre " + id; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/instructions/InstructionProcedure.java b/src/interpreteurlir/motscles/instructions/InstructionProcedure.java index 44a9170..83d939a 100644 --- a/src/interpreteurlir/motscles/instructions/InstructionProcedure.java +++ b/src/interpreteurlir/motscles/instructions/InstructionProcedure.java @@ -5,7 +5,6 @@ package interpreteurlir.motscles.instructions; import interpreteurlir.Contexte; -import interpreteurlir.ExecutionException; import interpreteurlir.InterpreteurException; import interpreteurlir.programmes.Etiquette; @@ -36,7 +35,7 @@ public class InstructionProcedure extends Instruction { public InstructionProcedure(String arguments, Contexte contexte) { super(arguments, contexte); - final String ERREUR_ARG = "procedure attend une étiquette en argument"; + final String ERREUR_ARG = "usage procedure <étiquette>"; if(arguments.isBlank()) { throw new InterpreteurException(ERREUR_ARG); @@ -63,7 +62,6 @@ public class InstructionProcedure extends Instruction { * de classe de Commande. */ public boolean executer() { - final String ERREUR_REFERENCEMENT = "Le programme doit être référencé " + "dans la classe commande"; diff --git a/src/interpreteurlir/motscles/instructions/InstructionRetour.java b/src/interpreteurlir/motscles/instructions/InstructionRetour.java index af519ea..ed9590d 100644 --- a/src/interpreteurlir/motscles/instructions/InstructionRetour.java +++ b/src/interpreteurlir/motscles/instructions/InstructionRetour.java @@ -32,7 +32,7 @@ public class InstructionRetour extends Instruction { public InstructionRetour(String arguments, Contexte contexte) { super(arguments, contexte); - final String ERREUR_ARG = "L'instruction retour n'a pas d'arguments"; + final String ERREUR_ARG = "l'instruction retour n'a pas d'arguments"; if (!arguments.isBlank()) { throw new InterpreteurException(ERREUR_ARG); @@ -70,4 +70,4 @@ public class InstructionRetour extends Instruction { return false; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/instructions/InstructionSi.java b/src/interpreteurlir/motscles/instructions/InstructionSi.java new file mode 100644 index 0000000..8907a0b --- /dev/null +++ b/src/interpreteurlir/motscles/instructions/InstructionSi.java @@ -0,0 +1,94 @@ +/** + * InstructionSi.java 22 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.motscles.instructions; + +import interpreteurlir.Contexte; +import interpreteurlir.ExecutionException; +import interpreteurlir.InterpreteurException; +import interpreteurlir.expressions.ExpressionBooleenne; +import interpreteurlir.programmes.Etiquette; + +/** + * Instruction de saut conditionnel. + * La syntaxe est "si expression_booléenne vaen etiquette". + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heïa Dexter + * @author Lucas Vabre + */ +public class InstructionSi extends Instruction { + + /** expression booléenne de this qui est la condition du saut */ + private ExpressionBooleenne condition; + + /** etiquette pour le saut conditionnel */ + private Etiquette saut; + + /** + * Initialise une instruction de saut conditionnel à partir des arguments + * @param arguments chaîne argument de la forme + * "si expression_booléenne vaen etiquette" + * @param contexte contexte global + * @throws InterpreteurException si syntaxe invalide (si ... vaen ...) + * ou si expression_booléenne invalide + * ou si etiquette invalide + */ + public InstructionSi(String arguments, Contexte contexte) { + super(arguments, contexte); + final String ERR_SYNTAXE = "usage si " + + " vaen <étiquette>"; + + arguments = arguments.trim(); + if (arguments.isBlank()) { + throw new InterpreteurException(ERR_SYNTAXE); + } + + int indexVaen = arguments.lastIndexOf("vaen"); + if (indexVaen < 1) { + throw new InterpreteurException(ERR_SYNTAXE); + } + + String expression = arguments.substring(0, indexVaen); + String etiquette = arguments.substring(indexVaen + 4, + arguments.length()); + + condition = new ExpressionBooleenne(expression); + saut = new Etiquette(etiquette); + + } + + /** + * Execution de l'instruction : + * Realise un saut a l'étiquette spécifiée + * si l'expression booléenne est true. + * @return false car aucun feedback affiché directement + * @throws RuntimeException si un programme n'est pas référencé en membre + * de classe de Commande. + * @throws ExecutionException si l'étiquette n'existe pas dans le programme + */ + @Override + public boolean executer() { + final String ERREUR_REFERENCEMENT = "Le programme doit être référencé " + + "dans la classe commande"; + + if (programmeGlobal == null) { + throw new RuntimeException(ERREUR_REFERENCEMENT); + } + + if (condition.calculer().getValeur()) { + programmeGlobal.vaen(saut); + } + return false; + } + + /* non javadoc + * @see interpreteurlir.motscles.instructions.Instruction#toString() + */ + @Override + public String toString() { + return "si " + condition + " vaen " + saut; + } +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/instructions/InstructionStop.java b/src/interpreteurlir/motscles/instructions/InstructionStop.java index c28510b..5235532 100644 --- a/src/interpreteurlir/motscles/instructions/InstructionStop.java +++ b/src/interpreteurlir/motscles/instructions/InstructionStop.java @@ -6,7 +6,6 @@ package interpreteurlir.motscles.instructions; import interpreteurlir.Contexte; import interpreteurlir.InterpreteurException; -import interpreteurlir.programmes.Programme; /** * Instruction stop servant à marquer la fin d'un programme de l'interpréteur @@ -22,7 +21,8 @@ public class InstructionStop extends Instruction { /** Message d'erreur si instruction passée avec des arguments */ private static final String ERREUR_ARGUMENTS = - "l'instruction stop n'accepte pas d'arguments"; + "l'instruction stop n'a pas d'arguments"; + /** * Initialise cette instruction stop à partir des arguments, du contexte * et du programme passés en paramètres. Cette instruction ne modifie que @@ -46,7 +46,7 @@ public class InstructionStop extends Instruction { public boolean executer() { final String ERREUR_REFERENCEMENT = "Le programme doit être référencé " - + "dans la classe commande"; + + "dans la classe commande"; if (programmeGlobal == null) { throw new RuntimeException(ERREUR_REFERENCEMENT); @@ -64,4 +64,4 @@ public class InstructionStop extends Instruction { public String toString() { return "stop"; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/instructions/InstructionVaen.java b/src/interpreteurlir/motscles/instructions/InstructionVaen.java index a4f43cc..1e6e7be 100644 --- a/src/interpreteurlir/motscles/instructions/InstructionVaen.java +++ b/src/interpreteurlir/motscles/instructions/InstructionVaen.java @@ -30,7 +30,7 @@ public class InstructionVaen extends Instruction { public InstructionVaen(String arguments, Contexte contexte) { super(arguments, contexte); - final String ERREUR_ARG = "vaen attend une étiquette en argument"; + final String ERREUR_ARG = "usage vaen <étiquette>"; if (arguments.isBlank()) { throw new InterpreteurException(ERREUR_ARG); @@ -49,16 +49,15 @@ public class InstructionVaen extends Instruction { /** * Execution de l'instruction : - * Realise un saut a l'étiquette spécifiée. - * L'appel s'empile sur le contexte appellant pour ce qui est du - * compteur ordinal. + * Réalise un saut à l'étiquette spécifiée. * @return false car aucun feedback affiché directement * @throws RuntimeException si un programme n'est pas référencé en membre * de classe de Commande. */ public boolean executer() { - final String ERREUR = "erreur exécution"; + final String ERREUR = "Le programme doit être référencé " + + "dans la classe commande"; if (programmeGlobal == null) { throw new RuntimeException(ERREUR); @@ -69,4 +68,4 @@ public class InstructionVaen extends Instruction { return false; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/instructions/InstructionVar.java b/src/interpreteurlir/motscles/instructions/InstructionVar.java index 0f88fa4..7aba799 100644 --- a/src/interpreteurlir/motscles/instructions/InstructionVar.java +++ b/src/interpreteurlir/motscles/instructions/InstructionVar.java @@ -7,7 +7,6 @@ package interpreteurlir.motscles.instructions; import interpreteurlir.Contexte; import interpreteurlir.InterpreteurException; import interpreteurlir.expressions.Expression; -import interpreteurlir.expressions.ExpressionChaine; /** * Instruction de déclaration et d'affectation de variables. La syntaxe de @@ -30,10 +29,11 @@ public class InstructionVar extends Instruction { */ public InstructionVar(String arguments, Contexte contexte) { super(arguments, contexte); + final String USAGE = "usage var = "; if (arguments == null || arguments.isBlank() - || ExpressionChaine.indexOperateur(arguments, '=') <= 0) - throw new InterpreteurException("erreur de syntaxe"); + || Expression.detecterCaractere(arguments, '=') <= 0) + throw new InterpreteurException(USAGE); aExecuter = Expression.determinerTypeExpression(arguments.trim()); } @@ -56,4 +56,4 @@ public class InstructionVar extends Instruction { public String toString() { return "var " + aExecuter; } -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/instructions/tests/TestInstruction.java b/src/interpreteurlir/motscles/instructions/tests/TestInstruction.java index 5156d8c..3655fff 100644 --- a/src/interpreteurlir/motscles/instructions/tests/TestInstruction.java +++ b/src/interpreteurlir/motscles/instructions/tests/TestInstruction.java @@ -1,52 +1,45 @@ -/** - * TestInstruction.java 9 mai 2021 - * IUT info1 2020-2021, pas de copyright, aucun droit - */ -package interpreteurlir.motscles.instructions.tests; +// Classe testée passé en abstract -import interpreteurlir.Contexte; -import interpreteurlir.motscles.instructions.Instruction; - -/** - * Tests unitaires des instructions - * @author Nicolas Caminade - * @author Sylvan Courtiol - * @author Pierre Debas - * @author Heïa Dexter - * @author Lucas Vabre - */ -public class TestInstruction { - - /** - * Test du constructeur - */ - public static void testInstruction() { - System.out.println("Test du constructeur"); - Instruction aTester = new Instruction("Bonjour", new Contexte()); - System.out.println("==> OK\n"); - } - - /** - * Test de toString() - */ - public static void testToString() { - System.out.println("Test de toString()"); - Instruction aTester = new Instruction("Bonjour", new Contexte()); - - if (!aTester.toString().equals("Instruction null")) - System.err.println("Echec du test"); - else - System.out.println("==> OK\n"); - - System.out.println(aTester); - } - - /** - * Lancement des tests - * @param args non utilisé - */ - public static void main(String[] args) { - testInstruction(); - testToString(); - } -} +///** +// * TestInstruction.java 9 mai 2021 +// * IUT info1 2020-2021, pas de copyright, aucun droit +// */ +//package interpreteurlir.motscles.instructions.tests; +// +//import static info1.outils.glg.Assertions.*; +//import interpreteurlir.Contexte; +//import interpreteurlir.InterpreteurException; +//import interpreteurlir.motscles.instructions.Instruction; +// +///** +// * Tests unitaires des instructions +// * +// * @author Nicolas Caminade +// * @author Sylvan Courtiol +// * @author Pierre Debas +// * @author Heïa Dexter +// * @author Lucas Vabre +// */ +//public class TestInstruction { +// +// /** +// * Test unitaire de {@link Instruction#Instruction(String, Contexte)} +// */ +// public static void testInstruction() { +// System.out.println("\tExécution du test de Instruction()"); +// try { +// new Instruction("Bonjour", new Contexte()); +// } catch (InterpreteurException lancee) { +// echec(); +// } +// } +// +// /** +// * Test unitaire de {@link Instruction#toString()} +// */ +// public static void testToString() { +// System.out.println("\tExécution du test de toString()"); +// Instruction aTester = new Instruction("Bonjour", new Contexte()); +// assertEquivalence(aTester.toString(), "Instruction null"); +// } +//} diff --git a/src/interpreteurlir/motscles/instructions/tests/TestInstructionAffiche.java b/src/interpreteurlir/motscles/instructions/tests/TestInstructionAffiche.java index ba1d0c5..d518002 100644 --- a/src/interpreteurlir/motscles/instructions/tests/TestInstructionAffiche.java +++ b/src/interpreteurlir/motscles/instructions/tests/TestInstructionAffiche.java @@ -56,7 +56,7 @@ public class TestInstructionAffiche { }; Expression.referencerContexte(CONTEXTE_GBL); - System.out.println("Exécution du test de InstructionAffiche(String" + System.out.println("\tExécution du test de InstructionAffiche(String" + ", Contexte)"); for (String argInvalide : INVALIDES) { try { @@ -73,12 +73,14 @@ public class TestInstructionAffiche { */ public static void testExecuter() { - System.out.println("Exécution du test de executer()\nTEST VISUEL SUR " + System.out.println("\tExécution du test de executer()\nTEST VISUEL SUR " + "CONSOLE :"); Expression.referencerContexte(CONTEXTE_GBL); - for (InstructionAffiche aLancer : FIXTURE) - aLancer.executer(); + for (InstructionAffiche aLancer : FIXTURE) { + System.out.println("\n\ttest visuel suivant : "); + aLancer.executer(); + } System.out.println(); } @@ -100,7 +102,7 @@ public class TestInstructionAffiche { "affiche \"300000000000000000 ça passe\"" }; - System.out.println("Exécution du test de toString()"); + System.out.println("\tExécution du test de toString()"); for (int i = 0 ; i < FIXTURE.length ; i++) { assertTrue(FIXTURE[i].toString().compareTo(ATTENDUS[i]) == 0); } diff --git a/src/interpreteurlir/motscles/instructions/tests/TestInstructionEntre.java b/src/interpreteurlir/motscles/instructions/tests/TestInstructionEntre.java index b7dd480..90b97d7 100644 --- a/src/interpreteurlir/motscles/instructions/tests/TestInstructionEntre.java +++ b/src/interpreteurlir/motscles/instructions/tests/TestInstructionEntre.java @@ -8,7 +8,6 @@ import interpreteurlir.motscles.instructions.InstructionEntre; import interpreteurlir.Contexte; import interpreteurlir.ExecutionException; import interpreteurlir.InterpreteurException; -import interpreteurlir.donnees.litteraux.Entier; import static info1.outils.glg.Assertions.*; /** @@ -117,5 +116,4 @@ public class TestInstructionEntre { System.out.println("Contexte : \n" + CONTEXTE_GLB); } - } diff --git a/src/interpreteurlir/motscles/instructions/tests/TestInstructionSi.java b/src/interpreteurlir/motscles/instructions/tests/TestInstructionSi.java new file mode 100644 index 0000000..bdb7056 --- /dev/null +++ b/src/interpreteurlir/motscles/instructions/tests/TestInstructionSi.java @@ -0,0 +1,184 @@ +/** + * TestInstructionSi.java 22 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.motscles.instructions.tests; + +import interpreteurlir.motscles.Commande; +import interpreteurlir.motscles.instructions.InstructionSi; +import interpreteurlir.motscles.instructions.InstructionVar; +import interpreteurlir.programmes.*; +import interpreteurlir.Contexte; +import interpreteurlir.InterpreteurException; +import interpreteurlir.donnees.*; +import interpreteurlir.donnees.litteraux.*; +import interpreteurlir.expressions.Expression; + +import static info1.outils.glg.Assertions.*; + +/** + * Tests unitaires de {@link InstructionSi} + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heïa Dexter + * @author Lucas Vabre + */ +public class TestInstructionSi { + + /** contexte pour les tests */ + private Contexte contexte = new Contexte(); + + /** programme pour les tests */ + private Programme prog = new Programme(); + + /** Jeu de donnée d'instruction si vaen valides pour les tests*/ + private InstructionSi[] fixture = { + new InstructionSi("45 = 2 vaen 15", contexte), + new InstructionSi("age >= 130 vaen 1000", contexte), + new InstructionSi("$prenom <>\"défaut\" vaen 16", contexte), + new InstructionSi("resultat < 20 vaen 17", contexte), + new InstructionSi("resultat < moyenne vaen 18", contexte), + new InstructionSi("age > 20 vaen 19", contexte), + new InstructionSi("\"tata\" = \"tata\"vaen 20", contexte), + new InstructionSi("\"toto \" > $toto vaen1502", contexte), + new InstructionSi("-5 <= 0 vaen 21", contexte), + new InstructionSi("resultat < 20 vaen 22", contexte), + }; + + /** + * Tests unitaires de {@link InstructionSi#InstructionSi(String, Contexte)} + */ + public void testInstructionSiStringContexte() { + final String[] ARGS_INVALIDES = { + "", + " \t", + " entier < index", + "vaen 1050", + "age = 10 vaen", + " $prenom = \"défaut\" va 10", + "$prenom <> $nom goto 45", + "$prenom <> $nom vaen dix", + "$prenom != $nom vaen 45", + /* erreur de type */ + "$prenom <> 5 vaen 450", + "age > \"\" vaen 450", + "age >= $prenom vaen 450", + "\"dix\" = 10 vaen 4500", + }; + + System.out.println("\tExécution du test de " + + "InstructionSi#InstructionSi(String, Contexte)"); + + for (String aTester : ARGS_INVALIDES) { + try { + new InstructionSi(aTester, contexte); + echec(); + } catch (InterpreteurException lancee) { + // testok + } + } + + try { + new InstructionSi("45 = 2 vaen 15", contexte); + new InstructionSi("age >= 130 vaen 1000", contexte); + new InstructionSi("$prenom <>\"défaut\" vaen 15", contexte); + new InstructionSi("resultat < 20 vaen 15", contexte); + new InstructionSi("resultat < moyenne vaen 15", contexte); + new InstructionSi("age > 20 vaen 15", contexte); + new InstructionSi("\"tata\" = \"tata\"vaen 15", contexte); + new InstructionSi("\"toto \" > $toto vaen1502", contexte); + new InstructionSi("-5 <= 0 vaen 15", contexte); + new InstructionSi("resultat < 20 vaen 15", contexte); + new InstructionSi("$chaine <= \"vaen 15\" vaen 15", contexte); + } catch (InterpreteurException lancee) { + echec(); + } + } + + /** + * Tests unitaires de {@link InstructionSi#toString()} + */ + public void testToString() { + final String[] ATTENDU = { + "si 45 = 2 vaen 15", + "si age >= 130 vaen 1000", + "si $prenom <> \"défaut\" vaen 16", + "si resultat < 20 vaen 17", + "si resultat < moyenne vaen 18", + "si age > 20 vaen 19", + "si \"tata\" = \"tata\" vaen 20", + "si \"toto \" > $toto vaen 1502", + "si -5 <= 0 vaen 21", + "si resultat < 20 vaen 22", + }; + System.out.println("\tExécution du test de InstructionSi#toString()"); + + for (int numTest = 0 ; numTest < ATTENDU.length ; numTest++) { + assertEquivalence(ATTENDU[numTest], fixture[numTest].toString()); + } + } + + /** + * Tests unitaires de {@link InstructionSi#executer()} + */ + public void testExecuter() { + Commande.referencerProgramme(prog); + prog.ajouterLigne(new Etiquette(15), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(16), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(17), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(18), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(19), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(20), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(21), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(22), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(1000), + new InstructionVar("valeur = valeur -1", contexte)); + prog.ajouterLigne(new Etiquette(1502), + new InstructionVar("valeur = valeur -1", contexte)); + Expression.referencerContexte(contexte); + + + final int[] VALEUR_ATTENDU = { + 0, // pas de saut + 0, + -9, // saut en 16 + -8, // saut en 17 + 0, + -6, // saut en 19 + -5, // saut en 20 + -1, // saut en 1502 + -4, // saut en 21 + -3, // saut en 22 + }; + + System.out.println("\tExécution du test de InstructionSi#executer()"); + + for (int numTest = 0 ; numTest < VALEUR_ATTENDU.length ; numTest++) { + /* initialisation du contexte */ + contexte.raz(); + contexte.ajouterVariable(new IdentificateurEntier("moyenne"), + new Entier("-2")); + contexte.ajouterVariable(new IdentificateurEntier("age"), + new Entier("99")); + contexte.ajouterVariable(new IdentificateurChaine("$toto"), + new Chaine("\"toto\"")); + + fixture[numTest].executer(); + assertEquivalence(VALEUR_ATTENDU[numTest], + ((Integer)contexte.lireValeurVariable( + new IdentificateurEntier("valeur")) + .getValeur()).intValue()); + } + } + + +} diff --git a/src/interpreteurlir/motscles/instructions/tests/TestInstructionStop.java b/src/interpreteurlir/motscles/instructions/tests/TestInstructionStop.java index c689480..f8ce5e0 100644 --- a/src/interpreteurlir/motscles/instructions/tests/TestInstructionStop.java +++ b/src/interpreteurlir/motscles/instructions/tests/TestInstructionStop.java @@ -44,7 +44,7 @@ public class TestInstructionStop { "entier = 2 + 3" }; - System.out.println("Exécution du test de InstructionStop" + System.out.println("\tExécution du test de InstructionStop" + "(String, Contexte)"); for (String aTester : INVALIDES) { try { @@ -59,32 +59,34 @@ public class TestInstructionStop { /** Test de executer() */ public static void testExecuter() { Programme pgmTest = new Programme(); - System.out.println("Exécution du test de executer()\ntestVisuel\n"); + System.out.println("\tExécution du test de executer()\nTest Visuels\n"); Commande.referencerProgramme(pgmTest); Expression.referencerContexte(CONTEXTE_TESTS); pgmTest.ajouterLigne(new Etiquette(10), - new InstructionAffiche("Bonjour", CONTEXTE_TESTS)); + new InstructionAffiche("\"Bonjour\"", CONTEXTE_TESTS)); pgmTest.ajouterLigne(new Etiquette(20), - new InstructionAffiche("Comment", CONTEXTE_TESTS)); + new InstructionAffiche("\"Comment\"", CONTEXTE_TESTS)); pgmTest.ajouterLigne(new Etiquette(30), - new InstructionAffiche("Allez", CONTEXTE_TESTS)); + new InstructionAffiche("\"Allez\"", CONTEXTE_TESTS)); pgmTest.ajouterLigne(new Etiquette(40), - new InstructionAffiche("Vous", CONTEXTE_TESTS)); + new InstructionAffiche("\"Vous\"", CONTEXTE_TESTS)); pgmTest.ajouterLigne(new Etiquette(45), new InstructionStop("", CONTEXTE_TESTS)); pgmTest.ajouterLigne(new Etiquette(50), - new InstructionAffiche("foobar", CONTEXTE_TESTS)); + new InstructionAffiche("\"foobar\"", CONTEXTE_TESTS)); System.out.println(pgmTest); System.out.println("lancement du programme : ne doit pas " + "afficher foobar"); pgmTest.lancer(); + + System.out.println(); } /** Tests de toString() */ public static void testToString() { final String ATTENDUE = "stop"; - System.out.println("Exécution du test de toString()"); + System.out.println("\tExécution du test de toString()"); for (InstructionStop valide : FIXTURE) assertTrue(valide.toString().compareTo(ATTENDUE) == 0); } diff --git a/src/interpreteurlir/motscles/instructions/tests/TestInstructionVar.java b/src/interpreteurlir/motscles/instructions/tests/TestInstructionVar.java index d0991ca..c371e21 100644 --- a/src/interpreteurlir/motscles/instructions/tests/TestInstructionVar.java +++ b/src/interpreteurlir/motscles/instructions/tests/TestInstructionVar.java @@ -4,12 +4,14 @@ */ package interpreteurlir.motscles.instructions.tests; +import static info1.outils.glg.Assertions.*; import interpreteurlir.Contexte; import interpreteurlir.InterpreteurException; import interpreteurlir.motscles.instructions.InstructionVar; /** - * Tests unitaires de l'instruction var + * Tests unitaires de la classe InstructionVar + * * @author Nicolas Caminade * @author Sylvan Courtiol * @author Pierre Debas @@ -25,59 +27,50 @@ public class TestInstructionVar { }; /** - * Test du constructeur InstructionVar + * Test unitaire de {@link InstructionVar#InstructionVar(String, Contexte)} */ public static void testInstructionVar() { final String[] EXPRESSIONS_INVALIDES = { - "bonjour", "", null, "$toto $tata", + "bonjour", "", "$toto $tata", }; - System.out.println("Test du constructeur\navec expressions invalides"); + System.out.println("\tExécution du test de InstructionVar(String, " + + "Contexte)"); + for (String aTester : EXPRESSIONS_INVALIDES) { try { new InstructionVar(aTester, new Contexte()); - throw new RuntimeException("Echec du test"); + echec(); } catch (InterpreteurException lancee) { - System.out.println(aTester + " ==> OK"); + // Test OK } } - System.out.println("Avec expressions valides"); - for (String aTester : VALIDES) - new InstructionVar(aTester, new Contexte()); - - System.out.println("Fin du test\n"); + for (String aTester : VALIDES) { + try { + new InstructionVar(aTester, new Contexte()); + } catch (InterpreteurException lancee) { + echec(); + } + } } /** - * Test de toString + * Test unitaire de {@link InstructionVar#toString()} */ public static void testToString() { final String[] CHAINES_ATTENDUES = { - "var $toto = $tata", "var entier=2+2", - "var $coucou = $toto + \\\"titi\\\"", + "var $toto = $tata", + "var entier = 2 + 2", + "var $coucou = $toto + \"titi\"", "var anneeNaissance = 1898" }; - System.out.println("Test de toString()"); + System.out.println("\tExécution du tes de toString()"); for (int i = 0 ; i < VALIDES.length ; i++) { - - try { - assert VALIDES[i].toString().equals(CHAINES_ATTENDUES[i]); - } catch (AssertionError lancee) { - System.err.println("Echec du test à l'indice " + i); - } + InstructionVar aTester = new InstructionVar(VALIDES[i], + new Contexte()); + assertTrue(CHAINES_ATTENDUES[i].equals(aTester.toString())); } - System.out.println("Fin du test\n"); } - - /** - * Lancement des tests - * @param args - */ - public static void main(String[] args) { - testInstructionVar(); - testToString(); - } - -} +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/tests/EssaiCommande.java b/src/interpreteurlir/motscles/tests/EssaiCommande.java index f8bdf7f..b4fae71 100644 --- a/src/interpreteurlir/motscles/tests/EssaiCommande.java +++ b/src/interpreteurlir/motscles/tests/EssaiCommande.java @@ -7,6 +7,7 @@ package interpreteurlir.motscles.tests; import interpreteurlir.Contexte; import interpreteurlir.InterpreteurException; import interpreteurlir.motscles.*; +import interpreteurlir.programmes.Programme; /** * Essais des commandes (création + éxécution) @@ -24,6 +25,7 @@ public class EssaiCommande { */ public static void main(String[] args) { Contexte contexte = new Contexte(); + Commande.referencerProgramme(new Programme()); /* Erreur dans commande */ System.out.println("? debut args"); @@ -49,9 +51,11 @@ public class EssaiCommande { System.out.println("? debut"); feedback(new CommandeDebut("", contexte).executer()); System.out.println("? defs"); - feedback(new CommandeDefs( "", contexte).executer()); + feedback(new CommandeDefs("", contexte).executer()); + System.out.println("? liste"); + feedback(new CommandeListe("", contexte).executer()); System.out.println("? fin"); - feedback(new CommandeFin( "", contexte).executer()); + feedback(new CommandeFin("", contexte).executer()); System.err.println("Erreur, la commande fin n'a pas quitter"); diff --git a/src/interpreteurlir/motscles/tests/TestCommande.java b/src/interpreteurlir/motscles/tests/TestCommande.java index f056649..4127e33 100644 --- a/src/interpreteurlir/motscles/tests/TestCommande.java +++ b/src/interpreteurlir/motscles/tests/TestCommande.java @@ -1,88 +1,90 @@ -/** - * TestCommande.java 7 mai 2021 - * IUT Rodez info1 2020-2021, pas de copyright, aucun droit - */ -package interpreteurlir.motscles.tests; +// Classe testée passé en abstract -import static info1.outils.glg.Assertions.*; - -import interpreteurlir.Contexte; -import interpreteurlir.expressions.Expression; -import interpreteurlir.motscles.Commande; -import interpreteurlir.programmes.Programme; - -/** - * Tests unitaires de {@link interpreteurlir.motscles.Commande} - * @author Nicolas Caminade - * @author Sylvan Courtiol - * @author Pierre Debas - * @author Heïa Dexter - * @author Lucas Vabre - */ -public class TestCommande { - - /** Jeux d'essais de Commande valides pour les tests */ - private Commande[] fixture = { - new Commande("", new Contexte()), - new Commande("coucou", new Contexte()), - new Commande("$chaine = \"toto\" + $tata", new Contexte()) - }; - - /** - * Tests unitaires de {@link Commande#referencerProgramme(Programme)} - */ - public void testReferencerProgramme() { - - Programme reference = new Programme(); - Programme[] programmes = { - null, reference, reference, new Programme() - }; - - boolean[] resultatAttendu = { false, true, true, false }; - - System.out.println("\tExécution du test de " - + "Commande#referencerProgramme(Programme)"); - for (int numTest = 0 ; numTest < programmes.length ; numTest++) { - assertTrue( Commande.referencerProgramme(programmes[numTest]) - == resultatAttendu[numTest]); - } - } - - /** - * Tests unitaires de {@link Commande#Commande(String, Contexte)} - */ - public void testCommandeStringContexte() { - System.out.println( - "\tExécution du test de Commande#Commande(String, Contexte)"); - - /* Tests Commande invalide */ - String[] arguments = { null, null, "" }; - Contexte[] contexte = { null, new Contexte(), null}; - for (int numTest = 0 ; numTest < arguments.length ; numTest++) { - try { - new Commande(arguments[numTest], contexte[numTest]); - echec(); - } catch (NullPointerException lancee) { - } - } - - try { - new Commande("", new Contexte()); - new Commande("coucou", new Contexte()); - new Commande("$chaine = \"toto\" + $tata", new Contexte()); - } catch (NullPointerException e) { - echec(); - } - } - - - /** - * Tests unitaires de {@link Commande#executer()} - */ - public void testExecuter() { - System.out.println("\tExécution du test de Commande#executer()"); - for (Commande aTester : fixture) { - assertFalse(aTester.executer()); - } - } -} +///** +// * TestCommande.java 7 mai 2021 +// * IUT Rodez info1 2020-2021, pas de copyright, aucun droit +// */ +//package interpreteurlir.motscles.tests; +// +//import static info1.outils.glg.Assertions.*; +// +//import interpreteurlir.Contexte; +//import interpreteurlir.expressions.Expression; +//import interpreteurlir.motscles.Commande; +//import interpreteurlir.programmes.Programme; +// +///** +// * Tests unitaires de {@link interpreteurlir.motscles.Commande} +// * @author Nicolas Caminade +// * @author Sylvan Courtiol +// * @author Pierre Debas +// * @author Heïa Dexter +// * @author Lucas Vabre +// */ +//public class TestCommande { +// +// /** Jeux d'essais de Commande valides pour les tests */ +// private Commande[] fixture = { +// new Commande("", new Contexte()), +// new Commande("coucou", new Contexte()), +// new Commande("$chaine = \"toto\" + $tata", new Contexte()) +// }; +// +// /** +// * Tests unitaires de {@link Commande#referencerProgramme(Programme)} +// */ +// public void testReferencerProgramme() { +// +// Programme reference = new Programme(); +// Programme[] programmes = { +// null, reference, reference, new Programme() +// }; +// +// boolean[] resultatAttendu = { false, true, true, false }; +// +// System.out.println("\tExécution du test de " +// + "Commande#referencerProgramme(Programme)"); +// for (int numTest = 0 ; numTest < programmes.length ; numTest++) { +// assertTrue( Commande.referencerProgramme(programmes[numTest]) +// == resultatAttendu[numTest]); +// } +// } +// +// /** +// * Tests unitaires de {@link Commande#Commande(String, Contexte)} +// */ +// public void testCommandeStringContexte() { +// System.out.println( +// "\tExécution du test de Commande#Commande(String, Contexte)"); +// +// /* Tests Commande invalide */ +// String[] arguments = { null, null, "" }; +// Contexte[] contexte = { null, new Contexte(), null}; +// for (int numTest = 0 ; numTest < arguments.length ; numTest++) { +// try { +// new Commande(arguments[numTest], contexte[numTest]); +// echec(); +// } catch (NullPointerException lancee) { +// } +// } +// +// try { +// new Commande("", new Contexte()); +// new Commande("coucou", new Contexte()); +// new Commande("$chaine = \"toto\" + $tata", new Contexte()); +// } catch (NullPointerException e) { +// echec(); +// } +// } +// +// +// /** +// * Tests unitaires de {@link Commande#executer()} +// */ +// public void testExecuter() { +// System.out.println("\tExécution du test de Commande#executer()"); +// for (Commande aTester : fixture) { +// assertFalse(aTester.executer()); +// } +// } +//} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/tests/TestCommandeCharge.java b/src/interpreteurlir/motscles/tests/TestCommandeCharge.java new file mode 100644 index 0000000..59dcc81 --- /dev/null +++ b/src/interpreteurlir/motscles/tests/TestCommandeCharge.java @@ -0,0 +1,111 @@ +/** + * TestCommandeCharge.java 21 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.motscles.tests; + +import interpreteurlir.Contexte; +import interpreteurlir.InterpreteurException; +import interpreteurlir.motscles.Commande; +import interpreteurlir.motscles.CommandeCharge; +import interpreteurlir.motscles.CommandeListe; +import interpreteurlir.programmes.Programme; + +import static info1.outils.glg.Assertions.*; + +/** + * Tests unitaires de {@link interpreteurlir.motscles.CommandeCharge} + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heia Dexter + * @author Lucas Vabre + */ +public class TestCommandeCharge { + + /** Contexte pour tests */ + private final static Contexte CONTEXTE_TESTS = new Contexte(); + + /** Programme global pour tests */ + private static Programme progGlobal = new Programme(); + + /** jeu de test valide */ + public static final CommandeCharge[] FIXTURE = { + new CommandeCharge("F:\\Programmation\\WorkspaceInterpreteurLIR" + + "\\outilTest\\dossierFichier\\" + + "lefichier1.lir", CONTEXTE_TESTS), + new CommandeCharge("dossierFichier\\lefichier2.lir", + CONTEXTE_TESTS), + new CommandeCharge("dossierFichier\\lefichier3.lir", + CONTEXTE_TESTS), + new CommandeCharge("dossierFichier\\test\\lefichier4.lir", + CONTEXTE_TESTS), + new CommandeCharge("dossierFichier\\test\\test2\\lefichier5.lir", + CONTEXTE_TESTS), + new CommandeCharge(" dossierFichier\\lefichier6.lir ", + CONTEXTE_TESTS), + new CommandeCharge("dossierFichier\\test\\test2\\..\\lefichier7.lir", + CONTEXTE_TESTS) + }; + + /** + * Tests unitaires de + * {@link CommandeCharge#CommandeCharge(String, Contexte)} + */ + public static void testCommandeCharge() { + + final String[] INVALIDE = { + null, + " ", + "", + "lefichier", + "dossier\\ lefichier", + "dossier \\lefichier", + }; + + for (int i = 0; i < INVALIDE.length ; i++) { + try { + new CommandeCharge(INVALIDE[i], CONTEXTE_TESTS); + echec(); + } catch (InterpreteurException | NullPointerException lancee) { + // Test OK + } + } + } + + /** + * Tests unitaires de + * {@link CommandeCharge#executer()} + */ + public static void testExecuter() { + + Commande.referencerProgramme(progGlobal); + + final CommandeCharge[] ERREUR = { + new CommandeCharge("dossierFichier\\erreur1.lir", + CONTEXTE_TESTS), + new CommandeCharge("dossierFichier\\erreur2.lir", + CONTEXTE_TESTS) + }; + + final int NB_TESTS = FIXTURE.length; + System.out.println("\nTest valides de CommandeCharge#executer():"); + for (int i = 0; i < NB_TESTS ; i++) { + System.out.println("Test " + (i+1) + '\\' + NB_TESTS + ":"); + FIXTURE[i].executer(); + new CommandeListe("", CONTEXTE_TESTS).executer(); + } + + System.out.println("\nTest invalides de CommandeCharge#executer():"); + for(int i = 0; i < ERREUR.length ; i++) { + try { + ERREUR[i].executer(); + echec(); + } catch (InterpreteurException lancee) { + // Test OK + new CommandeListe("", CONTEXTE_TESTS).executer(); + } + } + } + +} \ No newline at end of file diff --git a/src/interpreteurlir/motscles/tests/TestCommandeDebut.java b/src/interpreteurlir/motscles/tests/TestCommandeDebut.java index b69546f..c1be46b 100644 --- a/src/interpreteurlir/motscles/tests/TestCommandeDebut.java +++ b/src/interpreteurlir/motscles/tests/TestCommandeDebut.java @@ -8,7 +8,9 @@ import static info1.outils.glg.Assertions.*; import interpreteurlir.InterpreteurException; import interpreteurlir.Contexte; +import interpreteurlir.motscles.Commande; import interpreteurlir.motscles.CommandeDebut; +import interpreteurlir.programmes.Programme; /** * Tests unitaires de {@link interpreteurlir.motscles.CommandeDebut} @@ -59,6 +61,7 @@ public class TestCommandeDebut { * Tests unitaires de {@link CommandeDebut#executer()} */ public void testExecuter() { + Commande.referencerProgramme(new Programme()); System.out.println("\tExécution du test de CommandeDebut#executer()"); for (CommandeDebut cmd : fixture) { assertFalse(cmd.executer()); diff --git a/src/interpreteurlir/motscles/tests/TestCommandeEfface.java b/src/interpreteurlir/motscles/tests/TestCommandeEfface.java index 7d0257a..63d6386 100644 --- a/src/interpreteurlir/motscles/tests/TestCommandeEfface.java +++ b/src/interpreteurlir/motscles/tests/TestCommandeEfface.java @@ -54,14 +54,14 @@ public class TestCommandeEfface { "\'a\' : 99" }; - System.out.println("Exécution du test de CommandeEfface" + System.out.println("\tExécution du test de CommandeEfface" + "(String, Contexte)"); for (String aTester : INVALIDES) { try { new CommandeEfface(aTester, CONTEXTE_TESTS); echec(); } catch (InterpreteurException e) { - // TODO: handle exception + // test OK } } } @@ -69,7 +69,7 @@ public class TestCommandeEfface { /** Test de executer() */ public static void testExecuter() { - System.out.println("Exécution du test d'executer()\nTest visuel :"); + System.out.println("\tExécution du test d'executer()\nTest visuel :"); Commande.referencerProgramme(PGM_TESTS); PGM_TESTS.ajouterLigne(new Etiquette(10), new InstructionAffiche("Bonjour", CONTEXTE_TESTS)); diff --git a/src/interpreteurlir/motscles/tests/TestCommandeFin.java b/src/interpreteurlir/motscles/tests/TestCommandeFin.java index 327d758..0e6940b 100644 --- a/src/interpreteurlir/motscles/tests/TestCommandeFin.java +++ b/src/interpreteurlir/motscles/tests/TestCommandeFin.java @@ -19,11 +19,6 @@ import interpreteurlir.motscles.CommandeFin; * @author Lucas Vabre */ public class TestCommandeFin { - - /** Jeux d'essais de Commande valides pour les tests */ - private CommandeFin[] fixture = { - new CommandeFin("", new Contexte()), - }; /** * Tests unitaires de {@link CommandeFin#CommandeFin(String, Contexte)} @@ -61,7 +56,6 @@ public class TestCommandeFin { System.out.println("\tLe programme doit s'éteindre en affichant un " + "message d'aurevoir :"); System.out.println("Test exécuter désactiver"); -// fixture[0].executer(); - echec(); + //fixture[0].executer(); } } diff --git a/src/interpreteurlir/motscles/tests/TestCommandeLance.java b/src/interpreteurlir/motscles/tests/TestCommandeLance.java index 1f7abe7..b969620 100644 --- a/src/interpreteurlir/motscles/tests/TestCommandeLance.java +++ b/src/interpreteurlir/motscles/tests/TestCommandeLance.java @@ -8,10 +8,6 @@ import interpreteurlir.Contexte; import interpreteurlir.InterpreteurException; import interpreteurlir.expressions.Expression; import interpreteurlir.motscles.CommandeLance; -import interpreteurlir.motscles.instructions.Instruction; -import interpreteurlir.motscles.instructions.InstructionVar; -import interpreteurlir.programmes.Etiquette; -import interpreteurlir.programmes.Programme; import static info1.outils.glg.Assertions.*; @@ -29,7 +25,6 @@ import info1.outils.glg.TestException; public class TestCommandeLance { private Contexte contexteTest = new Contexte(); - private Programme programmeTest = new Programme(); private final CommandeLance[] FIXTURE = { new CommandeLance("", contexteTest), @@ -47,37 +42,7 @@ public class TestCommandeLance { "20", "70", "40" - }; - - private final Etiquette[] JEU_ETIQUETTES = { - new Etiquette(1), - new Etiquette(10), - new Etiquette(13), - new Etiquette(25), - new Etiquette(31), - new Etiquette(40), - new Etiquette(78), - new Etiquette(89) - }; - - private final Instruction[] JEU_INSTRUCTIONS = { - new InstructionVar("$res = \"1 \"", contexteTest), - new InstructionVar("$res = $res + \"10 \"", contexteTest), - new InstructionVar("$res = $res + \"13 \"", contexteTest), - new InstructionVar("$res = $res + \"25 \"", contexteTest), - new InstructionVar("$res = $res + \"31 \"", contexteTest), - new InstructionVar("$res = $res + \"40 \"", contexteTest), - new InstructionVar("$res = $res + \"78 \"", contexteTest), - new InstructionVar("$res = $res + \"89 \"", contexteTest) - }; - - private void ecrireProgrammeTest() { - for (int i = 0 ; i < JEU_ETIQUETTES.length ; i++) { - programmeTest.ajouterLigne(JEU_ETIQUETTES[i], - JEU_INSTRUCTIONS[i]); - } - } - + }; /** * Test unitaire de @@ -95,6 +60,9 @@ public class TestCommandeLance { Expression.referencerContexte(contexteTest); + System.out.println("\tExécution du test de " + + "CommandeLance#CommandeLance(String, Contexte)"); + for (int i = 0; i < ARGS_INVALIDES.length; i++) { try { new CommandeLance(ARGS_INVALIDES[i], contexteTest); @@ -122,6 +90,7 @@ public class TestCommandeLance { //ecrireProgrammeTest(); Expression.referencerContexte(contexteTest); + System.out.println("\tExécution du test de CommandeLance#executer()"); for (int i = 0 ; i < FIXTURE.length ; i++) { try { FIXTURE[i].executer(); diff --git a/src/interpreteurlir/motscles/tests/TestCommandeListe.java b/src/interpreteurlir/motscles/tests/TestCommandeListe.java index 67013de..1986278 100644 --- a/src/interpreteurlir/motscles/tests/TestCommandeListe.java +++ b/src/interpreteurlir/motscles/tests/TestCommandeListe.java @@ -91,6 +91,9 @@ public class TestCommandeListe { "1:100000" }; + System.out.println("\tExécution du test de " + + "CommandeListe#CommandeListe(String, Contexte)"); + for (int i = 0; i < ARGS_INVALIDES.length; i++) { try { new CommandeListe(ARGS_INVALIDES[i], contexteTest); @@ -130,6 +133,9 @@ public class TestCommandeListe { Commande.referencerProgramme(programmeTest); Expression.referencerContexte(contexteTest); + System.out.println("\tExécution du test de " + + "CommandeListe#executer()"); + for (int i = 0 ; i < FIXTURE.length ; i++) { try { FIXTURE[i].executer(); diff --git a/src/interpreteurlir/motscles/tests/TestCommandeSauve.java b/src/interpreteurlir/motscles/tests/TestCommandeSauve.java new file mode 100644 index 0000000..64951e0 --- /dev/null +++ b/src/interpreteurlir/motscles/tests/TestCommandeSauve.java @@ -0,0 +1,176 @@ +/** + * TestCommandeSauve.java 21 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.motscles.tests; + +import static info1.outils.glg.Assertions.*; + +import interpreteurlir.motscles.Commande; +import interpreteurlir.motscles.CommandeSauve; +import interpreteurlir.programmes.Programme; +import interpreteurlir.Contexte; +import interpreteurlir.ExecutionException; +import interpreteurlir.InterpreteurException; +import interpreteurlir.tests.ProgrammeDeTest; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; + +/** + * Tests unitaires de {@link CommandeSauve} + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heia Dexter + * @author Lucas Vabre + */ +public class TestCommandeSauve { + + /** contexte pour les tests */ + private Contexte contexte = new Contexte(); + + /** Programme pour les tests */ + private Programme progGlobal = new Programme(); + + /** Jeu de donnée de commandeSauve valides pour les tests */ + private CommandeSauve[] fixture = { + /* chemin valide */ + new CommandeSauve("monProgramme.lir", contexte), + new CommandeSauve("programmationLIR\\monProgramme.lir", contexte), + new CommandeSauve("D:\\testInterpreteurLIR\\test1.lir", contexte), + new CommandeSauve(" D:\\testInterpreteurLIR\\test2.lir\t", contexte), + + /* chemin invalide à l'exécution*/ + new CommandeSauve("\\\\monProgramme.lir", contexte), + new CommandeSauve("monPro//??!gr<>amme.lir", contexte), + /* chemin inexistant */ + new CommandeSauve("D:\\testInterpreteurLIR\\dossierNonCree\\test1.lir", + contexte), + /* lecteur inexistant */ + new CommandeSauve("X:\\testInterpreteurLIR\\test1.lir", contexte), + }; + + /** + * Tests unitaires de {@link CommandeSauve#CommandeSauve(String, Contexte)} + */ + public void testCommandeSauveStringContexte() { + final String[] ARGS_INVALIDES = { + "", + " \t ", + "D:\\utilisateurs\\defaut\\bureau\\", + "D:\\utilisateurs\\defaut\\bureau\\monProgramme.txt", + "D:\\utilisateurs\\defaut\\bureau\\monProgramme", + "nouveau dossier\\monProgramme.java", + "nouveau dossier\\monProgramme", + "monProgramme.class", + "monProgramme" + }; + + System.out.println("\tExécution du test de " + + "CommandeSauve#CommandeSauve(String, Contexte)"); + + for (String aTester : ARGS_INVALIDES) { + try { + new CommandeSauve(aTester, contexte); + echec(); + } catch (InterpreteurException e) { + // test ok + } + } + + try { + /* chemin valide */ + new CommandeSauve("monProgramme.lir", contexte); + new CommandeSauve("programmationLIR\\monProgramme.lir", contexte); + new CommandeSauve("D:\\testInterpreteurLIR\\test1.lir", contexte); + new CommandeSauve(" D:\\testInterpreteurLIR\\test2.lir\t", + contexte); + /* chemin invalide à l'exécution*/ + new CommandeSauve("\\\\monProgramme.lir", contexte); + new CommandeSauve("monPro//??!gr<>amme.lir", contexte); + /* chemin inexistant */ + new CommandeSauve("D:\\testInterpreteurLIR\\dossierNonCree\\" + + "test1.lir", contexte); + /* lecteur inexistant */ + new CommandeSauve("X:\\testInterpreteurLIR\\test1.lir", contexte); + } catch (InterpreteurException e) { + echec(); + } + + } + + /** + * Tests unitaires de {@link CommandeSauve#executer()} + */ + public void testExecuter() { + final int INDEX_INVALIDES = 4; + + Commande.referencerProgramme(progGlobal); + System.out.println("\tExécution du test de CommandeSauve#executer()"); + + /* Tests des chemins invalides */ + for (int index = INDEX_INVALIDES ; index < fixture.length ; index++) { + try { + fixture[index].executer(); + echec(); + } catch (ExecutionException lancee) { + // test OK + } + } + + + try { + assertFalse(fixture[0].executer()); + assertEquivalence(progGlobal.toString(), + lireFichier("monProgramme.lir")); + assertFalse(fixture[2].executer()); + assertEquivalence(progGlobal.toString(), + lireFichier("D:\\testInterpreteurLIR\\test1.lir")); + + ProgrammeDeTest.genererProgramme(progGlobal, contexte); + + assertFalse(fixture[1].executer()); + assertEquivalence(progGlobal.toString(), + lireFichier("programmationLIR\\monProgramme.lir")); + + assertFalse(fixture[3].executer()); + assertEquivalence(progGlobal.toString(), + lireFichier("D:\\testInterpreteurLIR\\test2.lir")); + + } catch (ExecutionException lancee) { + echec(); + } + + } + + /** + * Lit un fichier et retourne le contenu entier du fichier + * @param cheminFichier chemin du fichier à lire + * @return contenu du fichier + */ + private static String lireFichier(String cheminFichier) { + BufferedReader aTester; + StringBuilder contenu = new StringBuilder(""); + + aTester = null; + try { + aTester = new BufferedReader( + new InputStreamReader( + new FileInputStream(cheminFichier))); + String ligneLue; + do { + ligneLue = aTester.readLine(); + if (ligneLue != null) { + contenu.append(ligneLue).append("\n"); + } + } while (ligneLue != null); + aTester.close(); + } catch (Exception e) { + echec(); + } + + return contenu.toString(); + } +} diff --git a/src/interpreteurlir/programmes/Programme.java b/src/interpreteurlir/programmes/Programme.java index e7ea785..47931f7 100644 --- a/src/interpreteurlir/programmes/Programme.java +++ b/src/interpreteurlir/programmes/Programme.java @@ -30,7 +30,7 @@ import static interpreteurlir.programmes.Etiquette.VALEUR_ETIQUETTE_MIN; public class Programme { private static final String ERREUR_INTERVALLE = "erreur dans l'intervalle " - + "d'étiquettes. "; + + "d'étiquettes"; /** Pile LIFO pour la gestion des étiquettes */ private Stack compteurOrdinnal; @@ -42,15 +42,13 @@ public class Programme { /** * Initialisation de ce programme sans lignes de code - *

- * */ public Programme() { super(); + lignesCode = new TreeMap(); enExecution = false; compteurOrdinnal = new Stack(); - } /** @@ -91,11 +89,8 @@ public class Programme { @Override public String toString() { - Object[] tableauEtiquette - = lignesCode.keySet().toArray(); - - Object[] tableauInstruction - = lignesCode.values().toArray(); + Object[] tableauEtiquette = lignesCode.keySet().toArray(); + Object[] tableauInstruction = lignesCode.values().toArray(); StringBuilder aAfficher = new StringBuilder(""); @@ -150,9 +145,8 @@ public class Programme { } } while (lignesRestantes); - return aAfficher.toString().equals("") - ? "Aucune ligne de code dans cet intervalle.\n" - : aAfficher.toString(); + return aAfficher.toString().equals("") ? "aucune ligne à afficher\n" + : aAfficher.toString(); } /** @@ -236,8 +230,18 @@ public class Programme { /** * Change le compteur ordinal avec l'étiquette argument * @param destination étiquette où continuer l'exécution + * @throws ExecutionException si aucune instruction dans le programme + * n'a comme étiquette destination */ public void vaen(Etiquette destination) { + final String ERR_ETIQUETTE = "vaen impossible car l'étiquette " + + destination + + " ne correspond à aucune instruction"; + if (!lignesCode.containsKey(destination)) { + throw new ExecutionException(ERR_ETIQUETTE); + } + // else + if (!compteurOrdinnal.isEmpty()) { compteurOrdinnal.pop(); } @@ -258,12 +262,11 @@ public class Programme { /** * Retour d'une procédure en dépilant l'étiquette de départ dans * le compteurOrdinal - * @param depart étiquette du début de la procédure * @throws ExecutionException lorsque retourProcedure vide le * compteurOrdinnal */ public void retourProcedure() { - final String ERREUR_RETOUR = "erreur retour nécessite un appel de " + final String ERREUR_RETOUR = "retour nécessite un appel de " + "procédure au préalable"; try { compteurOrdinnal.pop(); diff --git a/src/interpreteurlir/programmes/tests/TestProgramme.java b/src/interpreteurlir/programmes/tests/TestProgramme.java index 6674842..496aad5 100644 --- a/src/interpreteurlir/programmes/tests/TestProgramme.java +++ b/src/interpreteurlir/programmes/tests/TestProgramme.java @@ -10,6 +10,9 @@ import interpreteurlir.ExecutionException; import interpreteurlir.InterpreteurException; import interpreteurlir.expressions.Expression; import interpreteurlir.motscles.instructions.*; +import interpreteurlir.motscles.instructions.tests.TestInstructionStop; +import interpreteurlir.motscles.instructions.tests.TestInstructionVaen; + import static info1.outils.glg.Assertions.*; /** @@ -156,7 +159,7 @@ public class TestProgramme { public void testListeBornee() { final String[] TEXTES_ATTENDUS = { - "Aucune ligne de code dans cet intervalle.\n", + "aucune ligne à afficher\n", "1 var $toto = \"toto\"\n" + "5 var $agreuagreu = \"agreu\"\n" + "10 var tata = 0 + 0\n" @@ -202,13 +205,6 @@ public class TestProgramme { */ public void testEffacer() { -// final Etiquette[][] BORNES = { -// { new Etiquette(6), new Etiquette(6) }, -// { new Etiquette(1), new Etiquette(90) }, -// { new Etiquette(31), new Etiquette(39) }, -// { new Etiquette(9), new Etiquette(41) } -// }; - final String[] TEXTES_ATTENDUS = { "1 var $toto = \"toto\"\n" + "5 var $agreuagreu = \"agreu\"\n" @@ -256,13 +252,11 @@ public class TestProgramme { /** * Test unitaire de {@link Programme#stop()} + * @see TestInstructionStop#testExecuter() */ public void testStop() { - //TODO écrire les tests lorsque l'instruction stop sera définie - - System.out.println("\tExécution du test de stop() : "); - - echec(); + System.out.println("\tExécution du test de Programme#stop() " + + ": voir TestInstructionStop#testExecuter()"); } /** @@ -271,7 +265,7 @@ public class TestProgramme { public void testLancerEtiquette() { final Etiquette[] ETIQUETTES_DEPART = { new Etiquette(1), - new Etiquette(9), + new Etiquette(10), new Etiquette(25), new Etiquette(90) }; @@ -297,7 +291,6 @@ public class TestProgramme { * Test unitaire de {@link Programme#lancer()} */ public void testLancer() { - Expression.referencerContexte(contexteTest); contexteTest.raz(); @@ -314,12 +307,33 @@ public class TestProgramme { * Test unitaire de {@link Programme#appelProcedure(Etiquette)} */ public void testAppelProcedure() { - //TODO écrire les tests System.out.println("\tExécution du test de appelProcedure(Etiquette) " + ": "); - echec(); + /* Cas Valides */ + try { + /* Simulation du lancement du programme */ + programmeTest.appelProcedure(new Etiquette(1)); + /* Lancement de 2 procédures */ + programmeTest.appelProcedure(new Etiquette(100)); + programmeTest.appelProcedure(new Etiquette(50)); + } catch (InterpreteurException lancee) { + echec(); + } + + /* Cas Invalides */ + try { + /* Simulation du lancement du programme */ + programmeTest.appelProcedure(new Etiquette(1)); + + /* Lancement de 2 procédures */ + programmeTest.appelProcedure(new Etiquette(-30)); + programmeTest.appelProcedure(new Etiquette(10000000)); + echec(); + } catch (InterpreteurException lancee) { + /* Test OK */ + } } /** @@ -352,13 +366,11 @@ public class TestProgramme { /** * Test unitaire de {@link Programme#vaen(Etiquette)} + * @see TestInstructionVaen#testExecuter() */ public void testVaen() { - //TODO écrire les tests - System.out.println("\tExécution du test de vaen(Etiquette) " - + ": "); - - echec(); + + ": voir TestInstructionVaen#testExecuter()"); + } } diff --git a/src/interpreteurlir/tests/ProgrammeDeTest.java b/src/interpreteurlir/tests/ProgrammeDeTest.java new file mode 100644 index 0000000..d0258c5 --- /dev/null +++ b/src/interpreteurlir/tests/ProgrammeDeTest.java @@ -0,0 +1,69 @@ +/** + * ProgrammeDeTest.java 18 mai 2021 + * IUT Rodez info1 2020-2021, pas de copyright, aucun droit + */ +package interpreteurlir.tests; + +import interpreteurlir.Contexte; +import interpreteurlir.motscles.instructions.*; +import interpreteurlir.programmes.Etiquette; +import interpreteurlir.programmes.Programme; + +/** + * Permet de générer un programme pour les tests contenant plusieurs lignes. + * @author Nicolas Caminade + * @author Sylvan Courtiol + * @author Pierre Debas + * @author Heïa Dexter + * @author Lucas Vabre + */ +public class ProgrammeDeTest { + + /** + * Génère en ajoutant au programme des lignes + * pour les tests + * @param aGenerer programme auquel est ajouté les lignes + * @param contexte contexte pour les instructions + */ + public static void genererProgramme(Programme aGenerer, Contexte contexte) { + Object[][] lignes = { + {new Etiquette(10), new InstructionAffiche("\"Bienvenue dans le programme\"", contexte)}, + {new Etiquette(20), new InstructionAffiche("", contexte)}, + {new Etiquette(30), new InstructionVar("instant = 2021", contexte)}, + {new Etiquette(40), new InstructionProcedure("500", contexte)}, + {new Etiquette(50), new InstructionVar("$message = \"Vous êtes \" + $prenom", contexte)}, + {new Etiquette(60), new InstructionVar("$message = $message+ \" \"", contexte)}, + {new Etiquette(65), new InstructionVar("$message = $message+ $nom", contexte)}, + {new Etiquette(70), new InstructionAffiche("$message", contexte)}, + {new Etiquette(80), new InstructionAffiche("", contexte)}, + {new Etiquette(90), new InstructionAffiche("\"age : \"", contexte)}, + {new Etiquette(100), new InstructionAffiche("age", contexte)}, + {new Etiquette(110), new InstructionAffiche("\" ans\"", contexte)}, + {new Etiquette(120), new InstructionVaen("130", contexte)}, + {new Etiquette(124), new InstructionAffiche("", contexte)}, + {new Etiquette(125), new InstructionAffiche("\"erreur vaen si affiché\"", contexte)}, + {new Etiquette(150), new InstructionAffiche("", contexte)}, + {new Etiquette(200), new InstructionAffiche("\"Merci d'avoir utilisé ce programme !\"", contexte)}, + {new Etiquette(400), new InstructionStop("", contexte)}, + // procedure saisie + {new Etiquette(500), new InstructionAffiche("\"Saisissez votre nom : \"", contexte)}, + {new Etiquette(510), new InstructionEntre("$nom", contexte)}, + {new Etiquette(520), new InstructionAffiche("\"Saisissez votre prénom : \"", contexte)}, + {new Etiquette(530), new InstructionEntre("$prenom", contexte)}, + {new Etiquette(540), new InstructionAffiche("\"Saisissez votre année de naissance (entier) : \"", contexte)}, + {new Etiquette(550), new InstructionEntre("naissance", contexte)}, + {new Etiquette(560), new InstructionProcedure("1000", contexte)}, + {new Etiquette(570), new InstructionRetour("", contexte)}, + // procedure calcul age + {new Etiquette(1000), new InstructionVar("age = instant - naissance", contexte)}, + {new Etiquette(1010), new InstructionRetour("", contexte)}, + + }; + + for (int index = 0 ; index < lignes.length ; index++) { + aGenerer.ajouterLigne((Etiquette)lignes[index][0], + (Instruction)lignes[index][1]); + } + } + +} diff --git a/src/interpreteurlir/tests/TestContexte.java b/src/interpreteurlir/tests/TestContexte.java index c2869bd..0b70d95 100644 --- a/src/interpreteurlir/tests/TestContexte.java +++ b/src/interpreteurlir/tests/TestContexte.java @@ -86,7 +86,6 @@ public class TestContexte { "aucune variable n'est définie\n", "aucune variable n'est définie\n", "aucune variable n'est définie\n", - // TODO refaire quand totalement fonctionnel }; System.out.println("\tExécution du test de Contexte#toString()"); @@ -136,7 +135,8 @@ public class TestContexte { assertEquivalence(fixture[0].lireValeurVariable( new IdentificateurChaine("$chaine")).getValeur(), ""); assertEquivalence(fixture[0].lireValeurVariable( - new IdentificateurEntier("entier")).getValeur(), Integer.valueOf(0)); + new IdentificateurEntier("entier")).getValeur(), + Integer.valueOf(0)); // lire valeur par défaut dans contexte non vide fixture[1].ajouterVariable(new IdentificateurChaine("$zoro"),