From 17736f98f9cd76fde5f22ec5a9e7c331d3478522 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Fri, 14 Feb 2025 16:50:43 +0100 Subject: [PATCH 01/37] more values & use typecheck --- .../interpreter/InterpreterConstants.java | 2 + .../interpreter/InterpreterDecorator.java | 31 +- .../interpreter/ConstructorNoParams.ftl | 3 +- .../AssignmentExpressionsInterpreter.java | 1572 ++++------------- .../CommonExpressionsInterpreter.java | 550 ++++-- .../_visitor/ExpressionsBasisInterpreter.java | 20 +- .../LambdaExpressionsInterpreter.java | 16 + .../_visitor/UglyExpressionsInterpreter.java | 120 ++ .../interpreter/InterpreterUtils.java | 197 +++ .../_visitor/MCCommonLiteralsInterpreter.java | 32 +- .../expressions/AbstractInterpreterTest.java | 246 +-- .../AssignmentExpressionsInterpreterTest.java | 1159 ++++++------ .../CommonExpressionsInterpreterTest.java | 2 +- .../de/monticore/interpreter/MIScope.java | 52 + .../interpreter/ModelInterpreter.java | 29 +- .../java/de/monticore/interpreter/Value.java | 90 +- .../monticore/interpreter/ValueFactory.java | 38 +- .../interpreter/values/BooleanValue.java | 6 +- .../interpreter/values/ByteValue.java | 48 + .../interpreter/values/CharValue.java | 5 - .../interpreter/values/DoubleValue.java | 21 +- .../interpreter/values/ErrorValue.java | 18 + .../interpreter/values/FloatValue.java | 15 - .../interpreter/values/FunctionValue.java | 18 + .../interpreter/values/IntValue.java | 5 - .../interpreter/values/LongValue.java | 10 - .../interpreter/values/NotAValue.java | 6 - .../interpreter/values/ShortValue.java | 43 + .../interpreter/values/StringValue.java | 33 - .../interpreter/values/VoidValue.java | 11 + .../src/main/grammars/Numerals.mc4 | 15 - .../src/main/grammars/SimpleEquations.mc4 | 21 - .../_visitor/NumeralsInterpreter.java | 28 - .../_visitor/SimpleEquationsInterpreter.java | 96 - .../SimpleEquationsInterpreterTest.java | 48 - 35 files changed, 1990 insertions(+), 2616 deletions(-) create mode 100644 monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteValue.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorValue.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionValue.java delete mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/NotAValue.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortValue.java delete mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/StringValue.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidValue.java delete mode 100644 monticore-test/01.experiments/interpreter/src/main/grammars/Numerals.mc4 delete mode 100644 monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 delete mode 100644 monticore-test/01.experiments/interpreter/src/main/java/numerals/_visitor/NumeralsInterpreter.java delete mode 100644 monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java delete mode 100644 monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java index 4d77a01605..ac54db586e 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java @@ -8,6 +8,8 @@ public final class InterpreterConstants { public static final String INTERPRET_METHOD_NAME = "interpret"; public static final String MODELINTERPRETER_FULLNAME = "de.monticore.interpreter.ModelInterpreter"; + + public static final String INTERPRETER_SCOPE_FULLNAME = "de.monticore.interpreter.MIScope"; public static final String VALUE_FULLNAME = "de.monticore.interpreter.Value"; diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java index 00a3220062..8f516f6b7f 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java @@ -126,29 +126,44 @@ EMPTY_BODY, method, new StringHookPoint( public List createMapMembers() { List members = new ArrayList<>(); - + members.add(cdAttributeFacade.createAttribute( PROTECTED.build(), - mcTypeFacade.createMapTypeOf(SYMBOL_FULLNAME, VALUE_FULLNAME), - "contextMap")); + mcTypeFacade.createBasicGenericTypeOf("java.util.Stack", INTERPRETER_SCOPE_FULLNAME), + "scopeCallstack")); ASTCDParameter symbolParameter = cdParameterFacade.createParameter(SYMBOL_FULLNAME, "symbol"); ASTCDParameter valueParameter = cdParameterFacade.createParameter(VALUE_FULLNAME, "value"); + + ASTCDMethod declareVarMethod = cdMethodFacade.createMethod( + PUBLIC.build(), "declareVariable", symbolParameter, valueParameter); + this.replaceTemplate(EMPTY_BODY, declareVarMethod, new StringHookPoint("getRealThis().getCurrentScope().declareVariable(symbol, value);")); + members.add(declareVarMethod); + ASTCDMethod storeMethod = cdMethodFacade.createMethod( PUBLIC.build(), "store", symbolParameter, valueParameter); - this.replaceTemplate(EMPTY_BODY, storeMethod, new StringHookPoint("getRealThis().getContextMap().put(symbol, value);")); + this.replaceTemplate(EMPTY_BODY, storeMethod, new StringHookPoint("getRealThis().getCurrentScope().store(symbol, value);")); members.add(storeMethod); ASTCDMethod loadMethod = cdMethodFacade.createMethod(PUBLIC.build(), VALUE_FULLNAME, "load", symbolParameter); - this.replaceTemplate(EMPTY_BODY, loadMethod, new StringHookPoint("return getRealThis().getContextMap().get(symbol);")); + this.replaceTemplate(EMPTY_BODY, loadMethod, new StringHookPoint("return getRealThis().getCurrentScope().load(symbol);")); members.add(loadMethod); ASTCDMethod getter = cdMethodFacade.createMethod( PUBLIC.build(), - mcTypeFacade.createMapTypeOf(SYMBOL_FULLNAME, VALUE_FULLNAME), - "getContextMap"); - this.replaceTemplate(EMPTY_BODY, getter, new StringHookPoint("return this.contextMap;")); + mcTypeFacade.createQualifiedType(INTERPRETER_SCOPE_FULLNAME), + "getCurrentScope"); + this.replaceTemplate(EMPTY_BODY, getter, new StringHookPoint("return this.scopeCallstack.peek();")); members.add(getter); + + ASTCDParameter scopeParameter = cdParameterFacade.createParameter(INTERPRETER_SCOPE_FULLNAME, "scope"); + ASTCDMethod pushScopeMethod = cdMethodFacade.createMethod(PUBLIC.build(), "pushScope", scopeParameter); + this.replaceTemplate(EMPTY_BODY, pushScopeMethod, new StringHookPoint("this.scopeCallstack.push(scope);")); + members.add(pushScopeMethod); + + ASTCDMethod popScopeMethod = cdMethodFacade.createMethod(PUBLIC.build(), "popScope"); + this.replaceTemplate(EMPTY_BODY, popScopeMethod, new StringHookPoint("this.scopeCallstack.pop();")); + members.add(popScopeMethod); return members; } diff --git a/monticore-generator/src/main/resources/interpreter/ConstructorNoParams.ftl b/monticore-generator/src/main/resources/interpreter/ConstructorNoParams.ftl index 21493050e3..5e8edee364 100644 --- a/monticore-generator/src/main/resources/interpreter/ConstructorNoParams.ftl +++ b/monticore-generator/src/main/resources/interpreter/ConstructorNoParams.ftl @@ -1,7 +1,8 @@ <#-- (c) https://github.com/MontiCore/monticore --> ${tc.signature("names", "types")} -this.contextMap = new java.util.HashMap<>(); +this.scopeCallstack = new Stack(); +this.scopeCallstack.push(new de.monticore.interpreter.MIScope()); this.setRealThis(this); <#list names as name> this.${name?uncap_first} = new ${types[name?index]}(this); diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java index a15c38bec7..09e2b71923 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java @@ -1,20 +1,24 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.expressions.assignmentexpressions._visitor; -import de.monticore.expressions.assignmentexpressions.AssignmentExpressionsMill; import de.monticore.expressions.assignmentexpressions._ast.*; +import de.monticore.expressions.expressionsbasis._ast.ASTExpression; +import de.monticore.interpreter.InterpreterUtils; import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.Value; -import de.monticore.interpreter.ValueFactory; -import de.monticore.interpreter.values.NotAValue; -import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; -import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.interpreter.values.ErrorValue; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symboltable.ISymbol; +import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.SymTypeRelations; +import de.monticore.types3.TypeCheck3; +import de.monticore.types3.util.TypeVisitorOperatorCalculator; import de.se_rwth.commons.logging.Log; import java.util.Optional; import static de.monticore.expressions.assignmentexpressions._ast.ASTConstantsAssignmentExpressions.*; +import static de.monticore.interpreter.ValueFactory.createValue; public class AssignmentExpressionsInterpreter extends AssignmentExpressionsInterpreterTOP { @@ -29,1317 +33,375 @@ public AssignmentExpressionsInterpreter() { //i++ @Override public Value interpret(ASTIncSuffixExpression n) { - String expr = AssignmentExpressionsMill.prettyPrint(n.getExpression(), false); - Optional symbol = ((IBasicSymbolsScope) n.getEnclosingScope()).resolveVariable(expr); - if (symbol.isPresent()) { - Value value = load(symbol.get()); - if (value.isInt()) { - Value res = ValueFactory.createValue(value.asInt() + 1); + ASTExpression expr = n.getExpression(); + SymTypeExpression type = TypeCheck3.typeOf(expr); + Optional symbol = type.getSourceInfo().getSourceSymbol(); + if (symbol.isEmpty()) { + String errorMsg = "Unknown variable symbol detected"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + Value value = load(symbol.get()); + if (value.isError()) return value; + + if (type.isPrimitive()) { + String primitive = type.asPrimitive().getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + Value res = createValue((byte)(value.asByte() + 1)); store(symbol.get(), res); - return res; - } else if (value.isChar()) { - Value res = ValueFactory.createValue(value.asChar() + 1); + return value; + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + Value res = createValue((short)(value.asShort() + 1)); store(symbol.get(), res); - return res; - } else if (value.isLong()) { - Value res = ValueFactory.createValue(value.asLong() + 1); + return value; + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + Value res = createValue((char)(value.asChar() + 1)); store(symbol.get(), res); - return res; - } else if (value.isFloat()) { - Value res = ValueFactory.createValue(value.asFloat() + 1); + return value; + } else if (primitive.equals(BasicSymbolsMill.INT)) { + Value res = createValue(value.asInt() + 1); store(symbol.get(), res); - return (res); - } else if (value.isDouble()) { - Value res = ValueFactory.createValue(value.asDouble() + 1); + return value; + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + Value res = createValue(value.asLong() + 1); store(symbol.get(), res); - return (res); - } else { - Log.error("Suffix incrementation operation is not suitable for this type."); + return value; + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + Value res = createValue(value.asFloat() + 1); + store(symbol.get(), res); + return value; + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + Value res = createValue(value.asDouble() + 1); + store(symbol.get(), res); + return value; } } - return new NotAValue(); + String errorMsg = "Suffix incrementation operation with operand of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } //++i @Override public Value interpret(ASTIncPrefixExpression n) { - String expr = AssignmentExpressionsMill.prettyPrint(n.getExpression(), false); - Optional symbol = ((IBasicSymbolsScope) n.getEnclosingScope()).resolveVariable(expr); - if (symbol.isPresent()) { - Value value = load(symbol.get()); - if (value.isInt()) { - Value res = ValueFactory.createValue(value.asInt() + 1); + ASTExpression expr = n.getExpression(); + SymTypeExpression type = TypeCheck3.typeOf(expr); + Optional symbol = type.getSourceInfo().getSourceSymbol(); + if (symbol.isEmpty()) { + String errorMsg = "Unknown variable symbol detected"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + Value value = load(symbol.get()); + if (value.isError()) return value; + + if (type.isPrimitive()) { + String primitive = type.asPrimitive().getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + Value res = createValue((byte)(value.asByte() + 1)); store(symbol.get(), res); - return (res); - } else if (value.isChar()) { - Value res = ValueFactory.createValue(value.asChar() + 1); + return res; + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + Value res = createValue((short)(value.asShort() + 1)); store(symbol.get(), res); - return (res); - } else if (value.isLong()) { - Value res = ValueFactory.createValue(value.asLong() + 1); + return res; + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + Value res = createValue((char)(value.asChar() + 1)); store(symbol.get(), res); - return (res); - - } else if (value.isFloat()) { - Value res = ValueFactory.createValue(value.asFloat() + 1); + return res; + } else if (primitive.equals(BasicSymbolsMill.INT)) { + Value res = createValue(value.asInt() + 1); store(symbol.get(), res); - return (res); - } else if (value.isDouble()) { - Value res = ValueFactory.createValue(value.asDouble() + 1); + return res; + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + Value res = createValue(value.asLong() + 1); store(symbol.get(), res); - return (res); - } else { - Log.error("Prefix incrementation operation is not suitable for this type."); + return res; + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + Value res = createValue(value.asFloat() + 1); + store(symbol.get(), res); + return res; + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + Value res = createValue(value.asDouble() + 1); + store(symbol.get(), res); + return res; } } - return new NotAValue(); + String errorMsg = "Prefix incrementation operation with operand of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } //i-- @Override public Value interpret(ASTDecSuffixExpression n) { - String expr = AssignmentExpressionsMill.prettyPrint(n.getExpression(), false); - Optional symbol = ((IBasicSymbolsScope) n.getEnclosingScope()).resolveVariable(expr); - if (symbol.isPresent()) { - Value value = load(symbol.get()); - if (value.isInt()) { - Value res = ValueFactory.createValue(value.asInt() - 1); + ASTExpression expr = n.getExpression(); + SymTypeExpression type = TypeCheck3.typeOf(expr); + Optional symbol = type.getSourceInfo().getSourceSymbol(); + if (symbol.isEmpty()) { + String errorMsg = "Unknown variable symbol detected"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + Value value = load(symbol.get()); + if (value.isError()) return value; + + if (type.isPrimitive()) { + String primitive = type.asPrimitive().getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + Value res = createValue((byte)(value.asByte() - 1)); store(symbol.get(), res); - return (res); - } else if (value.isChar()) { - Value res = ValueFactory.createValue(value.asChar() - 1); + return value; + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + Value res = createValue((short)(value.asShort() - 1)); store(symbol.get(), res); - return (res); - } else if (value.isLong()) { - Value res = ValueFactory.createValue(value.asLong() - 1); + return value; + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + Value res = createValue((char)(value.asChar() - 1)); store(symbol.get(), res); - return (res); - - } else if (value.isFloat()) { - Value res = ValueFactory.createValue(value.asFloat() - 1); + return value; + } else if (primitive.equals(BasicSymbolsMill.INT)) { + Value res = createValue(value.asInt() - 1); store(symbol.get(), res); - return (res); - } else if (value.isDouble()) { - Value res = ValueFactory.createValue(value.asDouble() - 1); + return value; + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + Value res = createValue(value.asLong() - 1); store(symbol.get(), res); - return (res); - } else { - Log.error("Suffix decremental operation is not suitable for this type."); + return value; + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + Value res = createValue(value.asFloat() - 1); + store(symbol.get(), res); + return value; + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + Value res = createValue(value.asDouble() - 1); + store(symbol.get(), res); + return value; } } - return new NotAValue(); + String errorMsg = "Suffix decrementation operation with operand of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } //--i @Override public Value interpret(ASTDecPrefixExpression n) { - String expr = AssignmentExpressionsMill.prettyPrint(n.getExpression(), false); - Optional symbol = ((IBasicSymbolsScope) n.getEnclosingScope()).resolveVariable(expr); - if (symbol.isPresent()) { - Value value = load(symbol.get()); - if (value.isInt()) { - Value res = ValueFactory.createValue(value.asInt() - 1); + ASTExpression expr = n.getExpression(); + SymTypeExpression type = TypeCheck3.typeOf(expr); + Optional symbol = type.getSourceInfo().getSourceSymbol(); + if (symbol.isEmpty()) { + String errorMsg = "Unknown variable symbol detected"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + Value value = load(symbol.get()); + if (value.isError()) return value; + + if (type.isPrimitive()) { + String primitive = type.asPrimitive().getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + Value res = createValue((byte)(value.asByte() - 1)); store(symbol.get(), res); - return (res); - } else if (value.isChar()) { - Value res = ValueFactory.createValue(value.asChar() - 1); + return res; + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + Value res = createValue((short)(value.asShort() - 1)); store(symbol.get(), res); - return (res); - } else if (value.isLong()) { - Value res = ValueFactory.createValue(value.asLong() - 1); + return res; + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + Value res = createValue((char)(value.asChar() - 1)); store(symbol.get(), res); - return (res); - - } else if (value.isFloat()) { - Value res = ValueFactory.createValue(value.asFloat() - 1); + return res; + } else if (primitive.equals(BasicSymbolsMill.INT)) { + Value res = createValue(value.asInt() - 1); store(symbol.get(), res); - return (res); - } else if (value.isDouble()) { - Value res = ValueFactory.createValue(value.asDouble() - 1); + return res; + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + Value res = createValue(value.asLong() - 1); store(symbol.get(), res); - return (res); - } else { - Log.error("Prefix decremental operation is not suitable for this type."); + return res; + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + Value res = createValue(value.asFloat() - 1); + store(symbol.get(), res); + return res; + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + Value res = createValue(value.asDouble() - 1); + store(symbol.get(), res); + return res; } } - return new NotAValue(); + String errorMsg = "Prefix decrementation operation with operand of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTAssignmentExpression n) { - String leftExpression = AssignmentExpressionsMill.prettyPrint(n.getLeft(), false); - Optional leftSymbol = ((IBasicSymbolsScope) n.getEnclosingScope()).resolveVariable(leftExpression); - - if (leftSymbol.isPresent()) { - Value rightValue = n.getRight().evaluate(getRealThis()); - int operator = n.getOperator(); - - switch (operator) { - case AND_EQUALS: { //bitwise and - Value leftValue = load(leftSymbol.get()); - if (!(rightValue.isInt() || rightValue.isLong() || rightValue.isChar())) { - Log.error("&= operation is not suitable for these types."); - } else if (!(leftValue.isInt() || leftValue.isLong() || leftValue.isChar())) { - Log.error("&= operation is not suitable for these types."); - } - - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() & rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() & rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() & rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() & rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() & rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() & rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() & rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() & rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() & rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } - - case EQUALS: { - VariableSymbol symbol = leftSymbol.get(); - - if (SymTypeRelations.isString(symbol.getType()) && rightValue.isString()) { - store(leftSymbol.get(), rightValue); - } else if (SymTypeRelations.isBoolean(symbol.getType()) && rightValue.isBoolean()) { - store(leftSymbol.get(), rightValue); - } else if (SymTypeRelations.isChar(symbol.getType()) && rightValue.isChar()) { - store(leftSymbol.get(), rightValue); - } else if (SymTypeRelations.isInt(symbol.getType()) && rightValue.isInt()) { - store(leftSymbol.get(), rightValue); - } else if (SymTypeRelations.isLong(symbol.getType()) && rightValue.isLong()) { - store(leftSymbol.get(), rightValue); - } else if (SymTypeRelations.isFloat(symbol.getType()) && rightValue.isFloat()) { - store(leftSymbol.get(), rightValue); - } else if (SymTypeRelations.isDouble(symbol.getType()) && rightValue.isDouble()) { - store(leftSymbol.get(), rightValue); - } else if (rightValue.isObject()) { - store(leftSymbol.get(), rightValue); - } else { - Log.error("The interpreter only allows = operation for operands of the same type."); - } - break; - } + ASTExpression leftExpr = n.getLeft(); + SymTypeExpression leftType = TypeCheck3.typeOf(leftExpr); + Optional leftSymbol = leftType.getSourceInfo().getSourceSymbol(); + if (leftSymbol.isEmpty()) { + String errorMsg = "Unknown variable symbol detected"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + int operator = n.getOperator(); - case GTGTEQUALS: { //bitwise rightValue shift - Value leftValue = load(leftSymbol.get()); - if (!(rightValue.isInt() || rightValue.isLong() || rightValue.isChar())) { - Log.error(">>= operation is not suitable for these types."); - } else if (!(leftValue.isChar() || leftValue.isInt() || leftValue.isLong())) { - Log.error(">>= operation is not suitable for these types."); - } - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() >> rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() >> rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() >> rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() >> rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() >> rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() >> rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() >> rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() >> rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() >> rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } + Value rightValue = n.getRight().evaluate(getRealThis()); + if (rightValue.isError()) return rightValue; + + SymTypeExpression rightType = TypeCheck3.typeOf(n.getRight()); + + // no operation + if (operator == EQUALS) { + if (leftType.deepEquals(rightType)) { + store(leftSymbol.get(), rightValue); + return rightValue; + } + + if (!SymTypeRelations.isCompatible(leftType, rightType)) { + String errorMsg = "A value of type " + rightType.print() + " can not be writen to a variable of type " + leftType.print() + "."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + if (leftType.isPrimitive() && rightType.isPrimitive()) { + rightValue = InterpreterUtils.convertToPrimitiveImplicit(leftType.asPrimitive().getPrimitiveName(), rightValue); + } else { + String errorMsg = "The implicit conversion from " + rightType.print() + " to " + leftType.print() + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + store(leftSymbol.get(), rightValue); + return rightValue; + } + + Value leftValue = load(leftSymbol.get()); + if (leftValue.isError()) return leftValue; + + Value resultValue; + SymTypeExpression resultType; + + switch (operator) { + case AND_EQUALS: { //bitwise and + resultType = TypeVisitorOperatorCalculator.binaryAnd(leftType, rightType).get(); + resultValue = InterpreterUtils.calcBitwiseLogicalOp(leftValue, rightValue, resultType, + (a, b) -> a & b, (a, b) -> a & b, (a, b) -> a & b, "Bitwise And Assignment"); + break; + } - case GTGTGTEQUALS: { //bitwise rightValue shift - Value leftValue = load(leftSymbol.get()); - if (!(rightValue.isInt() || rightValue.isLong() || rightValue.isChar())) { - Log.error(">>>= operation is not suitable for these types."); - } else if (!(leftValue.isInt() || leftValue.isLong() || leftValue.isChar())) { - Log.error(">>>= operation is not suitable for these types."); - } - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() >>> rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() >>> rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() >>> rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() >>> rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() >>> rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() >>> rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() >>> rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() >>> rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() >>> rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } + case GTGTEQUALS: { //bitwise rightValue shift + resultType = TypeVisitorOperatorCalculator.signedRightShift(leftType, rightType).get(); + resultValue = InterpreterUtils.calcShift(leftValue, rightValue, resultType, + (a, b) -> a >> b, (a, b) -> a >> b, "Bitwise Right Shift Assignment"); + break; + } - case LTLTEQUALS: { - Value leftValue = load(leftSymbol.get()); - if (!(rightValue.isInt() || rightValue.isLong() || rightValue.isChar())) { - Log.error("<<= operation is not suitable for these types."); - } else if (!(leftValue.isInt() || leftValue.isLong() || leftValue.isChar())) { - Log.error("<<= operation is not suitable for these types."); - } - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() << rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() << rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() << rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() << rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() << rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() << rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() << rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() << rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() << rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } + case GTGTGTEQUALS: { //bitwise rightValue shift + resultType = TypeVisitorOperatorCalculator.unsignedRightShift(leftType, rightType).get(); + resultValue = InterpreterUtils.calcShift(leftValue, rightValue, resultType, + (a, b) -> a >>> b, (a, b) -> a >>> b, "Logical Right Shift Assignment"); + break; + } - case MINUSEQUALS: { - Value leftValue = load(leftSymbol.get()); - if (rightValue.isObject() || rightValue.isString() || rightValue.isBoolean()) { - Log.error("-= operation is not suitable for these types."); - } else if (leftValue.isObject() || leftValue.isString() || leftValue.isBoolean()) { - Log.error("-= operation is not suitable for these types."); - } - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() - rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() - rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asInt() - rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asInt() - rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() - rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() - rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() - rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asLong() - rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asLong() - rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() - rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() - rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() - rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asChar() - rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asChar() - rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() - rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isFloat()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asFloat() - rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asFloat() - rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asFloat() - rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asFloat() - rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asFloat() - rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isDouble()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asDouble() - rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asDouble() - rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asDouble() - rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asDouble() - rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asDouble() - rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } + case LTLTEQUALS: { + resultType = TypeVisitorOperatorCalculator.leftShift(leftType, rightType).get(); + resultValue = InterpreterUtils.calcShift(leftValue, rightValue, resultType, + (a, b) -> a << b, (a, b) -> a << b, "Bitwise Left Shift Assignment"); + break; + } - case PERCENTEQUALS: { - Value leftValue = load(leftSymbol.get()); - if (rightValue.isObject() || rightValue.isString() || rightValue.isBoolean()) { - Log.error("%= operation is not suitable for these types."); - } else if (leftValue.isObject() || leftValue.isString() || leftValue.isBoolean()) { - Log.error("%= operation is not suitable for these types."); - } - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() % rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() % rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asInt() % rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asInt() % rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() % rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() % rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() % rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asLong() % rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asLong() % rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() % rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isFloat()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asFloat() % rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asFloat() % rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asFloat() % rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asFloat() % rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asFloat() % rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isDouble()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asDouble() % rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asDouble() % rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asDouble() % rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asDouble() % rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asDouble() % rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() % rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() % rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asChar() % rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asChar() % rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() % rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } + case MINUSEQUALS: { + resultType = TypeVisitorOperatorCalculator.minus(leftType, rightType).get(); + resultValue = InterpreterUtils.calcOp(leftValue, rightValue, resultType, + (a, b) -> a - b, (a, b) -> a - b, (a, b) -> a - b, (a, b) -> a - b, + "Minus Assignment"); + break; + } - case PIPEEQUALS: { - Value leftValue = load(leftSymbol.get()); - if (!(rightValue.isInt() || rightValue.isLong() || rightValue.isChar())) { - Log.error("|= operation is not suitable for these types."); - } else if (!(leftValue.isChar() || leftValue.isInt() || leftValue.isLong())) { - Log.error("|= operation is not suitable for these types."); - } - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() | rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() | rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() | rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() | rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() | rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() | rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() | rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() | rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() | rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } + case PERCENTEQUALS: { + resultType = TypeVisitorOperatorCalculator.modulo(leftType, rightType).get(); + resultValue = InterpreterUtils.calcOp(leftValue, rightValue, resultType, + (a, b) -> a % b, (a, b) -> a % b, (a, b) -> a % b, (a, b) -> a % b, + "Modulo Assignment"); + break; + } - case PLUSEQUALS: { - Value leftValue = load(leftSymbol.get()); + case PIPEEQUALS: { + resultType = TypeVisitorOperatorCalculator.binaryOr(leftType, rightType).get(); + resultValue = InterpreterUtils.calcBitwiseLogicalOp(leftValue, rightValue, resultType, + (a, b) -> a | b, (a, b) -> a | b, (a, b) -> a | b, "Bitwise Or Assignment"); + break; + } - if (leftValue.isString()) { - if (rightValue.isString()) { - Value res = ValueFactory.createValue(leftValue.asString() + rightValue.asString()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asString() + rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asString() + rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asString() + rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asString() + rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asString() + rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isBoolean()) { - Value res = ValueFactory.createValue(leftValue.asString() + rightValue.asBoolean()); - store(leftSymbol.get(), res); - return (res); - } - } else if (leftValue.isBoolean() || leftValue.isObject() || rightValue.isObject()) { - Log.error("+= operation is not suitable for these types."); - } else if (leftValue.isChar()) { - if (rightValue.isString()) { - Value res = ValueFactory.createValue(leftValue.asChar() + rightValue.asString()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() + rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() + rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() + rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asChar() + rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asChar() + rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isBoolean()) { - Log.error("+= operation is not suitable for these types."); - } - } else if (leftValue.isInt()) { - if (rightValue.isString()) { - Value res = ValueFactory.createValue(leftValue.asInt() + rightValue.asString()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() + rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() + rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() + rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asInt() + rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asInt() + rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isBoolean()) { - Log.error("+= operation is not suitable for these types."); - } - } else if (leftValue.isLong()) { - if (rightValue.isString()) { - Value res = ValueFactory.createValue(leftValue.asLong() + rightValue.asString()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() + rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() + rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() + rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asLong() + rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asLong() + rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isBoolean()) { - Log.error("+= operation is not suitable for these types."); - } - } else if (leftValue.isFloat()) { - if (rightValue.isString()) { - Value res = ValueFactory.createValue(leftValue.asFloat() + rightValue.asString()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asFloat() + rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asFloat() + rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asFloat() + rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asFloat() + rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asFloat() + rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isBoolean()) { - Log.error("+= operation is not suitable for these types."); - } - } else if (leftValue.isDouble()) { - if (rightValue.isString()) { - Value res = ValueFactory.createValue(leftValue.asDouble() + rightValue.asString()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asDouble() + rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asDouble() + rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asDouble() + rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asDouble() + rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asDouble() + rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } else if (rightValue.isBoolean()) { - Log.error("+= operation is not suitable for these types."); - } - } - break; - } + case PLUSEQUALS: { + resultType = TypeVisitorOperatorCalculator.plus(leftType, rightType).get(); + resultValue = InterpreterUtils.calcOp(leftValue, rightValue, resultType, + Integer::sum, Long::sum, Float::sum, Double::sum, + "Plus Assignment"); + break; + } - case ROOFEQUALS: { //XOR - Value leftValue = load(leftSymbol.get()); - if (!(rightValue.isInt() || rightValue.isLong() || rightValue.isChar())) { - Log.error("^= operation is not suitable for these types."); - } else if (!(leftValue.isChar() || leftValue.isInt() || leftValue.isLong())) { - Log.error("^= operation is not suitable for these types."); - } - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() ^ rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() ^ rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() ^ rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() ^ rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() ^ rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() ^ rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() ^ rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() ^ rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() ^ rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } + case ROOFEQUALS: { //XOR + resultType = TypeVisitorOperatorCalculator.binaryXor(leftType, rightType).get(); + resultValue = InterpreterUtils.calcBitwiseLogicalOp(leftValue, rightValue, resultType, + (a, b) -> a ^ b, (a, b) -> a ^ b, (a, b) -> a ^ b, "Bitwise Xor Assignment"); + break; + } - case SLASHEQUALS: { - Value leftValue = load(leftSymbol.get()); - if (rightValue.isObject() || rightValue.isString() || rightValue.isBoolean()) { - Log.error("/= operation is not suitable for these types."); - } else if (leftValue.isObject() || leftValue.isString() || leftValue.isBoolean()) { - Log.error("/= operation is not suitable for these types."); - } else if (leftValue.isLong()) { - if (rightValue.asDouble() == 0) { - Log.error("Division by 0 is not supported."); - } - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() / rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() / rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asLong() / rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asLong() / rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() / rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } else if (leftValue.isInt()) { - if (rightValue.asDouble() == 0) { - Log.error("Division by 0 is not supported."); - } - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() / rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() / rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asInt() / rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asInt() / rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() / rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } else if (leftValue.isChar()) { - if (rightValue.asDouble() == 0) { - Log.error("Division by 0 is not supported."); - } - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() / rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() / rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asChar() / rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asChar() / rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() / rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } else if (leftValue.isFloat()) { - if (rightValue.asDouble() == 0) { - Log.error("Division by 0 is not supported."); - } - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asFloat() / rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asFloat() / rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asFloat() / rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asFloat() / rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asFloat() / rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } else if (leftValue.isDouble()) { - if (rightValue.asDouble() == 0) { - Log.error("Division by 0 is not supported."); - } - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asDouble() / rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asDouble() / rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asDouble() / rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asDouble() / rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asDouble() / rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } + case SLASHEQUALS: { + resultType = TypeVisitorOperatorCalculator.divide(leftType, rightType).get(); + if (resultType.isPrimitive()) { + String resultPrimitive = resultType.asPrimitive().getPrimitiveName(); + + if (rightValue.asDouble() == 0.0) { + String errorMsg = "Division by zero is undefined"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + resultValue = InterpreterUtils.calcOpPrimitive(leftValue, rightValue, resultPrimitive, + (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, + "Division Assignment"); break; } + String errorMsg = "Division Assignment operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } - case (STAREQUALS): { - Value leftValue = load(leftSymbol.get()); - if (rightValue.isObject() || rightValue.isString() || rightValue.isBoolean()) { - Log.error("*= operation is not suitable for these types."); - } else if (leftValue.isObject() || leftValue.isString() || leftValue.isBoolean()) { - Log.error("*= operation is not suitable for these types."); - } - if (leftValue.isLong()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asLong() * rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asLong() * rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asLong() * rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asLong() * rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asLong() * rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isInt()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asInt() * rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asInt() * rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asInt() * rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asInt() * rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asInt() * rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isChar()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asChar() * rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asChar() * rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asChar() * rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asChar() * rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asChar() * rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isFloat()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asFloat() * rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asFloat() * rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asFloat() * rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asFloat() * rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asFloat() * rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - if (leftValue.isDouble()) { - if (rightValue.isInt()) { - Value res = ValueFactory.createValue(leftValue.asDouble() * rightValue.asInt()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isLong()) { - Value res = ValueFactory.createValue(leftValue.asDouble() * rightValue.asLong()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isFloat()) { - Value res = ValueFactory.createValue(leftValue.asDouble() * rightValue.asFloat()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isDouble()) { - Value res = ValueFactory.createValue(leftValue.asDouble() * rightValue.asDouble()); - store(leftSymbol.get(), res); - return (res); - } - if (rightValue.isChar()) { - Value res = ValueFactory.createValue(leftValue.asDouble() * rightValue.asChar()); - store(leftSymbol.get(), res); - return (res); - } - } - break; - } - default: - Log.error("Operator is not defined."); + case STAREQUALS: { + resultType = TypeVisitorOperatorCalculator.multiply(leftType, rightType).get(); + resultValue = InterpreterUtils.calcOp(leftValue, rightValue, resultType, + (a, b) -> a * b, (a, b) -> a * b, (a, b) -> a * b, (a, b) -> a * b, + "Multiplication Assignment"); + break; } + default: + Log.error("Operator is not defined."); + return new ErrorValue("Operator is not defined."); + } + + if (resultValue.isError()) return resultValue; + + if (leftType.deepEquals(resultType)) { + } else if (leftType.isPrimitive() && resultType.isPrimitive()) { + resultValue = InterpreterUtils.convertToPrimitiveExplicit(resultType.asPrimitive().getPrimitiveName(), + leftType.asPrimitive().getPrimitiveName(), resultValue); + } else { + String errorMsg = "Cast from " + resultType.print() + " to " + leftType.print() + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } - return new NotAValue(); + + if (resultValue.isError()) return resultValue; + + store(leftSymbol.get(), resultValue); + return resultValue; } } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index f80ebc505f..80e4f4cb8f 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -1,18 +1,18 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.expressions.commonexpressions._visitor; -import de.monticore.expressions.commonexpressions.CommonExpressionsMill; import de.monticore.expressions.commonexpressions._ast.*; import de.monticore.expressions.expressionsbasis._ast.ASTLiteralExpression; import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.Value; -import de.monticore.interpreter.values.NotAValue; -import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; -import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.interpreter.values.ErrorValue; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypePrimitive; +import de.monticore.types3.SymTypeRelations; +import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; -import java.util.Optional; - import static de.monticore.interpreter.ValueFactory.createValue; public class CommonExpressionsInterpreter extends CommonExpressionsInterpreterTOP { @@ -24,231 +24,437 @@ public CommonExpressionsInterpreter() { public CommonExpressionsInterpreter(ModelInterpreter realThis) { super(realThis); } + + public SymTypePrimitive getCompatibleType(SymTypePrimitive type1, SymTypePrimitive type2) { + return SymTypeRelations.isCompatible(type1, type2) + ? type1 + : ( + SymTypeRelations.isCompatible(type2, type1) + ? type2 + : null + ); + } + + public Value isEqual(SymTypePrimitive leftType, Value left, SymTypePrimitive rightType, Value right) { + SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); + if (compatibleType == null) { + String errorMsg = "Equality operation with operands ot type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + String primitive = compatibleType.getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BOOLEAN)) { + return createValue(left.asBoolean() == right.asBoolean()); + } else if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(left.asByte() == right.asByte()); + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(left.asShort() == right.asShort()); + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(left.asChar() == right.asChar()); + } else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(left.asInt() == right.asInt()); + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(left.asLong() == right.asLong()); + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(left.asFloat() == right.asFloat()); + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(left.asDouble() == right.asDouble()); + } + + String errorMsg = "Equality operator with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not implemented."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public Value subtract(SymTypePrimitive leftType, Value left, SymTypePrimitive rightType, Value right) { + SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); + if (compatibleType == null) { + String errorMsg = "Greater or Lesser operation with operands ot type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + String primitive = compatibleType.getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(left.asByte() - right.asByte()); + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(left.asShort() - right.asShort()); + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(left.asChar() - right.asChar()); + } else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(left.asInt() - right.asInt()); + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(left.asLong() - right.asLong()); + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(left.asFloat() - right.asFloat()); + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(left.asDouble() - right.asDouble()); + } + + String errorMsg = "Greater or Lesser operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } @Override public Value interpret(ASTPlusExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - - if (left.isString() || right.isString()) { - return createValue(left.asString() + right.asString()); - } else if (left.isBoolean() || right.isBoolean() || left.isObject() || right.isObject()) { - Log.error("Plus operation is not applicable for these types."); - } else if (left.isDouble() || right.isDouble()) { - return createValue(left.asDouble() + right.asDouble()); - } else if (left.isFloat() || right.isFloat()) { - return createValue(left.asFloat() + right.asFloat()); - } else if (left.isLong() || right.isLong()) { - return createValue(left.asLong() + right.asLong()); - } else if (left.isInt() || right.isInt() || left.isChar() || right.isChar()) { - return createValue(left.asInt() + right.asInt()); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression type = TypeCheck3.typeOf(node); + if (type.isPrimitive()) { + String primitive = type.asPrimitive().getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(left.asByte() + right.asByte()); + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(left.asShort() + right.asShort()); + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(left.asChar() + right.asChar()); + } else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(left.asInt() + right.asInt()); + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(left.asLong() + right.asLong()); + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(left.asFloat() + right.asFloat()); + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(left.asDouble() + right.asDouble()); + } } - return new NotAValue(); + + String errorMsg = "Plus operation with result of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTMinusExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - return compare(left, right); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression typeLeft = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression typeRight = TypeCheck3.typeOf(node.getRight()); + if (typeLeft.isPrimitive() && typeRight.isPrimitive()) { + return subtract(typeLeft.asPrimitive(), left, typeRight.asPrimitive(), right); + } + + String errorMsg = "Minus operation with operands of type '" + typeLeft.print() + "' and '" + + typeRight.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTMultExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - - if (left.isString() || right.isString() || left.isBoolean() || - right.isBoolean() || left.isObject() || right.isObject()) { - Log.error("Minus operation is not applicable for these types."); - } else if (left.isDouble() || right.isDouble()) { - return createValue(left.asDouble() * right.asDouble()); - } else if (left.isFloat() || right.isFloat()) { - return createValue(left.asFloat() * right.asFloat()); - } else if (left.isLong() || right.isLong()) { - return createValue(left.asLong() * right.asLong()); - } else if (left.isInt() || right.isInt() || left.isChar() || right.isChar()) { - return createValue(left.asInt() * right.asInt()); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression type = TypeCheck3.typeOf(node); + if (type.isPrimitive()) { + String primitive = type.asPrimitive().getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(left.asByte() * right.asByte()); + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(left.asShort() * right.asShort()); + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(left.asChar() * right.asChar()); + } else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(left.asInt() * right.asInt()); + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(left.asLong() * right.asLong()); + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(left.asFloat() * right.asFloat()); + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(left.asDouble() * right.asDouble()); + } } - return new NotAValue(); + + String errorMsg = "Multiplication operation with result of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTDivideExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - - if (left.isString() || right.isString() || left.isBoolean() || - right.isBoolean() || left.isObject() || right.isObject()) { - Log.error("Minus operation is not applicable for these types."); - return new NotAValue(); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression type = TypeCheck3.typeOf(node); + if (type.isPrimitive() && (type.asPrimitive().isIntegralType() || type.asPrimitive().isNumericType())) { + String primitive = type.asPrimitive().getPrimitiveName(); + if (right.asDouble() == 0.0) { + String errorMsg = "Division by zero is undefined"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(left.asByte() * right.asByte()); + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(left.asShort() * right.asShort()); + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(left.asChar() * right.asChar()); + } else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(left.asInt() * right.asInt()); + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(left.asLong() * right.asLong()); + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(left.asFloat() * right.asFloat()); + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(left.asDouble() * right.asDouble()); + } } - - if (right.asDouble() == 0) { - Log.error("Division by Zero is not defined."); - return new NotAValue(); - } - - if (left.isDouble() || right.isDouble()) { - return createValue(left.asDouble() / right.asDouble()); - } else if (left.isFloat() || right.isFloat()) { - return createValue(left.asFloat() / right.asFloat()); - } else if (left.isLong() || right.isLong()) { - return createValue(left.asLong() / right.asLong()); - } else if (left.isInt() || right.isInt() || left.isChar() || right.isChar()) { - return createValue(left.asInt() / right.asInt()); - } - - return new NotAValue(); + + String errorMsg = "Division operation with result of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTModuloExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - - if (left.isString() || right.isString() || left.isBoolean() || - right.isBoolean() || left.isObject() || right.isObject()) { - Log.error("Minus operation is not applicable for these types."); - } else if (left.isDouble() || right.isDouble()) { - return createValue(left.asDouble() % right.asDouble()); - } else if (left.isFloat() || right.isFloat()) { - return createValue(left.asFloat() % right.asFloat()); - } else if (left.isLong() || right.isLong()) { - return createValue(left.asLong() % right.asLong()); - } else if (left.isInt() || right.isInt() || left.isChar() || right.isChar()) { - return createValue(left.asInt() % right.asInt()); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression type = TypeCheck3.typeOf(node); + if (type.isPrimitive()) { + String primitive = type.asPrimitive().getPrimitiveName(); + + if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(left.asByte() % right.asByte()); + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(left.asShort() % right.asShort()); + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(left.asChar() % right.asChar()); + } else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(left.asInt() % right.asInt()); + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(left.asLong() % right.asLong()); + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(left.asFloat() % right.asFloat()); + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(left.asDouble() % right.asDouble()); + } } - return new NotAValue(); + + String errorMsg = "Modulo operation with result of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTMinusPrefixExpression node) { - Value expr = node.getExpression().evaluate(getRealThis()); - - if (expr.isObject() || expr.isBoolean() || expr.isString()) { - Log.error("Minus Prefix operation is not applicable for these types."); - } else if (expr.isInt()) { - return createValue(-expr.asInt()); - } else if (expr.isLong()) { - return createValue(-expr.asLong()); - } else if (expr.isDouble()) { - return createValue(-expr.asDouble()); - } else if (expr.isFloat()) { - return createValue(-expr.asFloat()); - } else if (expr.isChar()) { - return createValue(-expr.asChar()); + Value value = node.getExpression().evaluate(getRealThis()); + if (value.isError()) return value; + + SymTypeExpression type = TypeCheck3.typeOf(node); + if (type.isPrimitive()) { + String primitive = type.asPrimitive().getPrimitiveName(); + + if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(-value.asByte()); + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(-value.asShort()); + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(-value.asChar()); + } else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(-value.asInt()); + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(-value.asLong()); + } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(-value.asFloat()); + } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(-value.asDouble()); + } } - return new NotAValue(); + + String errorMsg = "Minus Prefix operation with result of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTPlusPrefixExpression node) { - Value expr = node.getExpression().evaluate(getRealThis()); - - if (expr.isObject() || expr.isBoolean() || expr.isString()) { - Log.error("Plus Prefix operation is not applicable for these types."); - } else if (expr.isInt()) { - return createValue(expr.asInt()); - } else if (expr.isLong()) { - return createValue(+expr.asLong()); - } else if (expr.isDouble()) { - return createValue(+expr.asDouble()); - } else if (expr.isFloat()) { - return createValue(+expr.asFloat()); - } else if (expr.isChar()) { - return createValue(+expr.asChar()); + Value value = node.getExpression().evaluate(getRealThis()); + if (value.isError()) return value; + + SymTypeExpression type = TypeCheck3.typeOf(node); + if (type.isPrimitive() && (type.asPrimitive().isNumericType() || type.asPrimitive().isIntegralType())) { + return value; } - return new NotAValue(); + + String errorMsg = "Minus Prefix operation with result of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTEqualsExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - - if (left.isBoolean() && right.isBoolean()) { - return createValue(left.asBoolean() == right.asBoolean()); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); + if (leftType.isPrimitive() && rightType.isPrimitive()) { + return isEqual(leftType.asPrimitive(), left, rightType.asPrimitive(), right); } - Value result = compare(left, right); - return result instanceof NotAValue ? result : createValue(result.asDouble() == 0); + + String errorMsg = "Equality operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTNotEqualsExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - - if (left.isBoolean() && right.isBoolean()) { - return createValue(left.asBoolean() != right.asBoolean()); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); + if (leftType.isPrimitive() && rightType.isPrimitive()) { + Value result = isEqual(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + if (result.isError()) return result; + + return createValue(!result.asBoolean()); } - Value result = compare(left, right); - return result instanceof NotAValue ? result : createValue(compare(left, right).asDouble() != 0); + + String errorMsg = "Inequality operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTGreaterThanExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - Value result = compare(left, right); - return result instanceof NotAValue ? result : createValue(compare(left, right).asDouble() > 0); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); + if (leftType.isPrimitive() && rightType.isPrimitive()) { + Value result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + if (result.isError()) return result; + + return createValue(result.asDouble() > 0.0); + } + + String errorMsg = "Greater than operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTLessThanExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - Value result = compare(left, right); - return result instanceof NotAValue ? result : createValue(compare(left, right).asDouble() < 0); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); + if (leftType.isPrimitive() && rightType.isPrimitive()) { + Value result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + if (result.isError()) return result; + + return createValue(result.asDouble() < 0.0); + } + + String errorMsg = "Less than operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTGreaterEqualExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - Value result = compare(left, right); - return result instanceof NotAValue ? result : createValue(compare(left, right).asDouble() >= 0); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); + if (leftType.isPrimitive() && rightType.isPrimitive()) { + Value result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + if (result.isError()) return result; + + return createValue(result.asDouble() >= 0.0); + } + + String errorMsg = "Greater equal operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTLessEqualExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - Value result = compare(left, right); - return result instanceof NotAValue ? result : createValue(compare(left, right).asDouble() <= 0); - } - - public Value compare(Value left, Value right) { - if (left.isString() || right.isString() || left.isBoolean() || - right.isBoolean() || left.isObject() || right.isObject()) { - Log.error("Operation is not applicable for these types."); - } else if (left.isDouble() || right.isDouble()) { - return createValue(left.asDouble() - right.asDouble()); - } else if (left.isFloat() || right.isFloat()) { - return createValue(left.asFloat() - right.asFloat()); - } else if (left.isLong() || right.isLong()) { - return createValue(left.asLong() - right.asLong()); - } else if (left.isInt() || right.isInt() || left.isChar() || right.isChar()) { - return createValue(left.asInt() - right.asInt()); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); + if (leftType.isPrimitive() && rightType.isPrimitive()) { + Value result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + if (result.isError()) return result; + + return createValue(result.asDouble() <= 0.0); } - return new NotAValue(); + + String errorMsg = "Less equal operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } //~ -> behaves as a bitwise complement @Override public Value interpret(ASTBooleanNotExpression node) { - Value res = node.getExpression().evaluate(getRealThis()); - - if (res.isFloat() || res.isObject() || res.isString() || res.isDouble() || res.isBoolean()) { - Log.error("Logical Not operation is not applicable for these types."); - } else if (res.isChar()) { - return createValue(~res.asChar()); - } else if (res.isInt()) { - return createValue(~res.asInt()); - } else if (res.isLong()) { - return createValue(~res.asLong()); + Value value = node.getExpression().evaluate(getRealThis()); + if (value.isError()) return value; + + SymTypeExpression type = TypeCheck3.typeOf(node.getExpression()); + if (type.isPrimitive() && type.asPrimitive().isIntegralType()) { + String primitive = type.asPrimitive().getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(~value.asByte()); + } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(~value.asShort()); + } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(~value.asChar()); + } else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(~value.asInt()); + } else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(~value.asLong()); + } } - return new NotAValue(); + + String errorMsg = "Bitwise Not opeartion with operand of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } /*=================================================================*/ @@ -257,37 +463,58 @@ public Value interpret(ASTBooleanNotExpression node) { @Override public Value interpret(ASTLogicalNotExpression node) { - Value res = node.getExpression().evaluate(getRealThis()); - - if (res.isBoolean()) { - return createValue(!res.asBoolean()); + Value value = node.getExpression().evaluate(getRealThis()); + if (value.isError()) return value; + + SymTypeExpression type = TypeCheck3.typeOf(node.getExpression()); + + if (value.isBoolean()) { + return createValue(!value.asBoolean()); } - Log.error("Logical Not operation is not applicable for these types."); - return new NotAValue(); + + String errorMsg = "Logical Not operation with operand of type '" + type.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTBooleanAndOpExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (left.isBoolean() && right.isBoolean()) { return createValue(left.asBoolean() && right.asBoolean()); } - Log.error("Logical And operation is not applicable."); - return new NotAValue(); + + String errorMsg = "Logical And operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTBooleanOrOpExpression node) { Value left = node.getLeft().evaluate(getRealThis()); Value right = node.getRight().evaluate(getRealThis()); - + if (left.isError()) return left; + if (right.isError()) return right; + + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); + SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); + if (left.isBoolean() && right.isBoolean()) { return createValue(left.asBoolean() || right.asBoolean()); } - Log.error("Logical Or operation is not applicable."); - return new NotAValue(); + + String errorMsg = "Logical Or operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override @@ -298,10 +525,8 @@ public Value interpret(ASTBracketExpression node) { @Override public Value interpret(ASTConditionalExpression node) { Value condition = node.getCondition().evaluate(getRealThis()); - if (!condition.isBoolean()) { - Log.error("Condition of Ternary Operator has to be a Boolean Type"); - return new NotAValue(); - } + if (condition.isError()) return condition; + return condition.asBoolean() ? node.getTrueExpression().evaluate(getRealThis()) : node.getFalseExpression().evaluate(getRealThis()); @@ -309,9 +534,12 @@ public Value interpret(ASTConditionalExpression node) { @Override public Value interpret(ASTFieldAccessExpression node) { - String expression = CommonExpressionsMill.prettyPrint(node, false); - Optional symbol = ((IBasicSymbolsScope) node.getEnclosingScope()).resolveVariable(expression); - return symbol.map(this::load).orElse(new NotAValue()); + String errorMsg = "Field Access operation not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); +// String expression = CommonExpressionsMill.prettyPrint(node, false); +// Optional symbol = ((IBasicSymbolsScope) node.getEnclosingScope()).resolveVariable(expression); +// return symbol.map(this::load).orElse(new NullValue()); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java index 543b0ac8af..e82ba24c80 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java @@ -5,9 +5,11 @@ import de.monticore.expressions.expressionsbasis._ast.ASTNameExpression; import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.Value; -import de.monticore.interpreter.values.NotAValue; -import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; -import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.interpreter.values.ErrorValue; +import de.monticore.symboltable.ISymbol; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types3.TypeCheck3; +import de.se_rwth.commons.logging.Log; import java.util.Optional; @@ -23,11 +25,15 @@ public ExpressionsBasisInterpreter(ModelInterpreter realThis) { @Override public Value interpret(ASTNameExpression n) { - Optional symbol = ((IBasicSymbolsScope) n.getEnclosingScope()).resolveVariable(n.getName()); - if (symbol.isPresent()) { - return load(symbol.get()); + SymTypeExpression type = TypeCheck3.typeOf(n); + Optional symbol = type.getSourceInfo().getSourceSymbol(); + if (symbol.isEmpty()) { + String errorMsg = "Unknown variable symbol detected"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } - return new NotAValue(); + + return load(symbol.get()); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java new file mode 100644 index 0000000000..36491273f9 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java @@ -0,0 +1,16 @@ +package de.monticore.expressions.lambdaexpressions._visitor; + +import de.monticore.interpreter.ModelInterpreter; + +public class LambdaExpressionsInterpreter extends LambdaExpressionsInterpreterTOP { + + public LambdaExpressionsInterpreter() { + super(); + } + + public LambdaExpressionsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + +} diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java new file mode 100644 index 0000000000..9664fa0f93 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java @@ -0,0 +1,120 @@ +package de.monticore.expressions.uglyexpressions._visitor; + +import de.monticore.expressions.uglyexpressions._ast.ASTTypeCastExpression; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.Value; +import de.monticore.interpreter.ValueFactory; +import de.monticore.interpreter.values.ErrorValue; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types3.TypeCheck3; +import de.se_rwth.commons.logging.Log; + +public class UglyExpressionsInterpreter extends UglyExpressionsInterpreterTOP { + + public UglyExpressionsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + public UglyExpressionsInterpreter() { + super(); + } + + @Override + public Value interpret(ASTTypeCastExpression node) { + SymTypeExpression afterType = TypeCheck3.symTypeFromAST(node.getMCType()); + SymTypeExpression beforeType = TypeCheck3.typeOf(node.getExpression()); + + Value value = node.getExpression().evaluate(getRealThis()); + + if (afterType.isPrimitive() && beforeType.isPrimitive()) { + return convertPrimitive(beforeType.asPrimitive().getPrimitiveName(), + afterType.asPrimitive().getPrimitiveName(), value); + } + + String errorMsg = "Type Cast operation from " + beforeType.print() + " to " + afterType.print() + + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public Value convertPrimitive(String fromType, String toType, Value value) { + if (toType.equals(BasicSymbolsMill.BOOLEAN) || fromType.equals(BasicSymbolsMill.BOOLEAN)) { + String errorMsg = "Cast to or from boolean is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + if (toType.equals(BasicSymbolsMill.BYTE)) { + if (fromType.equals(BasicSymbolsMill.DOUBLE)) { + return ValueFactory.createValue((byte)value.asDouble()); + } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { + return ValueFactory.createValue((byte)value.asFloat()); + } else if (fromType.equals(BasicSymbolsMill.LONG)) { + return ValueFactory.createValue((byte)value.asLong()); + } else if (fromType.equals(BasicSymbolsMill.INT)) { + return ValueFactory.createValue((byte)value.asInt()); + } else if (fromType.equals(BasicSymbolsMill.SHORT)) { + return ValueFactory.createValue((byte)value.asShort()); + } else if (fromType.equals(BasicSymbolsMill.CHAR)) { + return ValueFactory.createValue((byte)value.asChar()); + } + return ValueFactory.createValue(value.asByte()); + } else if (toType.equals(BasicSymbolsMill.SHORT)) { + if (fromType.equals(BasicSymbolsMill.DOUBLE)) { + return ValueFactory.createValue((short)value.asDouble()); + } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { + return ValueFactory.createValue((short)value.asFloat()); + } else if (fromType.equals(BasicSymbolsMill.LONG)) { + return ValueFactory.createValue((short)value.asLong()); + } else if (fromType.equals(BasicSymbolsMill.INT)) { + return ValueFactory.createValue((short)value.asInt()); + } else if (fromType.equals(BasicSymbolsMill.CHAR)) { + return ValueFactory.createValue((short)value.asChar()); + } + return ValueFactory.createValue(value.asShort()); + } else if (toType.equals(BasicSymbolsMill.CHAR)) { + if (fromType.equals(BasicSymbolsMill.DOUBLE)) { + return ValueFactory.createValue((char)value.asDouble()); + } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { + return ValueFactory.createValue((char)value.asFloat()); + } else if (fromType.equals(BasicSymbolsMill.LONG)) { + return ValueFactory.createValue((char)value.asLong()); + } else if (fromType.equals(BasicSymbolsMill.INT)) { + return ValueFactory.createValue((char)value.asInt()); + } else if (fromType.equals(BasicSymbolsMill.SHORT)) { + return ValueFactory.createValue((char)value.asShort()); + } else if (fromType.equals(BasicSymbolsMill.BYTE)) { + return ValueFactory.createValue((char)value.asByte()); + } + return ValueFactory.createValue(value.asChar()); + } else if (toType.equals(BasicSymbolsMill.INT)) { + if (fromType.equals(BasicSymbolsMill.DOUBLE)) { + return ValueFactory.createValue((int)value.asDouble()); + } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { + return ValueFactory.createValue((int)value.asFloat()); + } else if (fromType.equals(BasicSymbolsMill.LONG)) { + return ValueFactory.createValue((int)value.asLong()); + } + return ValueFactory.createValue(value.asInt()); + } else if (toType.equals(BasicSymbolsMill.LONG)) { + if (fromType.equals(BasicSymbolsMill.DOUBLE)) { + return ValueFactory.createValue((long)value.asDouble()); + } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { + return ValueFactory.createValue((long)value.asFloat()); + } + return ValueFactory.createValue(value.asLong()); + } else if (toType.equals(BasicSymbolsMill.FLOAT)) { + if (fromType.equals(BasicSymbolsMill.DOUBLE)) { + return ValueFactory.createValue((float)value.asDouble()); + } + return ValueFactory.createValue(value.asFloat()); + + } else if (toType.equals(BasicSymbolsMill.DOUBLE)) { + return ValueFactory.createValue(value.asDouble()); + } + + String errorMsg = "Cast from " + fromType + " to " + toType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java new file mode 100644 index 0000000000..3d5fa6a571 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java @@ -0,0 +1,197 @@ +package de.monticore.interpreter; + +import de.monticore.interpreter.values.ErrorValue; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.types.check.SymTypeExpression; +import de.se_rwth.commons.logging.Log; + +import java.util.function.BiFunction; +import java.util.function.BinaryOperator; + +import static de.monticore.interpreter.ValueFactory.createValue; + +public class InterpreterUtils { + + public static Value calcBitwiseOpPrimitive(Value v1, Value v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, + String opName) { + switch (resultType) { + case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); + case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); + } + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value calcBitwiseLogicalOpPrimitive(Value v1, Value v2, String resultType, BinaryOperator opBool, BinaryOperator opInt, + BinaryOperator opLong, String opName) { + switch (resultType) { + case BasicSymbolsMill.BOOLEAN: return createValue((boolean)opBool.apply(v1.asBoolean(), v2.asBoolean())); + case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); + case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); + } + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value calcOpPrimitive(Value v1, Value v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, + BinaryOperator opFloat, BinaryOperator opDouble, String opName) { + switch (resultType) { + case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); + case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); + case BasicSymbolsMill.FLOAT: return createValue((float)opFloat.apply(v1.asFloat(), v2.asFloat())); + case BasicSymbolsMill.DOUBLE: return createValue((double)opDouble.apply(v1.asDouble(), v2.asDouble())); + } + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value calcShiftPrimitive(Value v1, Value v2, String resultType, BiFunction opInt, BinaryOperator opLong, + String opName) { + switch (resultType) { + case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asLong())); + case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); + } + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value calcOp(Value v1, Value v2, SymTypeExpression resultType, BinaryOperator opInt, BinaryOperator opLong, + BinaryOperator opFloat, BinaryOperator opDouble, String opName) { + if (resultType.isPrimitive()) { + return calcOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opFloat, opDouble, opName); + } + + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value calcBitwiseOp(Value v1, Value v2, SymTypeExpression resultType, BinaryOperator opInt, BinaryOperator opLong, + String opName) { + if (resultType.isPrimitive()) { + return calcBitwiseOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opName); + } + + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value calcBitwiseLogicalOp(Value v1, Value v2, SymTypeExpression resultType, BinaryOperator opBool, BinaryOperator opInt, + BinaryOperator opLong, String opName) { + if (resultType.isPrimitive()) { + return calcBitwiseLogicalOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opBool, opInt, opLong, opName); + } + + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value calcShift(Value v1, Value v2, SymTypeExpression resultType, BiFunction opInt, + BinaryOperator opLong, String opName) { + if (resultType.isPrimitive()) { + return calcShiftPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opName); + } + + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value convertToPrimitiveExplicit(String from, String to, Value value) { + if (to.equals(BasicSymbolsMill.BOOLEAN) || from.equals(BasicSymbolsMill.BOOLEAN)) { + String errorMsg = "Cast to or from boolean is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + if (to.equals(BasicSymbolsMill.BYTE)) { + switch (from) { + case BasicSymbolsMill.DOUBLE: return createValue((byte) value.asDouble()); + case BasicSymbolsMill.FLOAT: return createValue((byte) value.asFloat()); + case BasicSymbolsMill.LONG: return createValue((byte) value.asLong()); + case BasicSymbolsMill.INT: return createValue((byte) value.asInt()); + case BasicSymbolsMill.SHORT: return createValue((byte) value.asShort()); + case BasicSymbolsMill.CHAR: return createValue((byte) value.asChar()); + default: return createValue(value.asByte()); + } + + } else if (to.equals(BasicSymbolsMill.SHORT)) { + switch (from) { + case BasicSymbolsMill.DOUBLE: return createValue((short) value.asDouble()); + case BasicSymbolsMill.FLOAT: return createValue((short) value.asFloat()); + case BasicSymbolsMill.LONG: return createValue((short) value.asLong()); + case BasicSymbolsMill.INT: return createValue((short) value.asInt()); + case BasicSymbolsMill.CHAR: return createValue((short) value.asChar()); + default: return createValue(value.asShort()); + } + + } else if (to.equals(BasicSymbolsMill.CHAR)) { + switch (from) { + case BasicSymbolsMill.DOUBLE: return createValue((char) value.asDouble()); + case BasicSymbolsMill.FLOAT: return createValue((char) value.asFloat()); + case BasicSymbolsMill.LONG: return createValue((char) value.asLong()); + case BasicSymbolsMill.INT: return createValue((char) value.asInt()); + case BasicSymbolsMill.SHORT: return createValue((char) value.asShort()); + case BasicSymbolsMill.BYTE: return createValue((char) value.asByte()); + default: return createValue(value.asChar()); + } + + } else if (to.equals(BasicSymbolsMill.INT)) { + switch (from) { + case BasicSymbolsMill.DOUBLE: return createValue((int) value.asDouble()); + case BasicSymbolsMill.FLOAT: return createValue((int) value.asFloat()); + case BasicSymbolsMill.LONG: return createValue((int) value.asLong()); + default: return createValue(value.asInt()); + } + + } else if (to.equals(BasicSymbolsMill.LONG)) { + if (from.equals(BasicSymbolsMill.DOUBLE)) { + return createValue((long)value.asDouble()); + } else if (from.equals(BasicSymbolsMill.FLOAT)) { + return createValue((long)value.asFloat()); + } + return createValue(value.asLong()); + + } else if (to.equals(BasicSymbolsMill.FLOAT)) { + if (from.equals(BasicSymbolsMill.DOUBLE)) { + return createValue((float)value.asDouble()); + } + return createValue(value.asFloat()); + + } else if (to.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(value.asDouble()); + } + + String errorMsg = "Cast from " + from + " to " + to + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + + public static Value convertToPrimitiveImplicit(String targetType, Value value) { + if (targetType.equals(BasicSymbolsMill.BYTE)) { + return createValue(value.asByte()); + } else if (targetType.equals(BasicSymbolsMill.SHORT)) { + return createValue(value.asShort()); + } else if (targetType.equals(BasicSymbolsMill.CHAR)) { + return createValue(value.asChar()); + } else if (targetType.equals(BasicSymbolsMill.INT)) { + return createValue(value.asInt()); + } else if (targetType.equals(BasicSymbolsMill.LONG)) { + return createValue(value.asLong()); + } else if (targetType.equals(BasicSymbolsMill.FLOAT)) { + return createValue(value.asFloat()); + } else if (targetType.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(value.asDouble()); + } + + String errorMsg = "Implicit cast to " + targetType + " is not supported."; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } + +} diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java index e96fa4d954..f4b2f54d6a 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java @@ -4,7 +4,11 @@ import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.Value; import de.monticore.interpreter.ValueFactory; +import de.monticore.interpreter.values.ErrorValue; import de.monticore.literals.mccommonliterals._ast.*; +import de.se_rwth.commons.logging.Log; + +import static de.monticore.interpreter.ValueFactory.createValue; public class MCCommonLiteralsInterpreter extends MCCommonLiteralsInterpreterTOP { @@ -17,63 +21,65 @@ public MCCommonLiteralsInterpreter(ModelInterpreter realThis) { } @Override - public Value interpret(ASTNullLiteral node){ - return ValueFactory.createValue(null); + public Value interpret(ASTNullLiteral node) { + String errorMsg = "Null should not be used"; + Log.error(errorMsg); + return new ErrorValue(errorMsg); } @Override public Value interpret(ASTBooleanLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTCharLiteral node) { - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTStringLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTNatLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTSignedNatLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTBasicLongLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTSignedBasicLongLiteral node) { - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTBasicFloatLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTSignedBasicFloatLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTBasicDoubleLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } @Override public Value interpret(ASTSignedBasicDoubleLiteral node){ - return ValueFactory.createValue(node.getValue()); + return createValue(node.getValue()); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java index e7561ebabf..3cb483512b 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java @@ -2,25 +2,28 @@ package de.monticore.expressions; import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; -import de.monticore.expressions.combineexpressionswithliterals._ast.ASTFoo; -import de.monticore.expressions.combineexpressionswithliterals._parser.CombineExpressionsWithLiteralsParser; import de.monticore.expressions.combineexpressionswithliterals._symboltable.CombineExpressionsWithLiteralsScopesGenitorDelegator; import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsInterpreter; +import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.interpreter.Value; -import de.monticore.interpreter.values.NotAValue; -import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.symboltable.modifiers.AccessModifier; +import de.monticore.interpreter.values.ErrorValue; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types3.AbstractTypeVisitorTest; +import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import java.io.IOException; -import java.util.Optional; +import static de.monticore.interpreter.ValueFactory.createValue; +import static de.monticore.types3.util.DefsTypesForTests.inScope; +import static de.monticore.types3.util.DefsTypesForTests.variable; import static junit.framework.TestCase.*; import static junit.framework.TestCase.assertEquals; -public abstract class AbstractInterpreterTest { +public abstract class AbstractInterpreterTest extends AbstractTypeVisitorTest { protected static final double delta = 0.00001; @@ -33,172 +36,76 @@ public abstract class AbstractInterpreterTest { protected static final int STRING = 64; protected CombineExpressionsWithLiteralsInterpreter interpreter; - protected CombineExpressionsWithLiteralsParser parser; protected CombineExpressionsWithLiteralsScopesGenitorDelegator delegator; - public void init(int values) { - CombineExpressionsWithLiteralsMill.reset(); - CombineExpressionsWithLiteralsMill.init(); - BasicSymbolsMill.initializePrimitives(); - BasicSymbolsMill.initializeString(); + public void init() { LogStub.init(); Log.clearFindings(); Log.enableFailQuick(false); - - parser = CombineExpressionsWithLiteralsMill.parser(); + delegator = CombineExpressionsWithLiteralsMill.scopesGenitorDelegator(); interpreter = new CombineExpressionsWithLiteralsInterpreter(); try { - if ((values & BOOL) != 0) { - initBool(); - } - - if ((values & INT) != 0) { - initInt(); - } - - if ((values & LONG) != 0) { - initLong(); - } - - if ((values & FLOAT) != 0) { - initFloat(); - } - - if ((values & DOUBLE) != 0) { - initDouble(); - } - - if ((values & CHAR) != 0) { - initChar(); - } - - if ((values & STRING) != 0) { - initString(); - } + initBool(); + initChar(); + initByte(); + initShort(); + initInt(); + initLong(); + initFloat(); + initDouble(); } catch (IOException e) { System.out.println(e.getMessage()); } } protected void initBool() throws IOException { - final Optional optAST = parser.parse_String("bar b = true"); - assertTrue(optAST.isPresent()); - final ASTFoo ast = optAST.get(); - delegator.createFromAST(ast); - CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("b", - CombineExpressionsWithLiteralsMill.variableSymbolBuilder() - .setType(SymTypeExpressionFactory.createPrimitive("boolean")) - .setName("b") - .setFullName("b") - .setPackageName("") - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) - .build()); - interpreter.interpret(ast); + VariableSymbol varSymbol = variable("b", SymTypeExpressionFactory.createPrimitive("boolean")); + inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); + interpreter.declareVariable(varSymbol, createValue(true)); + } + + protected void initChar() throws IOException { + VariableSymbol varSymbol = variable("c", SymTypeExpressionFactory.createPrimitive("char")); + inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); + interpreter.declareVariable(varSymbol, createValue('a')); + } + + protected void initByte() throws IOException { + VariableSymbol varSymbol = variable("by", SymTypeExpressionFactory.createPrimitive("byte")); + inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); + interpreter.declareVariable(varSymbol, createValue((byte)3)); + } + + protected void initShort() throws IOException { + VariableSymbol varSymbol = variable("s", SymTypeExpressionFactory.createPrimitive("short")); + inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); + interpreter.declareVariable(varSymbol, createValue((short)256)); } protected void initInt() throws IOException { - final Optional optAST = parser.parse_String("bar i = 1"); - assertTrue(optAST.isPresent()); - final ASTFoo ast = optAST.get(); - delegator.createFromAST(ast); - CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("i", - CombineExpressionsWithLiteralsMill.variableSymbolBuilder() - .setType(SymTypeExpressionFactory.createPrimitive("int")) - .setName("i") - .setFullName("i") - .setPackageName("") - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) - .build()); - interpreter.interpret(ast); + VariableSymbol varSymbol = variable("i", SymTypeExpressionFactory.createPrimitive("int")); + inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); + interpreter.declareVariable(varSymbol, createValue(1)); } protected void initLong() throws IOException { - final Optional optAST = parser.parse_String("bar l = 5L"); - assertTrue(optAST.isPresent()); - final ASTFoo ast = optAST.get(); - delegator.createFromAST(ast); - CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("l", - CombineExpressionsWithLiteralsMill.variableSymbolBuilder() - .setType(SymTypeExpressionFactory.createPrimitive("long")) - .setName("l") - .setFullName("l") - .setPackageName("") - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) - .build()); - interpreter.interpret(ast); + VariableSymbol varSymbol = variable("l", SymTypeExpressionFactory.createPrimitive("long")); + inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); + interpreter.declareVariable(varSymbol, createValue(5L)); } protected void initFloat() throws IOException { - final Optional optAST = parser.parse_String("bar f = 1.5f"); - assertTrue(optAST.isPresent()); - final ASTFoo ast = optAST.get(); - delegator.createFromAST(ast); - CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("f", - CombineExpressionsWithLiteralsMill.variableSymbolBuilder() - .setType(SymTypeExpressionFactory.createPrimitive("float")) - .setName("f") - .setFullName("f") - .setPackageName("") - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) - .build()); - interpreter.interpret(ast); + VariableSymbol varSymbol = variable("f", SymTypeExpressionFactory.createPrimitive("float")); + inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); + interpreter.declareVariable(varSymbol, createValue(1.5f)); } protected void initDouble() throws IOException { - final Optional optAST = parser.parse_String("bar d = 3.14"); - assertTrue(optAST.isPresent()); - final ASTFoo ast = optAST.get(); - delegator.createFromAST(ast); - CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("d", - CombineExpressionsWithLiteralsMill.variableSymbolBuilder() - .setType(SymTypeExpressionFactory.createPrimitive("double")) - .setName("d") - .setFullName("d") - .setPackageName("") - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) - .build()); - interpreter.interpret(ast); - } - - protected void initChar() throws IOException { - final Optional optAST = parser.parse_String("bar c = 'a'"); - assertTrue(optAST.isPresent()); - final ASTFoo ast = optAST.get(); - delegator.createFromAST(ast); - CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("c", - CombineExpressionsWithLiteralsMill.variableSymbolBuilder() - .setType(SymTypeExpressionFactory.createPrimitive("char")) - .setName("c") - .setFullName("c") - .setPackageName("") - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) - .build()); - interpreter.interpret(ast); - } - - protected void initString() throws IOException { - final Optional optAST = parser.parse_String("bar s = \"hello\""); - assertTrue(optAST.isPresent()); - final ASTFoo ast = optAST.get(); - delegator.createFromAST(ast); - CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("s", - CombineExpressionsWithLiteralsMill.variableSymbolBuilder() - .setType(SymTypeExpressionFactory.createPrimitive("String")) - .setName("s") - .setFullName("s") - .setPackageName("") - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) - .build()); - interpreter.interpret(ast); + VariableSymbol varSymbol = variable("d", SymTypeExpressionFactory.createPrimitive("double")); + inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); + interpreter.declareVariable(varSymbol, createValue(3.14)); } protected void testValidExpression(String expr, Value expected) { @@ -213,28 +120,31 @@ protected void testValidExpression(String expr, Value expected) { assertTrue(Log.getFindings().isEmpty()); if (expected.isBoolean()) { assertTrue(interpretationResult.isBoolean()); - assertEquals(interpretationResult.asBoolean(), expected.asBoolean()); + assertEquals(expected.asBoolean(), interpretationResult.asBoolean()); + } else if (expected.isByte()) { + assertTrue(interpretationResult.isByte()); + assertEquals(expected.asByte(), interpretationResult.asByte()); + } else if (expected.isShort()) { + assertTrue(interpretationResult.isShort()); + assertEquals(expected.asShort(), interpretationResult.asShort()); + } else if (expected.isChar()) { + assertTrue(interpretationResult.isChar()); + assertEquals(expected.asChar(), interpretationResult.asChar()); } else if (expected.isInt()) { assertTrue(interpretationResult.isInt()); - assertEquals(interpretationResult.asInt(), expected.asInt()); + assertEquals(expected.asInt(), interpretationResult.asInt()); } else if (expected.isLong()) { assertTrue(interpretationResult.isLong()); - assertEquals(interpretationResult.asLong(), expected.asLong()); + assertEquals(expected.asLong(), interpretationResult.asLong()); } else if (expected.isFloat()) { assertTrue(interpretationResult.isFloat()); - assertEquals(interpretationResult.asFloat(), expected.asFloat(), delta); + assertEquals(expected.asFloat(), interpretationResult.asFloat(), delta); } else if (expected.isDouble()) { assertTrue(interpretationResult.isDouble()); - assertEquals(interpretationResult.asDouble(), expected.asDouble(), delta); - } else if (expected.isChar()) { - assertTrue(interpretationResult.isChar()); - assertEquals(interpretationResult.asChar(), expected.asChar()); - } else if (expected.isString()) { - assertTrue(interpretationResult.isString()); - assertEquals(interpretationResult.asString(), expected.asString()); + assertEquals(expected.asDouble(), interpretationResult.asDouble(), delta); } else if (expected.isObject()) { assertTrue(interpretationResult.isObject()); - assertEquals(interpretationResult.asObject(), expected.asObject()); + assertEquals(expected.asObject(), interpretationResult.asObject()); } assertTrue(Log.getFindings().isEmpty()); } @@ -242,21 +152,27 @@ protected void testValidExpression(String expr, Value expected) { protected void testInvalidExpression(String expr) { Log.clearFindings(); Value interpretationResult = null; + try { interpretationResult = parseExpressionAndInterpret(expr); } catch (IOException e) { - System.out.println(e.getMessage()); + throw new RuntimeException(e); } + assertNotNull(interpretationResult); - assertEquals(Log.getFindings().size(), 1); - assertTrue(interpretationResult instanceof NotAValue); + assertFalse(Log.getFindings().isEmpty()); + assertTrue(interpretationResult.isError()); } protected Value parseExpressionAndInterpret(String expr) throws IOException { - final Optional optAST = parser.parse_String("bar " + expr); - assertTrue(optAST.isPresent()); - final ASTFoo ast = optAST.get(); - delegator.createFromAST(ast); + final ASTExpression ast = parseExpr(expr); + generateScopes(ast); + SymTypeExpression type = TypeCheck3.typeOf(ast); + if (type.isObscureType()) { + String errorMsg = "Invalid Expression: " + expr; + Log.error(errorMsg); + return new ErrorValue(errorMsg); + } return interpreter.interpret(ast); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java index 826ac66bdf..356ff4e963 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java @@ -9,7 +9,7 @@ import java.util.stream.Stream; -import static java.util.Objects.isNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; import static de.monticore.interpreter.ValueFactory.createValue; @@ -17,695 +17,578 @@ public class AssignmentExpressionsInterpreterTest extends AbstractInterpreterTes protected static Stream incSuffixExpression() { return Stream.of( - arguments("b++", null, BOOL), - arguments("i++", createValue(2), INT), - arguments("l++", createValue(6L), LONG), - arguments("f++", createValue(2.5f), FLOAT), - arguments("d++", createValue(4.14), DOUBLE), - arguments("c++", createValue(98), CHAR), - arguments("s++", null, STRING)); + arguments("b++", null), + arguments("by++", createValue((byte)3)), + arguments("s++", createValue((short)256)), + arguments("c++", createValue('a')), + arguments("i++", createValue(1)), + arguments("l++", createValue(5L)), + arguments("f++", createValue(1.5f)), + arguments("d++", createValue(3.14))); } protected static Stream incPrefixExpression() { return Stream.of( - arguments("++b", null, BOOL), - arguments("++i", createValue(2), INT), - arguments("++l", createValue(6L), LONG), - arguments("++f", createValue(2.5f), FLOAT), - arguments("++d", createValue(4.14), DOUBLE), - arguments("++c", createValue(98), CHAR), - arguments("++s", null, STRING)); + arguments("++b", null), + arguments("++by", createValue((byte)4)), + arguments("++s", createValue((short)257)), + arguments("++c", createValue('b')), + arguments("++i", createValue(2)), + arguments("++l", createValue(6L)), + arguments("++f", createValue(2.5f)), + arguments("++d", createValue(4.14))); } protected static Stream decSuffixExpression() { return Stream.of( - arguments("c--", createValue(96), CHAR), - arguments("s--", null, STRING), - arguments("i--", createValue(0), INT), - arguments("l--", createValue(4L), LONG), - arguments("f--", createValue(0.5f), FLOAT), - arguments("d--", createValue(2.14), DOUBLE), - arguments("b--", null, BOOL)); + arguments("b--", null), + arguments("by--", createValue((byte)3)), + arguments("s--", createValue((short)256)), + arguments("c--", createValue('a')), + arguments("i--", createValue(1)), + arguments("l--", createValue(5L)), + arguments("f--", createValue(1.5f)), + arguments("d--", createValue(3.14))); } protected static Stream decPrefixExpression() { return Stream.of( - arguments("--c", createValue(96), CHAR), - arguments("--s", null, STRING), - arguments("--i", createValue(0), INT), - arguments("--l", createValue(4L), LONG), - arguments("--f", createValue(0.5f), FLOAT), - arguments("--d", createValue(2.14), DOUBLE), - arguments("--b", null, BOOL)); + arguments("--b", null), + arguments("--by", createValue((byte)2)), + arguments("--s", createValue((short)255)), + arguments("--c", createValue('`')), + arguments("--i", createValue(0)), + arguments("--l", createValue(4L)), + arguments("--f", createValue(0.5f)), + arguments("--d", createValue(2.14))); } protected static Stream andEqualsExpression() { return Stream.of( - arguments("b &= false", null, BOOL), - arguments("b &= 1", null, BOOL), - arguments("b &= 2L", null, BOOL), - arguments("b &= 1.5f", null, BOOL), - arguments("b &= 3.14", null, BOOL), - arguments("b &= 'c'", null, BOOL), - arguments("b &= \"test\"", null, BOOL), - - arguments("i &= false", null, INT), - arguments("i &= 1", createValue(1), INT), - arguments("i &= 2L", createValue(0L), INT), - arguments("i &= 1.5f", null, INT), - arguments("i &= 3.14", null, INT), - arguments("i &= 'a'", createValue(1), INT), - arguments("i &= \"test\"", null, INT), - - arguments("l &= false", null, LONG), - arguments("l &= 1", createValue(1L), LONG), - arguments("l &= 2L", createValue(0L), LONG), - arguments("l &= 1.5f", null, LONG), - arguments("l &= 3.14", null, LONG), - arguments("l &= 'a'", createValue(1L), LONG), - arguments("l &= \"test\"", null, LONG), - - arguments("f &= false", null, FLOAT), - arguments("f &= 1", null, FLOAT), - arguments("f &= 2L", null, FLOAT), - arguments("f &= 1.5f", null, FLOAT), - arguments("f &= 3.14", null, FLOAT), - arguments("f &= 'a'", null, FLOAT), - arguments("f &= \"test\"", null, FLOAT), - - arguments("d &= false", null, DOUBLE), - arguments("d &= 1", null, DOUBLE), - arguments("d &= 2L", null, DOUBLE), - arguments("d &= 1.5f", null, DOUBLE), - arguments("d &= 3.14", null, DOUBLE), - arguments("d &= 'a'", null, DOUBLE), - arguments("d &= \"test\"", null, DOUBLE), - - arguments("c &= false", null, CHAR), - arguments("c &= 1", createValue(1), CHAR), - arguments("c &= 2L", createValue(0L), CHAR), - arguments("c &= 1.5f", null, CHAR), - arguments("c &= 3.14", null, CHAR), - arguments("c &= 'a'", createValue(97), CHAR), - arguments("c &= \"test\"", null, CHAR), - - arguments("s &= false", null, STRING), - arguments("s &= 1", null, STRING), - arguments("s &= 2L", null, STRING), - arguments("s &= 1.5f", null, STRING), - arguments("s &= 3.14", null, STRING), - arguments("s &= 'a'", null, STRING), - arguments("s &= \"test\"", null, STRING)); + arguments("b &= true", createValue(true)), + arguments("b &= (byte)3", null), + arguments("b &= (short)256", null), + arguments("b &= 'c'", null), + arguments("b &= 1", null), + arguments("b &= 2L", null), + arguments("b &= 1.5f", null), + arguments("b &= 3.14", null), + + arguments("by &= false", null), + arguments("by &= (byte)3", createValue((byte)3)), + arguments("by &= (short)256", createValue((byte)256)), + arguments("by &= 'a'", createValue((byte)1)), + arguments("by &= 1", createValue((byte)1)), + arguments("by &= 2L", createValue((byte)2L)), + arguments("by &= 1.5f", null), + arguments("by &= 3.14", null), + + arguments("s &= false", null), + arguments("s &= (byte)3", createValue((short)0)), + arguments("s &= (short)256", createValue((short)256)), + arguments("s &= 'a'", createValue((short)0)), + arguments("s &= 1", createValue((short)0)), + arguments("s &= 2L", createValue((short)0L)), + arguments("s &= 1.5f", null), + arguments("s &= 3.14", null), + + arguments("c &= false", null), + arguments("c &= (byte)3", null), + arguments("c &= (short)256", null), + arguments("c &= 'a'", createValue('a')), + arguments("c &= 1", createValue((char)1)), + arguments("c &= 2L", createValue((char)0L)), + arguments("c &= 1.5f", null), + arguments("c &= 3.14", null), + + arguments("i &= false", null), + arguments("i &= (byte)3", createValue(1)), + arguments("i &= (short)256", createValue(0)), + arguments("i &= 'a'", createValue(1)), + arguments("i &= 1", createValue(1)), + arguments("i &= 2L", createValue(0)), + arguments("i &= 1.5f", null), + arguments("i &= 3.14", null), + + arguments("l &= false", null), + arguments("l &= (byte)3", createValue(1L)), + arguments("l &= (short)256", createValue(0L)), + arguments("l &= 'a'", createValue(1L)), + arguments("l &= 1", createValue(1L)), + arguments("l &= 4L", createValue(4L)), + arguments("l &= 1.5f", null), + arguments("l &= 3.14", null), + + arguments("f &= false", null), + arguments("f &= 1", null), + arguments("f &= 2L", null), + arguments("f &= 1.5f", null), + arguments("f &= 3.14", null), + arguments("f &= 'a'", null), + + arguments("d &= false", null), + arguments("d &= 1", null), + arguments("d &= 2L", null), + arguments("d &= 1.5f", null), + arguments("d &= 3.14", null), + arguments("d &= 'a'", null)); } protected static Stream gTGTEqualsExpression() { return Stream.of( - arguments("b >>= false", null, BOOL), - arguments("b >>= 1", null, BOOL), - arguments("b >>= 2L", null, BOOL), - arguments("b >>= 1.5f", null, BOOL), - arguments("b >>= 3.14", null, BOOL), - arguments("b >>= 'a'", null, BOOL), - arguments("b >>= \"test\"", null, BOOL), - - arguments("i >>= false", null, INT), - arguments("i >>= 1", createValue(0), INT), - arguments("i >>= 2L", createValue(0), INT), - arguments("i >>= 1.5f", null, INT), - arguments("i >>= 3.14", null, INT), - arguments("i >>= 'a'", createValue(0), INT), - arguments("i >>= \"test\"", null, INT), - - arguments("l >>= false", null, LONG), - arguments("l >>= 1", createValue(2L), LONG), - arguments("l >>= 2L", createValue(1L), LONG), - arguments("l >>= 1.5f", null, LONG), - arguments("l >>= 3.14", null, LONG), - arguments("l >>= 'a'", createValue(0L), LONG), - arguments("l >>= \"test\"", null, LONG), - - arguments("f >>= false", null, FLOAT), - arguments("f >>= 1", null, FLOAT), - arguments("f >>= 2L", null, FLOAT), - arguments("f >>= 1.5f", null, FLOAT), - arguments("f >>= 3.14", null, FLOAT), - arguments("f >>= 'a'", null, FLOAT), - arguments("f >>= \"test\"", null, FLOAT), - - arguments("d >>= false", null, DOUBLE), - arguments("d >>= 1", null, DOUBLE), - arguments("d >>= 2L", null, DOUBLE), - arguments("d >>= 1.5f", null, DOUBLE), - arguments("d >>= 3.14", null, DOUBLE), - arguments("d >>= 'a'", null, DOUBLE), - arguments("d >>= \"test\"", null, DOUBLE), - - arguments("c >>= false", null, CHAR), - arguments("c >>= 1", createValue(48), CHAR), - arguments("c >>= 2L", createValue(24), CHAR), - arguments("c >>= 1.5f", null, CHAR), - arguments("c >>= 3.14", null, CHAR), - arguments("c >>= 'a'", createValue(48), CHAR), - arguments("c >>= \"test\"", null, CHAR), - - arguments("s >>= false", null, STRING), - arguments("s >>= 1", null, STRING), - arguments("s >>= 2L", null, STRING), - arguments("s >>= 1.5f", null, STRING), - arguments("s >>= 3.14", null, STRING), - arguments("s >>= 'a'", null, STRING), - arguments("s >>= \"test\"", null, STRING)); + arguments("b >>= false", null), + arguments("b >>= 1", null), + arguments("b >>= 2L", null), + arguments("b >>= 1.5f", null), + arguments("b >>= 3.14", null), + arguments("b >>= 'a'", null), + + arguments("i >>= false", null), + arguments("i >>= 1", createValue(0)), + arguments("i >>= 2L", createValue(0)), + arguments("i >>= 1.5f", null), + arguments("i >>= 3.14", null), + arguments("i >>= 'a'", createValue(0)), + + arguments("l >>= false", null), + arguments("l >>= 1", createValue(2L)), + arguments("l >>= 2L", createValue(1L)), + arguments("l >>= 1.5f", null), + arguments("l >>= 3.14", null), + arguments("l >>= 'a'", createValue(0L)), + + arguments("f >>= false", null), + arguments("f >>= 1", null), + arguments("f >>= 2L", null), + arguments("f >>= 1.5f", null), + arguments("f >>= 3.14", null), + arguments("f >>= 'a'", null), + + arguments("d >>= false", null), + arguments("d >>= 1", null), + arguments("d >>= 2L", null), + arguments("d >>= 1.5f", null), + arguments("d >>= 3.14", null), + arguments("d >>= 'a'", null), + + arguments("c >>= false", null), + arguments("c >>= 1", createValue(48)), + arguments("c >>= 2L", createValue(24)), + arguments("c >>= 1.5f", null), + arguments("c >>= 3.14", null), + arguments("c >>= 'a'", createValue(48))); } protected static Stream gTGTGTEqualsExpression() { return Stream.of( - arguments("b >>>= false", null, BOOL), - arguments("b >>>= 1", null, BOOL), - arguments("b >>>= 2L", null, BOOL), - arguments("b >>>= 1.5f", null, BOOL), - arguments("b >>>= 3.14", null, BOOL), - arguments("b >>>= 'a'", null, BOOL), - arguments("b >>>= \"test\"", null, BOOL), - - arguments("i >>>= false", null, INT), - arguments("i >>>= 1", createValue(0), INT), - arguments("i >>>= 2L", createValue(0), INT), - arguments("i >>>= 1.5f", null, INT), - arguments("i >>>= 3.14", null, INT), - arguments("i >>>= 'a'", createValue(0), INT), - arguments("i >>>= \"test\"", null, INT), - - arguments("l >>>= false", null, LONG), - arguments("l >>>= 1", createValue(2L), LONG), - arguments("l >>>= 2L", createValue(1L), LONG), - arguments("l >>>= 1.5f", null, LONG), - arguments("l >>>= 3.14", null, LONG), - arguments("l >>>= 'a'", createValue(0L), LONG), - arguments("l >>>= \"test\"", null, LONG), - - arguments("f >>>= false", null, FLOAT), - arguments("f >>>= 1", null, FLOAT), - arguments("f >>>= 2L", null, FLOAT), - arguments("f >>>= 1.5f", null, FLOAT), - arguments("f >>>= 3.14", null, FLOAT), - arguments("f >>>= 'a'", null, FLOAT), - arguments("f >>>= \"test\"", null, FLOAT), - - arguments("d >>>= false", null, DOUBLE), - arguments("d >>>= 1", null, DOUBLE), - arguments("d >>>= 2L", null, DOUBLE), - arguments("d >>>= 1.5f", null, DOUBLE), - arguments("d >>>= 3.14", null, DOUBLE), - arguments("d >>>= 'a'", null, DOUBLE), - arguments("d >>>= \"test\"", null, DOUBLE), - - arguments("c >>>= false", null, CHAR), - arguments("c >>>= 1", createValue(48), CHAR), - arguments("c >>>= 2L", createValue(24), CHAR), - arguments("c >>>= 1.5f", null, CHAR), - arguments("c >>>= 3.14", null, CHAR), - arguments("c >>>= 'a'", createValue(48), CHAR), - arguments("c >>>= \"test\"", null, CHAR), - - arguments("s >>>= false", null, STRING), - arguments("s >>>= 1", null, STRING), - arguments("s >>>= 2L", null, STRING), - arguments("s >>>= 1.5f", null, STRING), - arguments("s >>>= 3.14", null, STRING), - arguments("s >>>= 'a'", null, STRING), - arguments("s >>>= \"test\"", null, STRING)); + arguments("b >>>= false", null), + arguments("b >>>= 1", null), + arguments("b >>>= 2L", null), + arguments("b >>>= 1.5f", null), + arguments("b >>>= 3.14", null), + arguments("b >>>= 'a'", null), + + arguments("i >>>= false", null), + arguments("i >>>= 1", createValue(0)), + arguments("i >>>= 2L", createValue(0)), + arguments("i >>>= 1.5f", null), + arguments("i >>>= 3.14", null), + arguments("i >>>= 'a'", createValue(0)), + + arguments("l >>>= false", null), + arguments("l >>>= 1", createValue(2L)), + arguments("l >>>= 2L", createValue(1L)), + arguments("l >>>= 1.5f", null), + arguments("l >>>= 3.14", null), + arguments("l >>>= 'a'", createValue(0L)), + + arguments("f >>>= false", null), + arguments("f >>>= 1", null), + arguments("f >>>= 2L", null), + arguments("f >>>= 1.5f", null), + arguments("f >>>= 3.14", null), + arguments("f >>>= 'a'", null), + + arguments("d >>>= false", null), + arguments("d >>>= 1", null), + arguments("d >>>= 2L", null), + arguments("d >>>= 1.5f", null), + arguments("d >>>= 3.14", null), + arguments("d >>>= 'a'", null), + + arguments("c >>>= false", null), + arguments("c >>>= 1", createValue(48)), + arguments("c >>>= 2L", createValue(24)), + arguments("c >>>= 1.5f", null), + arguments("c >>>= 3.14", null), + arguments("c >>>= 'a'", createValue(48))); } protected static Stream lTLTEqualsExpression() { return Stream.of( - arguments("b <<= false", null, BOOL), - arguments("b <<= 1", null, BOOL), - arguments("b <<= 2L", null, BOOL), - arguments("b <<= 1.5f", null, BOOL), - arguments("b <<= 3.14", null, BOOL), - arguments("b <<= 'a'", null, BOOL), - arguments("b <<= \"test\"", null, BOOL), - - arguments("i <<= false", null, INT), - arguments("i <<= 1", createValue(2), INT), - arguments("i <<= 2L", createValue(4), INT), - arguments("i <<= 1.5f", null, INT), - arguments("i <<= 3.14", null, INT), - arguments("i <<= 'a'", createValue(2), INT), - arguments("i <<= \"test\"", null, INT), - - arguments("l <<= false", null, LONG), - arguments("l <<= 1", createValue(10L), LONG), - arguments("l <<= 2L", createValue(20L), LONG), - arguments("l <<= 1.5f", null, LONG), - arguments("l <<= 3.14", null, LONG), - arguments("l <<= 'a'", createValue(42949672960L), LONG), - arguments("l <<= \"test\"", null, LONG), - - arguments("f <<= false", null, FLOAT), - arguments("f <<= 1", null, FLOAT), - arguments("f <<= 2L", null, FLOAT), - arguments("f <<= 1.5f", null, FLOAT), - arguments("f <<= 3.14", null, FLOAT), - arguments("f <<= 'a'", null, FLOAT), - arguments("f <<= \"test\"", null, FLOAT), - - arguments("d <<= false", null, DOUBLE), - arguments("d <<= 1", null, DOUBLE), - arguments("d <<= 2L", null, DOUBLE), - arguments("d <<= 1.5f", null, DOUBLE), - arguments("d <<= 3.14", null, DOUBLE), - arguments("d <<= 'a'", null, DOUBLE), - arguments("d <<= \"test\"", null, DOUBLE), - - arguments("c <<= false", null, CHAR), - arguments("c <<= 1", createValue(194), CHAR), - arguments("c <<= 2L", createValue(388), CHAR), - arguments("c <<= 1.5f", null, CHAR), - arguments("c <<= 3.14", null, CHAR), - arguments("c <<= 'a'", createValue(194), CHAR), - arguments("c <<= \"test\"", null, CHAR), - - arguments("s <<= false", null, STRING), - arguments("s <<= 1", null, STRING), - arguments("s <<= 2L", null, STRING), - arguments("s <<= 1.5f", null, STRING), - arguments("s <<= 3.14", null, STRING), - arguments("s <<= 'a'", null, STRING), - arguments("s <<= \"test\"", null, STRING)); + arguments("b <<= false", null), + arguments("b <<= 1", null), + arguments("b <<= 2L", null), + arguments("b <<= 1.5f", null), + arguments("b <<= 3.14", null), + arguments("b <<= 'a'", null), + + arguments("i <<= false", null), + arguments("i <<= 1", createValue(2)), + arguments("i <<= 2L", createValue(4)), + arguments("i <<= 1.5f", null), + arguments("i <<= 3.14", null), + arguments("i <<= 'a'", createValue(2)), + + arguments("l <<= false", null), + arguments("l <<= 1", createValue(10L)), + arguments("l <<= 2L", createValue(20L)), + arguments("l <<= 1.5f", null), + arguments("l <<= 3.14", null), + arguments("l <<= 'a'", createValue(42949672960L)), + + arguments("f <<= false", null), + arguments("f <<= 1", null), + arguments("f <<= 2L", null), + arguments("f <<= 1.5f", null), + arguments("f <<= 3.14", null), + arguments("f <<= 'a'", null), + + arguments("d <<= false", null), + arguments("d <<= 1", null), + arguments("d <<= 2L", null), + arguments("d <<= 1.5f", null), + arguments("d <<= 3.14", null), + arguments("d <<= 'a'", null), + + arguments("c <<= false", null), + arguments("c <<= 1", createValue(194)), + arguments("c <<= 2L", createValue(388)), + arguments("c <<= 1.5f", null), + arguments("c <<= 3.14", null), + arguments("c <<= 'a'", createValue(194))); } protected static Stream minusEqualsExpression() { return Stream.of( - arguments("b -= false", null, BOOL), - arguments("b -= 1", null, BOOL), - arguments("b -= 2L", null, BOOL), - arguments("b -= 1.5f", null, BOOL), - arguments("b -= 3.14", null, BOOL), - arguments("b -= 'a'", null, BOOL), - arguments("b -= \"test\"", null, BOOL), - - arguments("i -= false", null, INT), - arguments("i -= 1", createValue(0), INT), - arguments("i -= 2L", createValue(-1L), INT), - arguments("i -= 1.5f", createValue(-.5f), INT), - arguments("i -= 3.14", createValue(-2.14), INT), - arguments("i -= 'a'", createValue(-96), INT), - arguments("i -= \"test\"", null, INT), - - arguments("l -= false", null, LONG), - arguments("l -= 1", createValue(4L), LONG), - arguments("l -= 2L", createValue(3L), LONG), - arguments("l -= 1.5f", createValue(3.5f), LONG), - arguments("l -= 3.14", createValue(1.86), LONG), - arguments("l -= 'a'", createValue(-92L), LONG), - arguments("l -= \"test\"", null, LONG), - - arguments("f -= false", null, FLOAT), - arguments("f -= 1", createValue(0.5f), FLOAT), - arguments("f -= 2L", createValue(-0.5f), FLOAT), - arguments("f -= 1.2f", createValue(.3f), FLOAT), - arguments("f -= 3.14", createValue(-1.64), FLOAT), - arguments("f -= 'a'", createValue(-95.5f), FLOAT), - arguments("f -= \"test\"", null, FLOAT), - - arguments("d -= false", null, DOUBLE), - arguments("d -= 1", createValue(2.14), DOUBLE), - arguments("d -= 2L", createValue(1.14), DOUBLE), - arguments("d -= 1.5f", createValue(1.64), DOUBLE), - arguments("d -= 3.04", createValue(.1), DOUBLE), - arguments("d -= 'a'", createValue(-93.86), DOUBLE), - arguments("d -= \"test\"", null, DOUBLE), - - arguments("c -= false", null, CHAR), - arguments("c -= 1", createValue(96), CHAR), - arguments("c -= 2L", createValue(95L), CHAR), - arguments("c -= 1.5f", createValue(95.5f), CHAR), - arguments("c -= 3.14", createValue(93.86), CHAR), - arguments("c -= 'a'", createValue(0), CHAR), - arguments("c -= \"test\"", null, CHAR), - - arguments("s -= false", null, STRING), - arguments("s -= 1", null, STRING), - arguments("s -= 2L", null, STRING), - arguments("s -= 1.5f", null, STRING), - arguments("s -= 3.14", null, STRING), - arguments("s -= 'a'", null, STRING), - arguments("s -= \"test\"", null, STRING)); + arguments("b -= false", null), + arguments("b -= 1", null), + arguments("b -= 2L", null), + arguments("b -= 1.5f", null), + arguments("b -= 3.14", null), + arguments("b -= 'a'", null), + + arguments("i -= false", null), + arguments("i -= 1", createValue(0)), + arguments("i -= 2L", createValue(-1L)), + arguments("i -= 1.5f", createValue(-.5f)), + arguments("i -= 3.14", createValue(-2.14)), + arguments("i -= 'a'", createValue(-96)), + + arguments("l -= false", null), + arguments("l -= 1", createValue(4L)), + arguments("l -= 2L", createValue(3L)), + arguments("l -= 1.5f", createValue(3.5f)), + arguments("l -= 3.14", createValue(1.86)), + arguments("l -= 'a'", createValue(-92L)), + + arguments("f -= false", null), + arguments("f -= 1", createValue(0.5f)), + arguments("f -= 2L", createValue(-0.5f)), + arguments("f -= 1.2f", createValue(.3f)), + arguments("f -= 3.14", createValue(-1.64)), + arguments("f -= 'a'", createValue(-95.5f)), + + arguments("d -= false", null), + arguments("d -= 1", createValue(2.14)), + arguments("d -= 2L", createValue(1.14)), + arguments("d -= 1.5f", createValue(1.64)), + arguments("d -= 3.04", createValue(.1)), + arguments("d -= 'a'", createValue(-93.86)), + + arguments("c -= false", null), + arguments("c -= 1", createValue(96)), + arguments("c -= 2L", createValue(95L)), + arguments("c -= 1.5f", createValue(95.5f)), + arguments("c -= 3.14", createValue(93.86)), + arguments("c -= 'a'", createValue(0))); } protected static Stream percentEqualsExpression() { return Stream.of( - arguments("b %= false", null, BOOL), - arguments("b %= 1", null, BOOL), - arguments("b %= 2L", null, BOOL), - arguments("b %= 1.5f", null, BOOL), - arguments("b %= 3.14", null, BOOL), - arguments("b %= 'a'", null, BOOL), - arguments("b %= \"test\"", null, BOOL), - - arguments("i %= false", null, INT), - arguments("i %= 1", createValue(0), INT), - arguments("i %= 2L", createValue(1L), INT), - arguments("i %= 1.5f", createValue(1f), INT), - arguments("i %= 3.14", createValue(1.), INT), - arguments("i %= 'a'", createValue(1), INT), - arguments("i %= \"test\"", null, INT), - - arguments("l %= false", null, LONG), - arguments("l %= 1", createValue(0L), LONG), - arguments("l %= 2L", createValue(1L), LONG), - arguments("l %= 1.5f", createValue(0.5f), LONG), - arguments("l %= 3.14", createValue(1.86), LONG), - arguments("l %= 'a'", createValue(5L), LONG), - arguments("l %= \"test\"", null, LONG), - - arguments("f %= false", null, FLOAT), - arguments("f %= 1", createValue(0.5f), FLOAT), - arguments("f %= 2L", createValue(1.5f), FLOAT), - arguments("f %= 1.5f", createValue(0f), FLOAT), - arguments("f %= 3.14", createValue(1.5), FLOAT), - arguments("f %= 'a'", createValue(1.5f), FLOAT), - arguments("f %= \"test\"", null, FLOAT), - - arguments("d %= false", null, DOUBLE), - arguments("d %= 1", createValue(0.14), DOUBLE), - arguments("d %= 2L", createValue(1.14), DOUBLE), - arguments("d %= 1.5f", createValue(0.14), DOUBLE), - arguments("d %= 3.14", createValue(0.), DOUBLE), - arguments("d %= 'a'", createValue(3.14), DOUBLE), - arguments("d %= \"test\"", null, DOUBLE), - - arguments("c %= false", null, CHAR), - arguments("c %= 1", createValue(0), CHAR), - arguments("c %= 2L", createValue(1L), CHAR), - arguments("c %= 1.5f", createValue(1f), CHAR), - arguments("c %= 3.14", createValue(2.8), CHAR), - arguments("c %= 'a'", createValue(0), CHAR), - arguments("c %= \"test\"", null, CHAR), - - arguments("s %= false", null, STRING), - arguments("s %= 1", null, STRING), - arguments("s %= 2L", null, STRING), - arguments("s %= 1.5f", null, STRING), - arguments("s %= 3.14", null, STRING), - arguments("s %= 'a'", null, STRING), - arguments("s %= \"test\"", null, STRING)); + arguments("b %= false", null), + arguments("b %= 1", null), + arguments("b %= 2L", null), + arguments("b %= 1.5f", null), + arguments("b %= 3.14", null), + arguments("b %= 'a'", null), + + arguments("i %= false", null), + arguments("i %= 1", createValue(0)), + arguments("i %= 2L", createValue(1L)), + arguments("i %= 1.5f", createValue(1f)), + arguments("i %= 3.14", createValue(1.)), + arguments("i %= 'a'", createValue(1)), + + arguments("l %= false", null), + arguments("l %= 1", createValue(0L)), + arguments("l %= 2L", createValue(1L)), + arguments("l %= 1.5f", createValue(0.5f)), + arguments("l %= 3.14", createValue(1.86)), + arguments("l %= 'a'", createValue(5L)), + + arguments("f %= false", null), + arguments("f %= 1", createValue(0.5f)), + arguments("f %= 2L", createValue(1.5f)), + arguments("f %= 1.5f", createValue(0f)), + arguments("f %= 3.14", createValue(1.5)), + arguments("f %= 'a'", createValue(1.5f)), + + arguments("d %= false", null), + arguments("d %= 1", createValue(0.14)), + arguments("d %= 2L", createValue(1.14)), + arguments("d %= 1.5f", createValue(0.14)), + arguments("d %= 3.14", createValue(0.)), + arguments("d %= 'a'", createValue(3.14)), + + arguments("c %= false", null), + arguments("c %= 1", createValue(0)), + arguments("c %= 2L", createValue(1L)), + arguments("c %= 1.5f", createValue(1f)), + arguments("c %= 3.14", createValue(2.8)), + arguments("c %= 'a'", createValue(0))); } protected static Stream pipeEqualsExpression() { return Stream.of( - arguments("b |= false", null, BOOL), - arguments("b |= 1", null, BOOL), - arguments("b |= 2L", null, BOOL), - arguments("b |= 1.5f", null, BOOL), - arguments("b |= 3.14", null, BOOL), - arguments("b |= 'a'", null, BOOL), - arguments("b |= \"test\"", null, BOOL), - - arguments("i |= false", null, INT), - arguments("i |= 1", createValue(1), INT), - arguments("i |= 2L", createValue(3L), INT), - arguments("i |= 1.5f", null, INT), - arguments("i |= 3.14", null, INT), - arguments("i |= 'a'", createValue(97), INT), - arguments("i |= \"test\"", null, INT), - - arguments("l |= false", null, LONG), - arguments("l |= 1", createValue(5L), LONG), - arguments("l |= 2L", createValue(7L), LONG), - arguments("l |= 1.5f", null, LONG), - arguments("l |= 3.14", null, LONG), - arguments("l |= 'a'", createValue(101L), LONG), - arguments("l |= \"test\"", null, LONG), - - arguments("f |= false", null, FLOAT), - arguments("f |= 1", null, FLOAT), - arguments("f |= 2L", null, FLOAT), - arguments("f |= 1.5f", null, FLOAT), - arguments("f |= 3.14", null, FLOAT), - arguments("f |= 'a'", null, FLOAT), - arguments("f |= \"test\"", null, FLOAT), - - arguments("d |= false", null, DOUBLE), - arguments("d |= 1", null, DOUBLE), - arguments("d |= 2L", null, DOUBLE), - arguments("d |= 1.5f", null, DOUBLE), - arguments("d |= 3.14", null, DOUBLE), - arguments("d |= 'a'", null, DOUBLE), - arguments("d |= \"test\"", null, DOUBLE), - - arguments("c |= false", null, CHAR), - arguments("c |= 1", createValue(97), CHAR), - arguments("c |= 2L", createValue(99L), CHAR), - arguments("c |= 1.5f", null, CHAR), - arguments("c |= 3.14", null, CHAR), - arguments("c |= 'a'", createValue(97), CHAR), - arguments("c |= \"test\"", null, CHAR), - - arguments("s |= false", null, STRING), - arguments("s |= 1", null, STRING), - arguments("s |= 2L", null, STRING), - arguments("s |= 1.5f", null, STRING), - arguments("s |= 3.14", null, STRING), - arguments("s |= 'a'", null, STRING), - arguments("s |= \"test\"", null, STRING)); + arguments("b |= false", null), + arguments("b |= 1", null), + arguments("b |= 2L", null), + arguments("b |= 1.5f", null), + arguments("b |= 3.14", null), + arguments("b |= 'a'", null), + + arguments("i |= false", null), + arguments("i |= 1", createValue(1)), + arguments("i |= 2L", createValue(3L)), + arguments("i |= 1.5f", null), + arguments("i |= 3.14", null), + arguments("i |= 'a'", createValue(97)), + + arguments("l |= false", null), + arguments("l |= 1", createValue(5L)), + arguments("l |= 2L", createValue(7L)), + arguments("l |= 1.5f", null), + arguments("l |= 3.14", null), + arguments("l |= 'a'", createValue(101L)), + + arguments("f |= false", null), + arguments("f |= 1", null), + arguments("f |= 2L", null), + arguments("f |= 1.5f", null), + arguments("f |= 3.14", null), + arguments("f |= 'a'", null), + + arguments("d |= false", null), + arguments("d |= 1", null), + arguments("d |= 2L", null), + arguments("d |= 1.5f", null), + arguments("d |= 3.14", null), + arguments("d |= 'a'", null), + + arguments("c |= false", null), + arguments("c |= 1", createValue(97)), + arguments("c |= 2L", createValue(99L)), + arguments("c |= 1.5f", null), + arguments("c |= 3.14", null), + arguments("c |= 'a'", createValue(97))); } protected static Stream plusEqualsExpression() { return Stream.of( - arguments("b += false", null, BOOL), - arguments("b += 1", null, BOOL), - arguments("b += 2L", null, BOOL), - arguments("b += 1.5f", null, BOOL), - arguments("b += 3.14", null, BOOL), - arguments("b += 'a'", null, BOOL), - arguments("b += \"test\"", null, BOOL), - - arguments("i += false", null, INT), - arguments("i += 1", createValue(2), INT), - arguments("i += 2L", createValue(3L), INT), - arguments("i += 1.5f", createValue(2.5f), INT), - arguments("i += 3.14", createValue(4.14), INT), - arguments("i += 'a'", createValue(98), INT), - arguments("i += \"test\"", null, INT), - - arguments("l += false", null, LONG), - arguments("l += 1", createValue(6L), LONG), - arguments("l += 2L", createValue(7L), LONG), - arguments("l += 1.5f", createValue(6.5f), LONG), - arguments("l += 3.14", createValue(8.14), LONG), - arguments("l += 'a'", createValue(102L), LONG), - arguments("l += \"test\"", null, LONG), - - arguments("f += false", null, FLOAT), - arguments("f += 1", createValue(2.5f), FLOAT), - arguments("f += 2L", createValue(3.5f), FLOAT), - arguments("f += 1.5f", createValue(3.0f), FLOAT), - arguments("f += 3.14", createValue(4.64), FLOAT), - arguments("f += 'a'", createValue(98.5f), FLOAT), - arguments("f += \"test\"", null, FLOAT), - - arguments("d += false", null, DOUBLE), - arguments("d += 1", createValue(4.14), DOUBLE), - arguments("d += 2L", createValue(5.14), DOUBLE), - arguments("d += 1.5f", createValue(4.64), DOUBLE), - arguments("d += 3.14", createValue(6.28), DOUBLE), - arguments("d += 'a'", createValue(100.14), DOUBLE), - arguments("d += \"test\"", null, DOUBLE), - - arguments("c += false", null, CHAR), - arguments("c += 1", createValue(98), CHAR), - arguments("c += 2L", createValue(99L), CHAR), - arguments("c += 1.5f", createValue(98.5f), CHAR), - arguments("c += 3.14", createValue(100.14), CHAR), - arguments("c += 'a'", createValue(194), CHAR), - arguments("c += \"test\"", null, CHAR), - - arguments("s += false", createValue("hellofalse"), STRING), - arguments("s += 1", createValue("hello1"), STRING), - arguments("s += 2L", createValue("hello2"), STRING), - arguments("s += 1.5f", createValue("hello1.5"), STRING), - arguments("s += 3.14", createValue("hello3.14"), STRING), - arguments("s += 'a'", createValue("helloa"), STRING), - arguments("s += \"test\"", createValue("hellotest"), STRING)); + arguments("b += false", null), + arguments("b += 1", null), + arguments("b += 2L", null), + arguments("b += 1.5f", null), + arguments("b += 3.14", null), + arguments("b += 'a'", null), + + arguments("by += false", null), + arguments("by += 1", createValue(2)), + arguments("by += 2L", createValue(3L)), + arguments("by += 1.5f", createValue(2.5f)), + arguments("by += 3.14", createValue(4.14)), + arguments("by += 'a'", createValue(98)), + + arguments("i += false", null), + arguments("i += 1", createValue(2)), + arguments("i += 2L", createValue(3L)), + arguments("i += 1.5f", createValue(2.5f)), + arguments("i += 3.14", createValue(4.14)), + arguments("i += 'a'", createValue(98)), + + arguments("l += false", null), + arguments("l += 1", createValue(6L)), + arguments("l += 2L", createValue(7L)), + arguments("l += 1.5f", createValue(6.5f)), + arguments("l += 3.14", createValue(8.14)), + arguments("l += 'a'", createValue(102L)), + + arguments("f += false", null), + arguments("f += 1", createValue(2.5f)), + arguments("f += 2L", createValue(3.5f)), + arguments("f += 1.5f", createValue(3.0f)), + arguments("f += 3.14", createValue(4.64)), + arguments("f += 'a'", createValue(98.5f)), + + arguments("d += false", null), + arguments("d += 1", createValue(4.14)), + arguments("d += 2L", createValue(5.14)), + arguments("d += 1.5f", createValue(4.64)), + arguments("d += 3.14", createValue(6.28)), + arguments("d += 'a'", createValue(100.14)), + + arguments("c += false", null), + arguments("c += 1", createValue(98)), + arguments("c += 2L", createValue(99L)), + arguments("c += 1.5f", createValue(98.5f)), + arguments("c += 3.14", createValue(100.14)), + arguments("c += 'a'", createValue(194))); } protected static Stream roofEqualsExpression() { return Stream.of( - arguments("b ^= false", null, BOOL), - arguments("b ^= 1", null, BOOL), - arguments("b ^= 2L", null, BOOL), - arguments("b ^= 1.5f", null, BOOL), - arguments("b ^= 3.14", null, BOOL), - arguments("b ^= 'a'", null, BOOL), - arguments("b ^= \"test\"", null, BOOL), - - arguments("i ^= false", null, INT), - arguments("i ^= 3", createValue(2), INT), - arguments("i ^= 4L", createValue(5L), INT), - arguments("i ^= 1.5f", null, INT), - arguments("i ^= 3.14", null, INT), - arguments("i ^= 'a'", createValue(96), INT), - arguments("i ^= \"test\"", null, INT), - - arguments("l ^= false", null, LONG), - arguments("l ^= 1", createValue(4L), LONG), - arguments("l ^= 2L", createValue(7L), LONG), - arguments("l ^= 1.5f", null, LONG), - arguments("l ^= 3.14", null, LONG), - arguments("l ^= 'a'", createValue(100L), LONG), - arguments("l ^= \"test\"", null, LONG), - - arguments("f ^= false", null, FLOAT), - arguments("f ^= 1", null, FLOAT), - arguments("f ^= 2L", null, FLOAT), - arguments("f ^= 1.5f", null, FLOAT), - arguments("f ^= 3.14", null, FLOAT), - arguments("f ^= 'a'", null, FLOAT), - arguments("f ^= \"test\"", null, FLOAT), - - arguments("d ^= false", null, DOUBLE), - arguments("d ^= 1", null, DOUBLE), - arguments("d ^= 2L", null, DOUBLE), - arguments("d ^= 1.5f", null, DOUBLE), - arguments("d ^= 3.14", null, DOUBLE), - arguments("d ^= 'a'", null, DOUBLE), - arguments("d ^= \"test\"", null, DOUBLE), - - arguments("c ^= false", null, CHAR), - arguments("c ^= 1", createValue(96), CHAR), - arguments("c ^= 2L", createValue(99L), CHAR), - arguments("c ^= 1.5f", null, CHAR), - arguments("c ^= 3.14", null, CHAR), - arguments("c ^= 'a'", createValue(0), CHAR), - arguments("c ^= \"test\"", null, CHAR), - - arguments("s ^= false", null, STRING), - arguments("s ^= 1", null, STRING), - arguments("s ^= 2L", null, STRING), - arguments("s ^= 1.5f", null, STRING), - arguments("s ^= 3.14", null, STRING), - arguments("s ^= 'a'", null, STRING), - arguments("s ^= \"test\"", null, STRING)); + arguments("b ^= false", null), + arguments("b ^= 1", null), + arguments("b ^= 2L", null), + arguments("b ^= 1.5f", null), + arguments("b ^= 3.14", null), + arguments("b ^= 'a'", null), + + arguments("i ^= false", null), + arguments("i ^= 3", createValue(2)), + arguments("i ^= 4L", createValue(5L)), + arguments("i ^= 1.5f", null), + arguments("i ^= 3.14", null), + arguments("i ^= 'a'", createValue(96)), + + arguments("l ^= false", null), + arguments("l ^= 1", createValue(4L)), + arguments("l ^= 2L", createValue(7L)), + arguments("l ^= 1.5f", null), + arguments("l ^= 3.14", null), + arguments("l ^= 'a'", createValue(100L)), + + arguments("f ^= false", null), + arguments("f ^= 1", null), + arguments("f ^= 2L", null), + arguments("f ^= 1.5f", null), + arguments("f ^= 3.14", null), + arguments("f ^= 'a'", null), + + arguments("d ^= false", null), + arguments("d ^= 1", null), + arguments("d ^= 2L", null), + arguments("d ^= 1.5f", null), + arguments("d ^= 3.14", null), + arguments("d ^= 'a'", null), + + arguments("c ^= false", null), + arguments("c ^= 1", createValue(96)), + arguments("c ^= 2L", createValue(99L)), + arguments("c ^= 1.5f", null), + arguments("c ^= 3.14", null), + arguments("c ^= 'a'", createValue(0))); } protected static Stream slashEqualsExpression() { return Stream.of( - arguments("b /= false", null, BOOL), - arguments("b /= 1", null, BOOL), - arguments("b /= 2L", null, BOOL), - arguments("b /= 1.5f", null, BOOL), - arguments("b /= 3.14", null, BOOL), - arguments("b /= 'a'", null, BOOL), - arguments("b /= \"test\"", null, BOOL), - - arguments("i /= false", null, INT), - arguments("i /= 0.25f", createValue(4.f), INT), - arguments("i /= 0.4", createValue(2.5), INT), - arguments("i /= 2", createValue(0), INT), - arguments("i /= 5L", createValue(0L), INT), - arguments("i /= 'A'", createValue(0), INT), - arguments("i /= \"test\"", null, INT), - - arguments("l /= false", null, LONG), - arguments("l /= 1.25f", createValue(4.f), LONG), - arguments("l /= 0.4", createValue(12.5), LONG), - arguments("l /= 2", createValue(2L), LONG), - arguments("l /= 5L", createValue(1L), LONG), - arguments("l /= 'A'", createValue(0L), LONG), - arguments("l /= \"test\"", null, LONG), - - arguments("f /= false", null, FLOAT), - arguments("f /= 3", createValue(.5f), FLOAT), - arguments("f /= 2L", createValue(0.75f), FLOAT), - arguments("f /= 0.025f", createValue(60.f), FLOAT), - arguments("f /= 2.5", createValue(.6), FLOAT), - arguments("f /= 'A'", createValue(0.0230769f), FLOAT), - arguments("f /= \"test\"", null, FLOAT), - - arguments("d /= false", null, DOUBLE), - arguments("d /= 1", createValue(3.14), DOUBLE), - arguments("d /= 2L", createValue(1.57), DOUBLE), - arguments("d /= 1.57f", createValue(2.), DOUBLE), - arguments("d /= 0.02", createValue(157.), DOUBLE), - arguments("d /= 'A'", createValue(0.048307692307), DOUBLE), - arguments("d /= \"test\"", null, DOUBLE), - - arguments("c /= false", null, CHAR), - arguments("c /= 1", createValue(97), CHAR), - arguments("c /= 97L", createValue(1L), CHAR), - arguments("c /= 0.25f", createValue(388.f), CHAR), - arguments("c /= 0.4", createValue(242.5), CHAR), - arguments("c /= 'A'", createValue(1), CHAR), - arguments("c /= \"test\"", null, CHAR), - - arguments("s /= false", null, STRING), - arguments("s /= 1", null, STRING), - arguments("s /= 2L", null, STRING), - arguments("s /= 1.5f", null, STRING), - arguments("s /= 3.14", null, STRING), - arguments("s /= 'a'", null, STRING), - arguments("s /= \"test\"", null, STRING)); + arguments("b /= false", null), + arguments("b /= 1", null), + arguments("b /= 2L", null), + arguments("b /= 1.5f", null), + arguments("b /= 3.14", null), + arguments("b /= 'a'", null), + + arguments("i /= false", null), + arguments("i /= 0.25f", createValue(4.f)), + arguments("i /= 0.4", createValue(2.5)), + arguments("i /= 2", createValue(0)), + arguments("i /= 5L", createValue(0L)), + arguments("i /= 'A'", createValue(0)), + + arguments("l /= false", null), + arguments("l /= 1.25f", createValue(4.f)), + arguments("l /= 0.4", createValue(12.5)), + arguments("l /= 2", createValue(2L)), + arguments("l /= 5L", createValue(1L)), + arguments("l /= 'A'", createValue(0L)), + + arguments("f /= false", null), + arguments("f /= 3", createValue(.5f)), + arguments("f /= 2L", createValue(0.75f)), + arguments("f /= 0.025f", createValue(60.f)), + arguments("f /= 2.5", createValue(.6)), + arguments("f /= 'A'", createValue(0.0230769f)), + + arguments("d /= false", null), + arguments("d /= 1", createValue(3.14)), + arguments("d /= 2L", createValue(1.57)), + arguments("d /= 1.57f", createValue(2.)), + arguments("d /= 0.02", createValue(157.)), + arguments("d /= 'A'", createValue(0.048307692307)), + + arguments("c /= false", null), + arguments("c /= 1", createValue(97)), + arguments("c /= 97L", createValue(1L)), + arguments("c /= 0.25f", createValue(388.f)), + arguments("c /= 0.4", createValue(242.5)), + arguments("c /= 'A'", createValue(1))); } protected static Stream starEqualsExpression() { return Stream.of( - arguments("b *= false", null, BOOL), - arguments("b *= 1", null, BOOL), - arguments("b *= 2L", null, BOOL), - arguments("b *= 1.5f", null, BOOL), - arguments("b *= 3.14", null, BOOL), - arguments("b *= 'a'", null, BOOL), - arguments("b *= \"test\"", null, BOOL), - - arguments("i *= false", null, INT), - arguments("i *= 0.25f", createValue(0.25f), INT), - arguments("i *= 4.5", createValue(4.5), INT), - arguments("i *= 2", createValue(2), INT), - arguments("i *= 2L", createValue(2L), INT), - arguments("i *= 'A'", createValue(65), INT), - arguments("i *= \"test\"", null, INT), - - arguments("l *= false", null, LONG), - arguments("l *= 0.5f", createValue(2.5f), LONG), - arguments("l *= 0.2", createValue(1.), LONG), - arguments("l *= 2", createValue(10L), LONG), - arguments("l *= 10L", createValue(50L), LONG), - arguments("l *= 'A'", createValue(325L), LONG), - arguments("l *= \"test\"", null, LONG), - - arguments("f *= false", null, FLOAT), - arguments("f *= 3", createValue(4.5f), FLOAT), - arguments("f *= 2L", createValue(3f), FLOAT), - arguments("f *= 0.5f", createValue(.75f), FLOAT), - arguments("f *= 0.5", createValue(.75), FLOAT), - arguments("f *= 'A'", createValue(97.5f), FLOAT), - arguments("f *= \"test\"", null, FLOAT), - - arguments("d *= false", null, DOUBLE), - arguments("d *= 1", createValue(3.14), DOUBLE), - arguments("d *= 2L", createValue(6.28), DOUBLE), - arguments("d *= 0.5f", createValue(1.57), DOUBLE), - arguments("d *= 0.5", createValue(1.57), DOUBLE), - arguments("d *= 'A'", createValue(204.1), DOUBLE), - arguments("d *= \"test\"", null, DOUBLE), - - arguments("c *= false", null, CHAR), - arguments("c *= 2", createValue(194), CHAR), - arguments("c *= 2L", createValue(194L), CHAR), - arguments("c *= 0.25f", createValue(24.25f), CHAR), - arguments("c *= 0.5", createValue(48.5), CHAR), - arguments("c *= 'A'", createValue(6305), CHAR), - arguments("c *= \"test\"", null, CHAR), - - arguments("s *= false", null, STRING), - arguments("s *= 1", null, STRING), - arguments("s *= 2L", null, STRING), - arguments("s *= 1.5f", null, STRING), - arguments("s *= 3.14", null, STRING), - arguments("s *= 'a'", null, STRING), - arguments("s *= \"test\"", null, STRING)); + arguments("b *= false", null), + arguments("b *= 1", null), + arguments("b *= 2L", null), + arguments("b *= 1.5f", null), + arguments("b *= 3.14", null), + arguments("b *= 'a'", null), + + arguments("i *= false", null), + arguments("i *= 0.25f", createValue(0.25f)), + arguments("i *= 4.5", createValue(4.5)), + arguments("i *= 2", createValue(2)), + arguments("i *= 2L", createValue(2L)), + arguments("i *= 'A'", createValue(65)), + + arguments("l *= false", null), + arguments("l *= 0.5f", createValue(2.5f)), + arguments("l *= 0.2", createValue(1.)), + arguments("l *= 2", createValue(10L)), + arguments("l *= 10L", createValue(50L)), + arguments("l *= 'A'", createValue(325L)), + + arguments("f *= false", null), + arguments("f *= 3", createValue(4.5f)), + arguments("f *= 2L", createValue(3f)), + arguments("f *= 0.5f", createValue(.75f)), + arguments("f *= 0.5", createValue(.75)), + arguments("f *= 'A'", createValue(97.5f)), + + arguments("d *= false", null), + arguments("d *= 1", createValue(3.14)), + arguments("d *= 2L", createValue(6.28)), + arguments("d *= 0.5f", createValue(1.57)), + arguments("d *= 0.5", createValue(1.57)), + arguments("d *= 'A'", createValue(204.1)), + + arguments("c *= false", null), + arguments("c *= 2", createValue(194)), + arguments("c *= 2L", createValue(194L)), + arguments("c *= 0.25f", createValue(24.25f)), + arguments("c *= 0.5", createValue(48.5)), + arguments("c *= 'A'", createValue(6305))); } @ParameterizedTest @@ -716,10 +599,10 @@ protected static Stream starEqualsExpression() { "percentEqualsExpression", "pipeEqualsExpression", "plusEqualsExpression", "roofEqualsExpression", "slashEqualsExpression", "starEqualsExpression" }) - public void testInterpreter(String expression, Value result, int types) { - init(types); - if (isNull(result)) { - testInvalidExpression(expression); + public void testInterpreter(String expression, Value result) { + init(); + if (result == null) { + assertThrows(Throwable.class, () -> testInvalidExpression(expression)); } else { testValidExpression(expression, result); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java index 3b596d8883..472a46412c 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java @@ -10,7 +10,7 @@ public class CommonExpressionsInterpreterTest extends AbstractInterpreterTest { @BeforeEach public void before() { - init(127); + init(); } @Test diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java new file mode 100644 index 0000000000..74f7e99973 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java @@ -0,0 +1,52 @@ +package de.monticore.interpreter; + +import de.monticore.interpreter.values.ErrorValue; +import de.monticore.symboltable.ISymbol; +import de.se_rwth.commons.logging.Log; + +import java.util.HashMap; +import java.util.Map; + +public class MIScope { + + private Map contextMap; + + private MIScope parent; + + public MIScope() { + this.contextMap = new HashMap(); + this.parent = null; + } + + public void declareVariable(ISymbol symbol, Value value) { + if (contextMap.containsKey(symbol)) { + Log.error("Variable was already declared"); + } + this.contextMap.put(symbol, value); + } + + public Value load(ISymbol symbol) { + Value value = contextMap.get(symbol); + if (value != null) { + return value; + } + + if (parent != null) { + return parent.load(symbol); + } + + Log.error("Failed to load Value of Symbol. Could not find Symbol in the current or any parent scope"); + return new ErrorValue("Failed to load Value of Symbol. Could not find Symbol in the current or any parent scope"); + } + + public void store(ISymbol symbol, Value value) { + if (contextMap.containsKey(symbol)) { + contextMap.put(symbol, value); + } else if (parent != null){ + parent.store(symbol, value); + } else { + Log.error("Failed to store Value in Symbol. Could not find Symbol in the current or any parent scope"); + } + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java b/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java index 6cd412289e..2838a076c2 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java @@ -2,30 +2,37 @@ package de.monticore.interpreter; import de.monticore.ast.ASTNode; -import de.monticore.interpreter.values.NotAValue; +import de.monticore.interpreter.values.ErrorValue; import de.monticore.symboltable.ISymbol; - -import java.util.HashMap; -import java.util.Map; +import de.se_rwth.commons.logging.Log; public interface ModelInterpreter { - + default Value interpret(ASTNode n) { - return new NotAValue(); + String errorMsg = "No implementation of ASTNode of type " + n.toString(); + Log.error(errorMsg); + return new ErrorValue(errorMsg); } void setRealThis(ModelInterpreter realThis); ModelInterpreter getRealThis(); - Map getContextMap(); + MIScope getCurrentScope(); + + void pushScope(MIScope scope); + void popScope(); - default Value load(ISymbol s){ - return getRealThis().load(s); + default void declareVariable(ISymbol symbol, Value value) { + getCurrentScope().declareVariable(symbol, value); + } + + default Value load(ISymbol symbol) { + return getRealThis().load(symbol); } - default void store (ISymbol n, Value res){ - getRealThis().store(n,res); + default void store (ISymbol symbol, Value value){ + getRealThis().store(symbol, value); } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/Value.java b/monticore-runtime/src/main/java/de/monticore/interpreter/Value.java index f72509d91f..e7f799817f 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/Value.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/Value.java @@ -8,7 +8,19 @@ public interface Value { default boolean isBoolean() { return false; } - + + default boolean isByte() { + return false; + } + + default boolean isChar() { + return false; + } + + default boolean isShort() { + return false; + } + default boolean isInt() { return false; } @@ -25,56 +37,70 @@ default boolean isDouble() { return false; } - default boolean isChar() { + default boolean isObject() { return false; } - - default boolean isString() { + + default boolean isFunction() { return false; } - - - default boolean isObject() { + + default boolean isVoid() { return false; } - + + default boolean isSIUnit() { + return false; + } + + default boolean isError() { + return false; + } + + default boolean asBoolean() { Log.error("0x31251 Type boolean is not applicable for result value."); return false; } - - default int asInt() { - Log.error("0x31252 Type int is not applicable for result value."); + + default byte asByte() { + Log.error("0x31252 Type byte is not applicable for result value."); return 0; } - - default double asDouble() { - Log.error("0x31253 Type double is not applicable for result value."); - return 0.0; - } - - default String asString() { - Log.error("0x31254 Type String is not applicable for result value."); - return ""; - } - + default char asChar() { - Log.error("0x31255 Type char is not applicable for result value."); - return '\u0000'; + Log.error("0x31253 Type char is not applicable for result value."); + return '\0'; } - - default Object asObject() { - Log.error("0x31256 Type Object is not applicable for result value."); - return new Object(); + + default short asShort() { + Log.error("0x31254 Type short is not applicable for result value."); + return 0; } - + + default int asInt() { + Log.error("0x31255 Type int is not applicable for result value."); + return 0; + } + default long asLong() { - Log.error("0x31257 Type long is not applicable for result value."); + Log.error("0x31256 Type long is not applicable for result value."); return 0L; } - + default float asFloat() { - Log.error("0x31258 Type float is not applicable for result value."); + Log.error("0x31257 Type float is not applicable for result value."); return 0.0f; } + + default double asDouble() { + Log.error("0x31258 Type double is not applicable for result value."); + return 0.0; + } + + default Object asObject() { + Log.error("0x31259 Type object is not applicable for result value."); + return null; + } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/ValueFactory.java b/monticore-runtime/src/main/java/de/monticore/interpreter/ValueFactory.java index d57dc6781c..48e04077d9 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/ValueFactory.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/ValueFactory.java @@ -4,37 +4,41 @@ import de.monticore.interpreter.values.*; public class ValueFactory { - - public static Value createValue(int Value) { - return new IntValue(Value); + + public static Value createValue(short value) { + return new ShortValue(value); } - public static Value createValue(double Value) { - return new DoubleValue(Value); + public static Value createValue(int value) { + return new IntValue(value); } - public static Value createValue(float Value) { - return new FloatValue(Value); + public static Value createValue(double value) { + return new DoubleValue(value); } - public static Value createValue(long Value) { - return new LongValue(Value); + public static Value createValue(float value) { + return new FloatValue(value); } - public static Value createValue(boolean Value) { - return new BooleanValue(Value); + public static Value createValue(long value) { + return new LongValue(value); } - public static Value createValue(char Value) { - return new CharValue(Value); + public static Value createValue(boolean value) { + return new BooleanValue(value); } - public static Value createValue(String Value) { - return new StringValue(Value); + public static Value createValue(char value) { + return new CharValue(value); + } + + public static Value createValue(byte value) { + return new ByteValue(value); } - public static Value createValue(Object Value) { - return new ObjectValue(Value); + public static Value createValue(Object value) { + return new ObjectValue(value); } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanValue.java index fe04113cbf..28813bd917 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanValue.java @@ -20,9 +20,5 @@ public boolean isBoolean() { public boolean asBoolean() { return value; } - - @Override - public String asString() { - return String.valueOf(value); - } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteValue.java new file mode 100644 index 0000000000..a3b034d818 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteValue.java @@ -0,0 +1,48 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.Value; + +public class ByteValue implements Value { + + protected byte value; + + public ByteValue(byte value) { + this.value = value; + } + + @Override + public boolean isByte() { + return true; + } + + @Override + public byte asByte() { + return value; + } + + @Override + public short asShort() { + return value; + } + + @Override + public int asInt() { + return value; + } + + @Override + public long asLong() { + return value; + } + + @Override + public float asFloat() { + return value; + } + + @Override + public double asDouble() { + return value; + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharValue.java index 120f6a8470..759dd008e4 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharValue.java @@ -27,11 +27,6 @@ public double asDouble() { return value; } - @Override - public String asString() { - return Character.toString(value); - } - @Override public char asChar() { return value; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleValue.java index 99d24ab8f3..10c12e8c5b 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleValue.java @@ -17,28 +17,9 @@ public boolean isDouble() { return true; } - @Override - public int asInt() { - return (int) value; - } - @Override public double asDouble() { return value; } - - @Override - public String asString() { - return Double.toString(value); - } - - @Override - public long asLong() { - return (long) value; - } - - @Override - public float asFloat() { - return (float) value; - } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorValue.java new file mode 100644 index 0000000000..073ee348b9 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorValue.java @@ -0,0 +1,18 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.Value; + +public class ErrorValue implements Value { + + String message; + + public ErrorValue(String message) { + this.message = message; + } + + @Override + public boolean isError() { + return true; + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatValue.java index 93f3fc783a..8dcc608bfb 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatValue.java @@ -16,26 +16,11 @@ public boolean isFloat() { return true; } - @Override - public int asInt() { - return (int) value; - } - @Override public double asDouble() { return value; } - @Override - public String asString() { - return Float.toString(value); - } - - @Override - public long asLong() { - return (long) value; - } - @Override public float asFloat() { return value; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionValue.java new file mode 100644 index 0000000000..5997d9ce02 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionValue.java @@ -0,0 +1,18 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.MIScope; +import de.monticore.interpreter.Value; +import de.se_rwth.commons.Symbol; + +public class FunctionValue implements Value { + + protected MIScope parentScope; + protected Symbol symbol; + + @Override + public boolean isFunction() { + return true; + } + + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntValue.java index 1bc312aec8..c32716b6fb 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntValue.java @@ -26,11 +26,6 @@ public double asDouble() { return value; } - @Override - public String asString() { - return Integer.toString(value); - } - @Override public long asLong() { return value; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongValue.java index 1876f67a89..293fa334a0 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongValue.java @@ -16,21 +16,11 @@ public boolean isLong() { return true; } - @Override - public int asInt() { - return (int) value; - } - @Override public double asDouble() { return value; } - @Override - public String asString() { - return Long.toString(value); - } - @Override public long asLong() { return value; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/NotAValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/NotAValue.java deleted file mode 100644 index 54d67cd1f7..0000000000 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/NotAValue.java +++ /dev/null @@ -1,6 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package de.monticore.interpreter.values; - -import de.monticore.interpreter.Value; - -public class NotAValue implements Value {} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortValue.java new file mode 100644 index 0000000000..cbb648fe67 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortValue.java @@ -0,0 +1,43 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.Value; + +public class ShortValue implements Value { + + protected short value; + + public ShortValue(short value) { + this.value = value; + } + + @Override + public boolean isShort() { + return true; + } + + @Override + public short asShort() { + return value; + } + + @Override + public int asInt() { + return value; + } + + @Override + public long asLong() { + return value; + } + + @Override + public float asFloat() { + return value; + } + + @Override + public double asDouble() { + return value; + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/StringValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/StringValue.java deleted file mode 100644 index c71b192b1c..0000000000 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/StringValue.java +++ /dev/null @@ -1,33 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package de.monticore.interpreter.values; - -import de.monticore.interpreter.Value; - -public class StringValue implements Value { - - protected String value; - - public StringValue(String value) { - this.value = value; - } - - @Override - public boolean isString() { - return true; - } - - @Override - public boolean isObject() { - return true; - } - - @Override - public String asString() { - return value; - } - - @Override - public Object asObject() { - return value; - } -} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidValue.java new file mode 100644 index 0000000000..35d6ee4bcd --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidValue.java @@ -0,0 +1,11 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.Value; + +public class VoidValue implements Value { + + @Override + public boolean isVoid() { + return true; + } +} diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/Numerals.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/Numerals.mc4 deleted file mode 100644 index dee899a64b..0000000000 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/Numerals.mc4 +++ /dev/null @@ -1,15 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ - -component grammar Numerals extends de.monticore.MCBasics { - - interface Number; - - Integer implements Number = negative:["-"]? Digits; - - Float implements Number = negative:["-"]? pre:Digits "." post:Digits; - - token Digits = Digit+; - - fragment token Digit = '0'..'9'; - -} \ No newline at end of file diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 deleted file mode 100644 index b7a6eb7159..0000000000 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ /dev/null @@ -1,21 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ - -grammar SimpleEquations extends Numerals { - - Program = (Statement ";")* (Expression ";")? ; - - interface Statement; - interface Expression; - - PlusEquation implements Expression = left:Expression "+" right:Expression; - MinusEquation implements Expression = left:Expression "-" right:Expression; - MultiplyEquation implements Expression = left:Expression "*" right:Expression; - DivideEquation implements Expression = left:Expression "/" right:Expression; - - symbol VariableDefinition implements Statement = "var" Name "=" value:Expression; - VariableUsage implements Statement = Name "=" value:Expression; - PrintStatement implements Statement = "print" "(" Expression ")"; - - NameExpression implements Expression = Name; - NumberExpression implements Expression = Number; -} \ No newline at end of file diff --git a/monticore-test/01.experiments/interpreter/src/main/java/numerals/_visitor/NumeralsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/numerals/_visitor/NumeralsInterpreter.java deleted file mode 100644 index 96ec00da88..0000000000 --- a/monticore-test/01.experiments/interpreter/src/main/java/numerals/_visitor/NumeralsInterpreter.java +++ /dev/null @@ -1,28 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package numerals._visitor; - -import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.Value; -import de.monticore.interpreter.ValueFactory; -import numerals._ast.ASTFloat; -import numerals._ast.ASTInteger; - -public class NumeralsInterpreter extends NumeralsInterpreterTOP { - - public NumeralsInterpreter(ModelInterpreter realThis) { - super(realThis); - } - - public Value interpret(ASTFloat node) { - return ValueFactory.createValue((float) - (Integer.parseInt(node.getPre()) + - Integer.parseInt(node.getPost()) * Math.pow(10, -node.getPost().length())) - * (node.isNegative() ? -1 : 1)); - } - - public Value interpret(ASTInteger node) { - return ValueFactory.createValue( - Integer.parseInt(node.getDigits()) * (node.isNegative() ? -1 : 1)); - } - -} diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java deleted file mode 100644 index c65567d3df..0000000000 --- a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java +++ /dev/null @@ -1,96 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package simpleequations._visitor; - -import de.monticore.interpreter.Value; -import de.monticore.interpreter.ValueFactory; -import de.monticore.interpreter.values.NotAValue; -import simpleequations._ast.*; - -public class SimpleEquationsInterpreter extends SimpleEquationsInterpreterTOP { - - public SimpleEquationsInterpreter() { - super(); - } - - public Value interpret(ASTProgram node) { - node.forEachStatements(s -> s.evaluate(getRealThis())); - if (node.isPresentExpression()) { - return node.getExpression().evaluate(getRealThis()); - } - return new NotAValue(); - } - - public Value interpret(ASTPlusEquation node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); - - if (left.isInt() && right.isInt()) { - return ValueFactory.createValue(left.asInt() + right.asInt()); - } - return ValueFactory.createValue(left.asFloat() + right.asFloat()); - } - - public Value interpret(ASTMinusEquation node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); - - if (left.isInt() && right.isInt()) { - return ValueFactory.createValue(left.asInt() - right.asInt()); - } - return ValueFactory.createValue(left.asFloat() - right.asFloat()); - } - - public Value interpret(ASTMultiplyEquation node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); - - if (left.isInt() && right.isInt()) { - return ValueFactory.createValue(left.asInt() * right.asInt()); - } - return ValueFactory.createValue(left.asFloat() * right.asFloat()); - } - - public Value interpret(ASTDivideEquation node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); - - if (left.isInt() && right.isInt()) { - return ValueFactory.createValue(left.asInt() / right.asInt()); - } - return ValueFactory.createValue(left.asFloat() / right.asFloat()); - } - - public Value interpret(ASTVariableDefinition node) { - Value value = node.getValue().evaluate(getRealThis()); - getRealThis().store(node.getSymbol(), value); - return new NotAValue(); - } - - public Value interpret(ASTVariableUsage node) { - var symbol = node.getEnclosingScope().resolveVariableDefinition(node.getName()); - Value value = node.getValue().evaluate(getRealThis()); - symbol.ifPresent(s -> getRealThis().store(s, value)); - return new NotAValue(); - } - - public Value interpret(ASTPrintStatement node) { - Value output = node.getExpression().evaluate(getRealThis()); - - if (output.isInt()) { - System.out.println(output.asInt()); - } else if (output.isFloat()) { - System.out.println(output.asFloat()); - } - return new NotAValue(); - } - - public Value interpret(ASTNameExpression node) { - var optSymbol = node.getEnclosingScope().resolveVariableDefinition(node.getName()); - return optSymbol.map(getRealThis()::load).orElse(new NotAValue()); - } - - public Value interpret(ASTNumberExpression node) { - return node.getNumber().evaluate(getRealThis()); - } - -} diff --git a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java deleted file mode 100644 index 2a9bbb2ccf..0000000000 --- a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package simpleequations._visitor; - -import de.monticore.interpreter.Value; -import org.junit.Test; -import simpleequations.SimpleEquationsMill; -import simpleequations._ast.ASTProgram; -import simpleequations._parser.SimpleEquationsParser; -import simpleequations._symboltable.SimpleEquationsScopesGenitorDelegator; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class SimpleEquationsInterpreterTest { - - @Test - public void test() throws IOException { - SimpleEquationsMill.init(); - SimpleEquationsParser parser = SimpleEquationsMill.parser(); - SimpleEquationsInterpreter interpreter = new SimpleEquationsInterpreter(); - SimpleEquationsScopesGenitorDelegator delegator = SimpleEquationsMill.scopesGenitorDelegator(); - - ASTProgram program = parser.parse_StringProgram("var a=3.5; var b=4; print(a); var c=a+b; c;").get(); - - delegator.createFromAST(program); - Value result = interpreter.interpret(program); - - assertTrue(result.isFloat()); - assertEquals(result.asFloat(), 7.5f, 0.0001f); - - SimpleEquationsMill.reset(); - SimpleEquationsMill.init(); - interpreter = new SimpleEquationsInterpreter(); - program = parser.parse_StringProgram( - "var a = 40; " + - "a = 45;" + - "a;").get(); - - delegator.createFromAST(program); - result = interpreter.interpret(program); - - assertTrue(result.isInt()); - assertEquals(result.asInt(), 45); - } - -} From 20d8cc901e99d306a018b0b41a14e6f137a5ad6a Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Thu, 20 Feb 2025 17:45:35 +0100 Subject: [PATCH 02/37] full common & assignment expressions; working tests --- .../interpreter/ASTEvaluateDecorator.java | 7 +- .../interpreter/InterpreterConstants.java | 2 +- .../AssignmentExpressionsInterpreter.java | 116 +-- .../CommonExpressionsInterpreter.java | 292 +++--- .../_visitor/ExpressionsBasisInterpreter.java | 10 +- .../LambdaExpressionsInterpreter.java | 8 + .../_visitor/UglyExpressionsInterpreter.java | 78 +- .../interpreter/InterpreterUtils.java | 61 +- .../_visitor/MCCommonLiteralsInterpreter.java | 33 +- .../expressions/AbstractInterpreterTest.java | 24 +- .../AssignmentExpressionsInterpreterTest.java | 171 ++-- .../CommonExpressionsInterpreterTest.java | 907 +++++++----------- .../main/java/de/monticore/ast/ASTNode.java | 4 +- .../de/monticore/interpreter/MIScope.java | 19 +- .../interpreter/{Value.java => MIValue.java} | 2 +- .../monticore/interpreter/MIValueFactory.java | 44 + .../interpreter/ModelInterpreter.java | 12 +- .../monticore/interpreter/ValueFactory.java | 44 - ...{BooleanValue.java => BooleanMIValue.java} | 6 +- .../{ByteValue.java => ByteMIValue.java} | 6 +- .../{CharValue.java => CharMIValue.java} | 7 +- .../{DoubleValue.java => DoubleMIValue.java} | 7 +- .../{ErrorValue.java => ErrorMIValue.java} | 6 +- .../{FloatValue.java => FloatMIValue.java} | 6 +- .../interpreter/values/FunctionMIValue.java | 28 + .../interpreter/values/FunctionValue.java | 18 - .../values/{IntValue.java => IntMIValue.java} | 6 +- .../{LongValue.java => LongMIValue.java} | 6 +- .../{ObjectValue.java => ObjectMIValue.java} | 6 +- .../{ShortValue.java => ShortMIValue.java} | 6 +- .../{VoidValue.java => VoidMIValue.java} | 4 +- 31 files changed, 858 insertions(+), 1088 deletions(-) rename monticore-runtime/src/main/java/de/monticore/interpreter/{Value.java => MIValue.java} (98%) create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/MIValueFactory.java delete mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/ValueFactory.java rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{BooleanValue.java => BooleanMIValue.java} (68%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{ByteValue.java => ByteMIValue.java} (81%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{CharValue.java => CharMIValue.java} (77%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{DoubleValue.java => DoubleMIValue.java} (63%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{ErrorValue.java => ErrorMIValue.java} (56%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{FloatValue.java => FloatMIValue.java} (73%) create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java delete mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionValue.java rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{IntValue.java => IntMIValue.java} (79%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{LongValue.java => LongMIValue.java} (76%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{ObjectValue.java => ObjectMIValue.java} (68%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{ShortValue.java => ShortMIValue.java} (79%) rename monticore-runtime/src/main/java/de/monticore/interpreter/values/{VoidValue.java => VoidMIValue.java} (55%) diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/ASTEvaluateDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/ASTEvaluateDecorator.java index aab35bc66d..5b985fa1e2 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/ASTEvaluateDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/ASTEvaluateDecorator.java @@ -1,6 +1,8 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.codegen.cd2java.interpreter; +import de.monticore.cd4code.CD4CodeMill; +import de.monticore.cd4code._util.ICD4CodeTypeDispatcher; import de.monticore.cd4codebasis._ast.ASTCDMethod; import de.monticore.cd4codebasis._ast.ASTCDParameter; import de.monticore.cdbasis._ast.*; @@ -35,9 +37,10 @@ public ASTEvaluateDecorator(GlobalExtensionManagement glex, public void decorate(ASTCDCompilationUnit input, ASTCDCompilationUnit decoratedCD) { ASTCDPackage astPackage = getPackage(input, decoratedCD, ASTConstants.AST_PACKAGE); + ICD4CodeTypeDispatcher dispatcher = CD4CodeMill.typeDispatcher(); astPackage.streamCDElements() - .filter(e -> e instanceof ASTCDClass) - .map(e -> (ASTCDClass) e) + .filter(dispatcher::isCDBasisASTCDClass) + .map(dispatcher::asCDBasisASTCDClass) .forEach(t -> t.addAllCDMembers(decorate(t))); } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java index ac54db586e..48e665e3d5 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java @@ -11,7 +11,7 @@ public final class InterpreterConstants { public static final String INTERPRETER_SCOPE_FULLNAME = "de.monticore.interpreter.MIScope"; - public static final String VALUE_FULLNAME = "de.monticore.interpreter.Value"; + public static final String VALUE_FULLNAME = "de.monticore.interpreter.MIValue"; public static final String NOT_A_VALUE_FULLNAME = "de.monticore.interpreter.values.NotAValue"; diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java index 09e2b71923..eb1017596b 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java @@ -5,8 +5,8 @@ import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.interpreter.InterpreterUtils; import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.Value; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symboltable.ISymbol; import de.monticore.types.check.SymTypeExpression; @@ -18,7 +18,7 @@ import java.util.Optional; import static de.monticore.expressions.assignmentexpressions._ast.ASTConstantsAssignmentExpressions.*; -import static de.monticore.interpreter.ValueFactory.createValue; +import static de.monticore.interpreter.MIValueFactory.createValue; public class AssignmentExpressionsInterpreter extends AssignmentExpressionsInterpreterTOP { @@ -32,226 +32,226 @@ public AssignmentExpressionsInterpreter() { //i++ @Override - public Value interpret(ASTIncSuffixExpression n) { + public MIValue interpret(ASTIncSuffixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); Optional symbol = type.getSourceInfo().getSourceSymbol(); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - Value value = load(symbol.get()); + MIValue value = load(symbol.get()); if (value.isError()) return value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { - Value res = createValue((byte)(value.asByte() + 1)); + MIValue res = createValue((byte)(value.asByte() + 1)); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - Value res = createValue((short)(value.asShort() + 1)); + MIValue res = createValue((short)(value.asShort() + 1)); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - Value res = createValue((char)(value.asChar() + 1)); + MIValue res = createValue((char)(value.asChar() + 1)); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.INT)) { - Value res = createValue(value.asInt() + 1); + MIValue res = createValue(value.asInt() + 1); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.LONG)) { - Value res = createValue(value.asLong() + 1); + MIValue res = createValue(value.asLong() + 1); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - Value res = createValue(value.asFloat() + 1); + MIValue res = createValue(value.asFloat() + 1); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - Value res = createValue(value.asDouble() + 1); + MIValue res = createValue(value.asDouble() + 1); store(symbol.get(), res); return value; } } String errorMsg = "Suffix incrementation operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } //++i @Override - public Value interpret(ASTIncPrefixExpression n) { + public MIValue interpret(ASTIncPrefixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); Optional symbol = type.getSourceInfo().getSourceSymbol(); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - Value value = load(symbol.get()); + MIValue value = load(symbol.get()); if (value.isError()) return value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { - Value res = createValue((byte)(value.asByte() + 1)); + MIValue res = createValue((byte)(value.asByte() + 1)); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - Value res = createValue((short)(value.asShort() + 1)); + MIValue res = createValue((short)(value.asShort() + 1)); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - Value res = createValue((char)(value.asChar() + 1)); + MIValue res = createValue((char)(value.asChar() + 1)); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.INT)) { - Value res = createValue(value.asInt() + 1); + MIValue res = createValue(value.asInt() + 1); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.LONG)) { - Value res = createValue(value.asLong() + 1); + MIValue res = createValue(value.asLong() + 1); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - Value res = createValue(value.asFloat() + 1); + MIValue res = createValue(value.asFloat() + 1); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - Value res = createValue(value.asDouble() + 1); + MIValue res = createValue(value.asDouble() + 1); store(symbol.get(), res); return res; } } String errorMsg = "Prefix incrementation operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } //i-- @Override - public Value interpret(ASTDecSuffixExpression n) { + public MIValue interpret(ASTDecSuffixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); Optional symbol = type.getSourceInfo().getSourceSymbol(); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - Value value = load(symbol.get()); + MIValue value = load(symbol.get()); if (value.isError()) return value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { - Value res = createValue((byte)(value.asByte() - 1)); + MIValue res = createValue((byte)(value.asByte() - 1)); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - Value res = createValue((short)(value.asShort() - 1)); + MIValue res = createValue((short)(value.asShort() - 1)); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - Value res = createValue((char)(value.asChar() - 1)); + MIValue res = createValue((char)(value.asChar() - 1)); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.INT)) { - Value res = createValue(value.asInt() - 1); + MIValue res = createValue(value.asInt() - 1); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.LONG)) { - Value res = createValue(value.asLong() - 1); + MIValue res = createValue(value.asLong() - 1); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - Value res = createValue(value.asFloat() - 1); + MIValue res = createValue(value.asFloat() - 1); store(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - Value res = createValue(value.asDouble() - 1); + MIValue res = createValue(value.asDouble() - 1); store(symbol.get(), res); return value; } } String errorMsg = "Suffix decrementation operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } //--i @Override - public Value interpret(ASTDecPrefixExpression n) { + public MIValue interpret(ASTDecPrefixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); Optional symbol = type.getSourceInfo().getSourceSymbol(); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - Value value = load(symbol.get()); + MIValue value = load(symbol.get()); if (value.isError()) return value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { - Value res = createValue((byte)(value.asByte() - 1)); + MIValue res = createValue((byte)(value.asByte() - 1)); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - Value res = createValue((short)(value.asShort() - 1)); + MIValue res = createValue((short)(value.asShort() - 1)); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - Value res = createValue((char)(value.asChar() - 1)); + MIValue res = createValue((char)(value.asChar() - 1)); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.INT)) { - Value res = createValue(value.asInt() - 1); + MIValue res = createValue(value.asInt() - 1); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.LONG)) { - Value res = createValue(value.asLong() - 1); + MIValue res = createValue(value.asLong() - 1); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - Value res = createValue(value.asFloat() - 1); + MIValue res = createValue(value.asFloat() - 1); store(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - Value res = createValue(value.asDouble() - 1); + MIValue res = createValue(value.asDouble() - 1); store(symbol.get(), res); return res; } } String errorMsg = "Prefix decrementation operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTAssignmentExpression n) { + public MIValue interpret(ASTAssignmentExpression n) { ASTExpression leftExpr = n.getLeft(); SymTypeExpression leftType = TypeCheck3.typeOf(leftExpr); Optional leftSymbol = leftType.getSourceInfo().getSourceSymbol(); if (leftSymbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } int operator = n.getOperator(); - Value rightValue = n.getRight().evaluate(getRealThis()); + MIValue rightValue = n.getRight().evaluate(getRealThis()); if (rightValue.isError()) return rightValue; SymTypeExpression rightType = TypeCheck3.typeOf(n.getRight()); @@ -266,7 +266,7 @@ public Value interpret(ASTAssignmentExpression n) { if (!SymTypeRelations.isCompatible(leftType, rightType)) { String errorMsg = "A value of type " + rightType.print() + " can not be writen to a variable of type " + leftType.print() + "."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } if (leftType.isPrimitive() && rightType.isPrimitive()) { @@ -274,17 +274,17 @@ public Value interpret(ASTAssignmentExpression n) { } else { String errorMsg = "The implicit conversion from " + rightType.print() + " to " + leftType.print() + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } store(leftSymbol.get(), rightValue); return rightValue; } - Value leftValue = load(leftSymbol.get()); + MIValue leftValue = load(leftSymbol.get()); if (leftValue.isError()) return leftValue; - Value resultValue; + MIValue resultValue; SymTypeExpression resultType; switch (operator) { @@ -362,7 +362,7 @@ public Value interpret(ASTAssignmentExpression n) { if (rightValue.asDouble() == 0.0) { String errorMsg = "Division by zero is undefined"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } resultValue = InterpreterUtils.calcOpPrimitive(leftValue, rightValue, resultPrimitive, @@ -372,7 +372,7 @@ public Value interpret(ASTAssignmentExpression n) { } String errorMsg = "Division Assignment operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } case STAREQUALS: { @@ -384,7 +384,7 @@ public Value interpret(ASTAssignmentExpression n) { } default: Log.error("Operator is not defined."); - return new ErrorValue("Operator is not defined."); + return new ErrorMIValue("Operator is not defined."); } if (resultValue.isError()) return resultValue; @@ -396,7 +396,7 @@ public Value interpret(ASTAssignmentExpression n) { } else { String errorMsg = "Cast from " + resultType.print() + " to " + leftType.print() + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } if (resultValue.isError()) return resultValue; diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index 80e4f4cb8f..ee571ff026 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -3,9 +3,11 @@ import de.monticore.expressions.commonexpressions._ast.*; import de.monticore.expressions.expressionsbasis._ast.ASTLiteralExpression; +import de.monticore.interpreter.InterpreterUtils; +import de.monticore.interpreter.MIScope; import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.Value; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypePrimitive; @@ -13,7 +15,7 @@ import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; -import static de.monticore.interpreter.ValueFactory.createValue; +import static de.monticore.interpreter.MIValueFactory.createValue; public class CommonExpressionsInterpreter extends CommonExpressionsInterpreterTOP { @@ -35,13 +37,13 @@ public SymTypePrimitive getCompatibleType(SymTypePrimitive type1, SymTypePrimiti ); } - public Value isEqual(SymTypePrimitive leftType, Value left, SymTypePrimitive rightType, Value right) { + public MIValue isEqual(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); if (compatibleType == null) { String errorMsg = "Equality operation with operands ot type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } String primitive = compatibleType.getPrimitiveName(); @@ -66,16 +68,16 @@ public Value isEqual(SymTypePrimitive leftType, Value left, SymTypePrimitive rig String errorMsg = "Equality operator with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not implemented."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public Value subtract(SymTypePrimitive leftType, Value left, SymTypePrimitive rightType, Value right) { + public MIValue subtract(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); if (compatibleType == null) { String errorMsg = "Greater or Lesser operation with operands ot type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } String primitive = compatibleType.getPrimitiveName(); @@ -98,166 +100,86 @@ public Value subtract(SymTypePrimitive leftType, Value left, SymTypePrimitive ri String errorMsg = "Greater or Lesser operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTPlusExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTPlusExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); - if (type.isPrimitive()) { - String primitive = type.asPrimitive().getPrimitiveName(); - if (primitive.equals(BasicSymbolsMill.BYTE)) { - return createValue(left.asByte() + right.asByte()); - } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - return createValue(left.asShort() + right.asShort()); - } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - return createValue(left.asChar() + right.asChar()); - } else if (primitive.equals(BasicSymbolsMill.INT)) { - return createValue(left.asInt() + right.asInt()); - } else if (primitive.equals(BasicSymbolsMill.LONG)) { - return createValue(left.asLong() + right.asLong()); - } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - return createValue(left.asFloat() + right.asFloat()); - } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - return createValue(left.asDouble() + right.asDouble()); - } - } - - String errorMsg = "Plus operation with result of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); - return new ErrorValue(errorMsg); + return InterpreterUtils.calcOp(left, right, type, Integer::sum, Long::sum, Float::sum, Double::sum, "Plus"); } @Override - public Value interpret(ASTMinusExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTMinusExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; - SymTypeExpression typeLeft = TypeCheck3.typeOf(node.getLeft()); - SymTypeExpression typeRight = TypeCheck3.typeOf(node.getRight()); - if (typeLeft.isPrimitive() && typeRight.isPrimitive()) { - return subtract(typeLeft.asPrimitive(), left, typeRight.asPrimitive(), right); - } - - String errorMsg = "Minus operation with operands of type '" + typeLeft.print() + "' and '" - + typeRight.print() + "' is not supported."; - Log.error(errorMsg); - return new ErrorValue(errorMsg); + SymTypeExpression type = TypeCheck3.typeOf(node); + return InterpreterUtils.calcOp(left, right, type, (a, b) -> a - b, (a, b) -> a - b, + (a, b) -> a - b, (a, b) -> a - b, "Minus"); } @Override - public Value interpret(ASTMultExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTMultExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); - if (type.isPrimitive()) { - String primitive = type.asPrimitive().getPrimitiveName(); - if (primitive.equals(BasicSymbolsMill.BYTE)) { - return createValue(left.asByte() * right.asByte()); - } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - return createValue(left.asShort() * right.asShort()); - } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - return createValue(left.asChar() * right.asChar()); - } else if (primitive.equals(BasicSymbolsMill.INT)) { - return createValue(left.asInt() * right.asInt()); - } else if (primitive.equals(BasicSymbolsMill.LONG)) { - return createValue(left.asLong() * right.asLong()); - } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - return createValue(left.asFloat() * right.asFloat()); - } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - return createValue(left.asDouble() * right.asDouble()); - } - } - - String errorMsg = "Multiplication operation with result of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); - return new ErrorValue(errorMsg); + return InterpreterUtils.calcOp(left, right, type, (a, b) -> a * b, (a, b) -> a * b, + (a, b) -> a * b, (a, b) -> a * b, "Multiplication"); } @Override - public Value interpret(ASTDivideExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTDivideExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); - if (type.isPrimitive() && (type.asPrimitive().isIntegralType() || type.asPrimitive().isNumericType())) { - String primitive = type.asPrimitive().getPrimitiveName(); + if (type.isPrimitive()) { + String resultPrimitive = type.asPrimitive().getPrimitiveName(); + if (right.asDouble() == 0.0) { String errorMsg = "Division by zero is undefined"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - if (primitive.equals(BasicSymbolsMill.BYTE)) { - return createValue(left.asByte() * right.asByte()); - } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - return createValue(left.asShort() * right.asShort()); - } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - return createValue(left.asChar() * right.asChar()); - } else if (primitive.equals(BasicSymbolsMill.INT)) { - return createValue(left.asInt() * right.asInt()); - } else if (primitive.equals(BasicSymbolsMill.LONG)) { - return createValue(left.asLong() * right.asLong()); - } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - return createValue(left.asFloat() * right.asFloat()); - } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - return createValue(left.asDouble() * right.asDouble()); - } + return InterpreterUtils.calcOpPrimitive(left, right, resultPrimitive, + (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, + "Division"); } String errorMsg = "Division operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTModuloExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTModuloExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); - if (type.isPrimitive()) { - String primitive = type.asPrimitive().getPrimitiveName(); - - if (primitive.equals(BasicSymbolsMill.BYTE)) { - return createValue(left.asByte() % right.asByte()); - } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - return createValue(left.asShort() % right.asShort()); - } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - return createValue(left.asChar() % right.asChar()); - } else if (primitive.equals(BasicSymbolsMill.INT)) { - return createValue(left.asInt() % right.asInt()); - } else if (primitive.equals(BasicSymbolsMill.LONG)) { - return createValue(left.asLong() % right.asLong()); - } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - return createValue(left.asFloat() % right.asFloat()); - } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - return createValue(left.asDouble() % right.asDouble()); - } - } - - String errorMsg = "Modulo operation with result of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); - return new ErrorValue(errorMsg); + return InterpreterUtils.calcOp(left, right, type, (a, b) -> a % b, (a, b) -> a % b, + (a, b) -> a % b, (a, b) -> a % b, "Modulo"); } @Override - public Value interpret(ASTMinusPrefixExpression node) { - Value value = node.getExpression().evaluate(getRealThis()); + public MIValue interpret(ASTMinusPrefixExpression node) { + MIValue value = node.getExpression().evaluate(getRealThis()); if (value.isError()) return value; SymTypeExpression type = TypeCheck3.typeOf(node); @@ -283,12 +205,12 @@ public Value interpret(ASTMinusPrefixExpression node) { String errorMsg = "Minus Prefix operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTPlusPrefixExpression node) { - Value value = node.getExpression().evaluate(getRealThis()); + public MIValue interpret(ASTPlusPrefixExpression node) { + MIValue value = node.getExpression().evaluate(getRealThis()); if (value.isError()) return value; SymTypeExpression type = TypeCheck3.typeOf(node); @@ -298,13 +220,13 @@ public Value interpret(ASTPlusPrefixExpression node) { String errorMsg = "Minus Prefix operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTEqualsExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTEqualsExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; @@ -317,20 +239,20 @@ public Value interpret(ASTEqualsExpression node) { String errorMsg = "Equality operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTNotEqualsExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTNotEqualsExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { - Value result = isEqual(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + MIValue result = isEqual(leftType.asPrimitive(), left, rightType.asPrimitive(), right); if (result.isError()) return result; return createValue(!result.asBoolean()); @@ -339,20 +261,20 @@ public Value interpret(ASTNotEqualsExpression node) { String errorMsg = "Inequality operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTGreaterThanExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTGreaterThanExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { - Value result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); if (result.isError()) return result; return createValue(result.asDouble() > 0.0); @@ -361,20 +283,20 @@ public Value interpret(ASTGreaterThanExpression node) { String errorMsg = "Greater than operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTLessThanExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTLessThanExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { - Value result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); if (result.isError()) return result; return createValue(result.asDouble() < 0.0); @@ -383,20 +305,20 @@ public Value interpret(ASTLessThanExpression node) { String errorMsg = "Less than operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTGreaterEqualExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTGreaterEqualExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { - Value result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); if (result.isError()) return result; return createValue(result.asDouble() >= 0.0); @@ -405,20 +327,20 @@ public Value interpret(ASTGreaterEqualExpression node) { String errorMsg = "Greater equal operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTLessEqualExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTLessEqualExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { - Value result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); + MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); if (result.isError()) return result; return createValue(result.asDouble() <= 0.0); @@ -427,13 +349,13 @@ public Value interpret(ASTLessEqualExpression node) { String errorMsg = "Less equal operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } //~ -> behaves as a bitwise complement @Override - public Value interpret(ASTBooleanNotExpression node) { - Value value = node.getExpression().evaluate(getRealThis()); + public MIValue interpret(ASTBooleanNotExpression node) { + MIValue value = node.getExpression().evaluate(getRealThis()); if (value.isError()) return value; SymTypeExpression type = TypeCheck3.typeOf(node.getExpression()); @@ -452,9 +374,9 @@ public Value interpret(ASTBooleanNotExpression node) { } } - String errorMsg = "Bitwise Not opeartion with operand of type '" + type.print() + "' is not supported."; + String errorMsg = "Bitwise Not operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } /*=================================================================*/ @@ -462,8 +384,8 @@ public Value interpret(ASTBooleanNotExpression node) { /*=================================================================*/ @Override - public Value interpret(ASTLogicalNotExpression node) { - Value value = node.getExpression().evaluate(getRealThis()); + public MIValue interpret(ASTLogicalNotExpression node) { + MIValue value = node.getExpression().evaluate(getRealThis()); if (value.isError()) return value; SymTypeExpression type = TypeCheck3.typeOf(node.getExpression()); @@ -474,13 +396,13 @@ public Value interpret(ASTLogicalNotExpression node) { String errorMsg = "Logical Not operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTBooleanAndOpExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTBooleanAndOpExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; @@ -494,13 +416,13 @@ public Value interpret(ASTBooleanAndOpExpression node) { String errorMsg = "Logical And operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTBooleanOrOpExpression node) { - Value left = node.getLeft().evaluate(getRealThis()); - Value right = node.getRight().evaluate(getRealThis()); + public MIValue interpret(ASTBooleanOrOpExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); if (left.isError()) return left; if (right.isError()) return right; @@ -514,17 +436,17 @@ public Value interpret(ASTBooleanOrOpExpression node) { String errorMsg = "Logical Or operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTBracketExpression node) { + public MIValue interpret(ASTBracketExpression node) { return node.getExpression().evaluate(getRealThis()); } @Override - public Value interpret(ASTConditionalExpression node) { - Value condition = node.getCondition().evaluate(getRealThis()); + public MIValue interpret(ASTConditionalExpression node) { + MIValue condition = node.getCondition().evaluate(getRealThis()); if (condition.isError()) return condition; return condition.asBoolean() @@ -533,17 +455,35 @@ public Value interpret(ASTConditionalExpression node) { } @Override - public Value interpret(ASTFieldAccessExpression node) { + public MIValue interpret(ASTFieldAccessExpression node) { String errorMsg = "Field Access operation not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); // String expression = CommonExpressionsMill.prettyPrint(node, false); // Optional symbol = ((IBasicSymbolsScope) node.getEnclosingScope()).resolveVariable(expression); // return symbol.map(this::load).orElse(new NullValue()); } @Override - public Value interpret(ASTLiteralExpression node) { + public MIValue interpret(ASTLiteralExpression node) { return node.getLiteral().evaluate(getRealThis()); } + + @Override + public MIValue interpret(ASTCallExpression node) { + // evaluate expression that gives lambda/function + // get original parent scope of lambda/function declaration + // create Scope with parent and arguments + // evaluate arguments in current scope & put into new scope + + // node.getExpression(); + // parent = whatever + +// MIScope scope = new MIScope(parent); +// List parameterSymbols = +// List arguments = node.getArguments().getExpressionList(); +// for (int i = 0; i < arguments.getSize(); i++) { +// scope.declareVariable() +// } + } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java index e82ba24c80..ce422de4da 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java @@ -4,8 +4,8 @@ import de.monticore.expressions.expressionsbasis._ast.ASTLiteralExpression; import de.monticore.expressions.expressionsbasis._ast.ASTNameExpression; import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.Value; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symboltable.ISymbol; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.TypeCheck3; @@ -24,20 +24,20 @@ public ExpressionsBasisInterpreter(ModelInterpreter realThis) { } @Override - public Value interpret(ASTNameExpression n) { + public MIValue interpret(ASTNameExpression n) { SymTypeExpression type = TypeCheck3.typeOf(n); Optional symbol = type.getSourceInfo().getSourceSymbol(); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } return load(symbol.get()); } @Override - public Value interpret(ASTLiteralExpression n) { + public MIValue interpret(ASTLiteralExpression n) { return n.getLiteral().evaluate(getRealThis()); } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java index 36491273f9..82ad275ead 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java @@ -1,6 +1,10 @@ package de.monticore.expressions.lambdaexpressions._visitor; +import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaExpression; import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.values.FunctionMIValue; +import de.monticore.interpreter.values.func.MILambdaValue; public class LambdaExpressionsInterpreter extends LambdaExpressionsInterpreterTOP { @@ -12,5 +16,9 @@ public LambdaExpressionsInterpreter(ModelInterpreter realThis) { super(realThis); } + @Override + public MIValue interpret(ASTLambdaExpression node) { + return new MILambdaValue(getRealThis().getCurrentScope(), node); + } } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java index 9664fa0f93..aec3ae7888 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java @@ -2,9 +2,9 @@ import de.monticore.expressions.uglyexpressions._ast.ASTTypeCastExpression; import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.Value; -import de.monticore.interpreter.ValueFactory; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.MIValueFactory; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.TypeCheck3; @@ -21,11 +21,11 @@ public UglyExpressionsInterpreter() { } @Override - public Value interpret(ASTTypeCastExpression node) { + public MIValue interpret(ASTTypeCastExpression node) { SymTypeExpression afterType = TypeCheck3.symTypeFromAST(node.getMCType()); SymTypeExpression beforeType = TypeCheck3.typeOf(node.getExpression()); - Value value = node.getExpression().evaluate(getRealThis()); + MIValue value = node.getExpression().evaluate(getRealThis()); if (afterType.isPrimitive() && beforeType.isPrimitive()) { return convertPrimitive(beforeType.asPrimitive().getPrimitiveName(), @@ -35,86 +35,86 @@ public Value interpret(ASTTypeCastExpression node) { String errorMsg = "Type Cast operation from " + beforeType.print() + " to " + afterType.print() + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public Value convertPrimitive(String fromType, String toType, Value value) { + public MIValue convertPrimitive(String fromType, String toType, MIValue value) { if (toType.equals(BasicSymbolsMill.BOOLEAN) || fromType.equals(BasicSymbolsMill.BOOLEAN)) { String errorMsg = "Cast to or from boolean is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } if (toType.equals(BasicSymbolsMill.BYTE)) { if (fromType.equals(BasicSymbolsMill.DOUBLE)) { - return ValueFactory.createValue((byte)value.asDouble()); + return MIValueFactory.createValue((byte)value.asDouble()); } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { - return ValueFactory.createValue((byte)value.asFloat()); + return MIValueFactory.createValue((byte)value.asFloat()); } else if (fromType.equals(BasicSymbolsMill.LONG)) { - return ValueFactory.createValue((byte)value.asLong()); + return MIValueFactory.createValue((byte)value.asLong()); } else if (fromType.equals(BasicSymbolsMill.INT)) { - return ValueFactory.createValue((byte)value.asInt()); + return MIValueFactory.createValue((byte)value.asInt()); } else if (fromType.equals(BasicSymbolsMill.SHORT)) { - return ValueFactory.createValue((byte)value.asShort()); + return MIValueFactory.createValue((byte)value.asShort()); } else if (fromType.equals(BasicSymbolsMill.CHAR)) { - return ValueFactory.createValue((byte)value.asChar()); + return MIValueFactory.createValue((byte)value.asChar()); } - return ValueFactory.createValue(value.asByte()); + return MIValueFactory.createValue(value.asByte()); } else if (toType.equals(BasicSymbolsMill.SHORT)) { if (fromType.equals(BasicSymbolsMill.DOUBLE)) { - return ValueFactory.createValue((short)value.asDouble()); + return MIValueFactory.createValue((short)value.asDouble()); } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { - return ValueFactory.createValue((short)value.asFloat()); + return MIValueFactory.createValue((short)value.asFloat()); } else if (fromType.equals(BasicSymbolsMill.LONG)) { - return ValueFactory.createValue((short)value.asLong()); + return MIValueFactory.createValue((short)value.asLong()); } else if (fromType.equals(BasicSymbolsMill.INT)) { - return ValueFactory.createValue((short)value.asInt()); + return MIValueFactory.createValue((short)value.asInt()); } else if (fromType.equals(BasicSymbolsMill.CHAR)) { - return ValueFactory.createValue((short)value.asChar()); + return MIValueFactory.createValue((short)value.asChar()); } - return ValueFactory.createValue(value.asShort()); + return MIValueFactory.createValue(value.asShort()); } else if (toType.equals(BasicSymbolsMill.CHAR)) { if (fromType.equals(BasicSymbolsMill.DOUBLE)) { - return ValueFactory.createValue((char)value.asDouble()); + return MIValueFactory.createValue((char)value.asDouble()); } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { - return ValueFactory.createValue((char)value.asFloat()); + return MIValueFactory.createValue((char)value.asFloat()); } else if (fromType.equals(BasicSymbolsMill.LONG)) { - return ValueFactory.createValue((char)value.asLong()); + return MIValueFactory.createValue((char)value.asLong()); } else if (fromType.equals(BasicSymbolsMill.INT)) { - return ValueFactory.createValue((char)value.asInt()); + return MIValueFactory.createValue((char)value.asInt()); } else if (fromType.equals(BasicSymbolsMill.SHORT)) { - return ValueFactory.createValue((char)value.asShort()); + return MIValueFactory.createValue((char)value.asShort()); } else if (fromType.equals(BasicSymbolsMill.BYTE)) { - return ValueFactory.createValue((char)value.asByte()); + return MIValueFactory.createValue((char)value.asByte()); } - return ValueFactory.createValue(value.asChar()); + return MIValueFactory.createValue(value.asChar()); } else if (toType.equals(BasicSymbolsMill.INT)) { if (fromType.equals(BasicSymbolsMill.DOUBLE)) { - return ValueFactory.createValue((int)value.asDouble()); + return MIValueFactory.createValue((int)value.asDouble()); } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { - return ValueFactory.createValue((int)value.asFloat()); + return MIValueFactory.createValue((int)value.asFloat()); } else if (fromType.equals(BasicSymbolsMill.LONG)) { - return ValueFactory.createValue((int)value.asLong()); + return MIValueFactory.createValue((int)value.asLong()); } - return ValueFactory.createValue(value.asInt()); + return MIValueFactory.createValue(value.asInt()); } else if (toType.equals(BasicSymbolsMill.LONG)) { if (fromType.equals(BasicSymbolsMill.DOUBLE)) { - return ValueFactory.createValue((long)value.asDouble()); + return MIValueFactory.createValue((long)value.asDouble()); } else if (fromType.equals(BasicSymbolsMill.FLOAT)) { - return ValueFactory.createValue((long)value.asFloat()); + return MIValueFactory.createValue((long)value.asFloat()); } - return ValueFactory.createValue(value.asLong()); + return MIValueFactory.createValue(value.asLong()); } else if (toType.equals(BasicSymbolsMill.FLOAT)) { if (fromType.equals(BasicSymbolsMill.DOUBLE)) { - return ValueFactory.createValue((float)value.asDouble()); + return MIValueFactory.createValue((float)value.asDouble()); } - return ValueFactory.createValue(value.asFloat()); + return MIValueFactory.createValue(value.asFloat()); } else if (toType.equals(BasicSymbolsMill.DOUBLE)) { - return ValueFactory.createValue(value.asDouble()); + return MIValueFactory.createValue(value.asDouble()); } String errorMsg = "Cast from " + fromType + " to " + toType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java index 3d5fa6a571..db1a45eee4 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java @@ -1,54 +1,57 @@ package de.monticore.interpreter; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; import de.se_rwth.commons.logging.Log; +import java.util.List; import java.util.function.BiFunction; import java.util.function.BinaryOperator; -import static de.monticore.interpreter.ValueFactory.createValue; +import static de.monticore.interpreter.MIValueFactory.createValue; public class InterpreterUtils { - public static Value calcBitwiseOpPrimitive(Value v1, Value v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, - String opName) { + public static MIValue calcOpPrimitive(MIValue v1, MIValue v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, + BinaryOperator opFloat, BinaryOperator opDouble, String opName) { + + switch (resultType) { case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); + case BasicSymbolsMill.FLOAT: return createValue((float)opFloat.apply(v1.asFloat(), v2.asFloat())); + case BasicSymbolsMill.DOUBLE: return createValue((double)opDouble.apply(v1.asDouble(), v2.asDouble())); } String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value calcBitwiseLogicalOpPrimitive(Value v1, Value v2, String resultType, BinaryOperator opBool, BinaryOperator opInt, - BinaryOperator opLong, String opName) { + public static MIValue calcBitwiseOpPrimitive(MIValue v1, MIValue v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, + String opName) { switch (resultType) { - case BasicSymbolsMill.BOOLEAN: return createValue((boolean)opBool.apply(v1.asBoolean(), v2.asBoolean())); case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); } String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value calcOpPrimitive(Value v1, Value v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, - BinaryOperator opFloat, BinaryOperator opDouble, String opName) { + public static MIValue calcBitwiseLogicalOpPrimitive(MIValue v1, MIValue v2, String resultType, BinaryOperator opBool, BinaryOperator opInt, + BinaryOperator opLong, String opName) { switch (resultType) { + case BasicSymbolsMill.BOOLEAN: return createValue((boolean)opBool.apply(v1.asBoolean(), v2.asBoolean())); case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); - case BasicSymbolsMill.FLOAT: return createValue((float)opFloat.apply(v1.asFloat(), v2.asFloat())); - case BasicSymbolsMill.DOUBLE: return createValue((double)opDouble.apply(v1.asDouble(), v2.asDouble())); } String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value calcShiftPrimitive(Value v1, Value v2, String resultType, BiFunction opInt, BinaryOperator opLong, + public static MIValue calcShiftPrimitive(MIValue v1, MIValue v2, String resultType, BiFunction opInt, BinaryOperator opLong, String opName) { switch (resultType) { case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asLong())); @@ -56,10 +59,10 @@ public static Value calcShiftPrimitive(Value v1, Value v2, String resultType, Bi } String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value calcOp(Value v1, Value v2, SymTypeExpression resultType, BinaryOperator opInt, BinaryOperator opLong, + public static MIValue calcOp(MIValue v1, MIValue v2, SymTypeExpression resultType, BinaryOperator opInt, BinaryOperator opLong, BinaryOperator opFloat, BinaryOperator opDouble, String opName) { if (resultType.isPrimitive()) { return calcOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opFloat, opDouble, opName); @@ -67,10 +70,10 @@ public static Value calcOp(Value v1, Value v2, SymTypeExpression resultType, Bin String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value calcBitwiseOp(Value v1, Value v2, SymTypeExpression resultType, BinaryOperator opInt, BinaryOperator opLong, + public static MIValue calcBitwiseOp(MIValue v1, MIValue v2, SymTypeExpression resultType, BinaryOperator opInt, BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { return calcBitwiseOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opName); @@ -78,10 +81,10 @@ public static Value calcBitwiseOp(Value v1, Value v2, SymTypeExpression resultTy String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value calcBitwiseLogicalOp(Value v1, Value v2, SymTypeExpression resultType, BinaryOperator opBool, BinaryOperator opInt, + public static MIValue calcBitwiseLogicalOp(MIValue v1, MIValue v2, SymTypeExpression resultType, BinaryOperator opBool, BinaryOperator opInt, BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { return calcBitwiseLogicalOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opBool, opInt, opLong, opName); @@ -89,10 +92,10 @@ public static Value calcBitwiseLogicalOp(Value v1, Value v2, SymTypeExpression r String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value calcShift(Value v1, Value v2, SymTypeExpression resultType, BiFunction opInt, + public static MIValue calcShift(MIValue v1, MIValue v2, SymTypeExpression resultType, BiFunction opInt, BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { return calcShiftPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opName); @@ -100,14 +103,14 @@ public static Value calcShift(Value v1, Value v2, SymTypeExpression resultType, String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value convertToPrimitiveExplicit(String from, String to, Value value) { + public static MIValue convertToPrimitiveExplicit(String from, String to, MIValue value) { if (to.equals(BasicSymbolsMill.BOOLEAN) || from.equals(BasicSymbolsMill.BOOLEAN)) { String errorMsg = "Cast to or from boolean is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } if (to.equals(BasicSymbolsMill.BYTE)) { switch (from) { @@ -169,10 +172,10 @@ public static Value convertToPrimitiveExplicit(String from, String to, Value val String errorMsg = "Cast from " + from + " to " + to + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } - public static Value convertToPrimitiveImplicit(String targetType, Value value) { + public static MIValue convertToPrimitiveImplicit(String targetType, MIValue value) { if (targetType.equals(BasicSymbolsMill.BYTE)) { return createValue(value.asByte()); } else if (targetType.equals(BasicSymbolsMill.SHORT)) { @@ -191,7 +194,7 @@ public static Value convertToPrimitiveImplicit(String targetType, Value value) { String errorMsg = "Implicit cast to " + targetType + " is not supported."; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java index f4b2f54d6a..8827e23cb6 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java @@ -2,13 +2,12 @@ package de.monticore.literals.mccommonliterals._visitor; import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.Value; -import de.monticore.interpreter.ValueFactory; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.literals.mccommonliterals._ast.*; import de.se_rwth.commons.logging.Log; -import static de.monticore.interpreter.ValueFactory.createValue; +import static de.monticore.interpreter.MIValueFactory.createValue; public class MCCommonLiteralsInterpreter extends MCCommonLiteralsInterpreterTOP { @@ -21,64 +20,64 @@ public MCCommonLiteralsInterpreter(ModelInterpreter realThis) { } @Override - public Value interpret(ASTNullLiteral node) { + public MIValue interpret(ASTNullLiteral node) { String errorMsg = "Null should not be used"; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } @Override - public Value interpret(ASTBooleanLiteral node){ + public MIValue interpret(ASTBooleanLiteral node){ return createValue(node.getValue()); } @Override - public Value interpret(ASTCharLiteral node) { + public MIValue interpret(ASTCharLiteral node) { return createValue(node.getValue()); } @Override - public Value interpret(ASTStringLiteral node){ + public MIValue interpret(ASTStringLiteral node){ return createValue(node.getValue()); } @Override - public Value interpret(ASTNatLiteral node){ + public MIValue interpret(ASTNatLiteral node){ return createValue(node.getValue()); } @Override - public Value interpret(ASTSignedNatLiteral node){ + public MIValue interpret(ASTSignedNatLiteral node){ return createValue(node.getValue()); } @Override - public Value interpret(ASTBasicLongLiteral node){ + public MIValue interpret(ASTBasicLongLiteral node){ return createValue(node.getValue()); } @Override - public Value interpret(ASTSignedBasicLongLiteral node) { + public MIValue interpret(ASTSignedBasicLongLiteral node) { return createValue(node.getValue()); } @Override - public Value interpret(ASTBasicFloatLiteral node){ + public MIValue interpret(ASTBasicFloatLiteral node){ return createValue(node.getValue()); } @Override - public Value interpret(ASTSignedBasicFloatLiteral node){ + public MIValue interpret(ASTSignedBasicFloatLiteral node){ return createValue(node.getValue()); } @Override - public Value interpret(ASTBasicDoubleLiteral node){ + public MIValue interpret(ASTBasicDoubleLiteral node){ return createValue(node.getValue()); } @Override - public Value interpret(ASTSignedBasicDoubleLiteral node){ + public MIValue interpret(ASTSignedBasicDoubleLiteral node){ return createValue(node.getValue()); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java index 3cb483512b..6b66ccea01 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java @@ -5,8 +5,8 @@ import de.monticore.expressions.combineexpressionswithliterals._symboltable.CombineExpressionsWithLiteralsScopesGenitorDelegator; import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsInterpreter; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; -import de.monticore.interpreter.Value; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; @@ -17,7 +17,7 @@ import java.io.IOException; -import static de.monticore.interpreter.ValueFactory.createValue; +import static de.monticore.interpreter.MIValueFactory.createValue; import static de.monticore.types3.util.DefsTypesForTests.inScope; import static de.monticore.types3.util.DefsTypesForTests.variable; import static junit.framework.TestCase.*; @@ -27,14 +27,6 @@ public abstract class AbstractInterpreterTest extends AbstractTypeVisitorTest { protected static final double delta = 0.00001; - protected static final int BOOL = 1; - protected static final int INT = 2; - protected static final int LONG = 4; - protected static final int FLOAT = 8; - protected static final int DOUBLE = 16; - protected static final int CHAR = 32; - protected static final int STRING = 64; - protected CombineExpressionsWithLiteralsInterpreter interpreter; protected CombineExpressionsWithLiteralsScopesGenitorDelegator delegator; @@ -108,9 +100,9 @@ protected void initDouble() throws IOException { interpreter.declareVariable(varSymbol, createValue(3.14)); } - protected void testValidExpression(String expr, Value expected) { + protected void testValidExpression(String expr, MIValue expected) { Log.clearFindings(); - Value interpretationResult = null; + MIValue interpretationResult = null; try { interpretationResult = parseExpressionAndInterpret(expr); } catch (IOException e) { @@ -151,7 +143,7 @@ protected void testValidExpression(String expr, Value expected) { protected void testInvalidExpression(String expr) { Log.clearFindings(); - Value interpretationResult = null; + MIValue interpretationResult; try { interpretationResult = parseExpressionAndInterpret(expr); @@ -164,14 +156,14 @@ protected void testInvalidExpression(String expr) { assertTrue(interpretationResult.isError()); } - protected Value parseExpressionAndInterpret(String expr) throws IOException { + protected MIValue parseExpressionAndInterpret(String expr) throws IOException { final ASTExpression ast = parseExpr(expr); generateScopes(ast); SymTypeExpression type = TypeCheck3.typeOf(ast); if (type.isObscureType()) { String errorMsg = "Invalid Expression: " + expr; Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } return interpreter.interpret(ast); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java index 356ff4e963..c4301a1188 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java @@ -2,16 +2,15 @@ package de.monticore.expressions.assignmentexpressions._visitor; import de.monticore.expressions.AbstractInterpreterTest; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; -import static de.monticore.interpreter.ValueFactory.createValue; +import static de.monticore.interpreter.MIValueFactory.createValue; public class AssignmentExpressionsInterpreterTest extends AbstractInterpreterTest { @@ -93,8 +92,8 @@ protected static Stream andEqualsExpression() { arguments("s &= 3.14", null), arguments("c &= false", null), - arguments("c &= (byte)3", null), - arguments("c &= (short)256", null), + arguments("c &= (byte)3", createValue((char)1)), + arguments("c &= (short)256", createValue((char)0)), arguments("c &= 'a'", createValue('a')), arguments("c &= 1", createValue((char)1)), arguments("c &= 2L", createValue((char)0L)), @@ -172,11 +171,11 @@ protected static Stream gTGTEqualsExpression() { arguments("d >>= 'a'", null), arguments("c >>= false", null), - arguments("c >>= 1", createValue(48)), - arguments("c >>= 2L", createValue(24)), + arguments("c >>= 1", createValue((char)48)), + arguments("c >>= 2L", createValue((char)24)), arguments("c >>= 1.5f", null), arguments("c >>= 3.14", null), - arguments("c >>= 'a'", createValue(48))); + arguments("c >>= 'a'", createValue((char)48))); } protected static Stream gTGTGTEqualsExpression() { @@ -217,11 +216,11 @@ protected static Stream gTGTGTEqualsExpression() { arguments("d >>>= 'a'", null), arguments("c >>>= false", null), - arguments("c >>>= 1", createValue(48)), - arguments("c >>>= 2L", createValue(24)), + arguments("c >>>= 1", createValue((char)48)), + arguments("c >>>= 2L", createValue((char)24)), arguments("c >>>= 1.5f", null), arguments("c >>>= 3.14", null), - arguments("c >>>= 'a'", createValue(48))); + arguments("c >>>= 'a'", createValue((char)48))); } protected static Stream lTLTEqualsExpression() { @@ -262,11 +261,11 @@ protected static Stream lTLTEqualsExpression() { arguments("d <<= 'a'", null), arguments("c <<= false", null), - arguments("c <<= 1", createValue(194)), - arguments("c <<= 2L", createValue(388)), + arguments("c <<= 1", createValue((char)194)), + arguments("c <<= 2L", createValue((char)388)), arguments("c <<= 1.5f", null), arguments("c <<= 3.14", null), - arguments("c <<= 'a'", createValue(194))); + arguments("c <<= 'a'", createValue((char)194))); } protected static Stream minusEqualsExpression() { @@ -280,23 +279,23 @@ protected static Stream minusEqualsExpression() { arguments("i -= false", null), arguments("i -= 1", createValue(0)), - arguments("i -= 2L", createValue(-1L)), - arguments("i -= 1.5f", createValue(-.5f)), - arguments("i -= 3.14", createValue(-2.14)), + arguments("i -= 2L", createValue(-1)), + arguments("i -= 1.5f", createValue(0)), + arguments("i -= 3.14", createValue(-2)), arguments("i -= 'a'", createValue(-96)), arguments("l -= false", null), arguments("l -= 1", createValue(4L)), arguments("l -= 2L", createValue(3L)), - arguments("l -= 1.5f", createValue(3.5f)), - arguments("l -= 3.14", createValue(1.86)), + arguments("l -= 1.5f", createValue(3L)), + arguments("l -= 3.14", createValue(1L)), arguments("l -= 'a'", createValue(-92L)), arguments("f -= false", null), arguments("f -= 1", createValue(0.5f)), arguments("f -= 2L", createValue(-0.5f)), arguments("f -= 1.2f", createValue(.3f)), - arguments("f -= 3.14", createValue(-1.64)), + arguments("f -= 3.14", createValue(-1.64f)), arguments("f -= 'a'", createValue(-95.5f)), arguments("d -= false", null), @@ -307,11 +306,11 @@ protected static Stream minusEqualsExpression() { arguments("d -= 'a'", createValue(-93.86)), arguments("c -= false", null), - arguments("c -= 1", createValue(96)), - arguments("c -= 2L", createValue(95L)), - arguments("c -= 1.5f", createValue(95.5f)), - arguments("c -= 3.14", createValue(93.86)), - arguments("c -= 'a'", createValue(0))); + arguments("c -= 1", createValue((char)96)), + arguments("c -= 2L", createValue((char)95)), + arguments("c -= 1.5f", createValue((char)95.5f)), + arguments("c -= 3.14", createValue((char)93.86)), + arguments("c -= 'a'", createValue((char)0))); } protected static Stream percentEqualsExpression() { @@ -325,23 +324,23 @@ protected static Stream percentEqualsExpression() { arguments("i %= false", null), arguments("i %= 1", createValue(0)), - arguments("i %= 2L", createValue(1L)), - arguments("i %= 1.5f", createValue(1f)), - arguments("i %= 3.14", createValue(1.)), + arguments("i %= 2L", createValue(1)), + arguments("i %= 1.5f", createValue(1)), + arguments("i %= 3.14", createValue(1)), arguments("i %= 'a'", createValue(1)), arguments("l %= false", null), arguments("l %= 1", createValue(0L)), arguments("l %= 2L", createValue(1L)), - arguments("l %= 1.5f", createValue(0.5f)), - arguments("l %= 3.14", createValue(1.86)), + arguments("l %= 1.5f", createValue(0L)), + arguments("l %= 3.14", createValue(1L)), arguments("l %= 'a'", createValue(5L)), arguments("f %= false", null), arguments("f %= 1", createValue(0.5f)), arguments("f %= 2L", createValue(1.5f)), arguments("f %= 1.5f", createValue(0f)), - arguments("f %= 3.14", createValue(1.5)), + arguments("f %= 3.14", createValue(1.5f)), arguments("f %= 'a'", createValue(1.5f)), arguments("d %= false", null), @@ -352,16 +351,16 @@ protected static Stream percentEqualsExpression() { arguments("d %= 'a'", createValue(3.14)), arguments("c %= false", null), - arguments("c %= 1", createValue(0)), - arguments("c %= 2L", createValue(1L)), - arguments("c %= 1.5f", createValue(1f)), - arguments("c %= 3.14", createValue(2.8)), - arguments("c %= 'a'", createValue(0))); + arguments("c %= 1", createValue((char)0)), + arguments("c %= 2L", createValue((char)1)), + arguments("c %= 1.5f", createValue((char)1)), + arguments("c %= 3.14", createValue((char)2)), + arguments("c %= 'a'", createValue((char)0))); } protected static Stream pipeEqualsExpression() { return Stream.of( - arguments("b |= false", null), + arguments("b |= false", createValue(true)), arguments("b |= 1", null), arguments("b |= 2L", null), arguments("b |= 1.5f", null), @@ -370,7 +369,7 @@ protected static Stream pipeEqualsExpression() { arguments("i |= false", null), arguments("i |= 1", createValue(1)), - arguments("i |= 2L", createValue(3L)), + arguments("i |= 2L", createValue(3)), arguments("i |= 1.5f", null), arguments("i |= 3.14", null), arguments("i |= 'a'", createValue(97)), @@ -397,11 +396,11 @@ protected static Stream pipeEqualsExpression() { arguments("d |= 'a'", null), arguments("c |= false", null), - arguments("c |= 1", createValue(97)), - arguments("c |= 2L", createValue(99L)), + arguments("c |= 1", createValue((char)97)), + arguments("c |= 2L", createValue((char)99)), arguments("c |= 1.5f", null), arguments("c |= 3.14", null), - arguments("c |= 'a'", createValue(97))); + arguments("c |= 'a'", createValue((char)97))); } protected static Stream plusEqualsExpression() { @@ -414,31 +413,31 @@ protected static Stream plusEqualsExpression() { arguments("b += 'a'", null), arguments("by += false", null), - arguments("by += 1", createValue(2)), - arguments("by += 2L", createValue(3L)), - arguments("by += 1.5f", createValue(2.5f)), - arguments("by += 3.14", createValue(4.14)), - arguments("by += 'a'", createValue(98)), + arguments("by += 1", createValue((byte)4)), + arguments("by += 2L", createValue((byte)5)), + arguments("by += 1.5f", createValue((byte)4)), + arguments("by += 3.14", createValue((byte)6)), + arguments("by += 'a'", createValue((byte)100)), arguments("i += false", null), arguments("i += 1", createValue(2)), - arguments("i += 2L", createValue(3L)), - arguments("i += 1.5f", createValue(2.5f)), - arguments("i += 3.14", createValue(4.14)), + arguments("i += 2L", createValue(3)), + arguments("i += 1.5f", createValue(2)), + arguments("i += 3.14", createValue(4)), arguments("i += 'a'", createValue(98)), arguments("l += false", null), arguments("l += 1", createValue(6L)), arguments("l += 2L", createValue(7L)), - arguments("l += 1.5f", createValue(6.5f)), - arguments("l += 3.14", createValue(8.14)), + arguments("l += 1.5f", createValue(6L)), + arguments("l += 3.14", createValue(8L)), arguments("l += 'a'", createValue(102L)), arguments("f += false", null), arguments("f += 1", createValue(2.5f)), arguments("f += 2L", createValue(3.5f)), arguments("f += 1.5f", createValue(3.0f)), - arguments("f += 3.14", createValue(4.64)), + arguments("f += 3.14", createValue(4.64f)), arguments("f += 'a'", createValue(98.5f)), arguments("d += false", null), @@ -449,16 +448,16 @@ protected static Stream plusEqualsExpression() { arguments("d += 'a'", createValue(100.14)), arguments("c += false", null), - arguments("c += 1", createValue(98)), - arguments("c += 2L", createValue(99L)), - arguments("c += 1.5f", createValue(98.5f)), - arguments("c += 3.14", createValue(100.14)), - arguments("c += 'a'", createValue(194))); + arguments("c += 1", createValue((char)98)), + arguments("c += 2L", createValue((char)99)), + arguments("c += 1.5f", createValue((char)98)), + arguments("c += 3.14", createValue((char)100)), + arguments("c += 'a'", createValue((char)194))); } protected static Stream roofEqualsExpression() { return Stream.of( - arguments("b ^= false", null), + arguments("b ^= false", createValue(true)), arguments("b ^= 1", null), arguments("b ^= 2L", null), arguments("b ^= 1.5f", null), @@ -467,7 +466,7 @@ protected static Stream roofEqualsExpression() { arguments("i ^= false", null), arguments("i ^= 3", createValue(2)), - arguments("i ^= 4L", createValue(5L)), + arguments("i ^= 4L", createValue(5)), arguments("i ^= 1.5f", null), arguments("i ^= 3.14", null), arguments("i ^= 'a'", createValue(96)), @@ -494,11 +493,11 @@ protected static Stream roofEqualsExpression() { arguments("d ^= 'a'", null), arguments("c ^= false", null), - arguments("c ^= 1", createValue(96)), - arguments("c ^= 2L", createValue(99L)), + arguments("c ^= 1", createValue((char)96)), + arguments("c ^= 2L", createValue((char)99)), arguments("c ^= 1.5f", null), arguments("c ^= 3.14", null), - arguments("c ^= 'a'", createValue(0))); + arguments("c ^= 'a'", createValue((char)0))); } protected static Stream slashEqualsExpression() { @@ -511,15 +510,15 @@ protected static Stream slashEqualsExpression() { arguments("b /= 'a'", null), arguments("i /= false", null), - arguments("i /= 0.25f", createValue(4.f)), - arguments("i /= 0.4", createValue(2.5)), + arguments("i /= 0.25f", createValue(4)), + arguments("i /= 0.4", createValue(2)), arguments("i /= 2", createValue(0)), - arguments("i /= 5L", createValue(0L)), + arguments("i /= 5L", createValue(0)), arguments("i /= 'A'", createValue(0)), arguments("l /= false", null), - arguments("l /= 1.25f", createValue(4.f)), - arguments("l /= 0.4", createValue(12.5)), + arguments("l /= 1.25f", createValue(4L)), + arguments("l /= 0.4", createValue(12L)), arguments("l /= 2", createValue(2L)), arguments("l /= 5L", createValue(1L)), arguments("l /= 'A'", createValue(0L)), @@ -528,7 +527,7 @@ protected static Stream slashEqualsExpression() { arguments("f /= 3", createValue(.5f)), arguments("f /= 2L", createValue(0.75f)), arguments("f /= 0.025f", createValue(60.f)), - arguments("f /= 2.5", createValue(.6)), + arguments("f /= 2.5", createValue(.6f)), arguments("f /= 'A'", createValue(0.0230769f)), arguments("d /= false", null), @@ -539,11 +538,11 @@ protected static Stream slashEqualsExpression() { arguments("d /= 'A'", createValue(0.048307692307)), arguments("c /= false", null), - arguments("c /= 1", createValue(97)), - arguments("c /= 97L", createValue(1L)), - arguments("c /= 0.25f", createValue(388.f)), - arguments("c /= 0.4", createValue(242.5)), - arguments("c /= 'A'", createValue(1))); + arguments("c /= 1", createValue((char)97)), + arguments("c /= 97L", createValue((char)1)), + arguments("c /= 0.25f", createValue((char)388)), + arguments("c /= 0.4", createValue((char)242)), + arguments("c /= 'A'", createValue((char)1))); } protected static Stream starEqualsExpression() { @@ -556,15 +555,15 @@ protected static Stream starEqualsExpression() { arguments("b *= 'a'", null), arguments("i *= false", null), - arguments("i *= 0.25f", createValue(0.25f)), - arguments("i *= 4.5", createValue(4.5)), + arguments("i *= 0.25f", createValue(0)), + arguments("i *= 4.5", createValue(4)), arguments("i *= 2", createValue(2)), - arguments("i *= 2L", createValue(2L)), + arguments("i *= 2L", createValue(2)), arguments("i *= 'A'", createValue(65)), arguments("l *= false", null), - arguments("l *= 0.5f", createValue(2.5f)), - arguments("l *= 0.2", createValue(1.)), + arguments("l *= 0.5f", createValue(2L)), + arguments("l *= 0.2", createValue(1L)), arguments("l *= 2", createValue(10L)), arguments("l *= 10L", createValue(50L)), arguments("l *= 'A'", createValue(325L)), @@ -573,7 +572,7 @@ protected static Stream starEqualsExpression() { arguments("f *= 3", createValue(4.5f)), arguments("f *= 2L", createValue(3f)), arguments("f *= 0.5f", createValue(.75f)), - arguments("f *= 0.5", createValue(.75)), + arguments("f *= 0.5", createValue(.75f)), arguments("f *= 'A'", createValue(97.5f)), arguments("d *= false", null), @@ -584,11 +583,11 @@ protected static Stream starEqualsExpression() { arguments("d *= 'A'", createValue(204.1)), arguments("c *= false", null), - arguments("c *= 2", createValue(194)), - arguments("c *= 2L", createValue(194L)), - arguments("c *= 0.25f", createValue(24.25f)), - arguments("c *= 0.5", createValue(48.5)), - arguments("c *= 'A'", createValue(6305))); + arguments("c *= 2", createValue((char)194)), + arguments("c *= 2L", createValue((char)194)), + arguments("c *= 0.25f", createValue((char)24)), + arguments("c *= 0.5", createValue((char)48)), + arguments("c *= 'A'", createValue((char)6305))); } @ParameterizedTest @@ -599,10 +598,10 @@ protected static Stream starEqualsExpression() { "percentEqualsExpression", "pipeEqualsExpression", "plusEqualsExpression", "roofEqualsExpression", "slashEqualsExpression", "starEqualsExpression" }) - public void testInterpreter(String expression, Value result) { + public void testInterpreter(String expression, MIValue result) { init(); if (result == null) { - assertThrows(Throwable.class, () -> testInvalidExpression(expression)); + testInvalidExpression(expression); } else { testValidExpression(expression, result); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java index 472a46412c..b2df595ff0 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java @@ -2,7 +2,7 @@ package de.monticore.expressions.commonexpressions._visitor; import de.monticore.expressions.AbstractInterpreterTest; -import de.monticore.interpreter.ValueFactory; +import de.monticore.interpreter.MIValueFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,61 +26,46 @@ public void testInterpretPlusExpression() { testInvalidExpression("1.5 + false"); testInvalidExpression("true + 'a'"); testInvalidExpression("'a' + false"); - testValidExpression("true + \"a\"", ValueFactory.createValue("truea")); - testValidExpression("\"a\" + false", ValueFactory.createValue("afalse")); - - testValidExpression("1 + 2", ValueFactory.createValue(3)); - testValidExpression("1L + 2", ValueFactory.createValue(3L)); - testValidExpression("1 + 2L", ValueFactory.createValue(3L)); - testValidExpression("1.5f + 2", ValueFactory.createValue(3.5f)); - testValidExpression("1 + 1.2f", ValueFactory.createValue(2.2f)); - testValidExpression("1.5 + 2", ValueFactory.createValue(3.5)); - testValidExpression("1 + 1.2", ValueFactory.createValue(2.2)); - testValidExpression("'a' + 2", ValueFactory.createValue(99)); - testValidExpression("1 + 'a'", ValueFactory.createValue(98)); - testValidExpression("\"a\" + 2", ValueFactory.createValue("a2")); - testValidExpression("1 + \"a\"", ValueFactory.createValue("1a")); - - testValidExpression("1L + 2L", ValueFactory.createValue(3L)); - testValidExpression("1.2f + 2L", ValueFactory.createValue(3.2f)); - testValidExpression("1L + 1.5f", ValueFactory.createValue(2.5f)); - testValidExpression("1L + 1.2", ValueFactory.createValue(2.2)); - testValidExpression("1.5 + 2L", ValueFactory.createValue(3.5)); - testValidExpression("1L + 'a'", ValueFactory.createValue(98L)); - testValidExpression("'a' + 2L", ValueFactory.createValue(99L)); - testValidExpression("1L + \"a\"", ValueFactory.createValue("1a")); - testValidExpression("\"a\" + 2L", ValueFactory.createValue("a2")); - - testValidExpression("1.2f + 1.5f", ValueFactory.createValue(2.7f)); - testValidExpression("1.2 + 1.5f", ValueFactory.createValue(2.7)); - testValidExpression("1.2f + 1.5", ValueFactory.createValue(2.7)); - testValidExpression("'a' + 1.5f", ValueFactory.createValue(98.5f)); - testValidExpression("1.2f + 'a'", ValueFactory.createValue(98.2f)); - testValidExpression("\"a\" + 1.5f", ValueFactory.createValue("a1.5")); - testValidExpression("1.2f + \"a\"", ValueFactory.createValue("1.2a")); - - testValidExpression("1.2 + 1.5", ValueFactory.createValue(2.7)); - testValidExpression("'a' + 1.5", ValueFactory.createValue(98.5)); - testValidExpression("1.2 + 'a'", ValueFactory.createValue(98.2)); - testValidExpression("\"a\" + 1.5", ValueFactory.createValue("a1.5")); - testValidExpression("1.2 + \"a\"", ValueFactory.createValue("1.2a")); - - testValidExpression("'a' + 'a'", ValueFactory.createValue(194)); - testValidExpression("\"a\" + 'b'", ValueFactory.createValue("ab")); - testValidExpression("'c' + \"a\"", ValueFactory.createValue("ca")); - - testValidExpression("\"a\" + \"b\"", ValueFactory.createValue("ab")); + + testValidExpression("1 + 2", MIValueFactory.createValue(3)); + testValidExpression("1L + 2", MIValueFactory.createValue(3L)); + testValidExpression("1 + 2L", MIValueFactory.createValue(3L)); + testValidExpression("1.5f + 2", MIValueFactory.createValue(3.5f)); + testValidExpression("1 + 1.2f", MIValueFactory.createValue(2.2f)); + testValidExpression("1.5 + 2", MIValueFactory.createValue(3.5)); + testValidExpression("1 + 1.2", MIValueFactory.createValue(2.2)); + testValidExpression("'a' + 2", MIValueFactory.createValue(99)); + testValidExpression("1 + 'a'", MIValueFactory.createValue(98)); + + testValidExpression("1L + 2L", MIValueFactory.createValue(3L)); + testValidExpression("1.2f + 2L", MIValueFactory.createValue(3.2f)); + testValidExpression("1L + 1.5f", MIValueFactory.createValue(2.5f)); + testValidExpression("1L + 1.2", MIValueFactory.createValue(2.2)); + testValidExpression("1.5 + 2L", MIValueFactory.createValue(3.5)); + testValidExpression("1L + 'a'", MIValueFactory.createValue(98L)); + testValidExpression("'a' + 2L", MIValueFactory.createValue(99L)); + + testValidExpression("1.2f + 1.5f", MIValueFactory.createValue(2.7f)); + testValidExpression("1.2 + 1.5f", MIValueFactory.createValue(2.7)); + testValidExpression("1.2f + 1.5", MIValueFactory.createValue(2.7)); + testValidExpression("'a' + 1.5f", MIValueFactory.createValue(98.5f)); + testValidExpression("1.2f + 'a'", MIValueFactory.createValue(98.2f)); + + testValidExpression("1.2 + 1.5", MIValueFactory.createValue(2.7)); + testValidExpression("'a' + 1.5", MIValueFactory.createValue(98.5)); + testValidExpression("1.2 + 'a'", MIValueFactory.createValue(98.2)); + + testValidExpression("'a' + 'a'", MIValueFactory.createValue(194)); } @Test public void testInterpretBracketExpression() { - testValidExpression("(true)", ValueFactory.createValue(true)); - testValidExpression("(1)", ValueFactory.createValue(1)); - testValidExpression("(2L)", ValueFactory.createValue(2L)); - testValidExpression("(2.5f)", ValueFactory.createValue(2.5f)); - testValidExpression("(3.14)", ValueFactory.createValue(3.14)); - testValidExpression("('a')", ValueFactory.createValue('a')); - testValidExpression("(\"abc\")", ValueFactory.createValue("abc")); + testValidExpression("(true)", MIValueFactory.createValue(true)); + testValidExpression("(1)", MIValueFactory.createValue(1)); + testValidExpression("(2L)", MIValueFactory.createValue(2L)); + testValidExpression("(2.5f)", MIValueFactory.createValue(2.5f)); + testValidExpression("(3.14)", MIValueFactory.createValue(3.14)); + testValidExpression("('a')", MIValueFactory.createValue('a')); } @Test @@ -96,50 +81,36 @@ public void testInterpretMinusExpression() { testInvalidExpression("1.5 - false"); testInvalidExpression("true - 'a'"); testInvalidExpression("'a' - false"); - testInvalidExpression("true - \"a\""); - testInvalidExpression("\"a\" - false"); - - testValidExpression("1 - 2", ValueFactory.createValue(-1)); - testValidExpression("1L - 2", ValueFactory.createValue(-1L)); - testValidExpression("1 - 2L", ValueFactory.createValue(-1L)); - testValidExpression("1.5f - 2", ValueFactory.createValue(-0.5f)); - testValidExpression("1 - 1.2f", ValueFactory.createValue(-0.2f)); - testValidExpression("1.5 - 2", ValueFactory.createValue(-0.5)); - testValidExpression("1 - 1.2", ValueFactory.createValue(-0.2)); - testValidExpression("'a' - 2", ValueFactory.createValue(95)); - testValidExpression("1 - 'a'", ValueFactory.createValue(-96)); - testInvalidExpression("\"a\" - 2"); - testInvalidExpression("1 - \"a\""); - - testValidExpression("1L - 2L", ValueFactory.createValue(-1L)); - testValidExpression("1.2f - 2L", ValueFactory.createValue(-0.8f)); - testValidExpression("1L - 1.5f", ValueFactory.createValue(-0.5f)); - testValidExpression("1L - 1.2", ValueFactory.createValue(-0.2)); - testValidExpression("1.5 - 2L", ValueFactory.createValue(-0.5)); - testValidExpression("1L - 'a'", ValueFactory.createValue(-96L)); - testValidExpression("'a' - 2L", ValueFactory.createValue(95L)); - testInvalidExpression("1L - \"a\""); - testInvalidExpression("\"a\" - 2L"); - - testValidExpression("1.2f - 1.5f", ValueFactory.createValue(-0.3f)); - testValidExpression("1.2 - 1.5f", ValueFactory.createValue(-0.3)); - testValidExpression("1.2f - 1.5", ValueFactory.createValue(-0.3)); - testValidExpression("'a' - 1.5f", ValueFactory.createValue(95.5f)); - testValidExpression("1.2f - 'a'", ValueFactory.createValue(-95.8f)); - testInvalidExpression("\"a\" - 1.5f"); - testInvalidExpression("1.2f - \"a\""); - - testValidExpression("1.2 - 1.5", ValueFactory.createValue(-0.3)); - testValidExpression("'a' - 1.5", ValueFactory.createValue(95.5)); - testValidExpression("1.2 - 'a'", ValueFactory.createValue(-95.8)); - testInvalidExpression("\"a\" - 1.5"); - testInvalidExpression("1.2 - \"a\""); - - testValidExpression("'a' - 'a'", ValueFactory.createValue(0)); - testInvalidExpression("\"a\" - 'a'"); - testInvalidExpression("'a' - \"a\""); - - testInvalidExpression("\"a\" - \"a\""); + + testValidExpression("1 - 2", MIValueFactory.createValue(-1)); + testValidExpression("1L - 2", MIValueFactory.createValue(-1L)); + testValidExpression("1 - 2L", MIValueFactory.createValue(-1L)); + testValidExpression("1.5f - 2", MIValueFactory.createValue(-0.5f)); + testValidExpression("1 - 1.2f", MIValueFactory.createValue(-0.2f)); + testValidExpression("1.5 - 2", MIValueFactory.createValue(-0.5)); + testValidExpression("1 - 1.2", MIValueFactory.createValue(-0.2)); + testValidExpression("'a' - 2", MIValueFactory.createValue(95)); + testValidExpression("1 - 'a'", MIValueFactory.createValue(-96)); + + testValidExpression("1L - 2L", MIValueFactory.createValue(-1L)); + testValidExpression("1.2f - 2L", MIValueFactory.createValue(-0.8f)); + testValidExpression("1L - 1.5f", MIValueFactory.createValue(-0.5f)); + testValidExpression("1L - 1.2", MIValueFactory.createValue(-0.2)); + testValidExpression("1.5 - 2L", MIValueFactory.createValue(-0.5)); + testValidExpression("1L - 'a'", MIValueFactory.createValue(-96L)); + testValidExpression("'a' - 2L", MIValueFactory.createValue(95L)); + + testValidExpression("1.2f - 1.5f", MIValueFactory.createValue(-0.3f)); + testValidExpression("1.2 - 1.5f", MIValueFactory.createValue(-0.3)); + testValidExpression("1.2f - 1.5", MIValueFactory.createValue(-0.3)); + testValidExpression("'a' - 1.5f", MIValueFactory.createValue(95.5f)); + testValidExpression("1.2f - 'a'", MIValueFactory.createValue(-95.8f)); + + testValidExpression("1.2 - 1.5", MIValueFactory.createValue(-0.3)); + testValidExpression("'a' - 1.5", MIValueFactory.createValue(95.5)); + testValidExpression("1.2 - 'a'", MIValueFactory.createValue(-95.8)); + + testValidExpression("'a' - 'a'", MIValueFactory.createValue(0)); } @Test @@ -155,50 +126,36 @@ public void testInterpretMultExpression() { testInvalidExpression("1.5 * false"); testInvalidExpression("true * 'a'"); testInvalidExpression("'a' * false"); - testInvalidExpression("true * \"a\""); - testInvalidExpression("\"a\" * false"); - - testValidExpression("1 * 2", ValueFactory.createValue(2)); - testValidExpression("1L * 2", ValueFactory.createValue(2L)); - testValidExpression("1 * 2L", ValueFactory.createValue(2L)); - testValidExpression("1.5f * 2", ValueFactory.createValue(3.f)); - testValidExpression("1 * 1.2f", ValueFactory.createValue(1.2f)); - testValidExpression("1.5 * 2", ValueFactory.createValue(3.)); - testValidExpression("1 * 1.2", ValueFactory.createValue(1.2)); - testValidExpression("'a' * 2", ValueFactory.createValue(194)); - testValidExpression("1 * 'a'", ValueFactory.createValue(97)); - testInvalidExpression("\"a\" * 2"); - testInvalidExpression("1 * \"a\""); - - testValidExpression("1L * 2L", ValueFactory.createValue(2L)); - testValidExpression("1.2f * 2L", ValueFactory.createValue(2.4f)); - testValidExpression("1L * 1.5f", ValueFactory.createValue(1.5f)); - testValidExpression("1L * 1.2", ValueFactory.createValue(1.2)); - testValidExpression("1.5 * 2L", ValueFactory.createValue(3.0)); - testValidExpression("1L * 'a'", ValueFactory.createValue(97L)); - testValidExpression("'a' * 2L", ValueFactory.createValue(194L)); - testInvalidExpression("1L * \"a\""); - testInvalidExpression("\"a\" * 2L"); - - testValidExpression("1.2f * 1.5f", ValueFactory.createValue(1.8f)); - testValidExpression("1.2 * 1.5f", ValueFactory.createValue(1.8)); - testValidExpression("1.2f * 1.5", ValueFactory.createValue(1.8)); - testValidExpression("'a' * 1.5f", ValueFactory.createValue(145.5f)); - testValidExpression("1.2f * 'a'", ValueFactory.createValue(116.4f)); - testInvalidExpression("\"a\" * 1.5f"); - testInvalidExpression("1.2f * \"a\""); - - testValidExpression("1.2 * 1.5", ValueFactory.createValue(1.8)); - testValidExpression("'a' * 1.5", ValueFactory.createValue(145.5)); - testValidExpression("1.2 * 'a'", ValueFactory.createValue(116.4)); - testInvalidExpression("\"a\" * 1.5"); - testInvalidExpression("1.2 * \"a\""); - - testValidExpression("'a' * 'a'", ValueFactory.createValue(9409)); - testInvalidExpression("\"a\" * 'a'"); - testInvalidExpression("'a' * \"a\""); - - testInvalidExpression("\"a\" * \"a\""); + + testValidExpression("1 * 2", MIValueFactory.createValue(2)); + testValidExpression("1L * 2", MIValueFactory.createValue(2L)); + testValidExpression("1 * 2L", MIValueFactory.createValue(2L)); + testValidExpression("1.5f * 2", MIValueFactory.createValue(3.f)); + testValidExpression("1 * 1.2f", MIValueFactory.createValue(1.2f)); + testValidExpression("1.5 * 2", MIValueFactory.createValue(3.)); + testValidExpression("1 * 1.2", MIValueFactory.createValue(1.2)); + testValidExpression("'a' * 2", MIValueFactory.createValue(194)); + testValidExpression("1 * 'a'", MIValueFactory.createValue(97)); + + testValidExpression("1L * 2L", MIValueFactory.createValue(2L)); + testValidExpression("1.2f * 2L", MIValueFactory.createValue(2.4f)); + testValidExpression("1L * 1.5f", MIValueFactory.createValue(1.5f)); + testValidExpression("1L * 1.2", MIValueFactory.createValue(1.2)); + testValidExpression("1.5 * 2L", MIValueFactory.createValue(3.0)); + testValidExpression("1L * 'a'", MIValueFactory.createValue(97L)); + testValidExpression("'a' * 2L", MIValueFactory.createValue(194L)); + + testValidExpression("1.2f * 1.5f", MIValueFactory.createValue(1.8f)); + testValidExpression("1.2 * 1.5f", MIValueFactory.createValue(1.8)); + testValidExpression("1.2f * 1.5", MIValueFactory.createValue(1.8)); + testValidExpression("'a' * 1.5f", MIValueFactory.createValue(145.5f)); + testValidExpression("1.2f * 'a'", MIValueFactory.createValue(116.4f)); + + testValidExpression("1.2 * 1.5", MIValueFactory.createValue(1.8)); + testValidExpression("'a' * 1.5", MIValueFactory.createValue(145.5)); + testValidExpression("1.2 * 'a'", MIValueFactory.createValue(116.4)); + + testValidExpression("'a' * 'a'", MIValueFactory.createValue(9409)); } @Test @@ -214,50 +171,36 @@ public void testInterpretDivideExpression() { testInvalidExpression("1.5 / false"); testInvalidExpression("true / 'a'"); testInvalidExpression("'a' / false"); - testInvalidExpression("true / \"a\""); - testInvalidExpression("\"a\" / false"); - - testValidExpression("1 / 2", ValueFactory.createValue(0)); - testValidExpression("1L / 2", ValueFactory.createValue(0L)); - testValidExpression("1 / 2L", ValueFactory.createValue(0L)); - testValidExpression("1.5f / 2", ValueFactory.createValue(0.75f)); - testValidExpression("3 / 1.5f", ValueFactory.createValue(2.f)); - testValidExpression("1.5 / 2", ValueFactory.createValue(0.75)); - testValidExpression("3 / 1.5", ValueFactory.createValue(2.)); - testValidExpression("'a' / 2", ValueFactory.createValue(48)); - testValidExpression("1 / 'a'", ValueFactory.createValue(0)); - testInvalidExpression("\"a\" / 2"); - testInvalidExpression("1 / \"a\""); - - testValidExpression("1L / 2L", ValueFactory.createValue(0L)); - testValidExpression("1.2f / 2L", ValueFactory.createValue(0.6f)); - testValidExpression("3L / 1.5f", ValueFactory.createValue(2.f)); - testValidExpression("3L / 1.5", ValueFactory.createValue(2.)); - testValidExpression("3.0 / 2L", ValueFactory.createValue(1.5)); - testValidExpression("1L / 'a'", ValueFactory.createValue(0L)); - testValidExpression("'a' / 2L", ValueFactory.createValue(48L)); - testInvalidExpression("1L / \"a\""); - testInvalidExpression("\"a\" / 2L"); - - testValidExpression("1.2f / 1.5f", ValueFactory.createValue(0.8f)); - testValidExpression("1.2 / 1.5f", ValueFactory.createValue(0.8)); - testValidExpression("1.2f / 1.5", ValueFactory.createValue(0.8)); - testValidExpression("'a' / 0.5f", ValueFactory.createValue(194.f)); - testValidExpression("194.0f / 'a'", ValueFactory.createValue(2.f)); - testInvalidExpression("\"a\" / 1.5f"); - testInvalidExpression("1.2f / \"a\""); - - testValidExpression("1.2 / 1.5", ValueFactory.createValue(0.8)); - testValidExpression("'a' / 2.0", ValueFactory.createValue(48.5)); - testValidExpression("97.0 / 'a'", ValueFactory.createValue(1.)); - testInvalidExpression("\"a\" / 1.5"); - testInvalidExpression("1.2 / \"a\""); - - testValidExpression("'a' / 'a'", ValueFactory.createValue(1)); - testInvalidExpression("\"a\" / 'a'"); - testInvalidExpression("'a' / \"a\""); - - testInvalidExpression("\"a\" / \"a\""); + + testValidExpression("1 / 2", MIValueFactory.createValue(0)); + testValidExpression("1L / 2", MIValueFactory.createValue(0L)); + testValidExpression("1 / 2L", MIValueFactory.createValue(0L)); + testValidExpression("1.5f / 2", MIValueFactory.createValue(0.75f)); + testValidExpression("3 / 1.5f", MIValueFactory.createValue(2.f)); + testValidExpression("1.5 / 2", MIValueFactory.createValue(0.75)); + testValidExpression("3 / 1.5", MIValueFactory.createValue(2.)); + testValidExpression("'a' / 2", MIValueFactory.createValue(48)); + testValidExpression("1 / 'a'", MIValueFactory.createValue(0)); + + testValidExpression("1L / 2L", MIValueFactory.createValue(0L)); + testValidExpression("1.2f / 2L", MIValueFactory.createValue(0.6f)); + testValidExpression("3L / 1.5f", MIValueFactory.createValue(2.f)); + testValidExpression("3L / 1.5", MIValueFactory.createValue(2.)); + testValidExpression("3.0 / 2L", MIValueFactory.createValue(1.5)); + testValidExpression("1L / 'a'", MIValueFactory.createValue(0L)); + testValidExpression("'a' / 2L", MIValueFactory.createValue(48L)); + + testValidExpression("1.2f / 1.5f", MIValueFactory.createValue(0.8f)); + testValidExpression("1.2 / 1.5f", MIValueFactory.createValue(0.8)); + testValidExpression("1.2f / 1.5", MIValueFactory.createValue(0.8)); + testValidExpression("'a' / 0.5f", MIValueFactory.createValue(194.f)); + testValidExpression("194.0f / 'a'", MIValueFactory.createValue(2.f)); + + testValidExpression("1.2 / 1.5", MIValueFactory.createValue(0.8)); + testValidExpression("'a' / 2.0", MIValueFactory.createValue(48.5)); + testValidExpression("97.0 / 'a'", MIValueFactory.createValue(1.)); + + testValidExpression("'a' / 'a'", MIValueFactory.createValue(1)); testInvalidExpression("1 / 0"); testInvalidExpression("'a' / 0"); @@ -280,55 +223,41 @@ public void testInterpretModuloExpression() { testInvalidExpression("1.5 % false"); testInvalidExpression("true % 'a'"); testInvalidExpression("'a' % false"); - testInvalidExpression("true % \"a\""); - testInvalidExpression("\"a\" % false"); - - testValidExpression("1 % 2", ValueFactory.createValue(1)); - testValidExpression("1L % 2", ValueFactory.createValue(1L)); - testValidExpression("1 % 2L", ValueFactory.createValue(1L)); - testValidExpression("1.5f % 2", ValueFactory.createValue(1.5f)); - testValidExpression("1 % 1.2f", ValueFactory.createValue(1.0f)); - testValidExpression("1.5 % 2", ValueFactory.createValue(1.5)); - testValidExpression("1 % 1.2", ValueFactory.createValue(1.0)); - testValidExpression("'a' % 2", ValueFactory.createValue(1)); - testValidExpression("1 % 'a'", ValueFactory.createValue(1)); - testInvalidExpression("\"a\" % 2"); - testInvalidExpression("1 % \"a\""); - - testValidExpression("1L % 2L", ValueFactory.createValue(1L)); - testValidExpression("1.2f % 2L", ValueFactory.createValue(1.2f)); - testValidExpression("1L % 1.5f", ValueFactory.createValue(1.0f)); - testValidExpression("1L % 1.2", ValueFactory.createValue(1.0)); - testValidExpression("1.5 % 2L", ValueFactory.createValue(1.5)); - testValidExpression("1L % 'a'", ValueFactory.createValue(1L)); - testValidExpression("'a' % 2L", ValueFactory.createValue(1L)); - testInvalidExpression("1L % \"a\""); - testInvalidExpression("\"a\" % 2L"); - - testValidExpression("1.2f % 1.5f", ValueFactory.createValue(1.2f)); - testValidExpression("1.2 % 1.5f", ValueFactory.createValue(1.2)); - testValidExpression("1.2f % 1.5", ValueFactory.createValue(1.2)); - testValidExpression("'a' % 1.5f", ValueFactory.createValue(1.0f)); - testValidExpression("1.2f % 'a'", ValueFactory.createValue(1.2f)); - testInvalidExpression("\"a\" % 1.5f"); - testInvalidExpression("1.2f % \"a\""); - - testValidExpression("1.2 % 1.5", ValueFactory.createValue(1.2)); - testValidExpression("'a' % 1.5", ValueFactory.createValue(1.0)); - testValidExpression("1.2 % 'a'", ValueFactory.createValue(1.2)); - testInvalidExpression("\"a\" % 1.5"); - testInvalidExpression("1.2 % \"a\""); - - testValidExpression("'a' % 'a'", ValueFactory.createValue(0)); - testInvalidExpression("\"a\" % 'a'"); - testInvalidExpression("'a' % \"a\""); - - testInvalidExpression("\"a\" % \"a\""); + + testValidExpression("1 % 2", MIValueFactory.createValue(1)); + testValidExpression("1L % 2", MIValueFactory.createValue(1L)); + testValidExpression("1 % 2L", MIValueFactory.createValue(1L)); + testValidExpression("1.5f % 2", MIValueFactory.createValue(1.5f)); + testValidExpression("1 % 1.2f", MIValueFactory.createValue(1.0f)); + testValidExpression("1.5 % 2", MIValueFactory.createValue(1.5)); + testValidExpression("1 % 1.2", MIValueFactory.createValue(1.0)); + testValidExpression("'a' % 2", MIValueFactory.createValue(1)); + testValidExpression("1 % 'a'", MIValueFactory.createValue(1)); + + testValidExpression("1L % 2L", MIValueFactory.createValue(1L)); + testValidExpression("1.2f % 2L", MIValueFactory.createValue(1.2f)); + testValidExpression("1L % 1.5f", MIValueFactory.createValue(1.0f)); + testValidExpression("1L % 1.2", MIValueFactory.createValue(1.0)); + testValidExpression("1.5 % 2L", MIValueFactory.createValue(1.5)); + testValidExpression("1L % 'a'", MIValueFactory.createValue(1L)); + testValidExpression("'a' % 2L", MIValueFactory.createValue(1L)); + + testValidExpression("1.2f % 1.5f", MIValueFactory.createValue(1.2f)); + testValidExpression("1.2 % 1.5f", MIValueFactory.createValue(1.2)); + testValidExpression("1.2f % 1.5", MIValueFactory.createValue(1.2)); + testValidExpression("'a' % 1.5f", MIValueFactory.createValue(1.0f)); + testValidExpression("1.2f % 'a'", MIValueFactory.createValue(1.2f)); + + testValidExpression("1.2 % 1.5", MIValueFactory.createValue(1.2)); + testValidExpression("'a' % 1.5", MIValueFactory.createValue(1.0)); + testValidExpression("1.2 % 'a'", MIValueFactory.createValue(1.2)); + + testValidExpression("'a' % 'a'", MIValueFactory.createValue(0)); } @Test public void testInterpretEqualsExpression() { - testValidExpression("true == false", ValueFactory.createValue(false)); + testValidExpression("true == false", MIValueFactory.createValue(false)); testInvalidExpression("true == 1"); testInvalidExpression("1 == false"); testInvalidExpression("true == 1L"); @@ -339,55 +268,41 @@ public void testInterpretEqualsExpression() { testInvalidExpression("1.5 == false"); testInvalidExpression("true == 'a'"); testInvalidExpression("'a' == false"); - testInvalidExpression("true == \"a\""); - testInvalidExpression("\"a\" == false"); - - testValidExpression("1 == 2", ValueFactory.createValue(false)); - testValidExpression("1L == 2", ValueFactory.createValue(false)); - testValidExpression("1 == 2L", ValueFactory.createValue(false)); - testValidExpression("1.5f == 2", ValueFactory.createValue(false)); - testValidExpression("1 == 1.2f", ValueFactory.createValue(false)); - testValidExpression("1.5 == 2", ValueFactory.createValue(false)); - testValidExpression("1 == 1.2", ValueFactory.createValue(false)); - testValidExpression("'a' == 2", ValueFactory.createValue(false)); - testValidExpression("1 == 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" == 2"); - testInvalidExpression("1 == \"a\""); - - testValidExpression("1L == 2L", ValueFactory.createValue(false)); - testValidExpression("1.2f == 2L", ValueFactory.createValue(false)); - testValidExpression("1L == 1.5f", ValueFactory.createValue(false)); - testValidExpression("1L == 1.2", ValueFactory.createValue(false)); - testValidExpression("1.5 == 2L", ValueFactory.createValue(false)); - testValidExpression("1L == 'a'", ValueFactory.createValue(false)); - testValidExpression("'a' == 2L", ValueFactory.createValue(false)); - testInvalidExpression("1L == \"a\""); - testInvalidExpression("\"a\" == 2L"); - - testValidExpression("1.2f == 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2 == 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2f == 1.5", ValueFactory.createValue(false)); - testValidExpression("'a' == 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2f == 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" == 1.5f"); - testInvalidExpression("1.2f == \"a\""); - - testValidExpression("1.2 == 1.5", ValueFactory.createValue(false)); - testValidExpression("'a' == 1.5", ValueFactory.createValue(false)); - testValidExpression("1.2 == 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" == 1.5"); - testInvalidExpression("1.2 == \"a\""); - - testValidExpression("'a' == 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" == 'a'"); - testInvalidExpression("'a' == \"a\""); - - testInvalidExpression("\"a\" == \"a\""); + + testValidExpression("1 == 2", MIValueFactory.createValue(false)); + testValidExpression("1L == 2", MIValueFactory.createValue(false)); + testValidExpression("1 == 2L", MIValueFactory.createValue(false)); + testValidExpression("1.5f == 2", MIValueFactory.createValue(false)); + testValidExpression("1 == 1.2f", MIValueFactory.createValue(false)); + testValidExpression("1.5 == 2", MIValueFactory.createValue(false)); + testValidExpression("1 == 1.2", MIValueFactory.createValue(false)); + testValidExpression("'a' == 2", MIValueFactory.createValue(false)); + testValidExpression("1 == 'a'", MIValueFactory.createValue(false)); + + testValidExpression("1L == 2L", MIValueFactory.createValue(false)); + testValidExpression("1.2f == 2L", MIValueFactory.createValue(false)); + testValidExpression("1L == 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1L == 1.2", MIValueFactory.createValue(false)); + testValidExpression("1.5 == 2L", MIValueFactory.createValue(false)); + testValidExpression("1L == 'a'", MIValueFactory.createValue(false)); + testValidExpression("'a' == 2L", MIValueFactory.createValue(false)); + + testValidExpression("1.2f == 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2 == 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2f == 1.5", MIValueFactory.createValue(false)); + testValidExpression("'a' == 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2f == 'a'", MIValueFactory.createValue(false)); + + testValidExpression("1.2 == 1.5", MIValueFactory.createValue(false)); + testValidExpression("'a' == 1.5", MIValueFactory.createValue(false)); + testValidExpression("1.2 == 'a'", MIValueFactory.createValue(false)); + + testValidExpression("'a' == 'a'", MIValueFactory.createValue(true)); } @Test public void testInterpretNotEqualsExpression() { - testValidExpression("true != false", ValueFactory.createValue(true)); + testValidExpression("true != false", MIValueFactory.createValue(true)); testInvalidExpression("true != 1"); testInvalidExpression("1 != false"); testInvalidExpression("true != 1L"); @@ -398,50 +313,36 @@ public void testInterpretNotEqualsExpression() { testInvalidExpression("1.5 != false"); testInvalidExpression("true != 'a'"); testInvalidExpression("'a' != false"); - testInvalidExpression("true != \"a\""); - testInvalidExpression("\"a\" != false"); - - testValidExpression("1 != 2", ValueFactory.createValue(true)); - testValidExpression("1L != 2", ValueFactory.createValue(true)); - testValidExpression("1 != 2L", ValueFactory.createValue(true)); - testValidExpression("1.5f != 2", ValueFactory.createValue(true)); - testValidExpression("1 != 1.2f", ValueFactory.createValue(true)); - testValidExpression("1.5 != 2", ValueFactory.createValue(true)); - testValidExpression("1 != 1.2", ValueFactory.createValue(true)); - testValidExpression("'a' != 2", ValueFactory.createValue(true)); - testValidExpression("1 != 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" != 2"); - testInvalidExpression("1 != \"a\""); - - testValidExpression("1L != 2L", ValueFactory.createValue(true)); - testValidExpression("1.2f != 2L", ValueFactory.createValue(true)); - testValidExpression("1L != 1.5f", ValueFactory.createValue(true)); - testValidExpression("1L != 1.2", ValueFactory.createValue(true)); - testValidExpression("1.5 != 2L", ValueFactory.createValue(true)); - testValidExpression("1L != 'a'", ValueFactory.createValue(true)); - testValidExpression("'a' != 2L", ValueFactory.createValue(true)); - testInvalidExpression("1L != \"a\""); - testInvalidExpression("\"a\" != 2L"); - - testValidExpression("1.2f != 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2 != 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2f != 1.5", ValueFactory.createValue(true)); - testValidExpression("'a' != 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2f != 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" != 1.5f"); - testInvalidExpression("1.2f != \"a\""); - - testValidExpression("1.2 != 1.5", ValueFactory.createValue(true)); - testValidExpression("'a' != 1.5", ValueFactory.createValue(true)); - testValidExpression("1.2 != 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" != 1.5"); - testInvalidExpression("1.2 != \"a\""); - - testValidExpression("'a' != 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" != 'a'"); - testInvalidExpression("'a' != \"a\""); - - testInvalidExpression("\"a\" != \"a\""); + + testValidExpression("1 != 2", MIValueFactory.createValue(true)); + testValidExpression("1L != 2", MIValueFactory.createValue(true)); + testValidExpression("1 != 2L", MIValueFactory.createValue(true)); + testValidExpression("1.5f != 2", MIValueFactory.createValue(true)); + testValidExpression("1 != 1.2f", MIValueFactory.createValue(true)); + testValidExpression("1.5 != 2", MIValueFactory.createValue(true)); + testValidExpression("1 != 1.2", MIValueFactory.createValue(true)); + testValidExpression("'a' != 2", MIValueFactory.createValue(true)); + testValidExpression("1 != 'a'", MIValueFactory.createValue(true)); + + testValidExpression("1L != 2L", MIValueFactory.createValue(true)); + testValidExpression("1.2f != 2L", MIValueFactory.createValue(true)); + testValidExpression("1L != 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1L != 1.2", MIValueFactory.createValue(true)); + testValidExpression("1.5 != 2L", MIValueFactory.createValue(true)); + testValidExpression("1L != 'a'", MIValueFactory.createValue(true)); + testValidExpression("'a' != 2L", MIValueFactory.createValue(true)); + + testValidExpression("1.2f != 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2 != 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2f != 1.5", MIValueFactory.createValue(true)); + testValidExpression("'a' != 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2f != 'a'", MIValueFactory.createValue(true)); + + testValidExpression("1.2 != 1.5", MIValueFactory.createValue(true)); + testValidExpression("'a' != 1.5", MIValueFactory.createValue(true)); + testValidExpression("1.2 != 'a'", MIValueFactory.createValue(true)); + + testValidExpression("'a' != 'a'", MIValueFactory.createValue(false)); } @Test @@ -457,50 +358,36 @@ public void testInterpretLessThanExpression() { testInvalidExpression("1.5 < false"); testInvalidExpression("true < 'a'"); testInvalidExpression("'a' < false"); - testInvalidExpression("true < \"a\""); - testInvalidExpression("\"a\" < false"); - - testValidExpression("1 < 2", ValueFactory.createValue(true)); - testValidExpression("1L < 2", ValueFactory.createValue(true)); - testValidExpression("1 < 2L", ValueFactory.createValue(true)); - testValidExpression("1.5f < 2", ValueFactory.createValue(true)); - testValidExpression("1 < 1.2f", ValueFactory.createValue(true)); - testValidExpression("1.5 < 2", ValueFactory.createValue(true)); - testValidExpression("1 < 1.2", ValueFactory.createValue(true)); - testValidExpression("'a' < 2", ValueFactory.createValue(false)); - testValidExpression("1 < 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" < 2"); - testInvalidExpression("1 < \"a\""); - - testValidExpression("1L < 2L", ValueFactory.createValue(true)); - testValidExpression("1.2f < 2L", ValueFactory.createValue(true)); - testValidExpression("1L < 1.5f", ValueFactory.createValue(true)); - testValidExpression("1L < 1.2", ValueFactory.createValue(true)); - testValidExpression("1.5 < 2L", ValueFactory.createValue(true)); - testValidExpression("1L < 'a'", ValueFactory.createValue(true)); - testValidExpression("'a' < 2L", ValueFactory.createValue(false)); - testInvalidExpression("1L < \"a\""); - testInvalidExpression("\"a\" < 2L"); - - testValidExpression("1.2f < 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2 < 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2f < 1.5", ValueFactory.createValue(true)); - testValidExpression("'a' < 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2f < 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" < 1.5f"); - testInvalidExpression("1.2f < \"a\""); - - testValidExpression("1.2 < 1.5", ValueFactory.createValue(true)); - testValidExpression("'a' < 1.5", ValueFactory.createValue(false)); - testValidExpression("1.2 < 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" < 1.5"); - testInvalidExpression("1.2 < \"a\""); - - testValidExpression("'a' < 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" < 'a'"); - testInvalidExpression("'a' < \"a\""); - - testInvalidExpression("\"a\" < \"a\""); + + testValidExpression("1 < 2", MIValueFactory.createValue(true)); + testValidExpression("1L < 2", MIValueFactory.createValue(true)); + testValidExpression("1 < 2L", MIValueFactory.createValue(true)); + testValidExpression("1.5f < 2", MIValueFactory.createValue(true)); + testValidExpression("1 < 1.2f", MIValueFactory.createValue(true)); + testValidExpression("1.5 < 2", MIValueFactory.createValue(true)); + testValidExpression("1 < 1.2", MIValueFactory.createValue(true)); + testValidExpression("'a' < 2", MIValueFactory.createValue(false)); + testValidExpression("1 < 'a'", MIValueFactory.createValue(true)); + + testValidExpression("1L < 2L", MIValueFactory.createValue(true)); + testValidExpression("1.2f < 2L", MIValueFactory.createValue(true)); + testValidExpression("1L < 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1L < 1.2", MIValueFactory.createValue(true)); + testValidExpression("1.5 < 2L", MIValueFactory.createValue(true)); + testValidExpression("1L < 'a'", MIValueFactory.createValue(true)); + testValidExpression("'a' < 2L", MIValueFactory.createValue(false)); + + testValidExpression("1.2f < 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2 < 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2f < 1.5", MIValueFactory.createValue(true)); + testValidExpression("'a' < 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2f < 'a'", MIValueFactory.createValue(true)); + + testValidExpression("1.2 < 1.5", MIValueFactory.createValue(true)); + testValidExpression("'a' < 1.5", MIValueFactory.createValue(false)); + testValidExpression("1.2 < 'a'", MIValueFactory.createValue(true)); + + testValidExpression("'a' < 'a'", MIValueFactory.createValue(false)); } @Test @@ -516,50 +403,36 @@ public void testInterpretGreaterThanExpression() { testInvalidExpression("1.5 > false"); testInvalidExpression("true > 'a'"); testInvalidExpression("'a' > false"); - testInvalidExpression("true > \"a\""); - testInvalidExpression("\"a\" > false"); - - testValidExpression("1 > 2", ValueFactory.createValue(false)); - testValidExpression("1L > 2", ValueFactory.createValue(false)); - testValidExpression("1 > 2L", ValueFactory.createValue(false)); - testValidExpression("1.5f > 2", ValueFactory.createValue(false)); - testValidExpression("1 > 1.2f", ValueFactory.createValue(false)); - testValidExpression("1.5 > 2", ValueFactory.createValue(false)); - testValidExpression("1 > 1.2", ValueFactory.createValue(false)); - testValidExpression("'a' > 2", ValueFactory.createValue(true)); - testValidExpression("1 > 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" > 2"); - testInvalidExpression("1 > \"a\""); - - testValidExpression("1L > 2L", ValueFactory.createValue(false)); - testValidExpression("1.2f > 2L", ValueFactory.createValue(false)); - testValidExpression("1L > 1.5f", ValueFactory.createValue(false)); - testValidExpression("1L > 1.2", ValueFactory.createValue(false)); - testValidExpression("1.5 > 2L", ValueFactory.createValue(false)); - testValidExpression("1L > 'a'", ValueFactory.createValue(false)); - testValidExpression("'a' > 2L", ValueFactory.createValue(true)); - testInvalidExpression("1L > \"a\""); - testInvalidExpression("\"a\" > 2L"); - - testValidExpression("1.2f > 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2 > 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2f > 1.5", ValueFactory.createValue(false)); - testValidExpression("'a' > 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2f > 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" > 1.5f"); - testInvalidExpression("1.2f > \"a\""); - - testValidExpression("1.2 > 1.5", ValueFactory.createValue(false)); - testValidExpression("'a' > 1.5", ValueFactory.createValue(true)); - testValidExpression("1.2 > 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" > 1.5"); - testInvalidExpression("1.2 > \"a\""); - - testValidExpression("'a' > 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" > 'a'"); - testInvalidExpression("'a' > \"a\""); - - testInvalidExpression("\"a\" > \"a\""); + + testValidExpression("1 > 2", MIValueFactory.createValue(false)); + testValidExpression("1L > 2", MIValueFactory.createValue(false)); + testValidExpression("1 > 2L", MIValueFactory.createValue(false)); + testValidExpression("1.5f > 2", MIValueFactory.createValue(false)); + testValidExpression("1 > 1.2f", MIValueFactory.createValue(false)); + testValidExpression("1.5 > 2", MIValueFactory.createValue(false)); + testValidExpression("1 > 1.2", MIValueFactory.createValue(false)); + testValidExpression("'a' > 2", MIValueFactory.createValue(true)); + testValidExpression("1 > 'a'", MIValueFactory.createValue(false)); + + testValidExpression("1L > 2L", MIValueFactory.createValue(false)); + testValidExpression("1.2f > 2L", MIValueFactory.createValue(false)); + testValidExpression("1L > 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1L > 1.2", MIValueFactory.createValue(false)); + testValidExpression("1.5 > 2L", MIValueFactory.createValue(false)); + testValidExpression("1L > 'a'", MIValueFactory.createValue(false)); + testValidExpression("'a' > 2L", MIValueFactory.createValue(true)); + + testValidExpression("1.2f > 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2 > 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2f > 1.5", MIValueFactory.createValue(false)); + testValidExpression("'a' > 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2f > 'a'", MIValueFactory.createValue(false)); + + testValidExpression("1.2 > 1.5", MIValueFactory.createValue(false)); + testValidExpression("'a' > 1.5", MIValueFactory.createValue(true)); + testValidExpression("1.2 > 'a'", MIValueFactory.createValue(false)); + + testValidExpression("'a' > 'a'", MIValueFactory.createValue(false)); } @Test @@ -575,50 +448,36 @@ public void testInterpretGreaterEqualExpression() { testInvalidExpression("1.5 >= false"); testInvalidExpression("true >= 'a'"); testInvalidExpression("'a' >= false"); - testInvalidExpression("true >= \"a\""); - testInvalidExpression("\"a\" >= false"); - - testValidExpression("1 >= 2", ValueFactory.createValue(false)); - testValidExpression("1L >= 2", ValueFactory.createValue(false)); - testValidExpression("1 >= 2L", ValueFactory.createValue(false)); - testValidExpression("1.5f >= 2", ValueFactory.createValue(false)); - testValidExpression("1 >= 1.2f", ValueFactory.createValue(false)); - testValidExpression("1.5 >= 2", ValueFactory.createValue(false)); - testValidExpression("1 >= 1.2", ValueFactory.createValue(false)); - testValidExpression("'a' >= 2", ValueFactory.createValue(true)); - testValidExpression("1 >= 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" >= 2"); - testInvalidExpression("1 >= \"a\""); - - testValidExpression("1L >= 2L", ValueFactory.createValue(false)); - testValidExpression("1.2f >= 2L", ValueFactory.createValue(false)); - testValidExpression("1L >= 1.5f", ValueFactory.createValue(false)); - testValidExpression("1L >= 1.2", ValueFactory.createValue(false)); - testValidExpression("1.5 >= 2L", ValueFactory.createValue(false)); - testValidExpression("1L >= 'a'", ValueFactory.createValue(false)); - testValidExpression("'a' >= 2L", ValueFactory.createValue(true)); - testInvalidExpression("1L >= \"a\""); - testInvalidExpression("\"a\" >= 2L"); - - testValidExpression("1.2f >= 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2 >= 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2f >= 1.5", ValueFactory.createValue(false)); - testValidExpression("'a' >= 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2f >= 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" >= 1.5f"); - testInvalidExpression("1.2f >= \"a\""); - - testValidExpression("1.2 >= 1.5", ValueFactory.createValue(false)); - testValidExpression("'a' >= 1.5", ValueFactory.createValue(true)); - testValidExpression("1.2 >= 'a'", ValueFactory.createValue(false)); - testInvalidExpression("\"a\" >= 1.5"); - testInvalidExpression("1.2 >= \"a\""); - - testValidExpression("'a' >= 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" >= 'a'"); - testInvalidExpression("'a' >= \"a\""); - - testInvalidExpression("\"a\" >= \"a\""); + + testValidExpression("1 >= 2", MIValueFactory.createValue(false)); + testValidExpression("1L >= 2", MIValueFactory.createValue(false)); + testValidExpression("1 >= 2L", MIValueFactory.createValue(false)); + testValidExpression("1.5f >= 2", MIValueFactory.createValue(false)); + testValidExpression("1 >= 1.2f", MIValueFactory.createValue(false)); + testValidExpression("1.5 >= 2", MIValueFactory.createValue(false)); + testValidExpression("1 >= 1.2", MIValueFactory.createValue(false)); + testValidExpression("'a' >= 2", MIValueFactory.createValue(true)); + testValidExpression("1 >= 'a'", MIValueFactory.createValue(false)); + + testValidExpression("1L >= 2L", MIValueFactory.createValue(false)); + testValidExpression("1.2f >= 2L", MIValueFactory.createValue(false)); + testValidExpression("1L >= 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1L >= 1.2", MIValueFactory.createValue(false)); + testValidExpression("1.5 >= 2L", MIValueFactory.createValue(false)); + testValidExpression("1L >= 'a'", MIValueFactory.createValue(false)); + testValidExpression("'a' >= 2L", MIValueFactory.createValue(true)); + + testValidExpression("1.2f >= 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2 >= 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2f >= 1.5", MIValueFactory.createValue(false)); + testValidExpression("'a' >= 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2f >= 'a'", MIValueFactory.createValue(false)); + + testValidExpression("1.2 >= 1.5", MIValueFactory.createValue(false)); + testValidExpression("'a' >= 1.5", MIValueFactory.createValue(true)); + testValidExpression("1.2 >= 'a'", MIValueFactory.createValue(false)); + + testValidExpression("'a' >= 'a'", MIValueFactory.createValue(true)); } @Test @@ -634,85 +493,69 @@ public void testInterpretLessEqualExpression() { testInvalidExpression("1.5 <= false"); testInvalidExpression("true <= 'a'"); testInvalidExpression("'a' <= false"); - testInvalidExpression("true <= \"a\""); - testInvalidExpression("\"a\" <= false"); - - testValidExpression("1 <= 2", ValueFactory.createValue(true)); - testValidExpression("1L <= 2", ValueFactory.createValue(true)); - testValidExpression("1 <= 2L", ValueFactory.createValue(true)); - testValidExpression("1.5f <= 2", ValueFactory.createValue(true)); - testValidExpression("1 <= 1.2f", ValueFactory.createValue(true)); - testValidExpression("1.5 <= 2", ValueFactory.createValue(true)); - testValidExpression("1 <= 1.2", ValueFactory.createValue(true)); - testValidExpression("'a' <= 2", ValueFactory.createValue(false)); - testValidExpression("1 <= 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" <= 2"); - testInvalidExpression("1 <= \"a\""); - - testValidExpression("1L <= 2L", ValueFactory.createValue(true)); - testValidExpression("1.2f <= 2L", ValueFactory.createValue(true)); - testValidExpression("1L <= 1.5f", ValueFactory.createValue(true)); - testValidExpression("1L <= 1.2", ValueFactory.createValue(true)); - testValidExpression("1.5 <= 2L", ValueFactory.createValue(true)); - testValidExpression("1L <= 'a'", ValueFactory.createValue(true)); - testValidExpression("'a' <= 2L", ValueFactory.createValue(false)); - testInvalidExpression("1L <= \"a\""); - testInvalidExpression("\"a\" <= 2L"); - - testValidExpression("1.2f <= 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2 <= 1.5f", ValueFactory.createValue(true)); - testValidExpression("1.2f <= 1.5", ValueFactory.createValue(true)); - testValidExpression("'a' <= 1.5f", ValueFactory.createValue(false)); - testValidExpression("1.2f <= 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" <= 1.5f"); - testInvalidExpression("1.2f <= \"a\""); - - testValidExpression("1.2 <= 1.5", ValueFactory.createValue(true)); - testValidExpression("'a' <= 1.5", ValueFactory.createValue(false)); - testValidExpression("1.2 <= 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" <= 1.5"); - testInvalidExpression("1.2 <= \"a\""); - - testValidExpression("'a' <= 'a'", ValueFactory.createValue(true)); - testInvalidExpression("\"a\" <= 'a'"); - testInvalidExpression("'a' <= \"a\""); - - testInvalidExpression("\"a\" <= \"a\""); + + testValidExpression("1 <= 2", MIValueFactory.createValue(true)); + testValidExpression("1L <= 2", MIValueFactory.createValue(true)); + testValidExpression("1 <= 2L", MIValueFactory.createValue(true)); + testValidExpression("1.5f <= 2", MIValueFactory.createValue(true)); + testValidExpression("1 <= 1.2f", MIValueFactory.createValue(true)); + testValidExpression("1.5 <= 2", MIValueFactory.createValue(true)); + testValidExpression("1 <= 1.2", MIValueFactory.createValue(true)); + testValidExpression("'a' <= 2", MIValueFactory.createValue(false)); + testValidExpression("1 <= 'a'", MIValueFactory.createValue(true)); + + testValidExpression("1L <= 2L", MIValueFactory.createValue(true)); + testValidExpression("1.2f <= 2L", MIValueFactory.createValue(true)); + testValidExpression("1L <= 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1L <= 1.2", MIValueFactory.createValue(true)); + testValidExpression("1.5 <= 2L", MIValueFactory.createValue(true)); + testValidExpression("1L <= 'a'", MIValueFactory.createValue(true)); + testValidExpression("'a' <= 2L", MIValueFactory.createValue(false)); + + testValidExpression("1.2f <= 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2 <= 1.5f", MIValueFactory.createValue(true)); + testValidExpression("1.2f <= 1.5", MIValueFactory.createValue(true)); + testValidExpression("'a' <= 1.5f", MIValueFactory.createValue(false)); + testValidExpression("1.2f <= 'a'", MIValueFactory.createValue(true)); + + testValidExpression("1.2 <= 1.5", MIValueFactory.createValue(true)); + testValidExpression("'a' <= 1.5", MIValueFactory.createValue(false)); + testValidExpression("1.2 <= 'a'", MIValueFactory.createValue(true)); + + testValidExpression("'a' <= 'a'", MIValueFactory.createValue(true)); } @Test public void testInterpretBooleanNotExpression() { testInvalidExpression("~true"); - testValidExpression("~1", ValueFactory.createValue(-2)); - testValidExpression("~-5", ValueFactory.createValue(4)); - testValidExpression("~708", ValueFactory.createValue(-709)); - testValidExpression("~1L", ValueFactory.createValue(-2L)); - testValidExpression("~-5L", ValueFactory.createValue(4L)); - testValidExpression("~708L", ValueFactory.createValue(-709L)); + testValidExpression("~1", MIValueFactory.createValue(-2)); + testValidExpression("~-5", MIValueFactory.createValue(4)); + testValidExpression("~708", MIValueFactory.createValue(-709)); + testValidExpression("~1L", MIValueFactory.createValue(-2L)); + testValidExpression("~-5L", MIValueFactory.createValue(4L)); + testValidExpression("~708L", MIValueFactory.createValue(-709L)); testInvalidExpression("~1.2f"); testInvalidExpression("~1.5"); - testValidExpression("~'a'", ValueFactory.createValue(-98)); - testInvalidExpression("~\"a\""); + testValidExpression("~'a'", MIValueFactory.createValue(-98)); } @Test public void testInterpretLogicalNotExpression() { - testValidExpression("!true", ValueFactory.createValue(false)); - testValidExpression("!false", ValueFactory.createValue(true)); + testValidExpression("!true", MIValueFactory.createValue(false)); + testValidExpression("!false", MIValueFactory.createValue(true)); testInvalidExpression("!1"); testInvalidExpression("!1L"); testInvalidExpression("!1.2f"); testInvalidExpression("!1.5"); testInvalidExpression("!'a'"); - testInvalidExpression("!\"a\""); } @Test public void testInterpretLogicalAndOpExpression() { - testValidExpression("true && true", ValueFactory.createValue(true)); - testValidExpression("false && false", ValueFactory.createValue(false)); - testValidExpression("true && false", ValueFactory.createValue(false)); - testValidExpression("false && true", ValueFactory.createValue(false)); + testValidExpression("true && true", MIValueFactory.createValue(true)); + testValidExpression("false && false", MIValueFactory.createValue(false)); + testValidExpression("true && false", MIValueFactory.createValue(false)); + testValidExpression("false && true", MIValueFactory.createValue(false)); testInvalidExpression("true && 1"); testInvalidExpression("1 && false"); testInvalidExpression("true && 1L"); @@ -723,8 +566,6 @@ public void testInterpretLogicalAndOpExpression() { testInvalidExpression("1.5 && false"); testInvalidExpression("true && 'a'"); testInvalidExpression("'a' && false"); - testInvalidExpression("true && \"a\""); - testInvalidExpression("\"a\" && false"); testInvalidExpression("1 && 2"); testInvalidExpression("1L && 2"); @@ -735,8 +576,6 @@ public void testInterpretLogicalAndOpExpression() { testInvalidExpression("1 && 1.2"); testInvalidExpression("'a' && 2"); testInvalidExpression("1 && 'a'"); - testInvalidExpression("\"a\" && 2"); - testInvalidExpression("1 && \"a\""); testInvalidExpression("1L && 2L"); testInvalidExpression("1.2f && 2L"); @@ -745,36 +584,26 @@ public void testInterpretLogicalAndOpExpression() { testInvalidExpression("1.5 && 2L"); testInvalidExpression("1L && 'a'"); testInvalidExpression("'a' && 2L"); - testInvalidExpression("1L && \"a\""); - testInvalidExpression("\"a\" && 2L"); testInvalidExpression("1.2f && 1.5f"); testInvalidExpression("1.2 && 1.5f"); testInvalidExpression("1.2f && 1.5"); testInvalidExpression("'a' && 1.5f"); testInvalidExpression("1.2f && 'a'"); - testInvalidExpression("\"a\" && 1.5f"); - testInvalidExpression("1.2f && \"a\""); testInvalidExpression("1.2 && 1.5"); testInvalidExpression("'a' && 1.5"); testInvalidExpression("1.2 && 'a'"); - testInvalidExpression("\"a\" && 1.5"); - testInvalidExpression("1.2 && \"a\""); testInvalidExpression("'a' && 'a'"); - testInvalidExpression("\"a\" && 'a'"); - testInvalidExpression("'a' && \"a\""); - - testInvalidExpression("\"a\" && \"a\""); } @Test public void testInterpretLogicalOrOpExpression() { - testValidExpression("true || true", ValueFactory.createValue(true)); - testValidExpression("false || false", ValueFactory.createValue(false)); - testValidExpression("true || false", ValueFactory.createValue(true)); - testValidExpression("false || true", ValueFactory.createValue(true)); + testValidExpression("true || true", MIValueFactory.createValue(true)); + testValidExpression("false || false", MIValueFactory.createValue(false)); + testValidExpression("true || false", MIValueFactory.createValue(true)); + testValidExpression("false || true", MIValueFactory.createValue(true)); testInvalidExpression("true || 1"); testInvalidExpression("1 || false"); testInvalidExpression("true || 1L"); @@ -785,8 +614,6 @@ public void testInterpretLogicalOrOpExpression() { testInvalidExpression("1.5 || false"); testInvalidExpression("true || 'a'"); testInvalidExpression("'a' || false"); - testInvalidExpression("true || \"a\""); - testInvalidExpression("\"a\" || false"); testInvalidExpression("1 || 2"); testInvalidExpression("1L || 2"); @@ -797,8 +624,6 @@ public void testInterpretLogicalOrOpExpression() { testInvalidExpression("1 || 1.2"); testInvalidExpression("'a' || 2"); testInvalidExpression("1 || 'a'"); - testInvalidExpression("\"a\" || 2"); - testInvalidExpression("1 || \"a\""); testInvalidExpression("1L || 2L"); testInvalidExpression("1.2f || 2L"); @@ -807,40 +632,30 @@ public void testInterpretLogicalOrOpExpression() { testInvalidExpression("1.5 || 2L"); testInvalidExpression("1L || 'a'"); testInvalidExpression("'a' || 2L"); - testInvalidExpression("1L || \"a\""); - testInvalidExpression("\"a\" || 2L"); testInvalidExpression("1.2f || 1.5f"); testInvalidExpression("1.2 || 1.5f"); testInvalidExpression("1.2f || 1.5"); testInvalidExpression("'a' || 1.5f"); testInvalidExpression("1.2f || 'a'"); - testInvalidExpression("\"a\" || 1.5f"); - testInvalidExpression("1.2f || \"a\""); testInvalidExpression("1.2 || 1.5"); testInvalidExpression("'a' || 1.5"); testInvalidExpression("1.2 || 'a'"); - testInvalidExpression("\"a\" || 1.5"); - testInvalidExpression("1.2 || \"a\""); testInvalidExpression("'a' || 'a'"); - testInvalidExpression("\"a\" || 'a'"); - testInvalidExpression("'a' || \"a\""); - - testInvalidExpression("\"a\" || \"a\""); } @Test public void testConditionalExpression() { - testValidExpression("(true) ? 1 : 2", ValueFactory.createValue(1)); - testValidExpression("5 <= 10%5 || !true && true ? (3 + 2 * 2) / 14.0 : ((1 > 2L) && ('z' <= 15.243f))", ValueFactory.createValue(false)); + testValidExpression("(true) ? 1 : 2", MIValueFactory.createValue(1)); + testValidExpression("5 <= 10%5 || !true && true ? (3 + 2 * 2) / 14.0 : ((1 > 2L) && ('z' <= 15.243f))", MIValueFactory.createValue(false)); } @Test public void testCombinedExpressions() { - testValidExpression("((1 > 2L) && ('z' <= 15.243f)) || true", ValueFactory.createValue(true)); - testValidExpression("(3 + 2 * 2) / 14.0", ValueFactory.createValue(0.5)); - testValidExpression("true && false || !true", ValueFactory.createValue(false)); + testValidExpression("((1 > 2L) && ('z' <= 15.243f)) || true", MIValueFactory.createValue(true)); + testValidExpression("(3 + 2 * 2) / 14.0", MIValueFactory.createValue(0.5)); + testValidExpression("true && false || !true", MIValueFactory.createValue(false)); } } diff --git a/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java b/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java index f6c2aa6c59..3e5345deda 100644 --- a/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java +++ b/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java @@ -3,7 +3,7 @@ package de.monticore.ast; import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symboltable.IScope; import de.monticore.visitor.ITraverser; import de.se_rwth.commons.SourcePosition; @@ -679,7 +679,7 @@ default void accept (ITraverser visitor) { visitor.handle(this); } - default Value evaluate(ModelInterpreter interpreter) { + default MIValue evaluate(ModelInterpreter interpreter) { return interpreter.interpret(this); } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java index 74f7e99973..7a628462da 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java @@ -1,6 +1,6 @@ package de.monticore.interpreter; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symboltable.ISymbol; import de.se_rwth.commons.logging.Log; @@ -9,24 +9,27 @@ public class MIScope { - private Map contextMap; + private Map contextMap = new HashMap<>(); private MIScope parent; public MIScope() { - this.contextMap = new HashMap(); this.parent = null; } - public void declareVariable(ISymbol symbol, Value value) { + public MIScope(MIScope parent) { + this.parent = parent; + } + + public void declareVariable(ISymbol symbol, MIValue value) { if (contextMap.containsKey(symbol)) { Log.error("Variable was already declared"); } this.contextMap.put(symbol, value); } - public Value load(ISymbol symbol) { - Value value = contextMap.get(symbol); + public MIValue load(ISymbol symbol) { + MIValue value = contextMap.get(symbol); if (value != null) { return value; } @@ -36,10 +39,10 @@ public Value load(ISymbol symbol) { } Log.error("Failed to load Value of Symbol. Could not find Symbol in the current or any parent scope"); - return new ErrorValue("Failed to load Value of Symbol. Could not find Symbol in the current or any parent scope"); + return new ErrorMIValue("Failed to load Value of Symbol. Could not find Symbol in the current or any parent scope"); } - public void store(ISymbol symbol, Value value) { + public void store(ISymbol symbol, MIValue value) { if (contextMap.containsKey(symbol)) { contextMap.put(symbol, value); } else if (parent != null){ diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/Value.java b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java similarity index 98% rename from monticore-runtime/src/main/java/de/monticore/interpreter/Value.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java index e7f799817f..b54315ae35 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/Value.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java @@ -3,7 +3,7 @@ import de.se_rwth.commons.logging.Log; -public interface Value { +public interface MIValue { default boolean isBoolean() { return false; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/MIValueFactory.java b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValueFactory.java new file mode 100644 index 0000000000..142df5ce9f --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValueFactory.java @@ -0,0 +1,44 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.interpreter; + +import de.monticore.interpreter.values.*; + +public class MIValueFactory { + + public static MIValue createValue(short value) { + return new ShortMIValue(value); + } + + public static MIValue createValue(int value) { + return new IntMIValue(value); + } + + public static MIValue createValue(double value) { + return new DoubleMIValue(value); + } + + public static MIValue createValue(float value) { + return new FloatMIValue(value); + } + + public static MIValue createValue(long value) { + return new LongMIValue(value); + } + + public static MIValue createValue(boolean value) { + return new BooleanMIValue(value); + } + + public static MIValue createValue(char value) { + return new CharMIValue(value); + } + + public static MIValue createValue(byte value) { + return new ByteMIValue(value); + } + + public static MIValue createValue(Object value) { + return new ObjectMIValue(value); + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java b/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java index 2838a076c2..aebc93c312 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java @@ -2,16 +2,16 @@ package de.monticore.interpreter; import de.monticore.ast.ASTNode; -import de.monticore.interpreter.values.ErrorValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symboltable.ISymbol; import de.se_rwth.commons.logging.Log; public interface ModelInterpreter { - default Value interpret(ASTNode n) { + default MIValue interpret(ASTNode n) { String errorMsg = "No implementation of ASTNode of type " + n.toString(); Log.error(errorMsg); - return new ErrorValue(errorMsg); + return new ErrorMIValue(errorMsg); } void setRealThis(ModelInterpreter realThis); @@ -23,15 +23,15 @@ default Value interpret(ASTNode n) { void pushScope(MIScope scope); void popScope(); - default void declareVariable(ISymbol symbol, Value value) { + default void declareVariable(ISymbol symbol, MIValue value) { getCurrentScope().declareVariable(symbol, value); } - default Value load(ISymbol symbol) { + default MIValue load(ISymbol symbol) { return getRealThis().load(symbol); } - default void store (ISymbol symbol, Value value){ + default void store (ISymbol symbol, MIValue value){ getRealThis().store(symbol, value); } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/ValueFactory.java b/monticore-runtime/src/main/java/de/monticore/interpreter/ValueFactory.java deleted file mode 100644 index 48e04077d9..0000000000 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/ValueFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package de.monticore.interpreter; - -import de.monticore.interpreter.values.*; - -public class ValueFactory { - - public static Value createValue(short value) { - return new ShortValue(value); - } - - public static Value createValue(int value) { - return new IntValue(value); - } - - public static Value createValue(double value) { - return new DoubleValue(value); - } - - public static Value createValue(float value) { - return new FloatValue(value); - } - - public static Value createValue(long value) { - return new LongValue(value); - } - - public static Value createValue(boolean value) { - return new BooleanValue(value); - } - - public static Value createValue(char value) { - return new CharValue(value); - } - - public static Value createValue(byte value) { - return new ByteValue(value); - } - - public static Value createValue(Object value) { - return new ObjectValue(value); - } - -} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java similarity index 68% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java index 28813bd917..17f5474f36 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java @@ -1,13 +1,13 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class BooleanValue implements Value { +public class BooleanMIValue implements MIValue { protected boolean value; - public BooleanValue(boolean value){ + public BooleanMIValue(boolean value){ this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java similarity index 81% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java index a3b034d818..3e658f67a6 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java @@ -1,12 +1,12 @@ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class ByteValue implements Value { +public class ByteMIValue implements MIValue { protected byte value; - public ByteValue(byte value) { + public ByteMIValue(byte value) { this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java similarity index 77% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/CharValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java index 759dd008e4..180840f169 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java @@ -1,14 +1,13 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; -import de.se_rwth.commons.logging.Log; +import de.monticore.interpreter.MIValue; -public class CharValue implements Value { +public class CharMIValue implements MIValue { protected char value; - public CharValue(char value){ + public CharMIValue(char value){ this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java similarity index 63% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java index 10c12e8c5b..c226dfe8fe 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java @@ -1,14 +1,13 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; -import de.se_rwth.commons.logging.Log; +import de.monticore.interpreter.MIValue; -public class DoubleValue implements Value { +public class DoubleMIValue implements MIValue { protected double value; - public DoubleValue(double value) { + public DoubleMIValue(double value) { this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java similarity index 56% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java index 073ee348b9..4a476873f9 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java @@ -1,12 +1,12 @@ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class ErrorValue implements Value { +public class ErrorMIValue implements MIValue { String message; - public ErrorValue(String message) { + public ErrorMIValue(String message) { this.message = message; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java similarity index 73% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java index 8dcc608bfb..b9322a8a5e 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java @@ -1,13 +1,13 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class FloatValue implements Value { +public class FloatMIValue implements MIValue { protected float value; - public FloatValue(float value) { + public FloatMIValue(float value) { this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java new file mode 100644 index 0000000000..3e0f4d784e --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java @@ -0,0 +1,28 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.MIScope; +import de.monticore.interpreter.MIValue; + +import java.util.List; + +abstract public class FunctionMIValue implements MIValue { + + protected MIScope parentScope; + + public FunctionMIValue(MIScope parentScope) { + this.parentScope = parentScope; + } + + @Override + public boolean isFunction() { + return true; + } + + /* + TODO MIFunctionSymbol, MIMethodSymbol, MILambdaValue + */ + + abstract public MIValue execute(List arguments); + + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionValue.java deleted file mode 100644 index 5997d9ce02..0000000000 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionValue.java +++ /dev/null @@ -1,18 +0,0 @@ -package de.monticore.interpreter.values; - -import de.monticore.interpreter.MIScope; -import de.monticore.interpreter.Value; -import de.se_rwth.commons.Symbol; - -public class FunctionValue implements Value { - - protected MIScope parentScope; - protected Symbol symbol; - - @Override - public boolean isFunction() { - return true; - } - - -} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java similarity index 79% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/IntValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java index c32716b6fb..152a49d43f 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java @@ -1,13 +1,13 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class IntValue implements Value { +public class IntMIValue implements MIValue { protected int value; - public IntValue(int value) { + public IntMIValue(int value) { this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java similarity index 76% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/LongValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java index 293fa334a0..c3d5cf91bf 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java @@ -1,13 +1,13 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class LongValue implements Value { +public class LongMIValue implements MIValue { protected long value; - public LongValue(long value) { + public LongMIValue(long value) { this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java similarity index 68% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java index 01a4f7a3c6..df0015fb6a 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java @@ -1,13 +1,13 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class ObjectValue implements Value { +public class ObjectMIValue implements MIValue { protected Object value; - public ObjectValue(Object value) { + public ObjectMIValue(Object value) { this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java similarity index 79% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java index cbb648fe67..e386a1d049 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java @@ -1,12 +1,12 @@ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class ShortValue implements Value { +public class ShortMIValue implements MIValue { protected short value; - public ShortValue(short value) { + public ShortMIValue(short value) { this.value = value; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java similarity index 55% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidValue.java rename to monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java index 35d6ee4bcd..37f1e16c3f 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java @@ -1,8 +1,8 @@ package de.monticore.interpreter.values; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; -public class VoidValue implements Value { +public class VoidMIValue implements MIValue { @Override public boolean isVoid() { From 4a5dc85177b0945c1992488045c3b5d2fe27684c Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Fri, 21 Feb 2025 12:19:11 +0100 Subject: [PATCH 03/37] fix --- .../CommonExpressionsInterpreter.java | 34 +++++++++---------- .../LambdaExpressionsInterpreter.java | 10 +++--- ...ineExpressionsWithLiteralsInterpreter.java | 4 +-- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index ee571ff026..682f19b4da 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -469,21 +469,21 @@ public MIValue interpret(ASTLiteralExpression node) { return node.getLiteral().evaluate(getRealThis()); } - @Override - public MIValue interpret(ASTCallExpression node) { - // evaluate expression that gives lambda/function - // get original parent scope of lambda/function declaration - // create Scope with parent and arguments - // evaluate arguments in current scope & put into new scope - - // node.getExpression(); - // parent = whatever - -// MIScope scope = new MIScope(parent); -// List parameterSymbols = -// List arguments = node.getArguments().getExpressionList(); -// for (int i = 0; i < arguments.getSize(); i++) { -// scope.declareVariable() -// } - } +// @Override +// public MIValue interpret(ASTCallExpression node) { +// // evaluate expression that gives lambda/function +// // get original parent scope of lambda/function declaration +// // create Scope with parent and arguments +// // evaluate arguments in current scope & put into new scope +// +// // node.getExpression(); +// // parent = whatever +// +//// MIScope scope = new MIScope(parent); +//// List parameterSymbols = +//// List arguments = node.getArguments().getExpressionList(); +//// for (int i = 0; i < arguments.getSize(); i++) { +//// scope.declareVariable() +//// } +// } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java index 82ad275ead..1869ad9641 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java @@ -4,7 +4,7 @@ import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.values.FunctionMIValue; -import de.monticore.interpreter.values.func.MILambdaValue; +//import de.monticore.interpreter.values.func.MILambdaValue; public class LambdaExpressionsInterpreter extends LambdaExpressionsInterpreterTOP { @@ -16,9 +16,9 @@ public LambdaExpressionsInterpreter(ModelInterpreter realThis) { super(realThis); } - @Override - public MIValue interpret(ASTLambdaExpression node) { - return new MILambdaValue(getRealThis().getCurrentScope(), node); - } +// @Override +// public MIValue interpret(ASTLambdaExpression node) { +// return new MILambdaValue(getRealThis().getCurrentScope(), node); +// } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/_visitor/CombineExpressionsWithLiteralsInterpreter.java b/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/_visitor/CombineExpressionsWithLiteralsInterpreter.java index 6b65b90b87..7bc245bb6e 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/_visitor/CombineExpressionsWithLiteralsInterpreter.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/_visitor/CombineExpressionsWithLiteralsInterpreter.java @@ -3,7 +3,7 @@ import de.monticore.expressions.combineexpressionswithliterals._ast.ASTFoo; import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; public class CombineExpressionsWithLiteralsInterpreter extends CombineExpressionsWithLiteralsInterpreterTOP { public CombineExpressionsWithLiteralsInterpreter() { @@ -15,7 +15,7 @@ public CombineExpressionsWithLiteralsInterpreter(ModelInterpreter realThis) { } @Override - public Value interpret(ASTFoo node) { + public MIValue interpret(ASTFoo node) { return node.getExpression().evaluate(getRealThis()); } From d48bbc07fb11fd1ad17ec2d71821a90f2082bc09 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Fri, 21 Feb 2025 13:05:26 +0100 Subject: [PATCH 04/37] fix InterpreterDecoratorTest --- .../interpreter/InterpreterDecoratorTest.java | 172 ++++++++++-------- 1 file changed, 93 insertions(+), 79 deletions(-) diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index 9c15c17f7c..3a550004f9 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -26,8 +26,7 @@ import static org.junit.Assert.assertTrue; public class InterpreterDecoratorTest extends DecoratorTestCase { - - + protected ASTCDCompilationUnit originalCompilationUnit; protected ASTCDClass decoratedClass; @@ -44,7 +43,7 @@ public void before() { @Test public void testMethodCount() { - assertEquals(5, decoratedClass.getCDMethodList().size()); + assertEquals(8, decoratedClass.getCDMethodList().size()); } @Test @@ -54,15 +53,10 @@ public void testConstructors() { assertEquals(2, constructors.size()); assertTrue(constructors.get(0).getCDParameterList().isEmpty()); - assertEquals( - constructors.get(1).getCDParameterList().size(), - 1); - assertEquals( - constructors.get(1).getCDParameter(0).getName(), - "realThis"); - assertEquals( - constructors.get(1).getCDParameter(0).getMCType().printType(), - InterpreterConstants.MODELINTERPRETER_FULLNAME); + assertEquals(1, constructors.get(1).getCDParameterList().size()); + assertEquals("realThis", constructors.get(1).getCDParameter(0).getName()); + assertEquals(InterpreterConstants.MODELINTERPRETER_FULLNAME, + constructors.get(1).getCDParameter(0).getMCType().printType()); } @Test @@ -80,32 +74,22 @@ public void testSuperInterfaces() { public void testClassAttributes() { List attributes = decoratedClass.getCDAttributeList(); - assertEquals(attributes.size(), 3); + assertEquals(3, attributes.size()); - assertEquals( - attributes.get(0).getName(), - "lexicalsInterpreter"); - assertEquals( - attributes.get(0).getMCType().printType(), - "de.monticore.codegen.ast.lexicals._visitor.ILexicalsInterpreter"); + assertEquals("lexicalsInterpreter", attributes.get(0).getName()); + assertEquals("de.monticore.codegen.ast.lexicals._visitor.ILexicalsInterpreter", + attributes.get(0).getMCType().printType()); - assertEquals( - attributes.get(1).getName(), - "realThis"); - assertEquals( - attributes.get(1).getMCType().printType(), - InterpreterConstants.MODELINTERPRETER_FULLNAME); + assertEquals("realThis", attributes.get(1).getName()); + assertEquals(InterpreterConstants.MODELINTERPRETER_FULLNAME, + attributes.get(1).getMCType().printType()); - assertEquals( - attributes.get(2).getName(), - "contextMap"); + assertEquals("scopeCallstack", attributes.get(2).getName()); assertTrue(attributes.get(2).getMCType() instanceof ASTMCMapType); - assertEquals( - ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(0).printType(), - InterpreterConstants.SYMBOL_FULLNAME); - assertEquals( - ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(1).printType(), - InterpreterConstants.VALUE_FULLNAME); + assertEquals(InterpreterConstants.SYMBOL_FULLNAME, + ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(0).printType()); + assertEquals(InterpreterConstants.VALUE_FULLNAME, + ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(1).printType()); } @Test @@ -119,9 +103,8 @@ public void testRealThisMethods() { ASTCDMethod getMethod = optGetMethod.get(); assertTrue(getMethod.getCDParameterList().isEmpty()); - assertEquals( - getMethod.getMCReturnType().printType(), - InterpreterConstants.MODELINTERPRETER_FULLNAME); + assertEquals(InterpreterConstants.MODELINTERPRETER_FULLNAME, + getMethod.getMCReturnType().printType()); Optional optSetMethod = decoratedClass.getCDMethodList() .stream() @@ -131,36 +114,49 @@ public void testRealThisMethods() { assertTrue(optSetMethod.isPresent()); ASTCDMethod setMethod = optSetMethod.get(); - assertEquals(setMethod.getCDParameterList().size(), 1); - assertEquals( - setMethod.getCDParameter(0).getMCType().printType(), - InterpreterConstants.MODELINTERPRETER_FULLNAME); - assertEquals( - setMethod.getCDParameter(0).getName(), - "realThis"); + assertEquals(1, setMethod.getCDParameterList().size()); + assertEquals(InterpreterConstants.MODELINTERPRETER_FULLNAME, + setMethod.getCDParameter(0).getMCType().printType()); + assertEquals("realThis", + setMethod.getCDParameter(0).getName()); assertTrue(setMethod.getMCReturnType().isPresentMCVoidType()); } @Test - public void testContextMethods() { + public void testVariableMethods() { + Optional optDeclareMethod = decoratedClass.getCDMethodList() + .stream() + .filter(m -> m.getName().equals("declareVariable")) + .findAny(); + + assertTrue(optDeclareMethod.isPresent()); + ASTCDMethod declareMethod = optDeclareMethod.get(); + + assertTrue(declareMethod.getMCReturnType().isPresentMCVoidType()); + assertEquals(2, declareMethod.getCDParameterList().size()); + assertEquals("symbol", declareMethod.getCDParameter(0).getName()); + assertEquals(InterpreterConstants.SYMBOL_FULLNAME, + declareMethod.getCDParameter(0).getMCType().printType()); + assertEquals("value", declareMethod.getCDParameter(1).getName()); + assertEquals(InterpreterConstants.VALUE_FULLNAME, + declareMethod.getCDParameter(1).getMCType().printType()); + Optional optStoreMethod = decoratedClass.getCDMethodList() .stream() .filter(m -> m.getName().equals("store")) .findAny(); - + assertTrue(optStoreMethod.isPresent()); ASTCDMethod storeMethod = optStoreMethod.get(); - + assertTrue(storeMethod.getMCReturnType().isPresentMCVoidType()); assertEquals(2, storeMethod.getCDParameterList().size()); - assertEquals(storeMethod.getCDParameter(0).getName(), "symbol"); - assertEquals( - storeMethod.getCDParameter(0).getMCType().printType(), - InterpreterConstants.SYMBOL_FULLNAME); - assertEquals(storeMethod.getCDParameter(1).getName(), "value"); - assertEquals( - storeMethod.getCDParameter(1).getMCType().printType(), - InterpreterConstants.VALUE_FULLNAME); + assertEquals("symbol", storeMethod.getCDParameter(0).getName()); + assertEquals(InterpreterConstants.SYMBOL_FULLNAME, + storeMethod.getCDParameter(0).getMCType().printType()); + assertEquals("value", storeMethod.getCDParameter(1).getName()); + assertEquals(InterpreterConstants.VALUE_FULLNAME, + storeMethod.getCDParameter(1).getMCType().printType()); Optional optLoadMethod = decoratedClass.getCDMethodList() .stream() @@ -170,33 +166,51 @@ public void testContextMethods() { assertTrue(optLoadMethod.isPresent()); ASTCDMethod loadMethod = optLoadMethod.get(); - assertEquals( - loadMethod.getMCReturnType().printType(), - InterpreterConstants.VALUE_FULLNAME); + assertEquals(InterpreterConstants.VALUE_FULLNAME, + loadMethod.getMCReturnType().printType()); assertEquals(1, loadMethod.getCDParameterList().size()); - assertEquals( - loadMethod.getCDParameter(0).getMCType().printType(), - InterpreterConstants.SYMBOL_FULLNAME); - assertEquals( - loadMethod.getCDParameter(0).getName(), - "symbol"); - - Optional optGetMap = decoratedClass.getCDMethodList() + assertEquals(InterpreterConstants.SYMBOL_FULLNAME, + loadMethod.getCDParameter(0).getMCType().printType()); + assertEquals("symbol", + loadMethod.getCDParameter(0).getName()); + } + + @Test + public void testScopeMethods() { + Optional optGetCurrentScope = decoratedClass.getCDMethodList() .stream() - .filter(m -> m.getName().equals("getContextMap")) + .filter(m -> m.getName().equals("getCurrentScope")) .findAny(); - - assertTrue(optGetMap.isPresent()); - ASTCDMethod getMapMethod = optGetMap.get(); - - assertTrue(getMapMethod.getCDParameterList().isEmpty()); - assertTrue(getMapMethod.getMCReturnType().getMCType() instanceof ASTMCMapType); - assertEquals( - ((ASTMCMapType) getMapMethod.getMCReturnType().getMCType()).getMCTypeArgument(0).printType(), - InterpreterConstants.SYMBOL_FULLNAME); - assertEquals( - ((ASTMCMapType) getMapMethod.getMCReturnType().getMCType()).getMCTypeArgument(1).printType(), - InterpreterConstants.VALUE_FULLNAME); + + assertTrue(optGetCurrentScope.isPresent()); + ASTCDMethod getCurrentScopeMethod = optGetCurrentScope.get(); + + assertTrue(getCurrentScopeMethod.getCDParameterList().isEmpty()); + assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, + ((ASTMCMapType) getCurrentScopeMethod.getMCReturnType().getMCType()).getMCTypeArgument(0).printType()); + + Optional optPushScope = decoratedClass.getCDMethodList() + .stream() + .filter(m -> m.getName().equals("pushScope")) + .findAny(); + + assertTrue(optPushScope.isPresent()); + ASTCDMethod pushScopeMethod = optPushScope.get(); + + assertEquals(1, pushScopeMethod.getCDParameterList().size()); + assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, pushScopeMethod.getCDParameter(0).getMCType().printType()); + assertTrue(pushScopeMethod.getMCReturnType().isPresentMCVoidType()); + + Optional optPopScope = decoratedClass.getCDMethodList() + .stream() + .filter(m -> m.getName().equals("popScope")) + .findAny(); + + assertTrue(optPopScope.isPresent()); + ASTCDMethod popScopeMethod = optPopScope.get(); + + assertTrue(popScopeMethod.getCDParameterList().isEmpty()); + assertTrue(pushScopeMethod.getMCReturnType().isPresentMCVoidType()); } @Test From f2bcb6df599751949b7830b2a0c14b8d43b9bfec Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Fri, 21 Feb 2025 14:10:48 +0100 Subject: [PATCH 05/37] fix InterpreterDecoratorTest --- .../cd2java/interpreter/InterpreterDecoratorTest.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index 3a550004f9..348a0e549a 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -10,6 +10,7 @@ import de.monticore.codegen.cd2java._visitor.VisitorService; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; +import de.monticore.types.mccollectiontypes._ast.ASTMCGenericType; import de.monticore.types.mccollectiontypes._ast.ASTMCMapType; import de.se_rwth.commons.logging.Log; import org.junit.After; @@ -85,11 +86,9 @@ public void testClassAttributes() { attributes.get(1).getMCType().printType()); assertEquals("scopeCallstack", attributes.get(2).getName()); - assertTrue(attributes.get(2).getMCType() instanceof ASTMCMapType); - assertEquals(InterpreterConstants.SYMBOL_FULLNAME, - ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(0).printType()); - assertEquals(InterpreterConstants.VALUE_FULLNAME, - ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(1).printType()); + assertEquals("java.util.Stack", ((ASTMCGenericType)attributes.get(2).getMCType()).printWithoutTypeArguments()); + assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, + ((ASTMCGenericType)attributes.get(2).getMCType()).getMCTypeArgument(0).printType()); } @Test @@ -187,7 +186,7 @@ public void testScopeMethods() { assertTrue(getCurrentScopeMethod.getCDParameterList().isEmpty()); assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, - ((ASTMCMapType) getCurrentScopeMethod.getMCReturnType().getMCType()).getMCTypeArgument(0).printType()); + getCurrentScopeMethod.getMCReturnType().getMCType().printType()); Optional optPushScope = decoratedClass.getCDMethodList() .stream() From 47663ba6c1834a30af22e18b733fae788d98a2ec Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Tue, 25 Feb 2025 15:28:28 +0100 Subject: [PATCH 06/37] Added FunctionValue & Lambdas --- .../interpreter/ASTEvaluateDecorator.java | 2 +- .../interpreter/InterpreterConstants.java | 1 + .../interpreter/InterpreterDecoratorTest.java | 2 - .../CommonExpressionsInterpreter.java | 43 +++++++++++-------- .../LambdaExpressionsInterpreter.java | 26 ++++++++--- .../interpreter/InterpreterUtils.java | 1 - .../de/monticore/interpreter/MIScope.java | 4 +- .../monticore/interpreter/MIValueFactory.java | 0 .../interpreter/ModelInterpreter.java | 11 +---- .../values/ASTFunctionMIValue.java | 36 ++++++++++++++++ .../interpreter/values/FunctionMIValue.java | 28 ++++++++++++ .../expressions/AbstractInterpreterTest.java | 7 ++- .../AssignmentExpressionsInterpreterTest.java | 1 - .../CommonExpressionsInterpreterTest.java | 6 --- .../LambdaExpressionsInterpreterTest.java | 27 ++++++++++++ .../main/java/de/monticore/ast/ASTNode.java | 4 +- .../interpreter/IModelInterpreter.java | 15 +++++++ .../interpreter/values/FunctionMIValue.java | 28 ------------ 18 files changed, 164 insertions(+), 78 deletions(-) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/MIScope.java (93%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/MIValueFactory.java (100%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/ModelInterpreter.java (63%) create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java create mode 100644 monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java delete mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/ASTEvaluateDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/ASTEvaluateDecorator.java index 5b985fa1e2..7fe335d1f1 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/ASTEvaluateDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/ASTEvaluateDecorator.java @@ -77,7 +77,7 @@ protected ASTCDMethod createEvaluateInterpreterMethod(ASTCDType cdType) { protected ASTCDMethod createEvaluateInterpreterSuperMethod(ASTCDType cdType) { ASTCDParameter parameter = cdParameterFacade.createParameter( - mcTypeFacade.createQualifiedType(InterpreterConstants.MODELINTERPRETER_FULLNAME), + mcTypeFacade.createQualifiedType(InterpreterConstants.IMODELINTERPRETER_FULLNAME), "interpreter"); ASTCDMethod method = cdMethodFacade.createMethod( PUBLIC.build(), InterpreterConstants.VALUE_FULLNAME, "evaluate", parameter); diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java index 48e665e3d5..36979834f4 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java @@ -8,6 +8,7 @@ public final class InterpreterConstants { public static final String INTERPRET_METHOD_NAME = "interpret"; public static final String MODELINTERPRETER_FULLNAME = "de.monticore.interpreter.ModelInterpreter"; + public static final String IMODELINTERPRETER_FULLNAME = "de.monticore.interpreter.IModelInterpreter"; public static final String INTERPRETER_SCOPE_FULLNAME = "de.monticore.interpreter.MIScope"; diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index 348a0e549a..e62995861d 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -11,13 +11,11 @@ import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; import de.monticore.types.mccollectiontypes._ast.ASTMCGenericType; -import de.monticore.types.mccollectiontypes._ast.ASTMCMapType; import de.se_rwth.commons.logging.Log; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; -import org.junit.jupiter.api.Disabled; import java.util.List; import java.util.Optional; diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index 682f19b4da..8d1c58c681 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -2,12 +2,13 @@ package de.monticore.expressions.commonexpressions._visitor; import de.monticore.expressions.commonexpressions._ast.*; +import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.expressions.expressionsbasis._ast.ASTLiteralExpression; import de.monticore.interpreter.InterpreterUtils; -import de.monticore.interpreter.MIScope; import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.FunctionMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypePrimitive; @@ -15,6 +16,9 @@ import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; +import java.util.ArrayList; +import java.util.List; + import static de.monticore.interpreter.MIValueFactory.createValue; public class CommonExpressionsInterpreter extends CommonExpressionsInterpreterTOP { @@ -469,21 +473,24 @@ public MIValue interpret(ASTLiteralExpression node) { return node.getLiteral().evaluate(getRealThis()); } -// @Override -// public MIValue interpret(ASTCallExpression node) { -// // evaluate expression that gives lambda/function -// // get original parent scope of lambda/function declaration -// // create Scope with parent and arguments -// // evaluate arguments in current scope & put into new scope -// -// // node.getExpression(); -// // parent = whatever -// -//// MIScope scope = new MIScope(parent); -//// List parameterSymbols = -//// List arguments = node.getArguments().getExpressionList(); -//// for (int i = 0; i < arguments.getSize(); i++) { -//// scope.declareVariable() -//// } -// } + @Override + public MIValue interpret(ASTCallExpression node) { + // evaluate expression that gives lambda/function + // get original parent scope of lambda/function declaration + // create Scope with parent and arguments + // evaluate arguments in current scope & put into new scope + MIValue value = node.getExpression().evaluate(getRealThis()); + if (!value.isFunction()) { + String errorMsg = "Call expression expected a function but got " + TypeCheck3.typeOf(node.getExpression()).print() + "."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + List args = new ArrayList<>(); + for (ASTExpression argument : node.getArguments().getExpressionList()) { + args.add(argument.evaluate(getRealThis())); + } + + return ((FunctionMIValue)value).execute(getRealThis(), args); + } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java index 1869ad9641..c322ae7630 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java @@ -1,10 +1,15 @@ package de.monticore.expressions.lambdaexpressions._visitor; import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaExpression; +import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaExpressionBody; +import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaParameter; import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; -import de.monticore.interpreter.values.FunctionMIValue; -//import de.monticore.interpreter.values.func.MILambdaValue; +import de.monticore.interpreter.values.ASTFunctionMIValue; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; + +import java.util.ArrayList; +import java.util.List; public class LambdaExpressionsInterpreter extends LambdaExpressionsInterpreterTOP { @@ -16,9 +21,18 @@ public LambdaExpressionsInterpreter(ModelInterpreter realThis) { super(realThis); } -// @Override -// public MIValue interpret(ASTLambdaExpression node) { -// return new MILambdaValue(getRealThis().getCurrentScope(), node); -// } + @Override + public MIValue interpret(ASTLambdaExpressionBody node) { + return node.getExpression().evaluate(getRealThis()); + } + + @Override + public MIValue interpret(ASTLambdaExpression node) { + List parameterSymbols = new ArrayList<>(); + for (ASTLambdaParameter parameter : node.getLambdaParameters().getLambdaParameterList()) { + parameterSymbols.add(parameter.getSymbol()); + } + return new ASTFunctionMIValue(getRealThis().getCurrentScope(), parameterSymbols, node.getLambdaBody()); + } } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java index db1a45eee4..7a4b53ad24 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java @@ -5,7 +5,6 @@ import de.monticore.types.check.SymTypeExpression; import de.se_rwth.commons.logging.Log; -import java.util.List; import java.util.function.BiFunction; import java.util.function.BinaryOperator; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java similarity index 93% rename from monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java index 7a628462da..c12cadcd84 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/MIScope.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java @@ -9,9 +9,9 @@ public class MIScope { - private Map contextMap = new HashMap<>(); + protected Map contextMap = new HashMap<>(); - private MIScope parent; + protected MIScope parent; public MIScope() { this.parent = null; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/MIValueFactory.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIValueFactory.java similarity index 100% rename from monticore-runtime/src/main/java/de/monticore/interpreter/MIValueFactory.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/MIValueFactory.java diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java similarity index 63% rename from monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java index aebc93c312..d50a9c68a1 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/ModelInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java @@ -1,18 +1,9 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter; -import de.monticore.ast.ASTNode; -import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symboltable.ISymbol; -import de.se_rwth.commons.logging.Log; -public interface ModelInterpreter { - - default MIValue interpret(ASTNode n) { - String errorMsg = "No implementation of ASTNode of type " + n.toString(); - Log.error(errorMsg); - return new ErrorMIValue(errorMsg); - } +public interface ModelInterpreter extends IModelInterpreter { void setRealThis(ModelInterpreter realThis); diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java new file mode 100644 index 0000000000..782b4fede1 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java @@ -0,0 +1,36 @@ +package de.monticore.interpreter.values; + +import de.monticore.ast.ASTNode; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.MIScope; + +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; + +import java.util.List; + +public class ASTFunctionMIValue extends FunctionMIValue { + + protected ASTNode body; + + public ASTFunctionMIValue(MIScope parentScope, List parameterSymbols, ASTNode body) { + super(parentScope, parameterSymbols); + this.body = body; + } + + @Override + public MIValue execute(ModelInterpreter interpreter, List arguments) { + MIScope newScope = new MIScope(parentScope); + + for (int i = 0; i < parameterSymbols.size(); i++) { + newScope.declareVariable(parameterSymbols.get(i), arguments.get(i)); + } + + interpreter.pushScope(newScope); + MIValue result = body.evaluate(interpreter); + interpreter.popScope(); + + return result; + } + +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java new file mode 100644 index 0000000000..9c3ce41b90 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java @@ -0,0 +1,28 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.MIScope; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; + +import java.util.List; + +abstract public class FunctionMIValue implements MIValue { + + protected MIScope parentScope; + protected List parameterSymbols; + + public FunctionMIValue(MIScope parentScope, List parameterSymbols) { + this.parentScope = parentScope; + this.parameterSymbols = parameterSymbols; + } + + @Override + public boolean isFunction() { + return true; + } + + abstract public MIValue execute(ModelInterpreter interpreter, List arguments); + + +} diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java index 6b66ccea01..da154b02f4 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java @@ -14,6 +14,7 @@ import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; import java.io.IOException; @@ -30,6 +31,7 @@ public abstract class AbstractInterpreterTest extends AbstractTypeVisitorTest { protected CombineExpressionsWithLiteralsInterpreter interpreter; protected CombineExpressionsWithLiteralsScopesGenitorDelegator delegator; + @BeforeEach public void init() { LogStub.init(); Log.clearFindings(); @@ -109,7 +111,10 @@ protected void testValidExpression(String expr, MIValue expected) { System.out.println(e.getMessage()); } assertNotNull(interpretationResult); - assertTrue(Log.getFindings().isEmpty()); + if (!Log.getFindings().isEmpty()) { + Log.printFindings(); + fail(); + } if (expected.isBoolean()) { assertTrue(interpretationResult.isBoolean()); assertEquals(expected.asBoolean(), interpretationResult.asBoolean()); diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java index c4301a1188..dbd5033483 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java @@ -599,7 +599,6 @@ protected static Stream starEqualsExpression() { "roofEqualsExpression", "slashEqualsExpression", "starEqualsExpression" }) public void testInterpreter(String expression, MIValue result) { - init(); if (result == null) { testInvalidExpression(expression); } else { diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java index b2df595ff0..13d81303a2 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java @@ -3,16 +3,10 @@ import de.monticore.expressions.AbstractInterpreterTest; import de.monticore.interpreter.MIValueFactory; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class CommonExpressionsInterpreterTest extends AbstractInterpreterTest { - @BeforeEach - public void before() { - init(); - } - @Test public void testInterpretPlusExpression() { testInvalidExpression("true + false"); diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java new file mode 100644 index 0000000000..26d575fbe7 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java @@ -0,0 +1,27 @@ +package de.monticore.expressions.lambdaexpressions; + +import de.monticore.expressions.AbstractInterpreterTest; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static de.monticore.interpreter.MIValueFactory.createValue; + +public class LambdaExpressionsInterpreterTest extends AbstractInterpreterTest { + + @Test + public void testSimpleLambda() throws IOException { + testValidExpression("(() -> 1)()", createValue(1)); + testValidExpression("(() -> () -> 2)()()", createValue(2)); + testValidExpression("((long a) -> a + 1)(41L)", createValue(42L)); + + testValidExpression("((long a) -> (byte b) -> a + b)(41L)((byte)28)", createValue(69L)); + testValidExpression("((long a, byte b) -> a + b)(41L,(byte)28)", createValue(69L)); + + testValidExpression("(() -> () -> (int a) -> () -> () -> a)()()(42)()()", createValue(42)); + + testValidExpression("((byte b) -> (char c) -> b + c)((byte)25)('a') == 'z'", createValue(true)); + } + +} + diff --git a/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java b/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java index 3e5345deda..01229d32a6 100644 --- a/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java +++ b/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java @@ -2,7 +2,7 @@ package de.monticore.ast; -import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.IModelInterpreter; import de.monticore.interpreter.MIValue; import de.monticore.symboltable.IScope; import de.monticore.visitor.ITraverser; @@ -679,7 +679,7 @@ default void accept (ITraverser visitor) { visitor.handle(this); } - default MIValue evaluate(ModelInterpreter interpreter) { + default MIValue evaluate(IModelInterpreter interpreter) { return interpreter.interpret(this); } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java b/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java new file mode 100644 index 0000000000..0872ea162f --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java @@ -0,0 +1,15 @@ +package de.monticore.interpreter; + +import de.monticore.ast.ASTNode; +import de.monticore.interpreter.values.ErrorMIValue; +import de.se_rwth.commons.logging.Log; + +public interface IModelInterpreter { + + default MIValue interpret(ASTNode n) { + String errorMsg = "No implementation of ASTNode of type " + n.toString(); + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java deleted file mode 100644 index 3e0f4d784e..0000000000 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java +++ /dev/null @@ -1,28 +0,0 @@ -package de.monticore.interpreter.values; - -import de.monticore.interpreter.MIScope; -import de.monticore.interpreter.MIValue; - -import java.util.List; - -abstract public class FunctionMIValue implements MIValue { - - protected MIScope parentScope; - - public FunctionMIValue(MIScope parentScope) { - this.parentScope = parentScope; - } - - @Override - public boolean isFunction() { - return true; - } - - /* - TODO MIFunctionSymbol, MIMethodSymbol, MILambdaValue - */ - - abstract public MIValue execute(List arguments); - - -} From 9d7bf71fd8a6a592064372ba2dbed7bd8283c275 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Mon, 10 Mar 2025 14:36:16 +0100 Subject: [PATCH 07/37] Added load/store for functions --- .../interpreter/InterpreterConstants.java | 4 +- .../interpreter/InterpreterDecorator.java | 31 ++++--- .../interpreter/InterpreterDecoratorTest.java | 48 +++++++++-- .../AssignmentExpressionsInterpreter.java | 84 +++++++++---------- .../_visitor/ExpressionsBasisInterpreter.java | 20 +++-- .../de/monticore/interpreter/MIScope.java | 54 ++++++++---- .../interpreter/ModelInterpreter.java | 22 +++-- .../de/monticore/types3/AbstractTypeTest.java | 2 - .../interpreter/values/ErrorMIValue.java | 4 + 9 files changed, 183 insertions(+), 86 deletions(-) diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java index 36979834f4..72348ad70b 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterConstants.java @@ -13,13 +13,15 @@ public final class InterpreterConstants { public static final String INTERPRETER_SCOPE_FULLNAME = "de.monticore.interpreter.MIScope"; public static final String VALUE_FULLNAME = "de.monticore.interpreter.MIValue"; + public static final String FUNCTION_VALUE_FULLNAME = "de.monticore.interpreter.values.FunctionMIValue"; - public static final String NOT_A_VALUE_FULLNAME = "de.monticore.interpreter.values.NotAValue"; public static final String NODE_TYPE = "de.monticore.ast.ASTNode"; public static final String NODE_PARAMETER = "node"; public static final String SYMBOL_FULLNAME = "de.monticore.symboltable.ISymbol"; + public static final String VARIABLE_SYMBOL_FULLNAME = "de.monticore.symbols.basicsymbols._symboltable.VariableSymbol"; + public static final String FUNCTION_SYMBOL_FULLNAME = "de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol"; } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java index 8f516f6b7f..e9f2543cc9 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java @@ -132,22 +132,33 @@ public List createMapMembers() { mcTypeFacade.createBasicGenericTypeOf("java.util.Stack", INTERPRETER_SCOPE_FULLNAME), "scopeCallstack")); - ASTCDParameter symbolParameter = cdParameterFacade.createParameter(SYMBOL_FULLNAME, "symbol"); + ASTCDParameter variableSymbolParameter = cdParameterFacade.createParameter(VARIABLE_SYMBOL_FULLNAME, "symbol"); + ASTCDParameter functionSymbolParameter = cdParameterFacade.createParameter(FUNCTION_SYMBOL_FULLNAME, "symbol"); ASTCDParameter valueParameter = cdParameterFacade.createParameter(VALUE_FULLNAME, "value"); + ASTCDParameter functionValueParameter = cdParameterFacade.createParameter(FUNCTION_VALUE_FULLNAME, "value"); + + ASTCDMethod declareFuncMethod = cdMethodFacade.createMethod( + PUBLIC.build(), "declareFunction", functionSymbolParameter, functionValueParameter); + this.replaceTemplate(EMPTY_BODY, declareFuncMethod, new StringHookPoint("getRealThis().getCurrentScope().declareFunction(symbol, value);")); + members.add(declareFuncMethod); + + ASTCDMethod loadFuncMethod = cdMethodFacade.createMethod(PUBLIC.build(), VALUE_FULLNAME, "loadFunction", functionSymbolParameter); + this.replaceTemplate(EMPTY_BODY, loadFuncMethod, new StringHookPoint("return getRealThis().getCurrentScope().loadFunction(symbol);")); + members.add(loadFuncMethod); ASTCDMethod declareVarMethod = cdMethodFacade.createMethod( - PUBLIC.build(), "declareVariable", symbolParameter, valueParameter); + PUBLIC.build(), "declareVariable", variableSymbolParameter, valueParameter); this.replaceTemplate(EMPTY_BODY, declareVarMethod, new StringHookPoint("getRealThis().getCurrentScope().declareVariable(symbol, value);")); members.add(declareVarMethod); - ASTCDMethod storeMethod = cdMethodFacade.createMethod( - PUBLIC.build(), "store", symbolParameter, valueParameter); - this.replaceTemplate(EMPTY_BODY, storeMethod, new StringHookPoint("getRealThis().getCurrentScope().store(symbol, value);")); - members.add(storeMethod); - - ASTCDMethod loadMethod = cdMethodFacade.createMethod(PUBLIC.build(), VALUE_FULLNAME, "load", symbolParameter); - this.replaceTemplate(EMPTY_BODY, loadMethod, new StringHookPoint("return getRealThis().getCurrentScope().load(symbol);")); - members.add(loadMethod); + ASTCDMethod loadVarMethod = cdMethodFacade.createMethod(PUBLIC.build(), VALUE_FULLNAME, "loadVariable", variableSymbolParameter); + this.replaceTemplate(EMPTY_BODY, loadVarMethod, new StringHookPoint("return getRealThis().getCurrentScope().loadVariable(symbol);")); + members.add(loadVarMethod); + + ASTCDMethod storeVarMethod = cdMethodFacade.createMethod( + PUBLIC.build(), "storeVariable", variableSymbolParameter, valueParameter); + this.replaceTemplate(EMPTY_BODY, storeVarMethod, new StringHookPoint("getRealThis().getCurrentScope().storeVariable(symbol, value);")); + members.add(storeVarMethod); ASTCDMethod getter = cdMethodFacade.createMethod( PUBLIC.build(), diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index e62995861d..6bbdd59f09 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -42,7 +42,7 @@ public void before() { @Test public void testMethodCount() { - assertEquals(8, decoratedClass.getCDMethodList().size()); + assertEquals(10, decoratedClass.getCDMethodList().size()); } @Test @@ -118,6 +118,42 @@ public void testRealThisMethods() { setMethod.getCDParameter(0).getName()); assertTrue(setMethod.getMCReturnType().isPresentMCVoidType()); } + + @Test + public void testFunctionMethods() { + Optional optDeclareMethod = decoratedClass.getCDMethodList() + .stream() + .filter(m -> m.getName().equals("declareFunction")) + .findAny(); + + assertTrue(optDeclareMethod.isPresent()); + ASTCDMethod declareMethod = optDeclareMethod.get(); + + assertTrue(declareMethod.getMCReturnType().isPresentMCVoidType()); + assertEquals(2, declareMethod.getCDParameterList().size()); + assertEquals("symbol", declareMethod.getCDParameter(0).getName()); + assertEquals(InterpreterConstants.FUNCTION_SYMBOL_FULLNAME, + declareMethod.getCDParameter(0).getMCType().printType()); + assertEquals("value", declareMethod.getCDParameter(1).getName()); + assertEquals(InterpreterConstants.FUNCTION_VALUE_FULLNAME, + declareMethod.getCDParameter(1).getMCType().printType()); + + Optional optLoadMethod = decoratedClass.getCDMethodList() + .stream() + .filter(m -> m.getName().equals("loadFunction")) + .findAny(); + + assertTrue(optLoadMethod.isPresent()); + ASTCDMethod loadMethod = optLoadMethod.get(); + + assertEquals(InterpreterConstants.VALUE_FULLNAME, + loadMethod.getMCReturnType().printType()); + assertEquals(1, loadMethod.getCDParameterList().size()); + assertEquals(InterpreterConstants.FUNCTION_SYMBOL_FULLNAME, + loadMethod.getCDParameter(0).getMCType().printType()); + assertEquals("symbol", + loadMethod.getCDParameter(0).getName()); + } @Test public void testVariableMethods() { @@ -132,7 +168,7 @@ public void testVariableMethods() { assertTrue(declareMethod.getMCReturnType().isPresentMCVoidType()); assertEquals(2, declareMethod.getCDParameterList().size()); assertEquals("symbol", declareMethod.getCDParameter(0).getName()); - assertEquals(InterpreterConstants.SYMBOL_FULLNAME, + assertEquals(InterpreterConstants.VARIABLE_SYMBOL_FULLNAME, declareMethod.getCDParameter(0).getMCType().printType()); assertEquals("value", declareMethod.getCDParameter(1).getName()); assertEquals(InterpreterConstants.VALUE_FULLNAME, @@ -140,7 +176,7 @@ public void testVariableMethods() { Optional optStoreMethod = decoratedClass.getCDMethodList() .stream() - .filter(m -> m.getName().equals("store")) + .filter(m -> m.getName().equals("storeVariable")) .findAny(); assertTrue(optStoreMethod.isPresent()); @@ -149,7 +185,7 @@ public void testVariableMethods() { assertTrue(storeMethod.getMCReturnType().isPresentMCVoidType()); assertEquals(2, storeMethod.getCDParameterList().size()); assertEquals("symbol", storeMethod.getCDParameter(0).getName()); - assertEquals(InterpreterConstants.SYMBOL_FULLNAME, + assertEquals(InterpreterConstants.VARIABLE_SYMBOL_FULLNAME, storeMethod.getCDParameter(0).getMCType().printType()); assertEquals("value", storeMethod.getCDParameter(1).getName()); assertEquals(InterpreterConstants.VALUE_FULLNAME, @@ -157,7 +193,7 @@ public void testVariableMethods() { Optional optLoadMethod = decoratedClass.getCDMethodList() .stream() - .filter(m -> m.getName().equals("load")) + .filter(m -> m.getName().equals("loadVariable")) .findAny(); assertTrue(optLoadMethod.isPresent()); @@ -166,7 +202,7 @@ public void testVariableMethods() { assertEquals(InterpreterConstants.VALUE_FULLNAME, loadMethod.getMCReturnType().printType()); assertEquals(1, loadMethod.getCDParameterList().size()); - assertEquals(InterpreterConstants.SYMBOL_FULLNAME, + assertEquals(InterpreterConstants.VARIABLE_SYMBOL_FULLNAME, loadMethod.getCDParameter(0).getMCType().printType()); assertEquals("symbol", loadMethod.getCDParameter(0).getName()); diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java index eb1017596b..2fbd83aaff 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java @@ -8,7 +8,7 @@ import de.monticore.interpreter.MIValue; import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.symboltable.ISymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; @@ -35,45 +35,45 @@ public AssignmentExpressionsInterpreter() { public MIValue interpret(ASTIncSuffixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); - Optional symbol = type.getSourceInfo().getSourceSymbol(); + Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - MIValue value = load(symbol.get()); + MIValue value = loadVariable(symbol.get()); if (value.isError()) return value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { MIValue res = createValue((byte)(value.asByte() + 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { MIValue res = createValue((short)(value.asShort() + 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { MIValue res = createValue((char)(value.asChar() + 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.INT)) { MIValue res = createValue(value.asInt() + 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.LONG)) { MIValue res = createValue(value.asLong() + 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { MIValue res = createValue(value.asFloat() + 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { MIValue res = createValue(value.asDouble() + 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } } @@ -87,45 +87,45 @@ public MIValue interpret(ASTIncSuffixExpression n) { public MIValue interpret(ASTIncPrefixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); - Optional symbol = type.getSourceInfo().getSourceSymbol(); + Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - MIValue value = load(symbol.get()); + MIValue value = loadVariable(symbol.get()); if (value.isError()) return value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { MIValue res = createValue((byte)(value.asByte() + 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { MIValue res = createValue((short)(value.asShort() + 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { MIValue res = createValue((char)(value.asChar() + 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.INT)) { MIValue res = createValue(value.asInt() + 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.LONG)) { MIValue res = createValue(value.asLong() + 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { MIValue res = createValue(value.asFloat() + 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { MIValue res = createValue(value.asDouble() + 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } } @@ -139,45 +139,45 @@ public MIValue interpret(ASTIncPrefixExpression n) { public MIValue interpret(ASTDecSuffixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); - Optional symbol = type.getSourceInfo().getSourceSymbol(); + Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - MIValue value = load(symbol.get()); + MIValue value = loadVariable(symbol.get()); if (value.isError()) return value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { MIValue res = createValue((byte)(value.asByte() - 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { MIValue res = createValue((short)(value.asShort() - 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { MIValue res = createValue((char)(value.asChar() - 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.INT)) { MIValue res = createValue(value.asInt() - 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.LONG)) { MIValue res = createValue(value.asLong() - 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { MIValue res = createValue(value.asFloat() - 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { MIValue res = createValue(value.asDouble() - 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return value; } } @@ -191,45 +191,45 @@ public MIValue interpret(ASTDecSuffixExpression n) { public MIValue interpret(ASTDecPrefixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); - Optional symbol = type.getSourceInfo().getSourceSymbol(); + Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - MIValue value = load(symbol.get()); + MIValue value = loadVariable(symbol.get()); if (value.isError()) return value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { MIValue res = createValue((byte)(value.asByte() - 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { MIValue res = createValue((short)(value.asShort() - 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { MIValue res = createValue((char)(value.asChar() - 1)); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.INT)) { MIValue res = createValue(value.asInt() - 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.LONG)) { MIValue res = createValue(value.asLong() - 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { MIValue res = createValue(value.asFloat() - 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { MIValue res = createValue(value.asDouble() - 1); - store(symbol.get(), res); + storeVariable(symbol.get(), res); return res; } } @@ -242,7 +242,7 @@ public MIValue interpret(ASTDecPrefixExpression n) { public MIValue interpret(ASTAssignmentExpression n) { ASTExpression leftExpr = n.getLeft(); SymTypeExpression leftType = TypeCheck3.typeOf(leftExpr); - Optional leftSymbol = leftType.getSourceInfo().getSourceSymbol(); + Optional leftSymbol = leftType.getSourceInfo().getSourceSymbol().map(symbol -> (VariableSymbol)symbol); if (leftSymbol.isEmpty()) { String errorMsg = "Unknown variable symbol detected"; Log.error(errorMsg); @@ -259,7 +259,7 @@ public MIValue interpret(ASTAssignmentExpression n) { // no operation if (operator == EQUALS) { if (leftType.deepEquals(rightType)) { - store(leftSymbol.get(), rightValue); + storeVariable(leftSymbol.get(), rightValue); return rightValue; } @@ -277,11 +277,11 @@ public MIValue interpret(ASTAssignmentExpression n) { return new ErrorMIValue(errorMsg); } - store(leftSymbol.get(), rightValue); + storeVariable(leftSymbol.get(), rightValue); return rightValue; } - MIValue leftValue = load(leftSymbol.get()); + MIValue leftValue = loadVariable(leftSymbol.get()); if (leftValue.isError()) return leftValue; MIValue resultValue; @@ -401,7 +401,7 @@ public MIValue interpret(ASTAssignmentExpression n) { if (resultValue.isError()) return resultValue; - store(leftSymbol.get(), resultValue); + storeVariable(leftSymbol.get(), resultValue); return resultValue; } } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java index ce422de4da..e04001b65f 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java @@ -6,7 +6,8 @@ import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.values.ErrorMIValue; -import de.monticore.symboltable.ISymbol; +import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; @@ -26,14 +27,23 @@ public ExpressionsBasisInterpreter(ModelInterpreter realThis) { @Override public MIValue interpret(ASTNameExpression n) { SymTypeExpression type = TypeCheck3.typeOf(n); - Optional symbol = type.getSourceInfo().getSourceSymbol(); + if (type.isFunctionType() && type.asFunctionType().hasSymbol()) { + Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (FunctionSymbol)s); + if (symbol.isEmpty()) { + String errorMsg = "Cannot resolve function '" + n.getName() + "'."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + return loadFunction(symbol.get()); + } + + Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { - String errorMsg = "Unknown variable symbol detected"; + String errorMsg = "Cannot resolve variable '" + n.getName() + "'."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - return load(symbol.get()); + return loadVariable(symbol.get()); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java index c12cadcd84..c60b9cef40 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java @@ -1,7 +1,9 @@ package de.monticore.interpreter; import de.monticore.interpreter.values.ErrorMIValue; -import de.monticore.symboltable.ISymbol; +import de.monticore.interpreter.values.FunctionMIValue; +import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.se_rwth.commons.logging.Log; import java.util.HashMap; @@ -9,7 +11,8 @@ public class MIScope { - protected Map contextMap = new HashMap<>(); + protected Map functionMap = new HashMap<>(); + protected Map variableMap = new HashMap<>(); protected MIScope parent; @@ -21,32 +24,55 @@ public MIScope(MIScope parent) { this.parent = parent; } - public void declareVariable(ISymbol symbol, MIValue value) { - if (contextMap.containsKey(symbol)) { + public void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { + if (functionMap.containsKey(symbol)) { + Log.error("Function was already declared"); + } + this.functionMap.put(symbol, value); + } + + public MIValue loadFunction(FunctionSymbol symbol) { + FunctionMIValue value = functionMap.get(symbol); + if (value != null) { + return value; + } + + if (parent != null) { + return parent.loadFunction(symbol); + } + + String errorMsg = "Failed to load Function by Symbol. Could not find Symbol in the current or any parent scope"; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + public void declareVariable(VariableSymbol symbol, MIValue value) { + if (variableMap.containsKey(symbol)) { Log.error("Variable was already declared"); } - this.contextMap.put(symbol, value); + this.variableMap.put(symbol, value); } - public MIValue load(ISymbol symbol) { - MIValue value = contextMap.get(symbol); + public MIValue loadVariable(VariableSymbol symbol) { + MIValue value = variableMap.get(symbol); if (value != null) { return value; } if (parent != null) { - return parent.load(symbol); + return parent.loadVariable(symbol); } - Log.error("Failed to load Value of Symbol. Could not find Symbol in the current or any parent scope"); - return new ErrorMIValue("Failed to load Value of Symbol. Could not find Symbol in the current or any parent scope"); + String errorMsg = "Failed to load Variable by Symbol. Could not find Symbol in the current or any parent scope"; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); } - public void store(ISymbol symbol, MIValue value) { - if (contextMap.containsKey(symbol)) { - contextMap.put(symbol, value); + public void storeVariable(VariableSymbol symbol, MIValue value) { + if (variableMap.containsKey(symbol)) { + variableMap.put(symbol, value); } else if (parent != null){ - parent.store(symbol, value); + parent.storeVariable(symbol, value); } else { Log.error("Failed to store Value in Symbol. Could not find Symbol in the current or any parent scope"); } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java index d50a9c68a1..e8e712e187 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java @@ -1,7 +1,9 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter; -import de.monticore.symboltable.ISymbol; +import de.monticore.interpreter.values.FunctionMIValue; +import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; public interface ModelInterpreter extends IModelInterpreter { @@ -14,16 +16,24 @@ public interface ModelInterpreter extends IModelInterpreter { void pushScope(MIScope scope); void popScope(); - default void declareVariable(ISymbol symbol, MIValue value) { + default void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { + getCurrentScope().declareFunction(symbol, value); + } + + default MIValue loadFunction(FunctionSymbol symbol) { + return getRealThis().loadFunction(symbol); + } + + default void declareVariable(VariableSymbol symbol, MIValue value) { getCurrentScope().declareVariable(symbol, value); } - default MIValue load(ISymbol symbol) { - return getRealThis().load(symbol); + default MIValue loadVariable(VariableSymbol symbol) { + return getRealThis().loadVariable(symbol); } - default void store (ISymbol symbol, MIValue value){ - getRealThis().store(symbol, value); + default void storeVariable (VariableSymbol symbol, MIValue value){ + getRealThis().storeVariable(symbol, value); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java index 9ccbb28b6f..4ae94c38f7 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java @@ -9,8 +9,6 @@ import java.util.stream.Collectors; -import static org.junit.Assert.assertTrue; - public class AbstractTypeTest { @BeforeEach diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java index 4a476873f9..9cf6e0c451 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java @@ -15,4 +15,8 @@ public boolean isError() { return true; } + public String getMessage() { + return message; + } + } From 14923be0209973aba282e2f3f7c79b1fe3325662 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Tue, 24 Jun 2025 13:05:25 +0200 Subject: [PATCH 08/37] Value -> MIValue --- .../cd2java/_symboltable/SymbolTableConstants.java | 2 +- .../symbolDeSer/Deserialize4SymbolDeSer.ftl | 2 +- .../symbol/SymbolBuilderDecoratorTest.java | 2 +- .../_symboltable/symbol/SymbolDecoratorTest.java | 2 +- .../symbol/SymbolSurrogateBuilderDecoratorTest.java | 2 +- .../symbol/SymbolSurrogateDecoratorTest.java | 2 +- .../_symboltable/BasicSymbolsStereoinfoDeSer.java | 4 ++-- .../BasicSymbolsStereoinfoDeSerTest.java | 6 +++--- .../main/java/de/monticore/symboltable/ISymbol.java | 4 ++-- .../symboltable/SymbolWithScopeOfUnknownKind.java | 6 +++--- .../SymbolWithScopeOfUnknownKindBuilder.java | 10 +++++----- .../symboltable/stereotypes/StereoinfoDeSer.java | 12 ++++++------ .../symboltable/stereotypes/StereoinfoDeSerTest.java | 4 ++-- 13 files changed, 29 insertions(+), 29 deletions(-) diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableConstants.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableConstants.java index a182ef2a91..8eb9ef6007 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableConstants.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableConstants.java @@ -88,7 +88,7 @@ private SymbolTableConstants() { public static final String I_STEREOTYPE_REFERENCE = "de.monticore.symboltable.stereotypes.IStereotypeReference"; - public static final String INTERPRETER_VALUE = "de.monticore.interpreter.Value"; + public static final String INTERPRETER_VALUE = "de.monticore.interpreter.MIValue"; /** * attribute names diff --git a/monticore-generator/src/main/resources/_symboltable/serialization/symbolDeSer/Deserialize4SymbolDeSer.ftl b/monticore-generator/src/main/resources/_symboltable/serialization/symbolDeSer/Deserialize4SymbolDeSer.ftl index 81faa30695..7c394ea029 100644 --- a/monticore-generator/src/main/resources/_symboltable/serialization/symbolDeSer/Deserialize4SymbolDeSer.ftl +++ b/monticore-generator/src/main/resources/_symboltable/serialization/symbolDeSer/Deserialize4SymbolDeSer.ftl @@ -11,7 +11,7 @@ ${tc.signature("symTabMill", "symbolFullName", "symbolSimpleName","symbolRuleAtt } if (symbolJson.hasArrayMember(de.monticore.symboltable.serialization.JsonDeSers.STEREO_INFO)) { for (de.monticore.symboltable.serialization.json.JsonElement stereoinfoJson : symbolJson.getArrayMember(de.monticore.symboltable.serialization.JsonDeSers.STEREO_INFO)) { - java.util.Map.Entry> stereoinfo = de.monticore.symboltable.stereotypes.StereoinfoDeSer.deserialize(stereoinfoJson, scope); + java.util.Map.Entry> stereoinfo = de.monticore.symboltable.stereotypes.StereoinfoDeSer.deserialize(stereoinfoJson, scope); if (stereoinfo.getValue().isPresent()) { builder.addStereoinfo(stereoinfo.getKey(), stereoinfo.getValue().get()); } else { diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolBuilderDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolBuilderDecoratorTest.java index e670afbe3d..102f430fe4 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolBuilderDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolBuilderDecoratorTest.java @@ -50,7 +50,7 @@ public class SymbolBuilderDecoratorTest extends DecoratorTestCase { private static final String I_STEREOTYPE_REF = "de.monticore.symboltable.stereotypes.IStereotypeReference"; - private static final String VALUE = "de.monticore.interpreter.Value"; + private static final String VALUE = "de.monticore.interpreter.MIValue"; @Before public void setup() { diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecoratorTest.java index c9d966c082..90f8237bda 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecoratorTest.java @@ -67,7 +67,7 @@ public class SymbolDecoratorTest extends DecoratorTestCase { private static final String I_STEREOTYPE_REF = "de.monticore.symboltable.stereotypes.IStereotypeReference"; - private static final String VALUE = "de.monticore.interpreter.Value"; + private static final String VALUE = "de.monticore.interpreter.MIValue"; private static final String I_AUTOMATON_SCOPE = "de.monticore.codegen.symboltable.automatonsymbolcd._symboltable.IAutomatonSymbolCDScope"; diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateBuilderDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateBuilderDecoratorTest.java index c240f344cb..a1231c291b 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateBuilderDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateBuilderDecoratorTest.java @@ -46,7 +46,7 @@ public class SymbolSurrogateBuilderDecoratorTest extends DecoratorTestCase { private static final String I_STEREOTYPE_REF = "de.monticore.symboltable.stereotypes.IStereotypeReference"; - private static final String VALUE = "de.monticore.interpreter.Value"; + private static final String VALUE = "de.monticore.interpreter.MIValue"; @Before public void setUp() { diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecoratorTest.java index 8eaeddd3e7..786c2ed3c2 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecoratorTest.java @@ -52,7 +52,7 @@ public class SymbolSurrogateDecoratorTest extends DecoratorTestCase { private static final String I_STEREOTYPE_REF = "de.monticore.symboltable.stereotypes.IStereotypeReference"; - private static final String VALUE = "de.monticore.interpreter.Value"; + private static final String VALUE = "de.monticore.interpreter.MIValue"; private static final String I_AUTOMATON_SCOPE = "de.monticore.codegen.symboltable.automatonsymbolcd._symboltable.IAutomatonSymbolCDScope"; diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsStereoinfoDeSer.java b/monticore-grammar/src/main/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsStereoinfoDeSer.java index 4e0a99dea7..630dc88d7d 100644 --- a/monticore-grammar/src/main/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsStereoinfoDeSer.java +++ b/monticore-grammar/src/main/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsStereoinfoDeSer.java @@ -1,7 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.symbols.basicsymbols._symboltable; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symboltable.IScope; import de.monticore.symboltable.serialization.json.JsonElement; import de.monticore.symboltable.stereotypes.IStereotypeReference; @@ -22,7 +22,7 @@ public static void init() { } @Override - protected Map.Entry> doDeserialize(JsonElement json, + protected Map.Entry> doDeserialize(JsonElement json, IScope enclosingScope) { if (json.getAsJsonObject().hasMember(STEREO_VALUE)) { Log.errorInternal( diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsStereoinfoDeSerTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsStereoinfoDeSerTest.java index c90ac866cb..5390807d86 100644 --- a/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsStereoinfoDeSerTest.java +++ b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsStereoinfoDeSerTest.java @@ -1,7 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.symbols.basicsymbols._symboltable; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symboltable.serialization.json.JsonElement; import de.monticore.symboltable.serialization.json.JsonElementFactory; @@ -88,7 +88,7 @@ void shouldDeserializeStereoInfoWithoutValueInOtherPackage() { BasicSymbolsMill.globalScope().addSubScope(artifactScope); // When - Map.Entry> deserialized = + Map.Entry> deserialized = StereoinfoDeSer.deserialize(jsonStereoInfo, BasicSymbolsMill.globalScope()); // Then @@ -119,7 +119,7 @@ void shouldDeserializeStereoInfoWithoutValueInSamePackage() { commonScope.add(stereoSym); // When - Map.Entry> deserialized = + Map.Entry> deserialized = StereoinfoDeSer.deserialize(jsonStereoInfo, commonScope); // Then diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/ISymbol.java b/monticore-runtime/src/main/java/de/monticore/symboltable/ISymbol.java index 96f1ee1b3a..95dea55be6 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/ISymbol.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/ISymbol.java @@ -3,7 +3,7 @@ import com.google.common.collect.ImmutableList; import de.monticore.ast.ASTNode; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symboltable.modifiers.AccessModifier; import de.monticore.symboltable.modifiers.BasicAccessModifier; import de.monticore.symboltable.stereotypes.IStereotypeReference; @@ -68,7 +68,7 @@ default AccessModifier getAccessModifier() { * The keys of the map reference {@link IStereotypeSymbol}s, while the values * reference the optionally associated stereovalue. */ - Map> getStereoinfo(); + Map> getStereoinfo(); boolean isPresentAstNode(); diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKind.java b/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKind.java index 37e41a03bf..5ded13eb24 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKind.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKind.java @@ -3,7 +3,7 @@ import java.util.*; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symboltable.modifiers.AccessModifier; import de.monticore.symboltable.stereotypes.IStereotypeReference; import de.monticore.visitor.ITraverser; @@ -20,7 +20,7 @@ public class SymbolWithScopeOfUnknownKind implements IScopeSpanningSymbol { protected AccessModifier accessModifier = AccessModifier.ALL_INCLUSION; - protected Map> stereoinfo = new HashMap<>(); + protected Map> stereoinfo = new HashMap<>(); protected String fullName; @@ -98,7 +98,7 @@ public String getPackageName() { } @Override - public Map> getStereoinfo() { + public Map> getStereoinfo() { return this.stereoinfo; } diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindBuilder.java b/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindBuilder.java index 55bed3424e..d495771fa8 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindBuilder.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindBuilder.java @@ -1,7 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.symboltable; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symboltable.modifiers.AccessModifier; import de.monticore.symboltable.stereotypes.IStereotypeReference; import de.se_rwth.commons.logging.Log; @@ -22,7 +22,7 @@ public class SymbolWithScopeOfUnknownKindBuilder { protected AccessModifier accessModifier; - protected Map> stereoinfo = new HashMap<>(); + protected Map> stereoinfo = new HashMap<>(); protected IScope enclosingScope; @@ -86,7 +86,7 @@ public AccessModifier getAccessModifier() { return this.accessModifier; } - public Map> getStereoinfo() { + public Map> getStereoinfo() { return this.stereoinfo; } @@ -119,7 +119,7 @@ public SymbolWithScopeOfUnknownKindBuilder setAccessModifier(AccessModifier acce } public SymbolWithScopeOfUnknownKindBuilder setStereoinfo( - Map> stereoinfo) { + Map> stereoinfo) { this.stereoinfo = stereoinfo; return this.realBuilder; @@ -131,7 +131,7 @@ public SymbolWithScopeOfUnknownKindBuilder addStereoinfo(IStereotypeReference st } public SymbolWithScopeOfUnknownKindBuilder addStereoinfo(IStereotypeReference stereotype, - Value stereovalue) { + MIValue stereovalue) { this.stereoinfo.put(stereotype, Optional.of(stereovalue)); return this.realBuilder; } diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/stereotypes/StereoinfoDeSer.java b/monticore-runtime/src/main/java/de/monticore/symboltable/stereotypes/StereoinfoDeSer.java index b7c3cf7dc2..c1380e8da8 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/stereotypes/StereoinfoDeSer.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/stereotypes/StereoinfoDeSer.java @@ -1,7 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.symboltable.stereotypes; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symboltable.IScope; import de.monticore.symboltable.serialization.JsonPrinter; import de.monticore.symboltable.serialization.json.JsonElement; @@ -64,7 +64,7 @@ protected static StereoinfoDeSer getInstance() { * See {@link StereoinfoDeSer} on how to configure how this facade behaves. */ public static String printAsJson( - Map.Entry> stereoinfo) { + Map.Entry> stereoinfo) { return printAsJson(stereoinfo.getKey(), stereoinfo.getValue()); } @@ -74,12 +74,12 @@ public static String printAsJson( *

* See {@link StereoinfoDeSer} on how to configure how this facade behaves. */ - public static String printAsJson(IStereotypeReference stereotype, Optional value) { + public static String printAsJson(IStereotypeReference stereotype, Optional value) { return getInstance().doPrintAsJson(stereotype, value); } - protected String doPrintAsJson(IStereotypeReference stereotype, Optional value) { + protected String doPrintAsJson(IStereotypeReference stereotype, Optional value) { if (value.isPresent()) { Log.errorInternal( "0x82401 Internal error: The serialization of values for symbolic stereotypes is not yet " + @@ -110,14 +110,14 @@ protected String doPrintAsJson(IStereotypeReference stereotype, Optional *

* See {@link StereoinfoDeSer} on how to configure how this facade behaves. */ - public static Map.Entry> deserialize( + public static Map.Entry> deserialize( JsonElement json, IScope enclosingScope) { return getInstance().doDeserialize(json, enclosingScope); } @SuppressWarnings("unused") - protected Map.Entry> doDeserialize(JsonElement json, + protected Map.Entry> doDeserialize(JsonElement json, IScope enclosingScope) { Log.errorInternal( "0x82402 Internal error: The deserialization of stereotype annotations is not supported by " + diff --git a/monticore-runtime/src/test/java/de/monticore/symboltable/stereotypes/StereoinfoDeSerTest.java b/monticore-runtime/src/test/java/de/monticore/symboltable/stereotypes/StereoinfoDeSerTest.java index 869af0ed19..a0ecd806cf 100644 --- a/monticore-runtime/src/test/java/de/monticore/symboltable/stereotypes/StereoinfoDeSerTest.java +++ b/monticore-runtime/src/test/java/de/monticore/symboltable/stereotypes/StereoinfoDeSerTest.java @@ -2,7 +2,7 @@ package de.monticore.symboltable.stereotypes; import de.monticore.ast.ASTNode; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symboltable.IScope; import de.monticore.symboltable.modifiers.AccessModifier; import de.se_rwth.commons.logging.LogStub; @@ -71,7 +71,7 @@ public IScope getEnclosingScope() { public void setAccessModifier(AccessModifier accessModifier) { } @Override - public Map> getStereoinfo() { + public Map> getStereoinfo() { return Map.of(); } From ade7049c34729955a534fae925d3e4727d56f940 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Tue, 24 Jun 2025 13:09:23 +0200 Subject: [PATCH 09/37] ILValueRelations fix package --- .../cocos/AssignmentExpressionsOnlyAssignToLValuesCoCo.java | 2 +- .../types/check/types3wrapper/TypeCheck3AsIDerive.java | 2 +- .../types/check/types3wrapper/TypeCheck3AsTypeCalculator.java | 2 +- .../main/java/de/monticore/types3/util/ILValueRelations.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/cocos/AssignmentExpressionsOnlyAssignToLValuesCoCo.java b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/cocos/AssignmentExpressionsOnlyAssignToLValuesCoCo.java index 8a72c9a628..77dbe7ddac 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/cocos/AssignmentExpressionsOnlyAssignToLValuesCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/cocos/AssignmentExpressionsOnlyAssignToLValuesCoCo.java @@ -12,7 +12,7 @@ import de.monticore.expressions.assignmentexpressions._cocos.AssignmentExpressionsASTIncPrefixExpressionCoCo; import de.monticore.expressions.assignmentexpressions._cocos.AssignmentExpressionsASTIncSuffixExpressionCoCo; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; -import de.monticore.expressions.expressionsbasis.types3.util.ILValueRelations; +import de.monticore.types3.util.ILValueRelations; import de.monticore.types3.util.LValueRelations; import de.se_rwth.commons.logging.Log; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/types3wrapper/TypeCheck3AsIDerive.java b/monticore-grammar/src/main/java/de/monticore/types/check/types3wrapper/TypeCheck3AsIDerive.java index 915074fa54..a72b4a05aa 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/types3wrapper/TypeCheck3AsIDerive.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/types3wrapper/TypeCheck3AsIDerive.java @@ -2,7 +2,7 @@ package de.monticore.types.check.types3wrapper; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; -import de.monticore.expressions.expressionsbasis.types3.util.ILValueRelations; +import de.monticore.types3.util.ILValueRelations; import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; import de.monticore.types.check.IDerive; import de.monticore.types.check.TypeCheckResult; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/types3wrapper/TypeCheck3AsTypeCalculator.java b/monticore-grammar/src/main/java/de/monticore/types/check/types3wrapper/TypeCheck3AsTypeCalculator.java index 80bead041d..5fd6555fff 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/types3wrapper/TypeCheck3AsTypeCalculator.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/types3wrapper/TypeCheck3AsTypeCalculator.java @@ -1,7 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types.check.types3wrapper; -import de.monticore.expressions.expressionsbasis.types3.util.ILValueRelations; +import de.monticore.types3.util.ILValueRelations; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/ILValueRelations.java b/monticore-grammar/src/main/java/de/monticore/types3/util/ILValueRelations.java index 07d525e81b..56942843f4 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/ILValueRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/ILValueRelations.java @@ -1,5 +1,5 @@ // (c) https://github.com/MontiCore/monticore -package de.monticore.expressions.expressionsbasis.types3.util; +package de.monticore.types3.util; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; From ff3a910cd8881f8bdd4943d68fef51bc4e5619f5 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Tue, 24 Jun 2025 13:11:24 +0200 Subject: [PATCH 10/37] Java-Objects & better errors --- monticore-grammar/build.gradle | 1 + .../AssignmentExpressionsInterpreter.java | 61 +++--- .../CommonExpressionsInterpreter.java | 111 ++++++++--- .../_visitor/ExpressionsBasisInterpreter.java | 4 +- .../_visitor/UglyExpressionsInterpreter.java | 6 +- .../interpreter/InterpreterUtils.java | 141 +++++++++++++- .../de/monticore/interpreter/MIScope.java | 10 +- .../values/ASTFunctionMIValue.java | 18 +- .../interpreter/values/FunctionMIValue.java | 13 +- .../values/JavaFunctionMIValue.java | 67 +++++++ .../interpreter/values/JavaMethodMIValue.java | 67 +++++++ .../_visitor/OCLExpressionsInterpreter.java | 41 ++++ .../_visitor/SetExpressionsInterpreter.java | 177 ++++++++++++++++++ .../interpreter/IModelInterpreter.java | 2 +- .../de/monticore/interpreter/MIValue.java | 28 ++- .../interpreter/values/BooleanMIValue.java | 9 + .../interpreter/values/ByteMIValue.java | 10 + .../interpreter/values/CharMIValue.java | 10 + .../interpreter/values/DoubleMIValue.java | 10 + .../interpreter/values/ErrorMIValue.java | 10 + .../interpreter/values/FloatMIValue.java | 10 + .../interpreter/values/IntMIValue.java | 10 + .../interpreter/values/LongMIValue.java | 10 + .../interpreter/values/ObjectMIValue.java | 10 + .../interpreter/values/ShortMIValue.java | 10 + .../interpreter/values/VoidMIValue.java | 10 + 26 files changed, 760 insertions(+), 96 deletions(-) create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaFunctionMIValue.java create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaMethodMIValue.java create mode 100644 monticore-grammar/src/main/java/de/monticore/ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreter.java diff --git a/monticore-grammar/build.gradle b/monticore-grammar/build.gradle index 074e2fa927..eb98fe2193 100644 --- a/monticore-grammar/build.gradle +++ b/monticore-grammar/build.gradle @@ -67,6 +67,7 @@ dependencies { api project(':monticore-runtime') implementation "com.google.guava:guava:$guava_version" implementation "org.apache.commons:commons-lang3:$commons_lang3_version" + testImplementation "de.monticore:class2mc:$version" testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_version" testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java index 2fbd83aaff..03ed5daa3a 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java @@ -37,7 +37,7 @@ public MIValue interpret(ASTIncSuffixExpression n) { SymTypeExpression type = TypeCheck3.typeOf(expr); Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { - String errorMsg = "Unknown variable symbol detected"; + String errorMsg = "0x57022 Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -77,7 +77,7 @@ public MIValue interpret(ASTIncSuffixExpression n) { return value; } } - String errorMsg = "Suffix incrementation operation with operand of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57023 Suffix incrementation operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -89,7 +89,7 @@ public MIValue interpret(ASTIncPrefixExpression n) { SymTypeExpression type = TypeCheck3.typeOf(expr); Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { - String errorMsg = "Unknown variable symbol detected"; + String errorMsg = "0x57024 Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -129,7 +129,7 @@ public MIValue interpret(ASTIncPrefixExpression n) { return res; } } - String errorMsg = "Prefix incrementation operation with operand of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57025 Prefix incrementation operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -141,7 +141,7 @@ public MIValue interpret(ASTDecSuffixExpression n) { SymTypeExpression type = TypeCheck3.typeOf(expr); Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { - String errorMsg = "Unknown variable symbol detected"; + String errorMsg = "0x57026 Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -181,7 +181,7 @@ public MIValue interpret(ASTDecSuffixExpression n) { return value; } } - String errorMsg = "Suffix decrementation operation with operand of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57027 Suffix decrementation operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -193,7 +193,7 @@ public MIValue interpret(ASTDecPrefixExpression n) { SymTypeExpression type = TypeCheck3.typeOf(expr); Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { - String errorMsg = "Unknown variable symbol detected"; + String errorMsg = "0x57028 Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -233,7 +233,7 @@ public MIValue interpret(ASTDecPrefixExpression n) { return res; } } - String errorMsg = "Prefix decrementation operation with operand of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57029 Prefix decrementation operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -244,7 +244,7 @@ public MIValue interpret(ASTAssignmentExpression n) { SymTypeExpression leftType = TypeCheck3.typeOf(leftExpr); Optional leftSymbol = leftType.getSourceInfo().getSourceSymbol().map(symbol -> (VariableSymbol)symbol); if (leftSymbol.isEmpty()) { - String errorMsg = "Unknown variable symbol detected"; + String errorMsg = "0x57030 Unknown variable symbol detected"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -264,7 +264,7 @@ public MIValue interpret(ASTAssignmentExpression n) { } if (!SymTypeRelations.isCompatible(leftType, rightType)) { - String errorMsg = "A value of type " + rightType.print() + " can not be writen to a variable of type " + leftType.print() + "."; + String errorMsg = "0x57031 A value of type " + rightType.print() + " can not be writen to a variable of type " + leftType.print() + "."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -272,7 +272,7 @@ public MIValue interpret(ASTAssignmentExpression n) { if (leftType.isPrimitive() && rightType.isPrimitive()) { rightValue = InterpreterUtils.convertToPrimitiveImplicit(leftType.asPrimitive().getPrimitiveName(), rightValue); } else { - String errorMsg = "The implicit conversion from " + rightType.print() + " to " + leftType.print() + " is not supported."; + String errorMsg = "0x57032 The implicit conversion from " + rightType.print() + " to " + leftType.print() + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -291,28 +291,32 @@ public MIValue interpret(ASTAssignmentExpression n) { case AND_EQUALS: { //bitwise and resultType = TypeVisitorOperatorCalculator.binaryAnd(leftType, rightType).get(); resultValue = InterpreterUtils.calcBitwiseLogicalOp(leftValue, rightValue, resultType, - (a, b) -> a & b, (a, b) -> a & b, (a, b) -> a & b, "Bitwise And Assignment"); + (a, b) -> a & b, (a, b) -> a & b, (a, b) -> a & b, + "0x57042 Bitwise And Assignment"); break; } case GTGTEQUALS: { //bitwise rightValue shift resultType = TypeVisitorOperatorCalculator.signedRightShift(leftType, rightType).get(); resultValue = InterpreterUtils.calcShift(leftValue, rightValue, resultType, - (a, b) -> a >> b, (a, b) -> a >> b, "Bitwise Right Shift Assignment"); + (a, b) -> a >> b, (a, b) -> a >> b, + "0x57043 Bitwise Right Shift Assignment"); break; } case GTGTGTEQUALS: { //bitwise rightValue shift resultType = TypeVisitorOperatorCalculator.unsignedRightShift(leftType, rightType).get(); resultValue = InterpreterUtils.calcShift(leftValue, rightValue, resultType, - (a, b) -> a >>> b, (a, b) -> a >>> b, "Logical Right Shift Assignment"); + (a, b) -> a >>> b, (a, b) -> a >>> b, + "0x57044 Logical Right Shift Assignment"); break; } case LTLTEQUALS: { resultType = TypeVisitorOperatorCalculator.leftShift(leftType, rightType).get(); resultValue = InterpreterUtils.calcShift(leftValue, rightValue, resultType, - (a, b) -> a << b, (a, b) -> a << b, "Bitwise Left Shift Assignment"); + (a, b) -> a << b, (a, b) -> a << b, + "0x57045 Bitwise Left Shift Assignment"); break; } @@ -320,7 +324,7 @@ public MIValue interpret(ASTAssignmentExpression n) { resultType = TypeVisitorOperatorCalculator.minus(leftType, rightType).get(); resultValue = InterpreterUtils.calcOp(leftValue, rightValue, resultType, (a, b) -> a - b, (a, b) -> a - b, (a, b) -> a - b, (a, b) -> a - b, - "Minus Assignment"); + "0x57046 Minus Assignment"); break; } @@ -328,14 +332,15 @@ public MIValue interpret(ASTAssignmentExpression n) { resultType = TypeVisitorOperatorCalculator.modulo(leftType, rightType).get(); resultValue = InterpreterUtils.calcOp(leftValue, rightValue, resultType, (a, b) -> a % b, (a, b) -> a % b, (a, b) -> a % b, (a, b) -> a % b, - "Modulo Assignment"); + "0x57047 Modulo Assignment"); break; } case PIPEEQUALS: { resultType = TypeVisitorOperatorCalculator.binaryOr(leftType, rightType).get(); resultValue = InterpreterUtils.calcBitwiseLogicalOp(leftValue, rightValue, resultType, - (a, b) -> a | b, (a, b) -> a | b, (a, b) -> a | b, "Bitwise Or Assignment"); + (a, b) -> a | b, (a, b) -> a | b, (a, b) -> a | b, + "0x57048 Bitwise Or Assignment"); break; } @@ -343,14 +348,15 @@ public MIValue interpret(ASTAssignmentExpression n) { resultType = TypeVisitorOperatorCalculator.plus(leftType, rightType).get(); resultValue = InterpreterUtils.calcOp(leftValue, rightValue, resultType, Integer::sum, Long::sum, Float::sum, Double::sum, - "Plus Assignment"); + "0x57049 Plus Assignment"); break; } case ROOFEQUALS: { //XOR resultType = TypeVisitorOperatorCalculator.binaryXor(leftType, rightType).get(); resultValue = InterpreterUtils.calcBitwiseLogicalOp(leftValue, rightValue, resultType, - (a, b) -> a ^ b, (a, b) -> a ^ b, (a, b) -> a ^ b, "Bitwise Xor Assignment"); + (a, b) -> a ^ b, (a, b) -> a ^ b, (a, b) -> a ^ b, + "0x57050 Bitwise Xor Assignment"); break; } @@ -360,17 +366,17 @@ public MIValue interpret(ASTAssignmentExpression n) { String resultPrimitive = resultType.asPrimitive().getPrimitiveName(); if (rightValue.asDouble() == 0.0) { - String errorMsg = "Division by zero is undefined"; + String errorMsg = "0x57033 Division by zero is undefined"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } resultValue = InterpreterUtils.calcOpPrimitive(leftValue, rightValue, resultPrimitive, (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, - "Division Assignment"); + "0x57051 Division Assignment"); break; } - String errorMsg = "Division Assignment operation with result of type " + resultType + " is not supported."; + String errorMsg = "0x57034 Division Assignment operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -379,12 +385,13 @@ public MIValue interpret(ASTAssignmentExpression n) { resultType = TypeVisitorOperatorCalculator.multiply(leftType, rightType).get(); resultValue = InterpreterUtils.calcOp(leftValue, rightValue, resultType, (a, b) -> a * b, (a, b) -> a * b, (a, b) -> a * b, (a, b) -> a * b, - "Multiplication Assignment"); + "0x57052 Multiplication Assignment"); break; } default: - Log.error("Operator is not defined."); - return new ErrorMIValue("Operator is not defined."); + String errorMsg = "0x57035 Operator is not defined"; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); } if (resultValue.isError()) return resultValue; @@ -394,7 +401,7 @@ public MIValue interpret(ASTAssignmentExpression n) { resultValue = InterpreterUtils.convertToPrimitiveExplicit(resultType.asPrimitive().getPrimitiveName(), leftType.asPrimitive().getPrimitiveName(), resultValue); } else { - String errorMsg = "Cast from " + resultType.print() + " to " + leftType.print() + " is not supported."; + String errorMsg = "0x57036 Cast from " + resultType.print() + " to " + leftType.print() + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index 8d1c58c681..2de9af4ade 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -7,9 +7,11 @@ import de.monticore.interpreter.InterpreterUtils; import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; -import de.monticore.interpreter.values.ErrorMIValue; -import de.monticore.interpreter.values.FunctionMIValue; +import de.monticore.interpreter.values.*; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; +import de.monticore.symboltable.ISymbol; +import de.monticore.symboltable.modifiers.StaticAccessModifier; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypePrimitive; import de.monticore.types3.SymTypeRelations; @@ -18,6 +20,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; import static de.monticore.interpreter.MIValueFactory.createValue; @@ -44,7 +47,7 @@ public SymTypePrimitive getCompatibleType(SymTypePrimitive type1, SymTypePrimiti public MIValue isEqual(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); if (compatibleType == null) { - String errorMsg = "Equality operation with operands ot type '" + leftType.print() + String errorMsg = "0x57000 Equality operation with operands ot type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -69,7 +72,7 @@ public MIValue isEqual(SymTypePrimitive leftType, MIValue left, SymTypePrimitive return createValue(left.asDouble() == right.asDouble()); } - String errorMsg = "Equality operator with operands of type '" + leftType.print() + String errorMsg = "0x57001 Equality operator with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not implemented."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -78,7 +81,7 @@ public MIValue isEqual(SymTypePrimitive leftType, MIValue left, SymTypePrimitive public MIValue subtract(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); if (compatibleType == null) { - String errorMsg = "Greater or Lesser operation with operands ot type '" + leftType.print() + String errorMsg = "0x57002 Greater or Lesser operation with operands ot type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -101,7 +104,7 @@ public MIValue subtract(SymTypePrimitive leftType, MIValue left, SymTypePrimitiv return createValue(left.asDouble() - right.asDouble()); } - String errorMsg = "Greater or Lesser operation with operands of type '" + leftType.print() + String errorMsg = "0x57003 Greater or Lesser operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -115,7 +118,7 @@ public MIValue interpret(ASTPlusExpression node) { if (right.isError()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); - return InterpreterUtils.calcOp(left, right, type, Integer::sum, Long::sum, Float::sum, Double::sum, "Plus"); + return InterpreterUtils.calcOp(left, right, type, Integer::sum, Long::sum, Float::sum, Double::sum, "0x57037 Plus"); } @Override @@ -127,7 +130,7 @@ public MIValue interpret(ASTMinusExpression node) { SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a - b, (a, b) -> a - b, - (a, b) -> a - b, (a, b) -> a - b, "Minus"); + (a, b) -> a - b, (a, b) -> a - b, "0x57038 Minus"); } @Override @@ -139,7 +142,7 @@ public MIValue interpret(ASTMultExpression node) { SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a * b, (a, b) -> a * b, - (a, b) -> a * b, (a, b) -> a * b, "Multiplication"); + (a, b) -> a * b, (a, b) -> a * b, "0x57039 Multiplication"); } @Override @@ -154,17 +157,17 @@ public MIValue interpret(ASTDivideExpression node) { String resultPrimitive = type.asPrimitive().getPrimitiveName(); if (right.asDouble() == 0.0) { - String errorMsg = "Division by zero is undefined"; + String errorMsg = "0x57004 Division by zero is undefined"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } return InterpreterUtils.calcOpPrimitive(left, right, resultPrimitive, (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, - "Division"); + "0x57040 Division"); } - String errorMsg = "Division operation with result of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57005 Division operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -178,7 +181,7 @@ public MIValue interpret(ASTModuloExpression node) { SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a % b, (a, b) -> a % b, - (a, b) -> a % b, (a, b) -> a % b, "Modulo"); + (a, b) -> a % b, (a, b) -> a % b, "0x57041 Modulo"); } @Override @@ -207,7 +210,7 @@ public MIValue interpret(ASTMinusPrefixExpression node) { } } - String errorMsg = "Minus Prefix operation with result of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57006 Minus Prefix operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -222,7 +225,7 @@ public MIValue interpret(ASTPlusPrefixExpression node) { return value; } - String errorMsg = "Minus Prefix operation with result of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57007 Minus Prefix operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -240,7 +243,7 @@ public MIValue interpret(ASTEqualsExpression node) { return isEqual(leftType.asPrimitive(), left, rightType.asPrimitive(), right); } - String errorMsg = "Equality operation with operands of type '" + leftType.print() + String errorMsg = "0x57008 Equality operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -262,7 +265,7 @@ public MIValue interpret(ASTNotEqualsExpression node) { return createValue(!result.asBoolean()); } - String errorMsg = "Inequality operation with operands of type '" + leftType.print() + String errorMsg = "0x57009 Inequality operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -284,7 +287,7 @@ public MIValue interpret(ASTGreaterThanExpression node) { return createValue(result.asDouble() > 0.0); } - String errorMsg = "Greater than operation with operands of type '" + leftType.print() + String errorMsg = "0x57010 Greater than operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -306,7 +309,7 @@ public MIValue interpret(ASTLessThanExpression node) { return createValue(result.asDouble() < 0.0); } - String errorMsg = "Less than operation with operands of type '" + leftType.print() + String errorMsg = "0x57011 Less than operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -328,7 +331,7 @@ public MIValue interpret(ASTGreaterEqualExpression node) { return createValue(result.asDouble() >= 0.0); } - String errorMsg = "Greater equal operation with operands of type '" + leftType.print() + String errorMsg = "0x57012Greater equal operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -350,7 +353,7 @@ public MIValue interpret(ASTLessEqualExpression node) { return createValue(result.asDouble() <= 0.0); } - String errorMsg = "Less equal operation with operands of type '" + leftType.print() + String errorMsg = "0x57013 Less equal operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -378,7 +381,7 @@ public MIValue interpret(ASTBooleanNotExpression node) { } } - String errorMsg = "Bitwise Not operation with operand of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57014 Bitwise Not operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -398,7 +401,7 @@ public MIValue interpret(ASTLogicalNotExpression node) { return createValue(!value.asBoolean()); } - String errorMsg = "Logical Not operation with operand of type '" + type.print() + "' is not supported."; + String errorMsg = "0x57015 Logical Not operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -417,7 +420,7 @@ public MIValue interpret(ASTBooleanAndOpExpression node) { return createValue(left.asBoolean() && right.asBoolean()); } - String errorMsg = "Logical And operation with operands of type '" + leftType.print() + String errorMsg = "0x57016 Logical And operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -437,7 +440,7 @@ public MIValue interpret(ASTBooleanOrOpExpression node) { return createValue(left.asBoolean() || right.asBoolean()); } - String errorMsg = "Logical Or operation with operands of type '" + leftType.print() + String errorMsg = "0x57017 Logical Or operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -460,12 +463,53 @@ public MIValue interpret(ASTConditionalExpression node) { @Override public MIValue interpret(ASTFieldAccessExpression node) { - String errorMsg = "Field Access operation not supported."; + SymTypeExpression type = TypeCheck3.typeOf(node); + Optional symbolOptional = type.getSourceInfo().getSourceSymbol(); + if (symbolOptional.isEmpty()) { + + } else { + ISymbol symbol = symbolOptional.get(); + if (symbol.getAccessModifier().getDimensionToModifierMap() + .getOrDefault(StaticAccessModifier.DIMENSION, StaticAccessModifier.NON_STATIC) == StaticAccessModifier.STATIC) { // static + if (type.isFunctionType()) { // static function + FunctionSymbol funcSymbol = (FunctionSymbol)symbol; + String funcName = funcSymbol.getName(); + String className = funcSymbol.getFullName().substring(0, funcName.length() + 1); // remove '.funcName' + Class classType; + try { + classType = Class.forName(className); + } catch (ClassNotFoundException e) { + String errorMsg = "0x57018 Failed to load class '" + className + "'."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + return new JavaFunctionMIValue(classType, funcName); + } else { // static attribute + // TODO + } + + } else { // non-static + MIValue leftValue = node.getExpression().evaluate(getRealThis()); + if (!leftValue.isObject()) { + String errorMsg = "0x57019 The Field Access operation expected an object as left side."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + // If class-declarations are supported this needs to be expanded + if (type.isFunctionType()) { // method call on object + FunctionSymbol funcSymbol = (FunctionSymbol)symbol; + String name = funcSymbol.getName(); + return new JavaMethodMIValue(leftValue.asObject(), name); + } else { // non-static attribute access + return InterpreterUtils.getObjectAttribute((ObjectMIValue)leftValue, node.getName(), type); + } + } + } + + String errorMsg = "0x57020 Field Access operation not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); -// String expression = CommonExpressionsMill.prettyPrint(node, false); -// Optional symbol = ((IBasicSymbolsScope) node.getEnclosingScope()).resolveVariable(expression); -// return symbol.map(this::load).orElse(new NullValue()); } @Override @@ -481,7 +525,7 @@ public MIValue interpret(ASTCallExpression node) { // evaluate arguments in current scope & put into new scope MIValue value = node.getExpression().evaluate(getRealThis()); if (!value.isFunction()) { - String errorMsg = "Call expression expected a function but got " + TypeCheck3.typeOf(node.getExpression()).print() + "."; + String errorMsg = "0x57021 Call expression expected a function but got " + TypeCheck3.typeOf(node.getExpression()).print() + "."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -491,6 +535,11 @@ public MIValue interpret(ASTCallExpression node) { args.add(argument.evaluate(getRealThis())); } - return ((FunctionMIValue)value).execute(getRealThis(), args); + // cast needed in case of subtyping + SymTypeExpression returnType = TypeCheck3.typeOf(node); + MIValue returnValue = ((FunctionMIValue)value).execute(getRealThis(), args); + return InterpreterUtils.convertImplicit(returnType, returnValue); } + + } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java index e04001b65f..8174fea18d 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java @@ -30,7 +30,7 @@ public MIValue interpret(ASTNameExpression n) { if (type.isFunctionType() && type.asFunctionType().hasSymbol()) { Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (FunctionSymbol)s); if (symbol.isEmpty()) { - String errorMsg = "Cannot resolve function '" + n.getName() + "'."; + String errorMsg = "0x57053 Cannot resolve function '" + n.getName() + "'."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -39,7 +39,7 @@ public MIValue interpret(ASTNameExpression n) { Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { - String errorMsg = "Cannot resolve variable '" + n.getName() + "'."; + String errorMsg = "0x57054 Cannot resolve variable '" + n.getName() + "'."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java index aec3ae7888..8330067a6f 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java @@ -32,7 +32,7 @@ public MIValue interpret(ASTTypeCastExpression node) { afterType.asPrimitive().getPrimitiveName(), value); } - String errorMsg = "Type Cast operation from " + beforeType.print() + " to " + afterType.print() + String errorMsg = "0x57055 Type Cast operation from " + beforeType.print() + " to " + afterType.print() + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); @@ -40,7 +40,7 @@ public MIValue interpret(ASTTypeCastExpression node) { public MIValue convertPrimitive(String fromType, String toType, MIValue value) { if (toType.equals(BasicSymbolsMill.BOOLEAN) || fromType.equals(BasicSymbolsMill.BOOLEAN)) { - String errorMsg = "Cast to or from boolean is not supported."; + String errorMsg = "0x57056 Cast to or from boolean is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -113,7 +113,7 @@ public MIValue convertPrimitive(String fromType, String toType, MIValue value) { return MIValueFactory.createValue(value.asDouble()); } - String errorMsg = "Cast from " + fromType + " to " + toType + " is not supported."; + String errorMsg = "0x57057 Cast from " + fromType + " to " + toType + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java index 7a4b53ad24..2cfb6815bd 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java @@ -1,10 +1,11 @@ package de.monticore.interpreter; -import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.*; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; import de.se_rwth.commons.logging.Log; +import java.lang.reflect.Field; import java.util.function.BiFunction; import java.util.function.BinaryOperator; @@ -107,7 +108,7 @@ public static MIValue calcShift(MIValue v1, MIValue v2, SymTypeExpression result public static MIValue convertToPrimitiveExplicit(String from, String to, MIValue value) { if (to.equals(BasicSymbolsMill.BOOLEAN) || from.equals(BasicSymbolsMill.BOOLEAN)) { - String errorMsg = "Cast to or from boolean is not supported."; + String errorMsg = "0x57060 Cast to or from boolean is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -169,7 +170,7 @@ public static MIValue convertToPrimitiveExplicit(String from, String to, MIValue return createValue(value.asDouble()); } - String errorMsg = "Cast from " + from + " to " + to + " is not supported."; + String errorMsg = "0x57061 Cast from " + from + " to " + to + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -191,9 +192,141 @@ public static MIValue convertToPrimitiveImplicit(String targetType, MIValue valu return createValue(value.asDouble()); } - String errorMsg = "Implicit cast to " + targetType + " is not supported."; + String errorMsg = "0x57062 Implicit cast to " + targetType + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } + public static MIValue convertImplicit(SymTypeExpression targetType, MIValue value) { + if (targetType.isPrimitive()) { + return convertToPrimitiveImplicit(targetType.asPrimitive().getPrimitiveName(), value); + } else { + return value; // everything else is an object or function which is handled by reflection + } + } + + public static MIValue getObjectAttribute(ObjectMIValue object, String attributeName, SymTypeExpression type) { + Field attribute; + try { + attribute = object.getClass().getField(attributeName); + } catch (NoSuchFieldException e) { + String errorMsg = "0x57063 Tried to access attribute '" + attributeName + "' of class '" + + object.getClass().getName() + "'. No such attribute exists."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + try { + if (type.isPrimitive()) { + String typeName = type.asPrimitive().getPrimitiveName(); + if (typeName.equals(BasicSymbolsMill.BOOLEAN)) { + return MIValueFactory.createValue(attribute.getBoolean(object)); + } else if (typeName.equals(BasicSymbolsMill.BYTE)) { + return MIValueFactory.createValue(attribute.getByte(object)); + } else if (typeName.equals(BasicSymbolsMill.SHORT)) { + return MIValueFactory.createValue(attribute.getShort(object)); + } else if (typeName.equals(BasicSymbolsMill.CHAR)) { + return MIValueFactory.createValue(attribute.getChar(object)); + } else if (typeName.equals(BasicSymbolsMill.INT)) { + return MIValueFactory.createValue(attribute.getInt(object)); + } else if (typeName.equals(BasicSymbolsMill.LONG)) { + return MIValueFactory.createValue(attribute.getLong(object)); + } else if (typeName.equals(BasicSymbolsMill.FLOAT)) { + return MIValueFactory.createValue(attribute.getFloat(object)); + } else if (typeName.equals(BasicSymbolsMill.DOUBLE)) { + return MIValueFactory.createValue(attribute.getDouble(object)); + } + + } else if (type.isObjectType()) { + return MIValueFactory.createValue(attribute.get(object)); + } + } catch (IllegalAccessException e) { + String errorMsg = "0x57064 Tried to access attribute '" + attributeName + "' of class '" + + object.getClass().getName() + "'. Attribute is not accessible."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + String errorMsg = "0x57065 Attribute Access operation does not support attributes of type '" + + type.printFullName() + "'."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + public static Class typeOfValue(MIValue value) { + if (value.isBoolean()) { + return boolean.class; + } else if (value.isChar()) { + return char.class; + } else if (value.isByte()) { + return byte.class; + } else if (value.isShort()) { + return short.class; + } else if (value.isInt()) { + return int.class; + } else if (value.isLong()) { + return long.class; + } else if (value.isFloat()) { + return float.class; + } else if (value.isDouble()) { + return double.class; + } else if (value.isObject()) { + return value.asObject().getClass(); + } else if (value.isFunction()) { + // TODO maybe abstract method in FunctionMIValue that builds Function-Object + } + String errorMsg = "0x57066 Failed to get java type of value."; + Log.error(errorMsg); + return null; + } + + public static Object valueToObject(MIValue value) { + if (value.isBoolean()) { + return value.asBoolean(); + } else if (value.isChar()) { + return value.asChar(); + } else if (value.isByte()) { + return value.asByte(); + } else if (value.isShort()) { + return value.asShort(); + } else if (value.isInt()) { + return value.asInt(); + } else if (value.isLong()) { + return value.asLong(); + } else if (value.isFloat()) { + return value.asFloat(); + } else if (value.isDouble()) { + return value.asDouble(); + } else if (value.isObject()) { + return value.asObject(); + } else if (value.isFunction()) { + // TODO maybe abstract method in FunctionMIValue that builds Function-Object + } + String errorMsg = "0x57067 Failed to get java type of value."; + Log.error(errorMsg); + return null; + } + + public static MIValue objectToValue(Object object) { + if (object instanceof Boolean) { + return new BooleanMIValue((Boolean)object); + } else if (object instanceof Character) { + return new CharMIValue((Character)object); + } else if (object instanceof Byte) { + return new ByteMIValue((Byte)object); + } else if (object instanceof Short) { + return new ShortMIValue((Short)object); + } else if (object instanceof Integer) { + return new IntMIValue((Integer)object); + } else if (object instanceof Long) { + return new LongMIValue((Long)object); + } else if (object instanceof Float) { + return new FloatMIValue((Float)object); + } else if (object instanceof Double) { + return new DoubleMIValue((Double)object); + } + + return new ObjectMIValue(object); + } + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java index c60b9cef40..e9d4262ae4 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java @@ -26,7 +26,7 @@ public MIScope(MIScope parent) { public void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { if (functionMap.containsKey(symbol)) { - Log.error("Function was already declared"); + Log.error("0x57068 Function was already declared"); } this.functionMap.put(symbol, value); } @@ -41,14 +41,14 @@ public MIValue loadFunction(FunctionSymbol symbol) { return parent.loadFunction(symbol); } - String errorMsg = "Failed to load Function by Symbol. Could not find Symbol in the current or any parent scope"; + String errorMsg = "0x57069 Failed to load Function by Symbol. Could not find Symbol in the current or any parent scope"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } public void declareVariable(VariableSymbol symbol, MIValue value) { if (variableMap.containsKey(symbol)) { - Log.error("Variable was already declared"); + Log.error("0x57070 Variable was already declared"); } this.variableMap.put(symbol, value); } @@ -63,7 +63,7 @@ public MIValue loadVariable(VariableSymbol symbol) { return parent.loadVariable(symbol); } - String errorMsg = "Failed to load Variable by Symbol. Could not find Symbol in the current or any parent scope"; + String errorMsg = "0x57071 Failed to load Variable by Symbol. Could not find Symbol in the current or any parent scope"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -74,7 +74,7 @@ public void storeVariable(VariableSymbol symbol, MIValue value) { } else if (parent != null){ parent.storeVariable(symbol, value); } else { - Log.error("Failed to store Value in Symbol. Could not find Symbol in the current or any parent scope"); + Log.error("0x57072 Failed to store Value in Symbol. Could not find Symbol in the current or any parent scope"); } } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java index 782b4fede1..781e5ea352 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java @@ -1,20 +1,25 @@ package de.monticore.interpreter.values; import de.monticore.ast.ASTNode; +import de.monticore.interpreter.InterpreterUtils; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.MIScope; import de.monticore.interpreter.ModelInterpreter; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.types.check.SymTypeExpression; import java.util.List; -public class ASTFunctionMIValue extends FunctionMIValue { +public class ASTFunctionMIValue implements FunctionMIValue { + protected MIScope parentScope; + protected List parameterSymbols; protected ASTNode body; public ASTFunctionMIValue(MIScope parentScope, List parameterSymbols, ASTNode body) { - super(parentScope, parameterSymbols); + this.parentScope = parentScope; + this.parameterSymbols = parameterSymbols; this.body = body; } @@ -23,7 +28,14 @@ public MIValue execute(ModelInterpreter interpreter, List arguments) { MIScope newScope = new MIScope(parentScope); for (int i = 0; i < parameterSymbols.size(); i++) { - newScope.declareVariable(parameterSymbols.get(i), arguments.get(i)); + VariableSymbol parameterSymbol = parameterSymbols.get(i); + SymTypeExpression paramType = parameterSymbol.getType(); + + MIValue argument = arguments.get(i); + argument = InterpreterUtils.convertImplicit(paramType, argument); + if (argument.isError()) return argument; + + newScope.declareVariable(parameterSymbol, argument); } interpreter.pushScope(newScope); diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java index 9c3ce41b90..cedd406e51 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java @@ -7,22 +7,13 @@ import java.util.List; -abstract public class FunctionMIValue implements MIValue { - - protected MIScope parentScope; - protected List parameterSymbols; - - public FunctionMIValue(MIScope parentScope, List parameterSymbols) { - this.parentScope = parentScope; - this.parameterSymbols = parameterSymbols; - } +public interface FunctionMIValue extends MIValue { @Override - public boolean isFunction() { + public default boolean isFunction() { return true; } abstract public MIValue execute(ModelInterpreter interpreter, List arguments); - } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaFunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaFunctionMIValue.java new file mode 100644 index 0000000000..67b8e5f677 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaFunctionMIValue.java @@ -0,0 +1,67 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.InterpreterUtils; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.se_rwth.commons.logging.Log; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.stream.Collectors; + +// TODO change to getting method by SymType +public class JavaFunctionMIValue implements FunctionMIValue { + + Class classType; + String functionName; + + public JavaFunctionMIValue(Class classType, String methodName) { + this.classType = classType; + this.functionName = methodName; + } + + @Override + public MIValue execute(ModelInterpreter interpreter, List arguments) { + List> argumentTypes = arguments.stream() + .map(InterpreterUtils::typeOfValue) + .collect(Collectors.toList()); + + Method function; + try { + function = classType.getDeclaredMethod(functionName, argumentTypes.toArray(new Class[0])); + } catch (NoSuchMethodException e) { + StringBuilder sb = new StringBuilder(); + sb.append("0x57058 Failed to find static function '") + .append(functionName) + .append("' in class '") + .append(classType.getName()) + .append("' with arguments of type ("); + for (int i = 0; i < argumentTypes.size(); i++) { + sb.append(argumentTypes.get(i).toString()); + if (i < argumentTypes.size() - 1) { + sb.append(", "); + } + } + sb.append(")."); + Log.error(sb.toString()); + return new ErrorMIValue(sb.toString()); + } + + Object[] argumentObjects = arguments.stream().map(InterpreterUtils::valueToObject).toArray(); + + Object returnObject; + try { + returnObject = function.invoke(null, argumentObjects); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + catch (InvocationTargetException e) { + String errorMsg = e.getMessage(); + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + return InterpreterUtils.objectToValue(returnObject); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaMethodMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaMethodMIValue.java new file mode 100644 index 0000000000..f08fb140c8 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaMethodMIValue.java @@ -0,0 +1,67 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.InterpreterUtils; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.se_rwth.commons.logging.Log; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.stream.Collectors; + +// TODO change to getting method by SymType +public class JavaMethodMIValue implements FunctionMIValue { + Object object; + String methodName; + + public JavaMethodMIValue(Object object, String methodName) { + this.object = object; + this.methodName = methodName; + } + + @Override + public MIValue execute(ModelInterpreter interpreter, List arguments) { + List> argumentTypes = arguments.stream() + .map(InterpreterUtils::typeOfValue) + .collect(Collectors.toList()); + + Method method; + try { + method = object.getClass().getDeclaredMethod(methodName, argumentTypes.toArray(new Class[0])); + } catch (NoSuchMethodException e) { + StringBuilder sb = new StringBuilder(); + sb.append("0x57059 Failed to find method '") + .append(methodName) + .append("' in class '") + .append(object.getClass().getName()) + .append("' with arguments of type ("); + for (int i = 0; i < argumentTypes.size(); i++) { + sb.append(argumentTypes.get(i).toString()); + if (i < argumentTypes.size() - 1) { + sb.append(", "); + } + } + sb.append(")."); + Log.error(sb.toString()); + return new ErrorMIValue(sb.toString()); + } + + Object[] argumentObjects = arguments.stream().map(InterpreterUtils::valueToObject).toArray(); + + Object returnObject; + try { + returnObject = method.invoke(object, argumentObjects); + } catch (IllegalAccessException e) { + String errorMsg = e.getMessage(); + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } catch (InvocationTargetException e) { + String errorMsg = e.getMessage(); + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + return InterpreterUtils.objectToValue(returnObject); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java new file mode 100644 index 0000000000..1dc301014d --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java @@ -0,0 +1,41 @@ +package de.monticore.ocl.oclexpressions._visitor; + +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.ocl.oclexpressions._ast.ASTIfThenElseExpression; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types3.TypeCheck3; +import de.se_rwth.commons.logging.Log; + +public class OCLExpressionsInterpreter extends OCLExpressionsInterpreterTOP { + + public OCLExpressionsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + public OCLExpressionsInterpreter() { + super(); + } + + @Override + public MIValue interpret(ASTIfThenElseExpression expr) { + SymTypeExpression condType = TypeCheck3.typeOf(expr.getCondition()); + if (!(condType.isPrimitive() && condType.asPrimitive().getPrimitiveName().equals(BasicSymbolsMill.BOOLEAN))) { + String errorMsg = "0x57074 The condition of the IfThenElseExpression was expected to be a boolean but was a " + condType.print() + "."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + MIValue conditionValue = expr.getCondition().evaluate(getRealThis()); + if (conditionValue.isError()) return conditionValue; + + if (conditionValue.asBoolean()) { + return expr.getThenExpression().evaluate(getRealThis()); + } else { + return expr.getElseExpression().evaluate(getRealThis()); + } + } + +} diff --git a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreter.java new file mode 100644 index 0000000000..77f74036b8 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreter.java @@ -0,0 +1,177 @@ +package de.monticore.ocl.setexpressions._visitor; + +import de.monticore.interpreter.*; +import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.VoidMIValue; +import de.monticore.ocl.setexpressions._ast.*; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types3.SymTypeRelations; +import de.monticore.types3.TypeCheck3; +import de.se_rwth.commons.logging.Log; + +import java.util.*; + +public class SetExpressionsInterpreter extends SetExpressionsInterpreterTOP { + + public SetExpressionsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + public SetExpressionsInterpreter() { + super(); + } + + @Override + public MIValue interpret(ASTSetValueItem node) { + return node.getExpression().evaluate(getRealThis()); + } + + @Override + public MIValue interpret(ASTSetValueRange node) { + MIValue lowerValue = node.getLowerBound().evaluate(getRealThis()); + MIValue upperValue = node.getUpperBound().evaluate(getRealThis()); + SymTypeExpression lowerType = TypeCheck3.typeOf(node.getLowerBound()); + SymTypeExpression upperType = TypeCheck3.typeOf(node.getUpperBound()); + Optional rangeType = SymTypeRelations.leastUpperBound(lowerType, upperType); + if (rangeType.isEmpty() || rangeType.get().isObscureType() + || !rangeType.get().isPrimitive() || !rangeType.get().asPrimitive().isIntegralType()) { + String errorMsg = "0x57076 Failed to get common type of SetValueRange."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + List values = new ArrayList<>(); + for (long l = lowerValue.asLong(); l <= upperValue.asLong(); l++) { + values.add(InterpreterUtils.convertToPrimitiveExplicit(BasicSymbolsMill.LONG, + rangeType.get().asPrimitive().getPrimitiveName(), MIValueFactory.createValue(l))); + } + + return MIValueFactory.createValue(values); + } + + @Override + public MIValue interpret(ASTSetEnumeration node) { + Collection result; + if (node.isList()) { + result = new ArrayList<>(); + } else { + result = new HashSet<>(); + } + + for (ASTSetCollectionItem setItem : node.getSetCollectionItemList()) { + MIValue element = setItem.evaluate(getRealThis()); + if (setItem instanceof ASTSetValueItem) { + result.add(InterpreterUtils.valueToObject(element)); + } else if (setItem instanceof ASTSetValueRange){ + for (MIValue value : (Collection)element.asObject()) { + result.add(InterpreterUtils.valueToObject(value)); + } + } + } + return MIValueFactory.createValue(result); + } + + @Override + public MIValue interpret(ASTGeneratorDeclaration node) { + String errorMsg = "0x57080 ASTGeneratorDeclaration should not be evaluated directly."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + @Override + public MIValue interpret(ASTSetVariableDeclaration node) { + MIValue value = node.getExpression().evaluate(getRealThis()); + if (value.isError()) return value; + + // should already be declared at start of SetComprehension + getRealThis().storeVariable(node.getSymbol(), value); + return new VoidMIValue(); + } + + private MIValue evaluateSetComprehensionItems(ASTSetComprehension node, int idx, Collection results) { + if (idx >= node.getSetComprehensionItemList().size()) { + MIValue result = node.getLeft().evaluate(getRealThis()); + if (result.isError()) return result; + results.add(InterpreterUtils.valueToObject(result)); + return new VoidMIValue(); + } + ASTSetComprehensionItem item = node.getSetComprehensionItemList().get(idx); + if (item.isPresentGeneratorDeclaration()) { + ASTGeneratorDeclaration generatorDeclaration = item.getGeneratorDeclaration(); + MIValue collection = generatorDeclaration.getExpression().evaluate(getRealThis()); + if (collection.isError()) return collection; + + Collection values = (Collection)collection.asObject(); + for (Object obj : values) { + getRealThis().storeVariable(generatorDeclaration.getSymbol(), + InterpreterUtils.objectToValue(obj)); + MIValue result = evaluateSetComprehensionItems(node, idx + 1, results); + if (result.isError()) return result; + } + return MIValueFactory.createValue(results); + + } else if (item.isPresentExpression()) { + MIValue filterValue = item.getExpression().evaluate(getRealThis()); + if (filterValue.isError()) return filterValue; + if (!filterValue.isBoolean()) { + String errorMsg = "0x57078 SetComprehensionItem of type Expression should return a Boolean. Got " + + filterValue.printType() + " (" + filterValue.printValue() + ")."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + if (!filterValue.asBoolean()) { + return new VoidMIValue(); + } + return evaluateSetComprehensionItems(node, idx+1, results); + + } else if (item.isPresentSetVariableDeclaration()) { + item.getSetVariableDeclaration().evaluate(getRealThis()); + return evaluateSetComprehensionItems(node, idx+1, results); + } + return new ErrorMIValue("0x57079 Encountered unexpected type of SetComprehensionItem."); + } + + @Override + public MIValue interpret(ASTSetComprehension node) { + Collection results; + if (node.isList()) { + results = new ArrayList<>(); + } else { + results = new HashSet<>(); + } + + MIScope scope = new MIScope(getRealThis().getCurrentScope()); + getRealThis().pushScope(scope); + for (ASTSetComprehensionItem item : node.getSetComprehensionItemList()) { + if (item.isPresentSetVariableDeclaration()) { + ASTSetVariableDeclaration variableDeclaration = item.getSetVariableDeclaration(); + getRealThis().declareVariable(variableDeclaration.getSymbol(), null); + } else if (item.isPresentGeneratorDeclaration()) { + ASTGeneratorDeclaration generatorDeclaration = item.getGeneratorDeclaration(); + getRealThis().declareVariable(generatorDeclaration.getSymbol(), null); + } + } + MIValue result = evaluateSetComprehensionItems(node, 0, results); + getRealThis().popScope(); + if (result.isError()) return result; + return MIValueFactory.createValue(results); + } + + @Override + public MIValue interpret(ASTSetComprehensionItem node) { + if (node.isPresentExpression()) { + return node.getExpression().evaluate(getRealThis()); + } else if (node.isPresentSetVariableDeclaration()) { + ASTSetVariableDeclaration variableDeclaration = node.getSetVariableDeclaration(); + MIValue value = variableDeclaration.getExpression().evaluate(getRealThis()); + if (value.isError()) return value; + getRealThis().declareVariable(variableDeclaration.getSymbol(), value); + return new VoidMIValue(); + } + + String errorMsg = "0x57077 Unexpected type of ASTSetComprehensionItem"; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java b/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java index 0872ea162f..1dd74a7787 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java @@ -7,7 +7,7 @@ public interface IModelInterpreter { default MIValue interpret(ASTNode n) { - String errorMsg = "No implementation of ASTNode of type " + n.toString(); + String errorMsg = "0x57073 No implementation of ASTNode of type " + n.toString(); Log.error(errorMsg); return new ErrorMIValue(errorMsg); } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java index b54315ae35..5019f8485f 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java @@ -59,48 +59,58 @@ default boolean isError() { default boolean asBoolean() { - Log.error("0x31251 Type boolean is not applicable for result value."); + Log.error("0x31251 Type boolean is not applicable for " + printType() + " (" + printValue() + ")."); return false; } default byte asByte() { - Log.error("0x31252 Type byte is not applicable for result value."); + Log.error("0x31252 Type byte is not applicable for " + printType() + " (" + printValue() + ")."); return 0; } default char asChar() { - Log.error("0x31253 Type char is not applicable for result value."); + Log.error("0x31253 Type char is not applicable for " + printType() + " (" + printValue() + ")."); return '\0'; } default short asShort() { - Log.error("0x31254 Type short is not applicable for result value."); + Log.error("0x31254 Type short is not applicable for " + printType() + " (" + printValue() + ")."); return 0; } default int asInt() { - Log.error("0x31255 Type int is not applicable for result value."); + Log.error("0x31255 Type int is not applicable for " + printType() + " (" + printValue() + ")."); return 0; } default long asLong() { - Log.error("0x31256 Type long is not applicable for result value."); + Log.error("0x31256 Type long is not applicable for " + printType() + " (" + printValue() + ")."); return 0L; } default float asFloat() { - Log.error("0x31257 Type float is not applicable for result value."); + Log.error("0x31257 Type float is not applicable for " + printType() + " (" + printValue() + ")."); return 0.0f; } default double asDouble() { - Log.error("0x31258 Type double is not applicable for result value."); + Log.error("0x31258 Type double is not applicable for " + printType() + " (" + printValue() + ")."); return 0.0; } default Object asObject() { - Log.error("0x31259 Type object is not applicable for result value."); + Log.error("0x31259 Type object is not applicable for " + printType() + " (" + printValue() + ")."); return null; } + default String printType() { + Log.error("0x31260 printType is not applicable for " + printType() + " (" + printValue() + ")."); + return "UnknownType"; + } + + default String printValue() { + Log.error("0x31261 printValue is not applicable for " + printType() + " (" + printValue() + ")."); + return "UnknownValue"; + } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java index 17f5474f36..a5814c6cb4 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java @@ -21,4 +21,13 @@ public boolean asBoolean() { return value; } + @Override + public String printType() { + return "Boolean"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java index 3e658f67a6..1f6ddf7a96 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java @@ -45,4 +45,14 @@ public double asDouble() { return value; } + @Override + public String printType() { + return "Byte"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java index 180840f169..0a40242db5 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java @@ -40,5 +40,15 @@ public long asLong() { public float asFloat() { return value; } + + @Override + public String printType() { + return "Char"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java index c226dfe8fe..ff270018c9 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java @@ -21,4 +21,14 @@ public double asDouble() { return value; } + @Override + public String printType() { + return "Double"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java index 9cf6e0c451..74bfc02be6 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java @@ -19,4 +19,14 @@ public String getMessage() { return message; } + @Override + public String printType() { + return "Error"; + } + + @Override + public String printValue() { + return message; + } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java index b9322a8a5e..8a0d87158b 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java @@ -25,4 +25,14 @@ public double asDouble() { public float asFloat() { return value; } + + @Override + public String printType() { + return "Float"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java index 152a49d43f..4cef2d3be1 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java @@ -35,4 +35,14 @@ public long asLong() { public float asFloat() { return value; } + + @Override + public String printType() { + return "Integer"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java index c3d5cf91bf..27da60e2d4 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java @@ -30,4 +30,14 @@ public long asLong() { public float asFloat() { return value; } + + @Override + public String printType() { + return "Long"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java index df0015fb6a..0c24fd39f8 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java @@ -20,4 +20,14 @@ public boolean isObject() { public Object asObject() { return value; } + + @Override + public String printType() { + return "Object"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java index e386a1d049..7d565cf8cd 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java @@ -39,5 +39,15 @@ public float asFloat() { public double asDouble() { return value; } + + @Override + public String printType() { + return "Short"; + } + + @Override + public String printValue() { + return String.valueOf(value); + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java index 37f1e16c3f..9165c37f0b 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java @@ -8,4 +8,14 @@ public class VoidMIValue implements MIValue { public boolean isVoid() { return true; } + + @Override + public String printType() { + return "Void"; + } + + @Override + public String printValue() { + return ""; + } } From 149fa6db66122f2f30207528a5c25f9d71bffa64 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Tue, 24 Jun 2025 13:11:44 +0200 Subject: [PATCH 11/37] class2mc --- .../expressions/AbstractInterpreterTest.java | 28 +++++++++++++++---- .../types3/AbstractTypeVisitorTest.java | 14 ++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java index da154b02f4..6239c40f62 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java @@ -8,6 +8,7 @@ import de.monticore.interpreter.MIValue; import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symboltable.ImportStatement; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types3.AbstractTypeVisitorTest; @@ -17,6 +18,8 @@ import org.junit.jupiter.api.BeforeEach; import java.io.IOException; +import java.util.Collections; +import java.util.List; import static de.monticore.interpreter.MIValueFactory.createValue; import static de.monticore.types3.util.DefsTypesForTests.inScope; @@ -101,12 +104,16 @@ protected void initDouble() throws IOException { inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, createValue(3.14)); } - + protected void testValidExpression(String expr, MIValue expected) { + testValidExpression(expr, expected, Collections.emptyList()); + } + + protected void testValidExpression(String expr, MIValue expected, List imports) { Log.clearFindings(); MIValue interpretationResult = null; try { - interpretationResult = parseExpressionAndInterpret(expr); + interpretationResult = parseExpressionAndInterpret(expr, imports); } catch (IOException e) { System.out.println(e.getMessage()); } @@ -145,13 +152,17 @@ protected void testValidExpression(String expr, MIValue expected) { } assertTrue(Log.getFindings().isEmpty()); } - + protected void testInvalidExpression(String expr) { + testInvalidExpression(expr, Collections.emptyList()); + } + + protected void testInvalidExpression(String expr, List imports) { Log.clearFindings(); MIValue interpretationResult; try { - interpretationResult = parseExpressionAndInterpret(expr); + interpretationResult = parseExpressionAndInterpret(expr, imports); } catch (IOException e) { throw new RuntimeException(e); } @@ -160,10 +171,11 @@ protected void testInvalidExpression(String expr) { assertFalse(Log.getFindings().isEmpty()); assertTrue(interpretationResult.isError()); } - - protected MIValue parseExpressionAndInterpret(String expr) throws IOException { + + protected MIValue parseExpressionAndInterpret(String expr, List imports) throws IOException { final ASTExpression ast = parseExpr(expr); generateScopes(ast); + addImports(imports); SymTypeExpression type = TypeCheck3.typeOf(ast); if (type.isObscureType()) { String errorMsg = "Invalid Expression: " + expr; @@ -172,5 +184,9 @@ protected MIValue parseExpressionAndInterpret(String expr) throws IOException { } return interpreter.interpret(ast); } + + protected void addImports(List imports) { + CombineExpressionsWithLiteralsMill.artifactScope().setImportsList(imports); + } } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java index 028d08ceff..21bc361bfa 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java @@ -1,6 +1,8 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3; +import de.monticore.class2mc.Class2MCResolver; +import de.monticore.class2mc.OOClass2MCResolver; import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.expressions.combineexpressionswithliterals._ast.ASTFoo; import de.monticore.expressions.combineexpressionswithliterals._parser.CombineExpressionsWithLiteralsParser; @@ -16,6 +18,7 @@ import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import de.monticore.symbols.oosymbols.OOSymbolsMill; import de.monticore.types.check.IDerive; import de.monticore.types.check.ISynthesize; import de.monticore.types.check.SymTypeExpression; @@ -113,6 +116,16 @@ public void setupDefaultMill() { typeMapTraverser = tc3.getTypeTraverser(); setupSymbolTableCompleter(typeMapTraverser, type4Ast); } + + protected void enableClass2MC() { + BasicSymbolsMill.globalScope().addAdaptedTypeSymbolResolver(new Class2MCResolver()); + } + + protected void enableClass2MC4OO() { + OOClass2MCResolver resolver = new OOClass2MCResolver(); + BasicSymbolsMill.globalScope().addAdaptedTypeSymbolResolver(resolver); + OOSymbolsMill.globalScope().addAdaptedOOTypeSymbolResolver(resolver); + } protected void setupSymbolTableCompleter( ITraverser typeMapTraverser, Type4Ast type4Ast) { @@ -203,6 +216,7 @@ protected void generateScopes(ASTExpression expr) { ICombineExpressionsWithLiteralsArtifactScope rootScope = CombineExpressionsWithLiteralsMill.scopesGenitorDelegator() .createFromAST(rootNode); + rootScope.setName("fooRoot"); // complete the symbol table expr.accept(getSymbolTableCompleter()); From ba434e23dd2ae04f7427930536b6860f893cc92d Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Mon, 4 Aug 2025 17:07:02 +0200 Subject: [PATCH 12/37] Interpreter Statements, Test-Klassen, WriteableMIValue --- .../java/de/monticore/MontiCoreScript.java | 4 +- .../interpreter/InterpreterDecorator.java | 144 +++++++------ .../interpreter/NoImplementation.ftl | 6 + .../interpreter/InterpreterDecoratorTest.java | 4 +- .../AssignmentExpressionsInterpreter.java | 204 +++++++++--------- .../CommonExpressionsInterpreter.java | 114 +++++----- .../_visitor/ExpressionsBasisInterpreter.java | 7 +- .../LambdaExpressionsInterpreter.java | 4 +- .../_visitor/UglyExpressionsInterpreter.java | 51 ++++- .../interpreter/InterpreterUtils.java | 101 ++++++++- .../interpreter/MICommonForIterator.java | 63 ++++++ .../interpreter/MIForEachIterator.java | 40 ++++ .../monticore/interpreter/MIForIterator.java | 9 + .../de/monticore/interpreter/MIScope.java | 50 +++-- .../interpreter/ModelInterpreter.java | 52 ++++- .../interpreter/values/BooleanMIValue.java | 7 +- .../interpreter/values/ByteMIValue.java | 5 + .../interpreter/values/CharMIValue.java | 5 + .../interpreter/values/DoubleMIValue.java | 5 + .../interpreter/values/FloatMIValue.java | 5 + .../interpreter/values/FunctionMIValue.java | 19 -- .../interpreter/values/IntMIValue.java | 5 + .../values/JavaAttributeMIValue.java | 62 ++++++ ...e.java => JavaNonStaticMethodMIValue.java} | 17 +- ...alue.java => JavaStaticMethodMIValue.java} | 18 +- .../interpreter/values/LongMIValue.java | 5 + ...MIValue.java => ModelFunctionMIValue.java} | 24 ++- .../interpreter/values/ObjectMIValue.java | 0 .../interpreter/values/ShortMIValue.java | 5 + .../interpreter/values/VariableMIValue.java | 45 ++++ .../interpreter/values/WriteableMIValue.java | 166 ++++++++++++++ .../_visitor/MCCommonLiteralsInterpreter.java | 7 - .../_visitor/OCLExpressionsInterpreter.java | 2 +- .../_visitor/SetExpressionsInterpreter.java | 41 ++-- .../MCCommonStatementsInterpreter.java | 202 +++++++++++++++++ .../MCLowLevelStatementsInterpreter.java | 28 +++ .../MCReturnStatementsInterpreter.java | 27 +++ ...MCVarDeclarationStatementsInterpreter.java | 50 +++++ .../de/monticore/types/check/SymTypeVoid.java | 2 +- .../CombineStatementsWithExpressions.mc4 | 13 ++ .../de/monticore/AbstractInterpreterTest.java | 146 +++++++++++++ ...=> AbstractExpressionInterpreterTest.java} | 146 ++++++++----- .../AssignmentExpressionsInterpreterTest.java | 4 +- .../CommonExpressionsInterpreterTest.java | 4 +- .../LambdaExpressionsInterpreterTest.java | 5 +- .../StreamExpressionsInterpreterTest.java | 17 ++ .../AbstractStatementInterpreterTest.java | 162 ++++++++++++++ ...eStatementsWithExpressionsInterpreter.java | 17 ++ .../CombineStatementsWithExpressionsTest.java | 158 ++++++++++++++ .../de/monticore/interpreter/IMIScope.java | 4 + .../interpreter/IModelInterpreter.java | 5 +- .../de/monticore/interpreter/MIValue.java | 36 +++- .../interpreter/values/ErrorMIValue.java | 7 +- .../interpreter/values/FunctionMIValue.java | 22 ++ .../interpreter/values/MIBreakSignal.java | 19 ++ .../interpreter/values/MIContinueSignal.java | 20 ++ .../values/MIFlowControlSignal.java | 11 + .../interpreter/values/MIReturnSignal.java | 36 ++++ settings.gradle | 2 +- 59 files changed, 2045 insertions(+), 394 deletions(-) create mode 100644 monticore-generator/src/main/resources/interpreter/NoImplementation.ftl create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/MICommonForIterator.java create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/MIForEachIterator.java create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/MIForIterator.java rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java (88%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/ByteMIValue.java (92%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/CharMIValue.java (91%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java (89%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/FloatMIValue.java (89%) delete mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/IntMIValue.java (91%) create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java rename monticore-grammar/src/main/java/de/monticore/interpreter/values/{JavaMethodMIValue.java => JavaNonStaticMethodMIValue.java} (81%) rename monticore-grammar/src/main/java/de/monticore/interpreter/values/{JavaFunctionMIValue.java => JavaStaticMethodMIValue.java} (80%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/LongMIValue.java (90%) rename monticore-grammar/src/main/java/de/monticore/interpreter/values/{ASTFunctionMIValue.java => ModelFunctionMIValue.java} (66%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java (100%) rename {monticore-runtime => monticore-grammar}/src/main/java/de/monticore/interpreter/values/ShortMIValue.java (91%) create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/values/VariableMIValue.java create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/values/WriteableMIValue.java create mode 100644 monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/statements/mclowlevelstatements/_visitor/MCLowLevelStatementsInterpreter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/statements/mcreturnstatements/_visitor/MCReturnStatementsInterpreter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_visitor/MCVarDeclarationStatementsInterpreter.java create mode 100644 monticore-grammar/src/test/grammars/de/monticore/statements/CombineStatementsWithExpressions.mc4 create mode 100644 monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java rename monticore-grammar/src/test/java/de/monticore/expressions/{AbstractInterpreterTest.java => AbstractExpressionInterpreterTest.java} (55%) create mode 100644 monticore-grammar/src/test/java/de/monticore/expressions/streamexpressions/parser/StreamExpressionsInterpreterTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsInterpreter.java create mode 100644 monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/IMIScope.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java create mode 100644 monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java diff --git a/monticore-generator/src/main/java/de/monticore/MontiCoreScript.java b/monticore-generator/src/main/java/de/monticore/MontiCoreScript.java index fd05516b8e..dee43bd83e 100644 --- a/monticore-generator/src/main/java/de/monticore/MontiCoreScript.java +++ b/monticore-generator/src/main/java/de/monticore/MontiCoreScript.java @@ -804,12 +804,14 @@ protected void decorateWithTraverser(ASTCDCompilationUnit cd, public void decorateWithInterpreter(List cds, ASTCDCompilationUnit decoratedCD, GlobalExtensionManagement glex) { + + ASTService astService = new ASTService(cds.get(0)); VisitorService visitorService = new VisitorService(cds.get(0)); InterpreterInterfaceDecorator interpreterInterfaceDecorator = new InterpreterInterfaceDecorator(glex, visitorService); interpreterInterfaceDecorator.decorate(cds.get(0), decoratedCD); - InterpreterDecorator interpreterDecorator = new InterpreterDecorator(glex, visitorService); + InterpreterDecorator interpreterDecorator = new InterpreterDecorator(glex, astService, visitorService); interpreterDecorator.decorate(cds.get(0), decoratedCD); ASTEvaluateDecorator evaluateDecorator = new ASTEvaluateDecorator(glex, visitorService); diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java index e9f2543cc9..4c32a6112d 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecorator.java @@ -9,6 +9,7 @@ import de.monticore.cdbasis._ast.*; import de.monticore.cdbasis._symboltable.CDTypeSymbol; import de.monticore.codegen.cd2java.AbstractCreator; +import de.monticore.codegen.cd2java._ast.ast_class.ASTService; import de.monticore.codegen.cd2java._visitor.VisitorConstants; import de.monticore.codegen.cd2java._visitor.VisitorService; import de.monticore.codegen.cd2java.methods.MethodDecorator; @@ -17,6 +18,7 @@ import de.monticore.generating.templateengine.TemplateHookPoint; import de.monticore.symbols.basicsymbols._symboltable.DiagramSymbol; import de.monticore.types.mcbasictypes._ast.ASTMCReturnType; +import de.monticore.types.mcbasictypes._ast.ASTMCType; import java.util.ArrayList; import java.util.List; @@ -28,13 +30,17 @@ public class InterpreterDecorator extends AbstractCreator { + + protected final ASTService astService; - protected final VisitorService service; + protected final VisitorService visitorService; public InterpreterDecorator(GlobalExtensionManagement glex, - VisitorService service) { + ASTService astService, + VisitorService visitorService) { super(glex); - this.service = service; + this.astService = astService; + this.visitorService = visitorService; } public void decorate(ASTCDCompilationUnit input, @@ -48,7 +54,7 @@ public void decorate(ASTCDCompilationUnit input, public ASTCDClass decorate(ASTCDCompilationUnit input) { return CD4CodeMill.cDClassBuilder() .setModifier(PUBLIC.build()) - .setName(service.getInterpreterSimpleName()) + .setName(visitorService.getInterpreterSimpleName()) .setCDInterfaceUsage(getSuperInterface()) .addAllCDMembers(getInterpreterAttributes()) .addAllCDMembers(getConstructors()) @@ -62,7 +68,7 @@ public List getConstructors() { ASTCDParameter parameter = cdParameterFacade.createParameter( MODELINTERPRETER_FULLNAME, "realThis"); - String interpreterName = service.getInterpreterSimpleName(); + String interpreterName = visitorService.getInterpreterSimpleName(); ASTCDConstructor constructorNoParams = cdConstructorFacade .createConstructor(PUBLIC.build(), interpreterName); ASTCDConstructor constructorRealThis = cdConstructorFacade @@ -71,9 +77,9 @@ public List getConstructors() { List names = new ArrayList<>(); List types = new ArrayList<>(); - for (DiagramSymbol symbol : service.getSuperCDsTransitive()) { - names.add(service.getInterpreterSimpleName(symbol)); - types.add(service.getInterpreterFullName(symbol)); + for (DiagramSymbol symbol : visitorService.getSuperCDsTransitive()) { + names.add(visitorService.getInterpreterSimpleName(symbol)); + types.add(visitorService.getInterpreterFullName(symbol)); } replaceTemplate(EMPTY_BODY, constructorRealThis, @@ -90,25 +96,29 @@ public List getInterpretMethods() { ASTMCReturnType returnType = CD4CodeMill.mCReturnTypeBuilder() .setMCType(mcTypeFacade.createQualifiedType(VALUE_FULLNAME)).build(); - for (CDTypeSymbol typeSymbol : service.getAllCDTypes()) { + for (CDTypeSymbol typeSymbol : visitorService.getAllCDTypes()) { if (typeSymbol.isIsClass() || typeSymbol.isIsInterface()) { ASTCDParameter parameter = cdParameterFacade - .createParameter(service.createASTFullName(typeSymbol), NODE_PARAMETER); + .createParameter(visitorService.createASTFullName(typeSymbol), NODE_PARAMETER); ASTCDMethod method = cdMethodFacade.createMethod( PUBLIC.build(), returnType, "interpret", parameter); - this.replaceTemplate( - EMPTY_BODY, method, new StringHookPoint("return node.evaluate(getRealThis());")); + + String errorCode = astService.getGeneratedErrorCode(typeSymbol.getFullName()); + + this.replaceTemplate(EMPTY_BODY, method, + new TemplateHookPoint("interpreter.NoImplementation", + typeSymbol.getFullName(), errorCode)); methods.add(method); } } - for (DiagramSymbol diagramSymbol : service.getSuperCDsTransitive()) { - if (diagramSymbol != service.getCDSymbol()) { - String interpreterName = uncapFirst(service.getInterpreterSimpleName(diagramSymbol)); - for (CDTypeSymbol typeSymbol : service.getAllCDTypes(diagramSymbol)) { + for (DiagramSymbol diagramSymbol : visitorService.getSuperCDsTransitive()) { + if (diagramSymbol != visitorService.getCDSymbol()) { + String interpreterName = uncapFirst(visitorService.getInterpreterSimpleName(diagramSymbol)); + for (CDTypeSymbol typeSymbol : visitorService.getAllCDTypes(diagramSymbol)) { if (typeSymbol.isIsClass() || typeSymbol.isIsInterface()) { ASTCDParameter parameter = cdParameterFacade - .createParameter(service.createASTFullName(typeSymbol), NODE_PARAMETER); + .createParameter(visitorService.createASTFullName(typeSymbol), NODE_PARAMETER); ASTCDMethod method = cdMethodFacade.createMethod( PUBLIC.build(), returnType, "interpret", parameter); this.replaceTemplate( @@ -127,54 +137,54 @@ EMPTY_BODY, method, new StringHookPoint( public List createMapMembers() { List members = new ArrayList<>(); - members.add(cdAttributeFacade.createAttribute( - PROTECTED.build(), - mcTypeFacade.createBasicGenericTypeOf("java.util.Stack", INTERPRETER_SCOPE_FULLNAME), - "scopeCallstack")); - - ASTCDParameter variableSymbolParameter = cdParameterFacade.createParameter(VARIABLE_SYMBOL_FULLNAME, "symbol"); - ASTCDParameter functionSymbolParameter = cdParameterFacade.createParameter(FUNCTION_SYMBOL_FULLNAME, "symbol"); - ASTCDParameter valueParameter = cdParameterFacade.createParameter(VALUE_FULLNAME, "value"); - ASTCDParameter functionValueParameter = cdParameterFacade.createParameter(FUNCTION_VALUE_FULLNAME, "value"); + ASTMCType scopeStackType = mcTypeFacade.createBasicGenericTypeOf("java.util.Stack", INTERPRETER_SCOPE_FULLNAME); - ASTCDMethod declareFuncMethod = cdMethodFacade.createMethod( - PUBLIC.build(), "declareFunction", functionSymbolParameter, functionValueParameter); - this.replaceTemplate(EMPTY_BODY, declareFuncMethod, new StringHookPoint("getRealThis().getCurrentScope().declareFunction(symbol, value);")); - members.add(declareFuncMethod); + members.add(cdAttributeFacade.createAttribute(PROTECTED.build(), scopeStackType, "scopeCallstack")); - ASTCDMethod loadFuncMethod = cdMethodFacade.createMethod(PUBLIC.build(), VALUE_FULLNAME, "loadFunction", functionSymbolParameter); - this.replaceTemplate(EMPTY_BODY, loadFuncMethod, new StringHookPoint("return getRealThis().getCurrentScope().loadFunction(symbol);")); - members.add(loadFuncMethod); +// ASTCDMethod declareFuncMethod = cdMethodFacade.createMethod( +// PUBLIC.build(), "declareFunction", functionSymbolParameter, functionValueParameter); +// this.replaceTemplate(EMPTY_BODY, declareFuncMethod, new StringHookPoint("getRealThis().getCurrentScope().declareFunction(symbol, value);")); +// members.add(declareFuncMethod); +// +// ASTCDMethod loadFuncMethod = cdMethodFacade.createMethod(PUBLIC.build(), VALUE_FULLNAME, "loadFunction", functionSymbolParameter); +// this.replaceTemplate(EMPTY_BODY, loadFuncMethod, new StringHookPoint("return getRealThis().getCurrentScope().loadFunction(symbol);")); +// members.add(loadFuncMethod); +// +// ASTCDMethod declareVarMethod = cdMethodFacade.createMethod( +// PUBLIC.build(), "declareVariable", variableSymbolParameter, optionalValueParameter); +// this.replaceTemplate(EMPTY_BODY, declareVarMethod, new StringHookPoint("getRealThis().getCurrentScope().declareVariable(symbol, value);")); +// members.add(declareVarMethod); +// +// ASTCDMethod loadVarMethod = cdMethodFacade.createMethod(PUBLIC.build(), VALUE_FULLNAME, +// "loadVariable", variableSymbolParameter); +// this.replaceTemplate(EMPTY_BODY, loadVarMethod, new StringHookPoint("return getRealThis().getCurrentScope().loadVariable(symbol);")); +// members.add(loadVarMethod); +// +// ASTCDMethod storeVarMethod = cdMethodFacade.createMethod( +// PUBLIC.build(), "storeVariable", variableSymbolParameter, valueParameter); +// this.replaceTemplate(EMPTY_BODY, storeVarMethod, new StringHookPoint("getRealThis().getCurrentScope().storeVariable(symbol, value);")); +// members.add(storeVarMethod); +// +// ASTCDMethod getter = cdMethodFacade.createMethod( +// PUBLIC.build(), +// mcTypeFacade.createQualifiedType(INTERPRETER_SCOPE_FULLNAME), +// "getCurrentScope"); +// this.replaceTemplate(EMPTY_BODY, getter, new StringHookPoint("return getRealThis().scopeCallstack.peek();")); +// members.add(getter); +// +// ASTCDParameter scopeParameter = cdParameterFacade.createParameter(INTERPRETER_SCOPE_FULLNAME, "scope"); +// ASTCDMethod pushScopeMethod = cdMethodFacade.createMethod(PUBLIC.build(), "pushScope", scopeParameter); +// this.replaceTemplate(EMPTY_BODY, pushScopeMethod, new StringHookPoint("getRealThis().scopeCallstack.push(scope);")); +// members.add(pushScopeMethod); +// +// ASTCDMethod popScopeMethod = cdMethodFacade.createMethod(PUBLIC.build(), "popScope"); +// this.replaceTemplate(EMPTY_BODY, popScopeMethod, new StringHookPoint("getRealThis().scopeCallstack.pop();")); +// members.add(popScopeMethod); - ASTCDMethod declareVarMethod = cdMethodFacade.createMethod( - PUBLIC.build(), "declareVariable", variableSymbolParameter, valueParameter); - this.replaceTemplate(EMPTY_BODY, declareVarMethod, new StringHookPoint("getRealThis().getCurrentScope().declareVariable(symbol, value);")); - members.add(declareVarMethod); - - ASTCDMethod loadVarMethod = cdMethodFacade.createMethod(PUBLIC.build(), VALUE_FULLNAME, "loadVariable", variableSymbolParameter); - this.replaceTemplate(EMPTY_BODY, loadVarMethod, new StringHookPoint("return getRealThis().getCurrentScope().loadVariable(symbol);")); - members.add(loadVarMethod); - - ASTCDMethod storeVarMethod = cdMethodFacade.createMethod( - PUBLIC.build(), "storeVariable", variableSymbolParameter, valueParameter); - this.replaceTemplate(EMPTY_BODY, storeVarMethod, new StringHookPoint("getRealThis().getCurrentScope().storeVariable(symbol, value);")); - members.add(storeVarMethod); - - ASTCDMethod getter = cdMethodFacade.createMethod( - PUBLIC.build(), - mcTypeFacade.createQualifiedType(INTERPRETER_SCOPE_FULLNAME), - "getCurrentScope"); - this.replaceTemplate(EMPTY_BODY, getter, new StringHookPoint("return this.scopeCallstack.peek();")); - members.add(getter); - - ASTCDParameter scopeParameter = cdParameterFacade.createParameter(INTERPRETER_SCOPE_FULLNAME, "scope"); - ASTCDMethod pushScopeMethod = cdMethodFacade.createMethod(PUBLIC.build(), "pushScope", scopeParameter); - this.replaceTemplate(EMPTY_BODY, pushScopeMethod, new StringHookPoint("this.scopeCallstack.push(scope);")); - members.add(pushScopeMethod); - - ASTCDMethod popScopeMethod = cdMethodFacade.createMethod(PUBLIC.build(), "popScope"); - this.replaceTemplate(EMPTY_BODY, popScopeMethod, new StringHookPoint("this.scopeCallstack.pop();")); - members.add(popScopeMethod); + ASTCDMethod getScopeCallstackMethod = cdMethodFacade.createMethod(PUBLIC.build(), scopeStackType, + "getScopeCallstack"); + this.replaceTemplate(EMPTY_BODY, getScopeCallstackMethod, new StringHookPoint("return scopeCallstack;")); + members.add(getScopeCallstackMethod); return members; } @@ -189,24 +199,24 @@ public List getRealThisComponents() { "realThis"); components.add(realThisAttribute); - MethodDecorator methodDecorator = new MethodDecorator(glex, service); + MethodDecorator methodDecorator = new MethodDecorator(glex, visitorService); components.addAll(methodDecorator.decorate(realThisAttribute)); return components; } public List getInterpreterAttributes() { - return service.getSuperCDsTransitive() + return visitorService.getSuperCDsTransitive() .stream() .map(s -> cdAttributeFacade.createAttribute( - PROTECTED.build(), service.getInterpreterType(s), - uncapFirst(service.getInterpreterSimpleName(s)))) + PROTECTED.build(), visitorService.getInterpreterType(s), + uncapFirst(visitorService.getInterpreterSimpleName(s)))) .collect(Collectors.toList()); } public ASTCDInterfaceUsage getSuperInterface() { return CDInterfaceUsageFacade.getInstance() - .createCDInterfaceUsage(service.getInterpreterInterfaceSimpleName()); + .createCDInterfaceUsage(visitorService.getInterpreterInterfaceSimpleName()); } protected String uncapFirst(String s) { diff --git a/monticore-generator/src/main/resources/interpreter/NoImplementation.ftl b/monticore-generator/src/main/resources/interpreter/NoImplementation.ftl new file mode 100644 index 0000000000..1f38bd05eb --- /dev/null +++ b/monticore-generator/src/main/resources/interpreter/NoImplementation.ftl @@ -0,0 +1,6 @@ +<#-- (c) https://github.com/MontiCore/monticore --> +${tc.signature("name", "errorCode")} + +String errorMsg = "0x57086${errorCode} Interpreter was not implemented for ${name}"; +de.se_rwth.commons.logging.Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); +return new de.monticore.interpreter.values.ErrorMIValue(errorMsg); \ No newline at end of file diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index 6bbdd59f09..93c7db2a70 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -7,6 +7,7 @@ import de.monticore.cdbasis._ast.ASTCDClass; import de.monticore.cdbasis._ast.ASTCDCompilationUnit; import de.monticore.codegen.cd2java.DecoratorTestCase; +import de.monticore.codegen.cd2java._ast.ast_class.ASTService; import de.monticore.codegen.cd2java._visitor.VisitorService; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; @@ -33,10 +34,11 @@ public class InterpreterDecoratorTest extends DecoratorTestCase { @Before public void before() { originalCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); + ASTService astService = new ASTService(originalCompilationUnit); VisitorService visitorService = new VisitorService(originalCompilationUnit); this.glex.setGlobalValue("service", new VisitorService(originalCompilationUnit)); - InterpreterDecorator decorator = new InterpreterDecorator(this.glex, visitorService); + InterpreterDecorator decorator = new InterpreterDecorator(this.glex, astService, visitorService); this.decoratedClass = decorator.decorate(originalCompilationUnit); } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java index 03ed5daa3a..eed3436688 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java @@ -7,6 +7,7 @@ import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.WriteableMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.types.check.SymTypeExpression; @@ -35,50 +36,51 @@ public AssignmentExpressionsInterpreter() { public MIValue interpret(ASTIncSuffixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); - Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); - if (symbol.isEmpty()) { - String errorMsg = "0x57022 Unknown variable symbol detected"; - Log.error(errorMsg); + MIValue value = n.getExpression().evaluate(getRealThis()); + + if (value.isFlowControlSignal()) return value; + if (!value.isWriteable()) { + String errorMsg = "0x57094 Expected an LValue. Got " + value.printType() + " (" + value.printValue() + ")."; + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - - MIValue value = loadVariable(symbol.get()); - if (value.isError()) return value; + WriteableMIValue variable = (WriteableMIValue)value; if (type.isPrimitive()) { + MIValue previousValue = variable.getMIValue(); String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { - MIValue res = createValue((byte)(value.asByte() + 1)); - storeVariable(symbol.get(), res); - return value; + MIValue res = createValue((byte)(variable.asByte() + 1)); + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - MIValue res = createValue((short)(value.asShort() + 1)); - storeVariable(symbol.get(), res); - return value; + MIValue res = createValue((short)(variable.asShort() + 1)); + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - MIValue res = createValue((char)(value.asChar() + 1)); - storeVariable(symbol.get(), res); - return value; + MIValue res = createValue((char)(variable.asChar() + 1)); + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.INT)) { - MIValue res = createValue(value.asInt() + 1); - storeVariable(symbol.get(), res); - return value; + MIValue res = createValue(variable.asInt() + 1); + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.LONG)) { - MIValue res = createValue(value.asLong() + 1); - storeVariable(symbol.get(), res); - return value; + MIValue res = createValue(variable.asLong() + 1L); + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - MIValue res = createValue(value.asFloat() + 1); - storeVariable(symbol.get(), res); - return value; + MIValue res = createValue(variable.asFloat() + 1.0f); + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - MIValue res = createValue(value.asDouble() + 1); - storeVariable(symbol.get(), res); - return value; + MIValue res = createValue(variable.asDouble() + 1.0); + variable.write(res); + return previousValue; } } String errorMsg = "0x57023 Suffix incrementation operation with operand of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -87,50 +89,50 @@ public MIValue interpret(ASTIncSuffixExpression n) { public MIValue interpret(ASTIncPrefixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); - Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); - if (symbol.isEmpty()) { - String errorMsg = "0x57024 Unknown variable symbol detected"; - Log.error(errorMsg); + MIValue value = n.getExpression().evaluate(getRealThis()); + + if (value.isFlowControlSignal()) return value; + if (!value.isWriteable()) { + String errorMsg = "0x57095 Expected an LValue. Got " + value.printType() + " (" + value.printValue() + ")."; + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - - MIValue value = loadVariable(symbol.get()); - if (value.isError()) return value; + WriteableMIValue variable = (WriteableMIValue)value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { MIValue res = createValue((byte)(value.asByte() + 1)); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { MIValue res = createValue((short)(value.asShort() + 1)); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { MIValue res = createValue((char)(value.asChar() + 1)); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.INT)) { MIValue res = createValue(value.asInt() + 1); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.LONG)) { MIValue res = createValue(value.asLong() + 1); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { MIValue res = createValue(value.asFloat() + 1); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { MIValue res = createValue(value.asDouble() + 1); - storeVariable(symbol.get(), res); + variable.write(res); return res; } } String errorMsg = "0x57025 Prefix incrementation operation with operand of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -139,50 +141,50 @@ public MIValue interpret(ASTIncPrefixExpression n) { public MIValue interpret(ASTDecSuffixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); - Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); - if (symbol.isEmpty()) { - String errorMsg = "0x57026 Unknown variable symbol detected"; - Log.error(errorMsg); + MIValue value = n.getExpression().evaluate(getRealThis()); + + if (value.isFlowControlSignal()) return value; + if (!value.isWriteable()) { + String errorMsg = "0x57096 Expected an LValue. Got " + value.printType() + " (" + value.printValue() + ")."; + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - - MIValue value = loadVariable(symbol.get()); - if (value.isError()) return value; - + WriteableMIValue variable = (WriteableMIValue)value; if (type.isPrimitive()) { + MIValue previousValue = variable.getMIValue(); String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { MIValue res = createValue((byte)(value.asByte() - 1)); - storeVariable(symbol.get(), res); - return value; + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { MIValue res = createValue((short)(value.asShort() - 1)); - storeVariable(symbol.get(), res); - return value; + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { MIValue res = createValue((char)(value.asChar() - 1)); - storeVariable(symbol.get(), res); - return value; + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.INT)) { MIValue res = createValue(value.asInt() - 1); - storeVariable(symbol.get(), res); - return value; + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.LONG)) { MIValue res = createValue(value.asLong() - 1); - storeVariable(symbol.get(), res); - return value; + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { MIValue res = createValue(value.asFloat() - 1); - storeVariable(symbol.get(), res); - return value; + variable.write(res); + return previousValue; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { MIValue res = createValue(value.asDouble() - 1); - storeVariable(symbol.get(), res); - return value; + variable.write(res); + return previousValue; } } String errorMsg = "0x57027 Suffix decrementation operation with operand of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -191,50 +193,50 @@ public MIValue interpret(ASTDecSuffixExpression n) { public MIValue interpret(ASTDecPrefixExpression n) { ASTExpression expr = n.getExpression(); SymTypeExpression type = TypeCheck3.typeOf(expr); - Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); - if (symbol.isEmpty()) { - String errorMsg = "0x57028 Unknown variable symbol detected"; - Log.error(errorMsg); + MIValue value = n.getExpression().evaluate(getRealThis()); + + if (value.isFlowControlSignal()) return value; + if (!value.isWriteable()) { + String errorMsg = "0x57097 Expected an LValue. Got " + value.printType() + " (" + value.printValue() + ")."; + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - - MIValue value = loadVariable(symbol.get()); - if (value.isError()) return value; + WriteableMIValue variable = (WriteableMIValue)value; if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { MIValue res = createValue((byte)(value.asByte() - 1)); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.SHORT)) { MIValue res = createValue((short)(value.asShort() - 1)); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.CHAR)) { MIValue res = createValue((char)(value.asChar() - 1)); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.INT)) { MIValue res = createValue(value.asInt() - 1); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.LONG)) { MIValue res = createValue(value.asLong() - 1); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { MIValue res = createValue(value.asFloat() - 1); - storeVariable(symbol.get(), res); + variable.write(res); return res; } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { MIValue res = createValue(value.asDouble() - 1); - storeVariable(symbol.get(), res); + variable.write(res); return res; } } String errorMsg = "0x57029 Prefix decrementation operation with operand of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -242,30 +244,33 @@ public MIValue interpret(ASTDecPrefixExpression n) { public MIValue interpret(ASTAssignmentExpression n) { ASTExpression leftExpr = n.getLeft(); SymTypeExpression leftType = TypeCheck3.typeOf(leftExpr); - Optional leftSymbol = leftType.getSourceInfo().getSourceSymbol().map(symbol -> (VariableSymbol)symbol); - if (leftSymbol.isEmpty()) { - String errorMsg = "0x57030 Unknown variable symbol detected"; - Log.error(errorMsg); + MIValue leftValue = n.getLeft().evaluate(getRealThis()); + + if (!leftValue.isWriteable()) { + String errorMsg = "0x57098 Expected an LValue. Got " + leftValue.printType() + + " (" + leftValue.printValue() + ")."; + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } + WriteableMIValue variable = (WriteableMIValue)leftValue; int operator = n.getOperator(); MIValue rightValue = n.getRight().evaluate(getRealThis()); - if (rightValue.isError()) return rightValue; + if (rightValue.isFlowControlSignal()) return rightValue; SymTypeExpression rightType = TypeCheck3.typeOf(n.getRight()); // no operation if (operator == EQUALS) { if (leftType.deepEquals(rightType)) { - storeVariable(leftSymbol.get(), rightValue); + variable.write(rightValue); return rightValue; } if (!SymTypeRelations.isCompatible(leftType, rightType)) { String errorMsg = "0x57031 A value of type " + rightType.print() + " can not be writen to a variable of type " + leftType.print() + "."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -273,16 +278,15 @@ public MIValue interpret(ASTAssignmentExpression n) { rightValue = InterpreterUtils.convertToPrimitiveImplicit(leftType.asPrimitive().getPrimitiveName(), rightValue); } else { String errorMsg = "0x57032 The implicit conversion from " + rightType.print() + " to " + leftType.print() + " is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - storeVariable(leftSymbol.get(), rightValue); + variable.write(rightValue); return rightValue; } - MIValue leftValue = loadVariable(leftSymbol.get()); - if (leftValue.isError()) return leftValue; + if (leftValue.isFlowControlSignal()) return leftValue; MIValue resultValue; SymTypeExpression resultType; @@ -367,7 +371,7 @@ public MIValue interpret(ASTAssignmentExpression n) { if (rightValue.asDouble() == 0.0) { String errorMsg = "0x57033 Division by zero is undefined"; - Log.error(errorMsg); + Log.error(errorMsg, n.getRight().get_SourcePositionStart(), n.getRight().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -377,7 +381,7 @@ public MIValue interpret(ASTAssignmentExpression n) { break; } String errorMsg = "0x57034 Division Assignment operation with result of type " + resultType + " is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -390,11 +394,11 @@ public MIValue interpret(ASTAssignmentExpression n) { } default: String errorMsg = "0x57035 Operator is not defined"; - Log.error(errorMsg); + Log.error(errorMsg, n.getLeft().get_SourcePositionEnd(), n.getRight().get_SourcePositionStart()); return new ErrorMIValue(errorMsg); } - if (resultValue.isError()) return resultValue; + if (resultValue.isFlowControlSignal()) return resultValue; if (leftType.deepEquals(resultType)) { } else if (leftType.isPrimitive() && resultType.isPrimitive()) { @@ -402,13 +406,13 @@ public MIValue interpret(ASTAssignmentExpression n) { leftType.asPrimitive().getPrimitiveName(), resultValue); } else { String errorMsg = "0x57036 Cast from " + resultType.print() + " to " + leftType.print() + " is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - if (resultValue.isError()) return resultValue; + if (resultValue.isFlowControlSignal()) return resultValue; - storeVariable(leftSymbol.get(), resultValue); + variable.write(resultValue); return resultValue; } } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index 2de9af4ade..231a4706bd 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -114,8 +114,8 @@ public MIValue subtract(SymTypePrimitive leftType, MIValue left, SymTypePrimitiv public MIValue interpret(ASTPlusExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, Integer::sum, Long::sum, Float::sum, Double::sum, "0x57037 Plus"); @@ -125,8 +125,8 @@ public MIValue interpret(ASTPlusExpression node) { public MIValue interpret(ASTMinusExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a - b, (a, b) -> a - b, @@ -137,8 +137,8 @@ public MIValue interpret(ASTMinusExpression node) { public MIValue interpret(ASTMultExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a * b, (a, b) -> a * b, @@ -149,8 +149,8 @@ public MIValue interpret(ASTMultExpression node) { public MIValue interpret(ASTDivideExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); if (type.isPrimitive()) { @@ -158,7 +158,7 @@ public MIValue interpret(ASTDivideExpression node) { if (right.asDouble() == 0.0) { String errorMsg = "0x57004 Division by zero is undefined"; - Log.error(errorMsg); + Log.error(errorMsg, node.getRight().get_SourcePositionStart(), node.getRight().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -168,7 +168,7 @@ public MIValue interpret(ASTDivideExpression node) { } String errorMsg = "0x57005 Division operation with result of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -176,8 +176,8 @@ public MIValue interpret(ASTDivideExpression node) { public MIValue interpret(ASTModuloExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a % b, (a, b) -> a % b, @@ -187,7 +187,7 @@ public MIValue interpret(ASTModuloExpression node) { @Override public MIValue interpret(ASTMinusPrefixExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isError()) return value; + if (value.isFlowControlSignal()) return value; SymTypeExpression type = TypeCheck3.typeOf(node); if (type.isPrimitive()) { @@ -211,14 +211,14 @@ public MIValue interpret(ASTMinusPrefixExpression node) { } String errorMsg = "0x57006 Minus Prefix operation with result of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @Override public MIValue interpret(ASTPlusPrefixExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isError()) return value; + if (value.isFlowControlSignal()) return value; SymTypeExpression type = TypeCheck3.typeOf(node); if (type.isPrimitive() && (type.asPrimitive().isNumericType() || type.asPrimitive().isIntegralType())) { @@ -226,7 +226,7 @@ public MIValue interpret(ASTPlusPrefixExpression node) { } String errorMsg = "0x57007 Minus Prefix operation with result of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -234,8 +234,8 @@ public MIValue interpret(ASTPlusPrefixExpression node) { public MIValue interpret(ASTEqualsExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); @@ -245,7 +245,7 @@ public MIValue interpret(ASTEqualsExpression node) { String errorMsg = "0x57008 Equality operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -253,21 +253,21 @@ public MIValue interpret(ASTEqualsExpression node) { public MIValue interpret(ASTNotEqualsExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = isEqual(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isError()) return result; + if (result.isFlowControlSignal()) return result; return createValue(!result.asBoolean()); } String errorMsg = "0x57009 Inequality operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -275,21 +275,21 @@ public MIValue interpret(ASTNotEqualsExpression node) { public MIValue interpret(ASTGreaterThanExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isError()) return result; + if (result.isFlowControlSignal()) return result; return createValue(result.asDouble() > 0.0); } String errorMsg = "0x57010 Greater than operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -297,21 +297,21 @@ public MIValue interpret(ASTGreaterThanExpression node) { public MIValue interpret(ASTLessThanExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isError()) return result; + if (result.isFlowControlSignal()) return result; return createValue(result.asDouble() < 0.0); } String errorMsg = "0x57011 Less than operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -319,21 +319,21 @@ public MIValue interpret(ASTLessThanExpression node) { public MIValue interpret(ASTGreaterEqualExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isError()) return result; + if (result.isFlowControlSignal()) return result; return createValue(result.asDouble() >= 0.0); } String errorMsg = "0x57012Greater equal operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -341,21 +341,21 @@ public MIValue interpret(ASTGreaterEqualExpression node) { public MIValue interpret(ASTLessEqualExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isError()) return result; + if (result.isFlowControlSignal()) return result; return createValue(result.asDouble() <= 0.0); } String errorMsg = "0x57013 Less equal operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -363,7 +363,7 @@ public MIValue interpret(ASTLessEqualExpression node) { @Override public MIValue interpret(ASTBooleanNotExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isError()) return value; + if (value.isFlowControlSignal()) return value; SymTypeExpression type = TypeCheck3.typeOf(node.getExpression()); if (type.isPrimitive() && type.asPrimitive().isIntegralType()) { @@ -382,7 +382,7 @@ public MIValue interpret(ASTBooleanNotExpression node) { } String errorMsg = "0x57014 Bitwise Not operation with operand of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -393,7 +393,7 @@ public MIValue interpret(ASTBooleanNotExpression node) { @Override public MIValue interpret(ASTLogicalNotExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isError()) return value; + if (value.isFlowControlSignal()) return value; SymTypeExpression type = TypeCheck3.typeOf(node.getExpression()); @@ -402,7 +402,7 @@ public MIValue interpret(ASTLogicalNotExpression node) { } String errorMsg = "0x57015 Logical Not operation with operand of type '" + type.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -410,8 +410,8 @@ public MIValue interpret(ASTLogicalNotExpression node) { public MIValue interpret(ASTBooleanAndOpExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); @@ -422,7 +422,7 @@ public MIValue interpret(ASTBooleanAndOpExpression node) { String errorMsg = "0x57016 Logical And operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -430,8 +430,8 @@ public MIValue interpret(ASTBooleanAndOpExpression node) { public MIValue interpret(ASTBooleanOrOpExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isError()) return left; - if (right.isError()) return right; + if (left.isFlowControlSignal()) return left; + if (right.isFlowControlSignal()) return right; SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); @@ -442,7 +442,7 @@ public MIValue interpret(ASTBooleanOrOpExpression node) { String errorMsg = "0x57017 Logical Or operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -454,7 +454,7 @@ public MIValue interpret(ASTBracketExpression node) { @Override public MIValue interpret(ASTConditionalExpression node) { MIValue condition = node.getCondition().evaluate(getRealThis()); - if (condition.isError()) return condition; + if (condition.isFlowControlSignal()) return condition; return condition.asBoolean() ? node.getTrueExpression().evaluate(getRealThis()) @@ -480,10 +480,10 @@ public MIValue interpret(ASTFieldAccessExpression node) { classType = Class.forName(className); } catch (ClassNotFoundException e) { String errorMsg = "0x57018 Failed to load class '" + className + "'."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - return new JavaFunctionMIValue(classType, funcName); + return new JavaStaticMethodMIValue(classType, funcName); } else { // static attribute // TODO } @@ -492,7 +492,7 @@ public MIValue interpret(ASTFieldAccessExpression node) { MIValue leftValue = node.getExpression().evaluate(getRealThis()); if (!leftValue.isObject()) { String errorMsg = "0x57019 The Field Access operation expected an object as left side."; - Log.error(errorMsg); + Log.error(errorMsg, node.getExpression().get_SourcePositionStart(), node.getExpression().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -500,7 +500,7 @@ public MIValue interpret(ASTFieldAccessExpression node) { if (type.isFunctionType()) { // method call on object FunctionSymbol funcSymbol = (FunctionSymbol)symbol; String name = funcSymbol.getName(); - return new JavaMethodMIValue(leftValue.asObject(), name); + return new JavaNonStaticMethodMIValue(leftValue.asObject(), name); } else { // non-static attribute access return InterpreterUtils.getObjectAttribute((ObjectMIValue)leftValue, node.getName(), type); } @@ -508,7 +508,7 @@ public MIValue interpret(ASTFieldAccessExpression node) { } String errorMsg = "0x57020 Field Access operation not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -526,7 +526,7 @@ public MIValue interpret(ASTCallExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); if (!value.isFunction()) { String errorMsg = "0x57021 Call expression expected a function but got " + TypeCheck3.typeOf(node.getExpression()).print() + "."; - Log.error(errorMsg); + Log.error(errorMsg, node.getExpression().get_SourcePositionStart(), node.getExpression().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -537,7 +537,7 @@ public MIValue interpret(ASTCallExpression node) { // cast needed in case of subtyping SymTypeExpression returnType = TypeCheck3.typeOf(node); - MIValue returnValue = ((FunctionMIValue)value).execute(getRealThis(), args); + MIValue returnValue = value.asFunction().execute(getRealThis(), args); return InterpreterUtils.convertImplicit(returnType, returnValue); } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java index 8174fea18d..f941bb489e 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java @@ -6,6 +6,7 @@ import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.VariableMIValue; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.types.check.SymTypeExpression; @@ -31,7 +32,7 @@ public MIValue interpret(ASTNameExpression n) { Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (FunctionSymbol)s); if (symbol.isEmpty()) { String errorMsg = "0x57053 Cannot resolve function '" + n.getName() + "'."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } return loadFunction(symbol.get()); @@ -40,10 +41,10 @@ public MIValue interpret(ASTNameExpression n) { Optional symbol = type.getSourceInfo().getSourceSymbol().map(s -> (VariableSymbol)s); if (symbol.isEmpty()) { String errorMsg = "0x57054 Cannot resolve variable '" + n.getName() + "'."; - Log.error(errorMsg); + Log.error(errorMsg, n.get_SourcePositionStart(), n.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - return loadVariable(symbol.get()); + return new VariableMIValue(getCurrentScope(), symbol.get()); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java index c322ae7630..076ed631a5 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java @@ -5,7 +5,7 @@ import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaParameter; import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; -import de.monticore.interpreter.values.ASTFunctionMIValue; +import de.monticore.interpreter.values.ModelFunctionMIValue; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import java.util.ArrayList; @@ -32,7 +32,7 @@ public MIValue interpret(ASTLambdaExpression node) { for (ASTLambdaParameter parameter : node.getLambdaParameters().getLambdaParameterList()) { parameterSymbols.add(parameter.getSymbol()); } - return new ASTFunctionMIValue(getRealThis().getCurrentScope(), parameterSymbols, node.getLambdaBody()); + return new ModelFunctionMIValue(getRealThis().getCurrentScope(), parameterSymbols, node.getLambdaBody()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java index 8330067a6f..f32b49f1e3 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java @@ -1,15 +1,21 @@ package de.monticore.expressions.uglyexpressions._visitor; +import de.monticore.expressions.uglyexpressions._ast.ASTClassCreator; +import de.monticore.expressions.uglyexpressions._ast.ASTCreatorExpression; import de.monticore.expressions.uglyexpressions._ast.ASTTypeCastExpression; import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.MIValueFactory; import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.VoidMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symboltable.ISymbol; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; +import java.util.Optional; + public class UglyExpressionsInterpreter extends UglyExpressionsInterpreterTOP { public UglyExpressionsInterpreter(ModelInterpreter realThis) { @@ -27,14 +33,39 @@ public MIValue interpret(ASTTypeCastExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); + if (afterType.isGenericType() || beforeType.isGenericType()) { + String errorMsg = "0x57089 Explicit casts with generic types are not supported yet."; + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); + } + if (afterType.isPrimitive() && beforeType.isPrimitive()) { return convertPrimitive(beforeType.asPrimitive().getPrimitiveName(), afterType.asPrimitive().getPrimitiveName(), value); } + if (afterType.isObjectType() && beforeType.isObjectType()) { + Class afterClassType; + try { + afterClassType = Class.forName(afterType.printFullName()); + } catch (ClassNotFoundException e) { + String errorMsg = "0x57089 Failed to load class '" + afterType.printFullName() + "'."; + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); + } + + if (!afterClassType.isInstance(value.asObject())) { + String errorMsg = "0x57090 Failed to explicitly cast object from '" + value.asObject().getClass().getName() + + "' to '" + afterType.printFullName() + "'."; + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); + } + return value; + } + String errorMsg = "0x57055 Type Cast operation from " + beforeType.print() + " to " + afterType.print() + " is not supported."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -117,4 +148,22 @@ public MIValue convertPrimitive(String fromType, String toType, MIValue value) { Log.error(errorMsg); return new ErrorMIValue(errorMsg); } + + @Override + public MIValue interpret(ASTCreatorExpression node) { + return node.getCreator().evaluate(getRealThis()); + } + + @Override + public MIValue interpret(ASTClassCreator node) { + SymTypeExpression type = TypeCheck3.symTypeFromAST(node.getMCType()); + Optional optSymbol = type.getSourceInfo().getSourceSymbol(); + if (optSymbol.isEmpty()) { + String errorMsg = "0x57081 Failed to load Symbol for Class."; + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); + } + + return new VoidMIValue(); + } } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java index 2cfb6815bd..e20d01701f 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java @@ -3,6 +3,7 @@ import de.monticore.interpreter.values.*; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; +import de.monticore.types3.SymTypeRelations; import de.se_rwth.commons.logging.Log; import java.lang.reflect.Field; @@ -16,7 +17,6 @@ public class InterpreterUtils { public static MIValue calcOpPrimitive(MIValue v1, MIValue v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, BinaryOperator opFloat, BinaryOperator opDouble, String opName) { - switch (resultType) { case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); @@ -199,9 +199,19 @@ public static MIValue convertToPrimitiveImplicit(String targetType, MIValue valu public static MIValue convertImplicit(SymTypeExpression targetType, MIValue value) { if (targetType.isPrimitive()) { + value = unboxType(value); return convertToPrimitiveImplicit(targetType.asPrimitive().getPrimitiveName(), value); + } else if (isBoxType(targetType)) { + SymTypeExpression unboxedType = SymTypeRelations.unbox(targetType); + value = convertToPrimitiveImplicit(unboxedType.asPrimitive().getPrimitiveName(), value); + value = boxValue(value, targetType); + return value; } else { - return value; // everything else is an object or function which is handled by reflection + // value may be primitive with targetType Object; int -> Integer -> Object + if (value.isPrimitive()) { + value = boxValue(value); + } + return value; } } @@ -272,10 +282,9 @@ public static Class typeOfValue(MIValue value) { return double.class; } else if (value.isObject()) { return value.asObject().getClass(); - } else if (value.isFunction()) { - // TODO maybe abstract method in FunctionMIValue that builds Function-Object } - String errorMsg = "0x57066 Failed to get java type of value."; + // Functions are not allowed + String errorMsg = "0x57066 Failed to get java type of " + value.printType() + "."; Log.error(errorMsg); return null; } @@ -299,10 +308,9 @@ public static Object valueToObject(MIValue value) { return value.asDouble(); } else if (value.isObject()) { return value.asObject(); - } else if (value.isFunction()) { - // TODO maybe abstract method in FunctionMIValue that builds Function-Object } - String errorMsg = "0x57067 Failed to get java type of value."; + // Functions are not allowed + String errorMsg = "0x57067 Failed to convert MIValue of type " + value.printType() + " to a java object."; Log.error(errorMsg); return null; } @@ -329,4 +337,81 @@ public static MIValue objectToValue(Object object) { return new ObjectMIValue(object); } + public static boolean isBoxType(SymTypeExpression type) { + return !type.isPrimitive() && (SymTypeRelations.isNumericType(type) || SymTypeRelations.isBoolean(type)); + } + + public static MIValue unboxType(MIValue value) { + if (!value.isObject()) return value; + + Object obj = value.asObject(); + if (obj instanceof Integer) { + return new IntMIValue((Integer)obj); + } else if (obj instanceof Long) { + return new LongMIValue((Long)obj); + } else if (obj instanceof Float) { + return new FloatMIValue((Float) obj); + } else if (obj instanceof Double) { + return new DoubleMIValue((Double)obj); + } else if (obj instanceof Character) { + return new CharMIValue((Character)obj); + } else if (obj instanceof Byte) { + return new ByteMIValue((Byte)obj); + } else if (obj instanceof Short) { + return new ShortMIValue((Short)obj); + } + + return value; + } + + public static MIValue boxValue(MIValue value) { + if (!value.isPrimitive()) { + return value; + } + + if (value.isBoolean()) { + return MIValueFactory.createValue((Boolean)value.asBoolean()); + } else if (value.isChar()) { + return MIValueFactory.createValue((Character)value.asChar()); + } else if (value.isByte()) { + return MIValueFactory.createValue((Byte)value.asByte()); + } else if (value.isShort()) { + return MIValueFactory.createValue((Short)value.asShort()); + } else if (value.isInt()) { + return MIValueFactory.createValue((Integer)value.asInt()); + } else if (value.isLong()) { + return MIValueFactory.createValue((Long)value.asLong()); + } else if (value.isFloat()) { + return MIValueFactory.createValue((Float)value.asFloat()); + } else if (value.isDouble()) { + return MIValueFactory.createValue((Double)value.asDouble()); + } + + return value; + } + + public static MIValue boxValue(MIValue value, SymTypeExpression boxType) { + if (SymTypeRelations.isInt(boxType)) { + return MIValueFactory.createValue(Integer.valueOf(value.asInt())); + } else if (SymTypeRelations.isLong(boxType)) { + return MIValueFactory.createValue(Long.valueOf(value.asLong())); + } else if (SymTypeRelations.isFloat(boxType)) { + return MIValueFactory.createValue(Float.valueOf(value.asFloat())); + } else if (SymTypeRelations.isDouble(boxType)) { + return MIValueFactory.createValue(Double.valueOf(value.asDouble())); + } else if (SymTypeRelations.isChar(boxType)) { + return MIValueFactory.createValue(Character.valueOf(value.asChar())); + } else if (SymTypeRelations.isByte(boxType)) { + return MIValueFactory.createValue(Byte.valueOf(value.asByte())); + } else if (SymTypeRelations.isShort(boxType)) { + return MIValueFactory.createValue(Short.valueOf(value.asShort())); + } else if (SymTypeRelations.isBoolean(boxType)) { + return MIValueFactory.createValue(Boolean.valueOf(value.asBoolean())); + } + + String errorMsg = "0x57084 Tried to convert to unknown boxed type."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MICommonForIterator.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MICommonForIterator.java new file mode 100644 index 0000000000..d21ba77741 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MICommonForIterator.java @@ -0,0 +1,63 @@ +package de.monticore.interpreter; + +import de.monticore.expressions.expressionsbasis._ast.ASTExpression; +import de.monticore.interpreter.values.VoidMIValue; +import de.monticore.statements.mccommonstatements._ast.ASTForInit; +import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; + +import java.util.List; +import java.util.Optional; + +public class MICommonForIterator implements MIForIterator { + + Optional initNode; + Optional condition; + List expressions; + + public MICommonForIterator(Optional initNode, Optional condition, List expressions) { + this.initNode = initNode; + this.condition = condition; + this.expressions = expressions; + } + + public MIValue checkCondition(ModelInterpreter interpreter) { + if (condition.isPresent()) { + return condition.get().evaluate(interpreter); + } else { + return MIValueFactory.createValue(true); + } + } + + public MIValue increment(ModelInterpreter interpreter) { + for (ASTExpression expression : expressions) { + MIValue result = expression.evaluate(interpreter); + if (result.isError()) return result; + } + return new VoidMIValue(); + } + + @Override + public MIValue execute(ModelInterpreter interpreter, ASTMCStatement body) { + if (initNode.isPresent()) { + MIValue result = initNode.get().evaluate(interpreter); + if (result.isFlowControlSignal()) + return result; + } + + MIValue conditionResult = checkCondition(interpreter); + while (conditionResult.isBoolean() && conditionResult.asBoolean()) { + MIValue statementResult = body.evaluate(interpreter); + if (statementResult.isBreak()) break; + if (statementResult.isFlowControlSignal() && !statementResult.isContinue()) return statementResult; + + MIValue incrementResult = increment(interpreter); + if (incrementResult.isFlowControlSignal()) { + return incrementResult; + } + + conditionResult = checkCondition(interpreter); + } + + return conditionResult.isFlowControlSignal() ? conditionResult : new VoidMIValue(); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIForEachIterator.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIForEachIterator.java new file mode 100644 index 0000000000..74640fe197 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIForEachIterator.java @@ -0,0 +1,40 @@ +package de.monticore.interpreter; + +import de.monticore.interpreter.values.VoidMIValue; +import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.types.check.SymTypeExpression; + +import java.util.Iterator; +import java.util.Optional; + +public class MIForEachIterator implements MIForIterator { + + VariableSymbol symbol; + Iterator iterator; + + public MIForEachIterator(VariableSymbol symbol, Iterator iterator) { + this.symbol = symbol; + this.iterator = iterator; + } + + @Override + public MIValue execute(ModelInterpreter interpreter, ASTMCStatement body) { + if (!iterator.hasNext()) return new VoidMIValue(); + + interpreter.declareVariable(symbol, Optional.empty()); + do { + SymTypeExpression targetType = symbol.getType(); + Object nextValue = iterator.next(); + MIValue convertedValue = InterpreterUtils.convertImplicit(targetType, MIValueFactory.createValue(nextValue)); + interpreter.storeVariable(symbol, convertedValue); + + MIValue statementResult = body.evaluate(interpreter); + if (statementResult.isContinue()) continue; + if (statementResult.isBreak()) break; + if (statementResult.isFlowControlSignal()) return statementResult; + } while (iterator.hasNext()); + + return new VoidMIValue(); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIForIterator.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIForIterator.java new file mode 100644 index 0000000000..20a4f8ae07 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIForIterator.java @@ -0,0 +1,9 @@ +package de.monticore.interpreter; + +import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; + +public interface MIForIterator { + + public MIValue execute(ModelInterpreter interpreter, ASTMCStatement body); + +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java index e9d4262ae4..3532539036 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java @@ -8,20 +8,29 @@ import java.util.HashMap; import java.util.Map; +import java.util.Optional; -public class MIScope { +public class MIScope implements IMIScope { protected Map functionMap = new HashMap<>(); - protected Map variableMap = new HashMap<>(); + protected Map> variableMap = new HashMap<>(); - protected MIScope parent; + protected Optional parent; public MIScope() { - this.parent = null; + this.parent = Optional.empty(); } public MIScope(MIScope parent) { - this.parent = parent; + this.parent = Optional.of(parent); + } + + public MIScope clone() { + MIScope clone = new MIScope(); + clone.parent = parent; + clone.variableMap = new HashMap<>(variableMap); + clone.functionMap = new HashMap<>(functionMap); + return clone; } public void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { @@ -32,13 +41,12 @@ public void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { } public MIValue loadFunction(FunctionSymbol symbol) { - FunctionMIValue value = functionMap.get(symbol); - if (value != null) { - return value; + if (functionMap.containsKey(symbol)) { + return functionMap.get(symbol); } - if (parent != null) { - return parent.loadFunction(symbol); + if (parent.isPresent()) { + return parent.get().loadFunction(symbol); } String errorMsg = "0x57069 Failed to load Function by Symbol. Could not find Symbol in the current or any parent scope"; @@ -46,7 +54,7 @@ public MIValue loadFunction(FunctionSymbol symbol) { return new ErrorMIValue(errorMsg); } - public void declareVariable(VariableSymbol symbol, MIValue value) { + public void declareVariable(VariableSymbol symbol, Optional value) { if (variableMap.containsKey(symbol)) { Log.error("0x57070 Variable was already declared"); } @@ -54,13 +62,19 @@ public void declareVariable(VariableSymbol symbol, MIValue value) { } public MIValue loadVariable(VariableSymbol symbol) { - MIValue value = variableMap.get(symbol); + Optional value = variableMap.get(symbol); if (value != null) { - return value; + if (value.isPresent()) { + return value.get(); + } else { + String errorMsg = "0x57087 Failed to load Variable by Symbol. Variable was declared but never initialized."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } } - if (parent != null) { - return parent.loadVariable(symbol); + if (parent.isPresent()) { + return parent.get().loadVariable(symbol); } String errorMsg = "0x57071 Failed to load Variable by Symbol. Could not find Symbol in the current or any parent scope"; @@ -70,9 +84,9 @@ public MIValue loadVariable(VariableSymbol symbol) { public void storeVariable(VariableSymbol symbol, MIValue value) { if (variableMap.containsKey(symbol)) { - variableMap.put(symbol, value); - } else if (parent != null){ - parent.storeVariable(symbol, value); + variableMap.put(symbol, Optional.of(value)); + } else if (parent.isPresent()){ + parent.get().storeVariable(symbol, value); } else { Log.error("0x57072 Failed to store Value in Symbol. Could not find Symbol in the current or any parent scope"); } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java index e8e712e187..ddb91380d9 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java @@ -1,39 +1,71 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter; +import de.monticore.ast.ASTNode; import de.monticore.interpreter.values.FunctionMIValue; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; -public interface ModelInterpreter extends IModelInterpreter { +import java.util.Optional; +import java.util.Stack; +public interface ModelInterpreter extends IModelInterpreter { + void setRealThis(ModelInterpreter realThis); ModelInterpreter getRealThis(); + + Stack getScopeCallstack(); - MIScope getCurrentScope(); + default MIScope getCurrentScope() { + return getRealThis().getScopeCallstack().peek(); + } - void pushScope(MIScope scope); - void popScope(); + /* + TODO Explicit cast is needed because: + Short version: Dependencies between symbols, scopes, functions & interpreter + Long version: + ModelFunctionMIValue has VariableSymbols as attributes + -> ModelFunctionMIValue must be in mc-grammar + MIScope uses Variable-/FunctionSymbol + -> must be in mc-grammar + ModelFunctionMIValue uses 'pushScope(MIScope)'; + IModelInterpreter must in mc-rte and has 'MIValue interpret()' + -> MIValue must be in mc-rte; + MIValue has 'FunctionMIValue asFunction()' + -> FunctionMIValue must be in mc-rte + FunctionMIValue needs 'execute(IModelInterpreter)' + -> ModelFunctionMIValue must use IModelInterpreter + -> ModelInterpreter needs 'pushScope(MIScope)' + MIScope cant be accessed -> IMIScope + IMIscope cant access Variable-/FunctionSymbol -> explicit cast + */ + default void pushScope(IMIScope scope) { + getRealThis().getScopeCallstack().push((MIScope)scope); + } + + default void popScope() { + getRealThis().getScopeCallstack().pop(); + } default void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { getCurrentScope().declareFunction(symbol, value); } default MIValue loadFunction(FunctionSymbol symbol) { - return getRealThis().loadFunction(symbol); + return getCurrentScope().loadFunction(symbol); } - default void declareVariable(VariableSymbol symbol, MIValue value) { + default void declareVariable(VariableSymbol symbol, Optional value) { getCurrentScope().declareVariable(symbol, value); } default MIValue loadVariable(VariableSymbol symbol) { - return getRealThis().loadVariable(symbol); + return getCurrentScope().loadVariable(symbol); } - default void storeVariable (VariableSymbol symbol, MIValue value){ - getRealThis().storeVariable(symbol, value); + default void storeVariable(VariableSymbol symbol, MIValue value){ + getCurrentScope().storeVariable(symbol, value); } - + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java similarity index 88% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java index a5814c6cb4..bef968eec6 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java @@ -15,7 +15,12 @@ public BooleanMIValue(boolean value){ public boolean isBoolean() { return true; } - + + @Override + public boolean isPrimitive() { + return true; + } + @Override public boolean asBoolean() { return value; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ByteMIValue.java similarity index 92% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/ByteMIValue.java index 1f6ddf7a96..087ca8fa6c 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ByteMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ByteMIValue.java @@ -10,6 +10,11 @@ public ByteMIValue(byte value) { this.value = value; } + @Override + public boolean isPrimitive() { + return true; + } + @Override public boolean isByte() { return true; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/CharMIValue.java similarity index 91% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/CharMIValue.java index 0a40242db5..f0c3abe739 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/CharMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/CharMIValue.java @@ -10,6 +10,11 @@ public class CharMIValue implements MIValue { public CharMIValue(char value){ this.value = value; } + + @Override + public boolean isPrimitive() { + return true; + } @Override public boolean isChar() { diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java similarity index 89% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java index ff270018c9..bda87a63c8 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java @@ -10,6 +10,11 @@ public class DoubleMIValue implements MIValue { public DoubleMIValue(double value) { this.value = value; } + + @Override + public boolean isPrimitive() { + return true; + } @Override public boolean isDouble() { diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java similarity index 89% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java index 8a0d87158b..f409f66e87 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FloatMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java @@ -10,6 +10,11 @@ public class FloatMIValue implements MIValue { public FloatMIValue(float value) { this.value = value; } + + @Override + public boolean isPrimitive() { + return true; + } @Override public boolean isFloat() { diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java deleted file mode 100644 index cedd406e51..0000000000 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java +++ /dev/null @@ -1,19 +0,0 @@ -package de.monticore.interpreter.values; - -import de.monticore.interpreter.MIScope; -import de.monticore.interpreter.MIValue; -import de.monticore.interpreter.ModelInterpreter; -import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; - -import java.util.List; - -public interface FunctionMIValue extends MIValue { - - @Override - public default boolean isFunction() { - return true; - } - - abstract public MIValue execute(ModelInterpreter interpreter, List arguments); - -} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/IntMIValue.java similarity index 91% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/IntMIValue.java index 4cef2d3be1..567248a84f 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/IntMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/IntMIValue.java @@ -10,6 +10,11 @@ public class IntMIValue implements MIValue { public IntMIValue(int value) { this.value = value; } + + @Override + public boolean isPrimitive() { + return true; + } @Override public boolean isInt() { diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java new file mode 100644 index 0000000000..5f3e1c4eab --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java @@ -0,0 +1,62 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.InterpreterUtils; +import de.monticore.interpreter.MIValue; +import de.se_rwth.commons.logging.Log; + +import java.lang.reflect.Field; +import java.util.Optional; + +public class JavaAttributeMIValue extends WriteableMIValue { + + Object obj; // null -> static attribute (that's how java does it) + Field attribute; + + Optional innerValue = Optional.empty(); + + public JavaAttributeMIValue(Object obj, Field attribute) { + this.obj = obj; + this.attribute = attribute; + } + + @Override + public void write(MIValue value) { + try { + attribute.set(obj, InterpreterUtils.valueToObject(value)); + innerValue = Optional.of(value); + } catch (IllegalAccessException e) { + String errorMsg = "0x57094 Failed to assign value " + value.printType() + + "(" + value.printValue() + ") to attribute '" + attribute.getName() + + "' of class '" + attribute.getDeclaringClass().getName() + "'."; + Log.error(errorMsg); + } + } + + @Override + public MIValue getMIValue() { + if (!innerValue.isPresent()) { + try { + innerValue = Optional.of( + InterpreterUtils.objectToValue(attribute.get(obj))); + } catch (IllegalAccessException e) { + String errorMsg = "0x57093 Failed to access attribute '" + + attribute.getName() + "' of class '" + + attribute.getDeclaringClass().getName() + "'."; + Log.error(errorMsg); + innerValue = Optional.of(new ErrorMIValue(errorMsg)); + } + } + + return innerValue.get(); + } + + @Override + public String printType() { + return "Attribute"; + } + + @Override + public String printValue() { + return getMIValue().printType() + " (" + getMIValue().printValue() + ")"; + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaMethodMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaNonStaticMethodMIValue.java similarity index 81% rename from monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaMethodMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaNonStaticMethodMIValue.java index f08fb140c8..2b1110e3a0 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaMethodMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaNonStaticMethodMIValue.java @@ -1,5 +1,6 @@ package de.monticore.interpreter.values; +import de.monticore.interpreter.IModelInterpreter; import de.monticore.interpreter.InterpreterUtils; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.ModelInterpreter; @@ -11,17 +12,17 @@ import java.util.stream.Collectors; // TODO change to getting method by SymType -public class JavaMethodMIValue implements FunctionMIValue { +public class JavaNonStaticMethodMIValue implements FunctionMIValue { Object object; String methodName; - public JavaMethodMIValue(Object object, String methodName) { + public JavaNonStaticMethodMIValue(Object object, String methodName) { this.object = object; this.methodName = methodName; } @Override - public MIValue execute(ModelInterpreter interpreter, List arguments) { + public MIValue execute(IModelInterpreter interpreter, List arguments) { List> argumentTypes = arguments.stream() .map(InterpreterUtils::typeOfValue) .collect(Collectors.toList()); @@ -64,4 +65,14 @@ public MIValue execute(ModelInterpreter interpreter, List arguments) { return InterpreterUtils.objectToValue(returnObject); } + + @Override + public String printType() { + return "Java-Method"; + } + + @Override + public String printValue() { + return object.getClass().getName() + "." + methodName; + } } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaFunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaStaticMethodMIValue.java similarity index 80% rename from monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaFunctionMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaStaticMethodMIValue.java index 67b8e5f677..b0ee4935c6 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaFunctionMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaStaticMethodMIValue.java @@ -1,8 +1,8 @@ package de.monticore.interpreter.values; +import de.monticore.interpreter.IModelInterpreter; import de.monticore.interpreter.InterpreterUtils; import de.monticore.interpreter.MIValue; -import de.monticore.interpreter.ModelInterpreter; import de.se_rwth.commons.logging.Log; import java.lang.reflect.InvocationTargetException; @@ -11,18 +11,18 @@ import java.util.stream.Collectors; // TODO change to getting method by SymType -public class JavaFunctionMIValue implements FunctionMIValue { +public class JavaStaticMethodMIValue implements FunctionMIValue { Class classType; String functionName; - public JavaFunctionMIValue(Class classType, String methodName) { + public JavaStaticMethodMIValue(Class classType, String methodName) { this.classType = classType; this.functionName = methodName; } @Override - public MIValue execute(ModelInterpreter interpreter, List arguments) { + public MIValue execute(IModelInterpreter interpreter, List arguments) { List> argumentTypes = arguments.stream() .map(InterpreterUtils::typeOfValue) .collect(Collectors.toList()); @@ -64,4 +64,14 @@ public MIValue execute(ModelInterpreter interpreter, List arguments) { return InterpreterUtils.objectToValue(returnObject); } + + @Override + public String printType() { + return "Java-Function"; + } + + @Override + public String printValue() { + return classType.getName() + "." + functionName; + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java similarity index 90% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java index 27da60e2d4..9e2e403564 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/LongMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java @@ -10,6 +10,11 @@ public class LongMIValue implements MIValue { public LongMIValue(long value) { this.value = value; } + + @Override + public boolean isPrimitive() { + return true; + } @Override public boolean isLong() { diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ModelFunctionMIValue.java similarity index 66% rename from monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/ModelFunctionMIValue.java index 781e5ea352..e51372e67f 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ASTFunctionMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ModelFunctionMIValue.java @@ -1,30 +1,28 @@ package de.monticore.interpreter.values; import de.monticore.ast.ASTNode; -import de.monticore.interpreter.InterpreterUtils; -import de.monticore.interpreter.MIValue; -import de.monticore.interpreter.MIScope; +import de.monticore.interpreter.*; -import de.monticore.interpreter.ModelInterpreter; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.types.check.SymTypeExpression; import java.util.List; +import java.util.Optional; -public class ASTFunctionMIValue implements FunctionMIValue { +public class ModelFunctionMIValue implements FunctionMIValue { protected MIScope parentScope; protected List parameterSymbols; protected ASTNode body; - public ASTFunctionMIValue(MIScope parentScope, List parameterSymbols, ASTNode body) { + public ModelFunctionMIValue(MIScope parentScope, List parameterSymbols, ASTNode body) { this.parentScope = parentScope; this.parameterSymbols = parameterSymbols; this.body = body; } @Override - public MIValue execute(ModelInterpreter interpreter, List arguments) { + public MIValue execute(IModelInterpreter interpreter, List arguments) { MIScope newScope = new MIScope(parentScope); for (int i = 0; i < parameterSymbols.size(); i++) { @@ -35,7 +33,7 @@ public MIValue execute(ModelInterpreter interpreter, List arguments) { argument = InterpreterUtils.convertImplicit(paramType, argument); if (argument.isError()) return argument; - newScope.declareVariable(parameterSymbol, argument); + newScope.declareVariable(parameterSymbol, Optional.of(argument)); } interpreter.pushScope(newScope); @@ -44,5 +42,15 @@ public MIValue execute(ModelInterpreter interpreter, List arguments) { return result; } + + @Override + public String printType() { + return "Model-Function"; + } + + @Override + public String printValue() { + return ""; + } } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java similarity index 100% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ShortMIValue.java similarity index 91% rename from monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/values/ShortMIValue.java index 7d565cf8cd..daf0232e3a 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ShortMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ShortMIValue.java @@ -10,6 +10,11 @@ public ShortMIValue(short value) { this.value = value; } + @Override + public boolean isPrimitive() { + return true; + } + @Override public boolean isShort() { return true; diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/VariableMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/VariableMIValue.java new file mode 100644 index 0000000000..39033a0b56 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/VariableMIValue.java @@ -0,0 +1,45 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.MIScope; +import de.monticore.interpreter.MIValue; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; + +import java.util.Optional; + +public class VariableMIValue extends WriteableMIValue { + + protected MIScope scope; + protected VariableSymbol symbol; + + protected Optional innerValue = Optional.empty(); + + public VariableMIValue(MIScope scope, VariableSymbol symbol) { + this.scope = scope; + this.symbol = symbol; + } + + @Override + public void write(MIValue value) { + scope.storeVariable(symbol, value); + innerValue = Optional.of(value); + } + + @Override + public MIValue getMIValue() { + if (!innerValue.isPresent()) { + innerValue = Optional.of(scope.loadVariable(symbol)); + } + + return innerValue.get(); + } + + @Override + public String printType() { + return "Variable"; + } + + @Override + public String printValue() { + return getMIValue().printType() + " (" + getMIValue().printValue() + ")"; + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/WriteableMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/WriteableMIValue.java new file mode 100644 index 0000000000..2627b314d4 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/WriteableMIValue.java @@ -0,0 +1,166 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.MIValue; + +public abstract class WriteableMIValue implements MIValue { + + @Override + public boolean isWriteable() { + return true; + } + + public abstract void write(MIValue value); + + public abstract MIValue getMIValue(); + + @Override + public boolean isPrimitive() { + + return getMIValue().isPrimitive(); + } + + @Override + public boolean isBoolean() { + return getMIValue().isBoolean(); + } + + @Override + public boolean isByte() { + return getMIValue().isByte(); + } + + @Override + public boolean isChar() { + return getMIValue().isChar(); + } + + @Override + public boolean isShort() { + return getMIValue().isShort(); + } + + @Override + public boolean isInt() { + return getMIValue().isInt(); + } + + @Override + public boolean isLong() { + return getMIValue().isLong(); + } + + @Override + public boolean isFloat() { + return getMIValue().isFloat(); + } + + @Override + public boolean isDouble() { + return getMIValue().isDouble(); + } + + @Override + public boolean isObject() { + return getMIValue().isObject(); + } + + @Override + public boolean isFunction() { + return getMIValue().isFunction(); + } + + @Override + public boolean isVoid() { + return getMIValue().isVoid(); + } + + @Override + public boolean isSIUnit() { + return getMIValue().isSIUnit(); + } + + @Override + public boolean isFlowControlSignal() { + return getMIValue().isFlowControlSignal(); + } + + @Override + public boolean isError() { + return getMIValue().isError(); + } + + @Override + public boolean isBreak() { + return getMIValue().isBreak(); + } + + @Override + public boolean isContinue() { + return getMIValue().isContinue(); + } + + @Override + public boolean isReturn() { + return getMIValue().isReturn(); + } + + @Override + public boolean asBoolean() { + return getMIValue().asBoolean(); + } + + @Override + public byte asByte() { + return getMIValue().asByte(); + } + + @Override + public char asChar() { + return getMIValue().asChar(); + } + + @Override + public short asShort() { + return getMIValue().asShort(); + } + + @Override + public int asInt() { + return getMIValue().asInt(); + } + + @Override + public long asLong() { + return getMIValue().asLong(); + } + + @Override + public float asFloat() { + return getMIValue().asFloat(); + } + + @Override + public double asDouble() { + return getMIValue().asDouble(); + } + + @Override + public FunctionMIValue asFunction() { + return getMIValue().asFunction(); + } + + @Override + public Object asObject() { + return getMIValue().asObject(); + } + + @Override + public MIValue asReturnValue() { + return getMIValue().asReturnValue(); + } + + @Override + public String asError() { + return getMIValue().asError(); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java index 8827e23cb6..b049567759 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java @@ -19,13 +19,6 @@ public MCCommonLiteralsInterpreter(ModelInterpreter realThis) { super(realThis); } - @Override - public MIValue interpret(ASTNullLiteral node) { - String errorMsg = "Null should not be used"; - Log.error(errorMsg); - return new ErrorMIValue(errorMsg); - } - @Override public MIValue interpret(ASTBooleanLiteral node){ return createValue(node.getValue()); diff --git a/monticore-grammar/src/main/java/de/monticore/ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java index 1dc301014d..90247bbfc0 100644 --- a/monticore-grammar/src/main/java/de/monticore/ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java @@ -29,7 +29,7 @@ public MIValue interpret(ASTIfThenElseExpression expr) { } MIValue conditionValue = expr.getCondition().evaluate(getRealThis()); - if (conditionValue.isError()) return conditionValue; + if (conditionValue.isFlowControlSignal()) return conditionValue; if (conditionValue.asBoolean()) { return expr.getThenExpression().evaluate(getRealThis()); diff --git a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreter.java index 77f74036b8..3f56e8bac9 100644 --- a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreter.java @@ -37,7 +37,7 @@ public MIValue interpret(ASTSetValueRange node) { if (rangeType.isEmpty() || rangeType.get().isObscureType() || !rangeType.get().isPrimitive() || !rangeType.get().asPrimitive().isIntegralType()) { String errorMsg = "0x57076 Failed to get common type of SetValueRange."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @@ -75,24 +75,24 @@ public MIValue interpret(ASTSetEnumeration node) { @Override public MIValue interpret(ASTGeneratorDeclaration node) { String errorMsg = "0x57080 ASTGeneratorDeclaration should not be evaluated directly."; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } @Override public MIValue interpret(ASTSetVariableDeclaration node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isError()) return value; + if (value.isFlowControlSignal()) return value; // should already be declared at start of SetComprehension - getRealThis().storeVariable(node.getSymbol(), value); + storeVariable(node.getSymbol(), value); return new VoidMIValue(); } private MIValue evaluateSetComprehensionItems(ASTSetComprehension node, int idx, Collection results) { if (idx >= node.getSetComprehensionItemList().size()) { MIValue result = node.getLeft().evaluate(getRealThis()); - if (result.isError()) return result; + if (result.isFlowControlSignal()) return result; results.add(InterpreterUtils.valueToObject(result)); return new VoidMIValue(); } @@ -100,24 +100,24 @@ private MIValue evaluateSetComprehensionItems(ASTSetComprehension node, int idx, if (item.isPresentGeneratorDeclaration()) { ASTGeneratorDeclaration generatorDeclaration = item.getGeneratorDeclaration(); MIValue collection = generatorDeclaration.getExpression().evaluate(getRealThis()); - if (collection.isError()) return collection; + if (collection.isFlowControlSignal()) return collection; Collection values = (Collection)collection.asObject(); for (Object obj : values) { - getRealThis().storeVariable(generatorDeclaration.getSymbol(), + storeVariable(generatorDeclaration.getSymbol(), InterpreterUtils.objectToValue(obj)); MIValue result = evaluateSetComprehensionItems(node, idx + 1, results); - if (result.isError()) return result; + if (result.isFlowControlSignal()) return result; } return MIValueFactory.createValue(results); } else if (item.isPresentExpression()) { MIValue filterValue = item.getExpression().evaluate(getRealThis()); - if (filterValue.isError()) return filterValue; + if (filterValue.isFlowControlSignal()) return filterValue; if (!filterValue.isBoolean()) { String errorMsg = "0x57078 SetComprehensionItem of type Expression should return a Boolean. Got " + filterValue.printType() + " (" + filterValue.printValue() + ")."; - Log.error(errorMsg); + Log.error(errorMsg, item.getExpression().get_SourcePositionStart(), item.getExpression().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } if (!filterValue.asBoolean()) { @@ -129,7 +129,10 @@ private MIValue evaluateSetComprehensionItems(ASTSetComprehension node, int idx, item.getSetVariableDeclaration().evaluate(getRealThis()); return evaluateSetComprehensionItems(node, idx+1, results); } - return new ErrorMIValue("0x57079 Encountered unexpected type of SetComprehensionItem."); + + String errorMsg = "0x57079 Encountered unexpected type of SetComprehensionItem."; + Log.error(errorMsg, item.get_SourcePositionStart(), item.get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); } @Override @@ -142,19 +145,19 @@ public MIValue interpret(ASTSetComprehension node) { } MIScope scope = new MIScope(getRealThis().getCurrentScope()); - getRealThis().pushScope(scope); + pushScope(scope); for (ASTSetComprehensionItem item : node.getSetComprehensionItemList()) { if (item.isPresentSetVariableDeclaration()) { ASTSetVariableDeclaration variableDeclaration = item.getSetVariableDeclaration(); - getRealThis().declareVariable(variableDeclaration.getSymbol(), null); + declareVariable(variableDeclaration.getSymbol(), Optional.empty()); } else if (item.isPresentGeneratorDeclaration()) { ASTGeneratorDeclaration generatorDeclaration = item.getGeneratorDeclaration(); - getRealThis().declareVariable(generatorDeclaration.getSymbol(), null); + declareVariable(generatorDeclaration.getSymbol(), Optional.empty()); } } MIValue result = evaluateSetComprehensionItems(node, 0, results); - getRealThis().popScope(); - if (result.isError()) return result; + popScope(); + if (result.isFlowControlSignal()) return result; return MIValueFactory.createValue(results); } @@ -165,13 +168,13 @@ public MIValue interpret(ASTSetComprehensionItem node) { } else if (node.isPresentSetVariableDeclaration()) { ASTSetVariableDeclaration variableDeclaration = node.getSetVariableDeclaration(); MIValue value = variableDeclaration.getExpression().evaluate(getRealThis()); - if (value.isError()) return value; - getRealThis().declareVariable(variableDeclaration.getSymbol(), value); + if (value.isFlowControlSignal()) return value; + getRealThis().declareVariable(variableDeclaration.getSymbol(), Optional.of(value)); return new VoidMIValue(); } String errorMsg = "0x57077 Unexpected type of ASTSetComprehensionItem"; - Log.error(errorMsg); + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } } diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java new file mode 100644 index 0000000000..97979cb7d4 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java @@ -0,0 +1,202 @@ +package de.monticore.statements.mccommonstatements._visitor; + +import de.monticore.expressions.expressionsbasis._ast.ASTExpression; +import de.monticore.interpreter.*; +import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.MIBreakSignal; +import de.monticore.interpreter.values.VoidMIValue; +import de.monticore.statements.mccommonstatements._ast.*; +import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.se_rwth.commons.logging.Log; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +public class MCCommonStatementsInterpreter extends MCCommonStatementsInterpreterTOP { + + public MCCommonStatementsInterpreter() { + super(); + } + + public MCCommonStatementsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + @Override + public MIValue interpret(ASTMCJavaBlock node) { + MIScope scope = new MIScope(getRealThis().getCurrentScope()); + pushScope(scope); + + for (ASTMCBlockStatement statement : node.getMCBlockStatementList()) { + MIValue result = statement.evaluate(getRealThis()); + if (result.isFlowControlSignal()) { + popScope(); + return result; + } + } + + popScope(); + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTIfStatement node) { + MIValue condition = node.getCondition().evaluate(getRealThis()); + if (condition.isFlowControlSignal()) return condition; + + if (condition.asBoolean()) { + MIValue result = node.getThenStatement().evaluate(getRealThis()); + if (result.isFlowControlSignal()) return result; + } else if (node.isPresentElseStatement()) { + MIValue result = node.getElseStatement().evaluate(getRealThis()); + if (result.isFlowControlSignal()) return result; + } + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTWhileStatement node) { + MIScope scope = new MIScope(getRealThis().getCurrentScope()); + pushScope(scope); + + MIValue condition = node.getCondition().evaluate(getRealThis()); + while (condition.isBoolean() && condition.asBoolean()) { + MIValue result = node.getMCStatement().evaluate(getRealThis()); + if (result.isBreak()) break; + if (result.isContinue()) continue; + if (result.isFlowControlSignal()) { + popScope(); + return result; + } + + condition = node.getCondition().evaluate(getRealThis()); + } + + popScope(); + if (condition.isFlowControlSignal()) { + return condition; + } else { + return new VoidMIValue(); + } + } + + @Override + public MIValue interpret(ASTDoWhileStatement node) { + MIScope scope = new MIScope(getRealThis().getCurrentScope()); + pushScope(scope); + + MIValue condition = MIValueFactory.createValue(true); + while (condition.isBoolean() && condition.asBoolean()) { + MIValue result = node.getMCStatement().evaluate(getRealThis()); + if (result.isBreak()) break; + if (result.isContinue()) continue; + if (result.isFlowControlSignal()) { + popScope(); + return result; + } + + condition = node.getCondition().evaluate(getRealThis()); + } + + popScope(); + if (condition.isFlowControlSignal()) { + return condition; + } else { + return new VoidMIValue(); + } + } + + @Override + public MIValue interpret(ASTEmptyStatement node) { + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTExpressionStatement node) { + MIValue result = node.getExpression().evaluate(getRealThis()); + if (result.isFlowControlSignal()) return result; + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTForStatement node) { + MIScope scope = new MIScope(getRealThis().getCurrentScope()); + pushScope(scope); + + MIValue control = node.getForControl().evaluate(getRealThis()); + if (control.isFlowControlSignal()) { + popScope(); + return control; + } + + MIForIterator controlIterator = (MIForIterator)control.asObject(); + + MIValue result = controlIterator.execute(getRealThis(), node.getMCStatement()); + popScope(); + return result.isFlowControlSignal() ? result : new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTCommonForControl node) { + Optional initNode = node.isPresentForInit() ? Optional.of(node.getForInit()) : Optional.empty(); + Optional condition = node.isPresentCondition() ? Optional.of(node.getCondition()) : Optional.empty(); + List expressions = node.getExpressionList(); + MICommonForIterator iterator = new MICommonForIterator(initNode, condition, expressions); + return MIValueFactory.createValue(iterator); + } + + @Override + public MIValue interpret(ASTForInit node) { + if (node.isPresentForInitByExpressions()) { + return node.getForInitByExpressions().evaluate(getRealThis()); + } else if (node.isPresentLocalVariableDeclaration()) { + return node.getLocalVariableDeclaration().evaluate(getRealThis()); + } + + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTForInitByExpressions node) { + for (ASTExpression expression : node.getExpressionList()) { + MIValue result = expression.evaluate(getRealThis()); + if (result.isFlowControlSignal()) return result; + } + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTEnhancedForControl node) { + MIValue collectionValue = node.getExpression().evaluate(getRealThis()); + if (collectionValue.isFlowControlSignal()) return collectionValue; + + if (!(collectionValue.asObject() instanceof Collection)) { + String errorMsg = "0x57082 Expected a collection in for-each loop. Got " + collectionValue.printType() + + " (" + collectionValue.printValue() + ")."; + Log.error(errorMsg, node.getExpression().get_SourcePositionStart(), node.getExpression().get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); + } + + Collection collection = (Collection)(collectionValue.asObject()); + VariableSymbol symbol = node.getFormalParameter().getDeclarator().getSymbol(); + MIForIterator iterator = new MIForEachIterator(symbol, collection.iterator()); + return MIValueFactory.createValue(iterator); + } + + @Override + public MIValue interpret(ASTFormalParameter node) { + MIValue result = node.getDeclarator().evaluate(getRealThis()); + if (result.isFlowControlSignal()) { + return result; + } else { + return new VoidMIValue(); + } + } + + @Override + public MIValue interpret(ASTBreakStatement node) { + return new MIBreakSignal(); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mclowlevelstatements/_visitor/MCLowLevelStatementsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/statements/mclowlevelstatements/_visitor/MCLowLevelStatementsInterpreter.java new file mode 100644 index 0000000000..3b752f11af --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/statements/mclowlevelstatements/_visitor/MCLowLevelStatementsInterpreter.java @@ -0,0 +1,28 @@ +package de.monticore.statements.mclowlevelstatements._visitor; + +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.MIContinueSignal; +import de.monticore.statements.mclowlevelstatements._ast.ASTContinueStatement; +import de.se_rwth.commons.logging.Log; + +public class MCLowLevelStatementsInterpreter extends MCLowLevelStatementsInterpreterTOP { + + public MCLowLevelStatementsInterpreter() {} + + public MCLowLevelStatementsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + @Override + public MIValue interpret(ASTContinueStatement node) { + if (node.isPresentLabel()) { + String errorMsg = "0x57085 Labels are not supported for Continue Statements."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + return new MIContinueSignal(); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mcreturnstatements/_visitor/MCReturnStatementsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/statements/mcreturnstatements/_visitor/MCReturnStatementsInterpreter.java new file mode 100644 index 0000000000..6355e58201 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/statements/mcreturnstatements/_visitor/MCReturnStatementsInterpreter.java @@ -0,0 +1,27 @@ +package de.monticore.statements.mcreturnstatements._visitor; + +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.values.MIReturnSignal; +import de.monticore.statements.mcreturnstatements._ast.ASTReturnStatement; + +public class MCReturnStatementsInterpreter extends MCReturnStatementsInterpreterTOP { + + public MCReturnStatementsInterpreter() {} + + public MCReturnStatementsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + @Override + public MIValue interpret(ASTReturnStatement node) { + if (node.isPresentExpression()) { + MIValue returnValue = node.getExpression().evaluate(getRealThis()); + if (returnValue.isFlowControlSignal()) return returnValue; + + return new MIReturnSignal(returnValue); + } else { + return new MIReturnSignal(); + } + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_visitor/MCVarDeclarationStatementsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_visitor/MCVarDeclarationStatementsInterpreter.java new file mode 100644 index 0000000000..8d3a64c8c3 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_visitor/MCVarDeclarationStatementsInterpreter.java @@ -0,0 +1,50 @@ +package de.monticore.statements.mcvardeclarationstatements._visitor; + +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.values.VoidMIValue; +import de.monticore.statements.mcvardeclarationstatements._ast.*; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; + +import java.util.Optional; + +public class MCVarDeclarationStatementsInterpreter extends MCVarDeclarationStatementsInterpreterTOP { + + public MCVarDeclarationStatementsInterpreter() {} + + public MCVarDeclarationStatementsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + @Override + public MIValue interpret(ASTLocalVariableDeclarationStatement node) { + MIValue result = node.getLocalVariableDeclaration().evaluate(getRealThis()); + if (result.isError()) return result; + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTLocalVariableDeclaration node) { + for (ASTVariableDeclarator declarator : node.getVariableDeclaratorList()) { + MIValue result = declarator.evaluate(getRealThis()); + if (result.isError()) return result; + } + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTVariableDeclarator node) { + VariableSymbol symbol = node.getDeclarator().getSymbol(); + if (node.isPresentVariableInit()) { + MIValue initialValue = node.getVariableInit().evaluate(getRealThis()); + if (initialValue.isError()) return initialValue; + getRealThis().declareVariable(symbol, Optional.of(initialValue)); + } + return new VoidMIValue(); + } + + @Override + public MIValue interpret(ASTSimpleInit node) { + return node.getExpression().evaluate(getRealThis()); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeVoid.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeVoid.java index e1d2f5bbfd..a044c0c654 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeVoid.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeVoid.java @@ -15,7 +15,7 @@ public class SymTypeVoid extends SymTypeExpression { @Deprecated public SymTypeVoid() { typeSymbol = new TypeSymbolSurrogate(BasicSymbolsMill.VOID); - typeSymbol.setEnclosingScope(BasicSymbolsMill.scope()); + typeSymbol.setEnclosingScope(BasicSymbolsMill.globalScope()); } @Override diff --git a/monticore-grammar/src/test/grammars/de/monticore/statements/CombineStatementsWithExpressions.mc4 b/monticore-grammar/src/test/grammars/de/monticore/statements/CombineStatementsWithExpressions.mc4 new file mode 100644 index 0000000000..a8b17a13e9 --- /dev/null +++ b/monticore-grammar/src/test/grammars/de/monticore/statements/CombineStatementsWithExpressions.mc4 @@ -0,0 +1,13 @@ +/* (c) https://github.com/MontiCore/monticore */ + +package de.monticore.statements; + +grammar CombineStatementsWithExpressions + extends MCCommonStatements, + MCReturnStatements, + MCLowLevelStatements, + de.monticore.expressions.CombineExpressionsWithLiterals { + + start MCBlockStatement; + +} \ No newline at end of file diff --git a/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java new file mode 100644 index 0000000000..bc8902c81a --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java @@ -0,0 +1,146 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore; + +import de.monticore.antlr4.MCConcreteParser; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.types3.SymTypeRelations; +import de.monticore.types3.Type4Ast; +import de.monticore.types3.util.*; +import de.monticore.visitor.ITraverser; +import de.se_rwth.commons.logging.Finding; +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; + +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; + +public abstract class AbstractInterpreterTest { + + protected static final double delta = 0.00001; + + protected Type4Ast type4Ast; + + protected ITraverser typeMapTraverser; + + @Deprecated + protected ITraverser scopeGenitor; + + protected ITraverser symbolTableCompleter; + + protected MCConcreteParser parser; + protected ModelInterpreter interpreter; + + protected Supplier parserSupplier; + protected Runnable resetMill; + protected Runnable initMill; + + + @BeforeEach + public void init() { + LogStub.init(); + Log.clearFindings(); + Log.enableFailQuick(false); + + resetMill.run(); + initMill.run(); + BasicSymbolsMill.initializePrimitives(); + SymTypeRelations.init(); + WithinScopeBasicSymbolsResolver.init(); + WithinTypeBasicSymbolsResolver.init(); + TypeVisitorOperatorCalculator.init(); + DefsTypesForTests.setup(); + parser = parserSupplier.get(); + MapBasedTypeCheck3 tc3 = CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); + type4Ast = tc3.getType4Ast(); + typeMapTraverser = tc3.getTypeTraverser(); + setupSymbolTableCompleter(typeMapTraverser, type4Ast); + } + + protected abstract void setupSymbolTableCompleter(ITraverser typeMapTraverser, Type4Ast type4Ast); + + protected Type4Ast getType4Ast() { + return type4Ast; + } + + protected ITraverser getSymbolTableCompleter() { + return symbolTableCompleter; + } + + /** + * @return all findings as one String + */ + protected static String getAllFindingsAsString() { + return Log.getFindings().stream() + .map(Finding::buildMsg) + .collect(Collectors.joining(System.lineSeparator())) + ; + } + + public MIValue loadVariable(String name) { + VariableSymbol symbol = BasicSymbolsMill.globalScope().resolveVariable(name).get(); + return interpreter.loadVariable(symbol); + } + + public MIValue loadFunction(String name) { + FunctionSymbol symbol = BasicSymbolsMill.globalScope().resolveFunction(name).get(); + return interpreter.loadFunction(symbol); + } + + public void assertValue(MIValue expected, MIValue actual) { + if (expected.isVoid()) { + assertTrue(actual.isVoid()); + } else if (expected.isError()) { + assertTrue(actual.isError()); + assertEquals(expected.asError(), actual.asError()); + } else if (expected.isBreak()) { + assertTrue(actual.isBreak()); + } else if (expected.isContinue()) { + assertTrue(actual.isContinue()); + } else if (expected.isReturn()) { + assertTrue(actual.isReturn()); + assertValue(expected.asReturnValue(), actual.asReturnValue()); + } else if (expected.isBoolean()) { + assertTrue(actual.isBoolean()); + assertEquals(expected.asBoolean(), actual.asBoolean()); + } else if (expected.isByte()) { + assertTrue(actual.isByte()); + Assertions.assertEquals(expected.asByte(), actual.asByte()); + } else if (expected.isShort()) { + assertTrue(actual.isShort()); + assertEquals(expected.asShort(), actual.asShort()); + } else if (expected.isChar()) { + assertTrue(actual.isChar()); + assertEquals(expected.asChar(), actual.asChar()); + } else if (expected.isInt()) { + assertTrue(actual.isInt()); + assertEquals(expected.asInt(), actual.asInt()); + } else if (expected.isLong()) { + assertTrue(actual.isLong()); + assertEquals(expected.asLong(), actual.asLong()); + } else if (expected.isFloat()) { + assertTrue(actual.isFloat()); + assertEquals(expected.asFloat(), actual.asFloat()); + } else if (expected.isDouble()) { + assertTrue(actual.isDouble()); + assertEquals(expected.asDouble(), actual.asDouble()); + } else if (expected.isFunction()) { + assertTrue(actual.isFunction()); + } else if (expected.isObject()) { + assertTrue(actual.isObject()); + assertEquals(expected.asObject(), actual.asObject()); + } else { + Log.error("Trying to compare unsupported MIValue type '" + expected.printType() + "'."); + fail(); + } + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java similarity index 55% rename from monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java rename to monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java index 6239c40f62..09a26cfde4 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java @@ -1,48 +1,53 @@ -/* (c) https://github.com/MontiCore/monticore */ package de.monticore.expressions; +import de.monticore.AbstractInterpreterTest; import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; -import de.monticore.expressions.combineexpressionswithliterals._symboltable.CombineExpressionsWithLiteralsScopesGenitorDelegator; +import de.monticore.expressions.combineexpressionswithliterals._ast.ASTFoo; +import de.monticore.expressions.combineexpressionswithliterals._parser.CombineExpressionsWithLiteralsParser; +import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsArtifactScope; import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsInterpreter; +import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsTraverser; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; +import de.monticore.expressions.lambdaexpressions._symboltable.LambdaExpressionsSTCompleteTypes2; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.ocl.oclexpressions.symboltable.OCLExpressionsSymbolTableCompleter; +import de.monticore.ocl.setexpressions.symboltable.SetExpressionsSymbolTableCompleter; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; -import de.monticore.symboltable.ImportStatement; +import de.monticore.types.check.IDerive; +import de.monticore.types.check.ISynthesize; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types3.AbstractTypeVisitorTest; +import de.monticore.types.check.types3wrapper.TypeCheck3AsIDerive; +import de.monticore.types.check.types3wrapper.TypeCheck3AsISynthesize; +import de.monticore.types3.Type4Ast; import de.monticore.types3.TypeCheck3; +import de.monticore.visitor.ITraverser; import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import java.io.IOException; -import java.util.Collections; -import java.util.List; +import java.util.Optional; import static de.monticore.interpreter.MIValueFactory.createValue; import static de.monticore.types3.util.DefsTypesForTests.inScope; import static de.monticore.types3.util.DefsTypesForTests.variable; -import static junit.framework.TestCase.*; -import static junit.framework.TestCase.assertEquals; +import static org.junit.jupiter.api.Assertions.*; -public abstract class AbstractInterpreterTest extends AbstractTypeVisitorTest { - - protected static final double delta = 0.00001; - - protected CombineExpressionsWithLiteralsInterpreter interpreter; - protected CombineExpressionsWithLiteralsScopesGenitorDelegator delegator; +public class AbstractExpressionInterpreterTest extends AbstractInterpreterTest { + @Override @BeforeEach public void init() { - LogStub.init(); - Log.clearFindings(); - Log.enableFailQuick(false); + parserSupplier = CombineExpressionsWithLiteralsMill::parser; + resetMill = CombineExpressionsWithLiteralsMill::reset; + initMill = CombineExpressionsWithLiteralsMill::init; + + super.init(); - delegator = CombineExpressionsWithLiteralsMill.scopesGenitorDelegator(); interpreter = new CombineExpressionsWithLiteralsInterpreter(); - + try { initBool(); initChar(); @@ -56,64 +61,60 @@ public void init() { System.out.println(e.getMessage()); } } - + protected void initBool() throws IOException { VariableSymbol varSymbol = variable("b", SymTypeExpressionFactory.createPrimitive("boolean")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); - interpreter.declareVariable(varSymbol, createValue(true)); + interpreter.declareVariable(varSymbol, Optional.of(createValue(true))); } protected void initChar() throws IOException { VariableSymbol varSymbol = variable("c", SymTypeExpressionFactory.createPrimitive("char")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); - interpreter.declareVariable(varSymbol, createValue('a')); + interpreter.declareVariable(varSymbol, Optional.of(createValue('a'))); } protected void initByte() throws IOException { VariableSymbol varSymbol = variable("by", SymTypeExpressionFactory.createPrimitive("byte")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); - interpreter.declareVariable(varSymbol, createValue((byte)3)); + interpreter.declareVariable(varSymbol, Optional.of(createValue((byte)3))); } protected void initShort() throws IOException { VariableSymbol varSymbol = variable("s", SymTypeExpressionFactory.createPrimitive("short")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); - interpreter.declareVariable(varSymbol, createValue((short)256)); + interpreter.declareVariable(varSymbol, Optional.of(createValue((short)256))); } - + protected void initInt() throws IOException { VariableSymbol varSymbol = variable("i", SymTypeExpressionFactory.createPrimitive("int")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); - interpreter.declareVariable(varSymbol, createValue(1)); + interpreter.declareVariable(varSymbol, Optional.of(createValue(1))); } - + protected void initLong() throws IOException { VariableSymbol varSymbol = variable("l", SymTypeExpressionFactory.createPrimitive("long")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); - interpreter.declareVariable(varSymbol, createValue(5L)); + interpreter.declareVariable(varSymbol, Optional.of(createValue(5L))); } - + protected void initFloat() throws IOException { VariableSymbol varSymbol = variable("f", SymTypeExpressionFactory.createPrimitive("float")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); - interpreter.declareVariable(varSymbol, createValue(1.5f)); + interpreter.declareVariable(varSymbol, Optional.of(createValue(1.5f))); } - + protected void initDouble() throws IOException { VariableSymbol varSymbol = variable("d", SymTypeExpressionFactory.createPrimitive("double")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); - interpreter.declareVariable(varSymbol, createValue(3.14)); + interpreter.declareVariable(varSymbol, Optional.of(createValue(3.14))); } protected void testValidExpression(String expr, MIValue expected) { - testValidExpression(expr, expected, Collections.emptyList()); - } - - protected void testValidExpression(String expr, MIValue expected, List imports) { Log.clearFindings(); MIValue interpretationResult = null; try { - interpretationResult = parseExpressionAndInterpret(expr, imports); + interpretationResult = parseExpressionAndInterpret(expr); } catch (IOException e) { System.out.println(e.getMessage()); } @@ -154,15 +155,11 @@ protected void testValidExpression(String expr, MIValue expected, List imports) { Log.clearFindings(); MIValue interpretationResult; try { - interpretationResult = parseExpressionAndInterpret(expr, imports); + interpretationResult = parseExpressionAndInterpret(expr); } catch (IOException e) { throw new RuntimeException(e); } @@ -172,21 +169,72 @@ protected void testInvalidExpression(String expr, List imports) assertTrue(interpretationResult.isError()); } - protected MIValue parseExpressionAndInterpret(String expr, List imports) throws IOException { + protected MIValue parseExpressionAndInterpret(String expr) throws IOException { final ASTExpression ast = parseExpr(expr); generateScopes(ast); - addImports(imports); SymTypeExpression type = TypeCheck3.typeOf(ast); if (type.isObscureType()) { - String errorMsg = "Invalid Expression: " + expr; + String errorMsg = "Invalid Model: " + expr; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - return interpreter.interpret(ast); + return ast.evaluate(interpreter); + } + + protected ASTExpression parseExpr(String exprStr) throws IOException { + Optional astExpression = parseStringExpr(exprStr); + Assertions.assertTrue(astExpression.isPresent(), getAllFindingsAsString()); + return astExpression.get(); } - protected void addImports(List imports) { - CombineExpressionsWithLiteralsMill.artifactScope().setImportsList(imports); + // Parse a String expression of the according language + protected Optional parseStringExpr(String exprStr) + throws IOException { + return ((CombineExpressionsWithLiteralsParser)parser).parse_StringExpression(exprStr); + } + + protected void generateScopes(ASTExpression expr) { + // create a root + ASTFoo rootNode = CombineExpressionsWithLiteralsMill.fooBuilder() + .setExpression(expr) + .build(); + ICombineExpressionsWithLiteralsArtifactScope rootScope = + CombineExpressionsWithLiteralsMill.scopesGenitorDelegator() + .createFromAST(rootNode); + + rootScope.setName("fooRoot"); + // complete the symbol table + expr.accept(getSymbolTableCompleter()); + } + + protected void setupSymbolTableCompleter( + ITraverser typeMapTraverser, Type4Ast type4Ast) { + CombineExpressionsWithLiteralsTraverser combinedScopesCompleter = + CombineExpressionsWithLiteralsMill.traverser(); + IDerive deriver = new TypeCheck3AsIDerive(); + ISynthesize synthesizer = new TypeCheck3AsISynthesize(); + combinedScopesCompleter.add4LambdaExpressions( + new LambdaExpressionsSTCompleteTypes2( + typeMapTraverser, + getType4Ast() + ) + ); + OCLExpressionsSymbolTableCompleter oclExprCompleter = + new OCLExpressionsSymbolTableCompleter(); + oclExprCompleter.setDeriver(deriver); + oclExprCompleter.setSynthesizer(synthesizer); + combinedScopesCompleter.add4OCLExpressions(oclExprCompleter); + combinedScopesCompleter.setOCLExpressionsHandler(oclExprCompleter); + + SetExpressionsSymbolTableCompleter setExprCompleter = + new SetExpressionsSymbolTableCompleter(); + setExprCompleter.setDeriver(deriver); + setExprCompleter.setSynthesizer(synthesizer); + combinedScopesCompleter.add4SetExpressions(setExprCompleter); + combinedScopesCompleter.setSetExpressionsHandler(setExprCompleter); + + symbolTableCompleter = combinedScopesCompleter; + scopeGenitor = combinedScopesCompleter; } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java index dbd5033483..a0691523c4 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java @@ -1,7 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.expressions.assignmentexpressions._visitor; -import de.monticore.expressions.AbstractInterpreterTest; +import de.monticore.expressions.AbstractExpressionInterpreterTest; import de.monticore.interpreter.MIValue; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -12,7 +12,7 @@ import static org.junit.jupiter.params.provider.Arguments.arguments; import static de.monticore.interpreter.MIValueFactory.createValue; -public class AssignmentExpressionsInterpreterTest extends AbstractInterpreterTest { +public class AssignmentExpressionsInterpreterTest extends AbstractExpressionInterpreterTest { protected static Stream incSuffixExpression() { return Stream.of( diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java index 13d81303a2..39041da3d9 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java @@ -1,11 +1,11 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.expressions.commonexpressions._visitor; -import de.monticore.expressions.AbstractInterpreterTest; +import de.monticore.expressions.AbstractExpressionInterpreterTest; import de.monticore.interpreter.MIValueFactory; import org.junit.jupiter.api.Test; -public class CommonExpressionsInterpreterTest extends AbstractInterpreterTest { +public class CommonExpressionsInterpreterTest extends AbstractExpressionInterpreterTest { @Test public void testInterpretPlusExpression() { diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java index 26d575fbe7..c796f23d21 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java @@ -1,13 +1,14 @@ package de.monticore.expressions.lambdaexpressions; -import de.monticore.expressions.AbstractInterpreterTest; +import de.monticore.AbstractInterpreterTest; +import de.monticore.expressions.AbstractExpressionInterpreterTest; import org.junit.jupiter.api.Test; import java.io.IOException; import static de.monticore.interpreter.MIValueFactory.createValue; -public class LambdaExpressionsInterpreterTest extends AbstractInterpreterTest { +public class LambdaExpressionsInterpreterTest extends AbstractExpressionInterpreterTest { @Test public void testSimpleLambda() throws IOException { diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/streamexpressions/parser/StreamExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/streamexpressions/parser/StreamExpressionsInterpreterTest.java new file mode 100644 index 0000000000..69d603d075 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/expressions/streamexpressions/parser/StreamExpressionsInterpreterTest.java @@ -0,0 +1,17 @@ +package de.monticore.expressions.streamexpressions.parser; + +import de.monticore.expressions.AbstractExpressionInterpreterTest; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static de.monticore.interpreter.MIValueFactory.createValue; + +public class StreamExpressionsInterpreterTest extends AbstractExpressionInterpreterTest { + + @Test + public void testSimpleLambda() throws IOException { + testValidExpression("(() -> 1)()", createValue(1)); + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java new file mode 100644 index 0000000000..822bfc2ac5 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java @@ -0,0 +1,162 @@ +package de.monticore.statements; + +import de.monticore.AbstractInterpreterTest; +import de.monticore.class2mc.OOClass2MCResolver; +import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; +import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsArtifactScope; +import de.monticore.expressions.lambdaexpressions._symboltable.LambdaExpressionsSTCompleteTypes2; +import de.monticore.interpreter.MIValue; +import de.monticore.io.paths.MCPath; +import de.monticore.ocl.oclexpressions.symboltable.OCLExpressionsSymbolTableCompleter; +import de.monticore.ocl.setexpressions.symboltable.SetExpressionsSymbolTableCompleter; +import de.monticore.statements.combinestatementswithexpressions.CombineStatementsWithExpressionsMill; +import de.monticore.statements.combinestatementswithexpressions._parser.CombineStatementsWithExpressionsParser; +import de.monticore.statements.combinestatementswithexpressions._symboltable.CombineStatementsWithExpressionsScopesGenitorDelegator; +import de.monticore.statements.combinestatementswithexpressions._symboltable.ICombineStatementsWithExpressionsArtifactScope; +import de.monticore.statements.combinestatementswithexpressions._visitor.CombineStatementsWithExpressionsInterpreter; +import de.monticore.statements.combinestatementswithexpressions._visitor.CombineStatementsWithExpressionsTraverser; +import de.monticore.statements.mccommonstatements._symboltable.MCCommonStatementsSymTabCompletion; +import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; +import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; +import de.monticore.statements.mcvardeclarationstatements._symboltable.MCVarDeclarationStatementsSymTabCompletion; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.oosymbols.OOSymbolsMill; +import de.monticore.symboltable.ImportStatement; +import de.monticore.types.check.IDerive; +import de.monticore.types.check.ISynthesize; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.types3wrapper.TypeCheck3AsIDerive; +import de.monticore.types.check.types3wrapper.TypeCheck3AsISynthesize; +import de.monticore.types3.Type4Ast; +import de.monticore.types3.TypeCheck3; +import de.monticore.types3.util.DefsTypesForTests; +import de.monticore.visitor.ITraverser; +import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +public abstract class AbstractStatementInterpreterTest extends AbstractInterpreterTest { + + @Override + @BeforeEach + public void init() { + parserSupplier = CombineStatementsWithExpressionsMill::parser; + resetMill = CombineStatementsWithExpressionsMill::reset; + initMill = CombineStatementsWithExpressionsMill::init; + + super.init(); + + interpreter = new CombineStatementsWithExpressionsInterpreter(); + } + + protected MIValue testValidModel(String model) { + return testValidModel(model, Collections.emptyList()); + } + + protected MIValue testValidModel(String model, List imports) { + Log.clearFindings(); + Optional astNodeOpt = Optional.empty(); + try { + astNodeOpt = ((CombineStatementsWithExpressionsParser)parser).parse_String(model); + } catch (IOException e) { + System.out.println(e.getMessage()); + fail(); + } + + if (!Log.getFindings().isEmpty()) { + Log.printFindings(); + fail(); + } + assertTrue(astNodeOpt.isPresent()); + + CombineStatementsWithExpressionsMill.artifactScope().setImportsList(imports); + + OOClass2MCResolver resolver = new OOClass2MCResolver(); + + OOSymbolsMill.reset(); + OOSymbolsMill.init(); + CombineStatementsWithExpressionsMill.reset(); + CombineStatementsWithExpressionsMill.init(); + CombineStatementsWithExpressionsMill.globalScope().clear(); + + DefsTypesForTests.setup(); + + CombineStatementsWithExpressionsMill.globalScope().getSymbolPath().addEntry(OOClass2MCResolver.getJRTPath()); + CombineStatementsWithExpressionsMill.globalScope().addAdaptedTypeSymbolResolver(resolver); + CombineStatementsWithExpressionsMill.globalScope().addAdaptedOOTypeSymbolResolver(resolver); + + CombineStatementsWithExpressionsMill.globalScope().setSymbolPath(new MCPath()); + + ICombineStatementsWithExpressionsArtifactScope rootScope = + CombineStatementsWithExpressionsMill.scopesGenitorDelegator() + .createFromAST(astNodeOpt.get()); + + rootScope.setName("root"); + + astNodeOpt.get().accept(getSymbolTableCompleter()); + + MIValue interpretationResult = astNodeOpt.get().evaluate(interpreter); + + assertNotNull(interpretationResult); + if (!Log.getFindings().isEmpty()) { + Log.printFindings(); + fail(); + } + + assertTrue(interpretationResult.isReturn() || interpretationResult.isVoid()); + if (interpretationResult.isReturn()) { + interpretationResult = interpretationResult.asReturnValue(); + } + + return interpretationResult; + } + + protected void addImports(List imports) { + CombineStatementsWithExpressionsMill.artifactScope().setImportsList(imports); + } + + protected void setupSymbolTableCompleter( + ITraverser typeMapTraverser, Type4Ast type4Ast) { + CombineStatementsWithExpressionsTraverser combinedScopesCompleter = + CombineStatementsWithExpressionsMill.traverser(); + IDerive deriver = new TypeCheck3AsIDerive(); + ISynthesize synthesizer = new TypeCheck3AsISynthesize(); + combinedScopesCompleter.add4LambdaExpressions( + new LambdaExpressionsSTCompleteTypes2( + typeMapTraverser, + getType4Ast() + ) + ); + OCLExpressionsSymbolTableCompleter oclExprCompleter = + new OCLExpressionsSymbolTableCompleter(); + oclExprCompleter.setDeriver(deriver); + oclExprCompleter.setSynthesizer(synthesizer); + combinedScopesCompleter.add4OCLExpressions(oclExprCompleter); + combinedScopesCompleter.setOCLExpressionsHandler(oclExprCompleter); + + SetExpressionsSymbolTableCompleter setExprCompleter = + new SetExpressionsSymbolTableCompleter(); + setExprCompleter.setDeriver(deriver); + setExprCompleter.setSynthesizer(synthesizer); + combinedScopesCompleter.add4SetExpressions(setExprCompleter); + + MCVarDeclarationStatementsSymTabCompletion varDeclCompleter = + new MCVarDeclarationStatementsSymTabCompletion(); + combinedScopesCompleter.add4MCVarDeclarationStatements(varDeclCompleter); + + MCCommonStatementsSymTabCompletion commonStmtCompleter = + new MCCommonStatementsSymTabCompletion(); + combinedScopesCompleter.add4MCCommonStatements(commonStmtCompleter); + + combinedScopesCompleter.setSetExpressionsHandler(setExprCompleter); + symbolTableCompleter = combinedScopesCompleter; + scopeGenitor = combinedScopesCompleter; + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsInterpreter.java b/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsInterpreter.java new file mode 100644 index 0000000000..ff1f20fc77 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsInterpreter.java @@ -0,0 +1,17 @@ +package de.monticore.statements.combinestatementswithexpressions._visitor; + +import de.monticore.interpreter.ModelInterpreter; + +public class CombineStatementsWithExpressionsInterpreter extends CombineStatementsWithExpressionsInterpreterTOP { + + public CombineStatementsWithExpressionsInterpreter() { + super(); + } + + public CombineStatementsWithExpressionsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + + +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java b/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java new file mode 100644 index 0000000000..1aace4ad93 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java @@ -0,0 +1,158 @@ +package de.monticore.statements.combinestatementswithexpressions._visitor; + +import de.monticore.interpreter.MIValue; +import de.monticore.statements.AbstractStatementInterpreterTest; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static de.monticore.interpreter.MIValueFactory.createValue; + +public class CombineStatementsWithExpressionsTest extends AbstractStatementInterpreterTest { + + @Test + public void testVarDeclarationStatement() { + testValidModel("int i = 0;"); + assertValue(createValue(0), loadVariable("i")); + + testValidModel("int j = 1, k = 2;"); + assertValue(createValue(1), loadVariable("j")); + assertValue(createValue(2), loadVariable("k")); + } + + @Test + public void testJavaBlockStatement() { + MIValue result = testValidModel( + "{ \n" + + " int i = 0; \n" + + " int j = 1; \n" + + " { \n" + + " int k = 2 * j; \n" + + " k += 40; \n" + + " j = k; \n" + + " } \n" + + " return [i, j]; \n" + + "} " + ); + assertValue(createValue(List.of(0, 42)), result); + } + + @Test + public void testCommonWhileStatement() { + MIValue result = testValidModel( + "{ \n" + + " int i = 255, count = 0; \n" + + " while (i != 0) { \n" + + " i /= 2; \n" + + " count++; \n" + + " } \n" + + " return count; \n" + + "} " + ); + assertValue(createValue(8), result); + } + + @Test + public void testCommonDoWhileStatement() { + MIValue result = testValidModel( + "{ \n" + + " int i = 0, count = 0; \n" + + " do { \n" + + " i /= 2; \n" + + " count++; \n" + + " } while (false); \n" + + " return count; \n" + + "} " + ); + assertValue(createValue(1), result); + } + + @Test + public void testCommonForStatement() { + MIValue result = testValidModel( + "{ \n" + + " int count = 0; \n" + + " for (int i = 0; i < 10; i++) { \n" + + " count++; \n" + + " } \n" + + " return count; \n" + + "} " + ); + assertValue(createValue(10), result); + } + + @Test + public void testForEachStatement() { + MIValue result = testValidModel( + "{ \n" + + " int sum = 0; \n" + + " for (int i : [1..4]) { \n" + + " sum += i; \n" + + " } \n" + + " return sum; \n" + + "}" + ); + assertValue(createValue(10), result); + } + + @Test + public void testContinueStatement() { + MIValue result = testValidModel( + "{ \n" + + " int count = 0; \n" + + " for (int i = 0; i < 10; i++) { \n" + + " if (i % 2 != 0) continue; \n" + + " count++; \n" + + " } \n" + + " return count; \n" + + "} " + ); + assertValue(createValue(5), result); + } + + @Test + public void testBreakStatement() { + MIValue result = testValidModel( + "{ \n" + + " int count = 0; \n" + + " for (int i = 0; i < 10; i++) { \n" + + " count++; \n" + + " if (i > 5) break; \n" + + " } \n" + + " return count; \n" + + "} " + ); + assertValue(createValue(7), result); + } + + @Test + public void testLeibnizEfficiency() { + long startTime = System.nanoTime(); + MIValue result = testValidModel( + "{ \n" + + " double pi = 1; \n" + + " double x = 1; \n" + + " for (int i = 2; i < 10000002; i++) { \n" + + " x = x * -1; \n" + + " pi = pi + x / (2 * i - 1); \n" + + " } \n" + + " pi = pi * 4; \n" + + " return pi; \n" + + "} " + ); + System.out.println(result.asDouble()); + long endTime = System.nanoTime(); + System.out.println("Elapsed time: " + ((endTime - startTime) / 1000000) + " ms"); + /* Iterations | Elapsed Time + ------------|-------------- + 100 | 1266 ms + 1k | 1300 ms + 10k | 1371 ms + 100k | 1792 ms + 1M | 3581 ms + 10M | 19059 ms + 100M | 171227 ms + */ + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/IMIScope.java b/monticore-runtime/src/main/java/de/monticore/interpreter/IMIScope.java new file mode 100644 index 0000000000..6a2773a974 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/IMIScope.java @@ -0,0 +1,4 @@ +package de.monticore.interpreter; + +public interface IMIScope { +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java b/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java index 1dd74a7787..cad6659098 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java @@ -11,5 +11,8 @@ default MIValue interpret(ASTNode n) { Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + + public void popScope(); + public void pushScope(IMIScope scope); + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java index 5019f8485f..338b585703 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java @@ -1,9 +1,14 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter; +import de.monticore.interpreter.values.FunctionMIValue; import de.se_rwth.commons.logging.Log; public interface MIValue { + + default boolean isWriteable() { return false; } + + default boolean isPrimitive() { return false; } default boolean isBoolean() { return false; @@ -53,10 +58,23 @@ default boolean isSIUnit() { return false; } + default boolean isFlowControlSignal() { return false;} + default boolean isError() { return false; } + default boolean isBreak() { + return false; + } + + default boolean isContinue() { + return false; + } + + default boolean isReturn() { + return false; + } default boolean asBoolean() { Log.error("0x31251 Type boolean is not applicable for " + printType() + " (" + printValue() + ")."); @@ -98,18 +116,32 @@ default double asDouble() { return 0.0; } + default FunctionMIValue asFunction() { + Log.error("0x57099 Type function is not applicable for " + printType() + " (" + printValue() + ")."); + return null; + } + default Object asObject() { Log.error("0x31259 Type object is not applicable for " + printType() + " (" + printValue() + ")."); return null; } + default String asError() { + Log.error("0x57092 Type Error is not applicable for " + printType() + " (" + printValue() + ")."); + return null; + } + + default MIValue asReturnValue() { + Log.error("0x57083 Type ReturnValue is not applicable for " + printType() + " (" + printValue() + ")."); + return null; + } default String printType() { - Log.error("0x31260 printType is not applicable for " + printType() + " (" + printValue() + ")."); + Log.error("0x31260 printType is not applicable for '" + getClass().getName() + "'."); return "UnknownType"; } default String printValue() { - Log.error("0x31261 printValue is not applicable for " + printType() + " (" + printValue() + ")."); + Log.error("0x31261 printValue is not applicable for '" + getClass().getName() + "'."); return "UnknownValue"; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java index 74bfc02be6..25b832a43e 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java @@ -1,8 +1,6 @@ package de.monticore.interpreter.values; -import de.monticore.interpreter.MIValue; - -public class ErrorMIValue implements MIValue { +public class ErrorMIValue implements MIFlowControlSignal { String message; @@ -15,7 +13,8 @@ public boolean isError() { return true; } - public String getMessage() { + @Override + public String asError() { return message; } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java new file mode 100644 index 0000000000..4aa3294033 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java @@ -0,0 +1,22 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.IModelInterpreter; +import de.monticore.interpreter.MIValue; + +import java.util.List; + +public interface FunctionMIValue extends MIValue { + + @Override + public default boolean isFunction() { + return true; + } + + @Override + public default FunctionMIValue asFunction() { + return this; + } + + public MIValue execute(IModelInterpreter interpreter, List arguments); + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java new file mode 100644 index 0000000000..729081c70a --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java @@ -0,0 +1,19 @@ +package de.monticore.interpreter.values; + +public class MIBreakSignal implements MIFlowControlSignal { + + @Override + public boolean isBreak() { + return true; + } + + @Override + public String printType() { + return "Break"; + } + + @Override + public String printValue() { + return ""; + } +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java new file mode 100644 index 0000000000..8246694f20 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java @@ -0,0 +1,20 @@ +package de.monticore.interpreter.values; + +public class MIContinueSignal implements MIFlowControlSignal { + + @Override + public boolean isContinue() { + return true; + } + + @Override + public String printType() { + return "Continue"; + } + + @Override + public String printValue() { + return ""; + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java new file mode 100644 index 0000000000..91337db4b5 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java @@ -0,0 +1,11 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.MIValue; + +public interface MIFlowControlSignal extends MIValue { + + @Override + public default boolean isFlowControlSignal() { + return true; + } +} diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java new file mode 100644 index 0000000000..8857a0b646 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java @@ -0,0 +1,36 @@ +package de.monticore.interpreter.values; + +import de.monticore.interpreter.MIValue; + +public class MIReturnSignal implements MIFlowControlSignal { + + MIValue value; + + public MIReturnSignal() { + this.value = new VoidMIValue(); + } + + public MIReturnSignal(MIValue value) { + this.value = value; + } + + @Override + public boolean isReturn() { + return true; + } + + @Override + public MIValue asReturnValue() { + return value; + } + + @Override + public String printType() { + return "Return"; + } + + @Override + public String printValue() { + return value.printType() + "(" + value.printValue() + ")"; + } +} diff --git a/settings.gradle b/settings.gradle index a69db0a087..232a89166a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -74,7 +74,7 @@ include(':monticore-test:01experiments:forAst') include(':monticore-test:01experiments:forConcSt') include(':monticore-test:01experiments:forMill') include(':monticore-test:01experiments:interpreter') -include(':monticore-test:01experiments:forParser') +// include(':monticore-test:01experiments:forParser') include(':monticore-test:01experiments:forVisitors') include(':monticore-test:01experiments:generator') include(':monticore-test:01experiments:glex') From 9b887d7b1e13e6105f84367ca6055ed7be11129e Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Fri, 8 Aug 2025 21:13:16 +0200 Subject: [PATCH 13/37] Fix InterpreterDecoratorTest --- .../interpreter/InterpreterDecoratorTest.java | 147 ++---------------- 1 file changed, 11 insertions(+), 136 deletions(-) diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index 93c7db2a70..9e54836c71 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -11,6 +11,8 @@ import de.monticore.codegen.cd2java._visitor.VisitorService; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; +import de.monticore.types.mcbasictypes._ast.ASTMCReturnType; +import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mccollectiontypes._ast.ASTMCGenericType; import de.se_rwth.commons.logging.Log; import org.junit.After; @@ -44,7 +46,7 @@ public void before() { @Test public void testMethodCount() { - assertEquals(10, decoratedClass.getCDMethodList().size()); + assertEquals(3, decoratedClass.getCDMethodList().size()); } @Test @@ -120,148 +122,21 @@ public void testRealThisMethods() { setMethod.getCDParameter(0).getName()); assertTrue(setMethod.getMCReturnType().isPresentMCVoidType()); } - - @Test - public void testFunctionMethods() { - Optional optDeclareMethod = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("declareFunction")) - .findAny(); - - assertTrue(optDeclareMethod.isPresent()); - ASTCDMethod declareMethod = optDeclareMethod.get(); - - assertTrue(declareMethod.getMCReturnType().isPresentMCVoidType()); - assertEquals(2, declareMethod.getCDParameterList().size()); - assertEquals("symbol", declareMethod.getCDParameter(0).getName()); - assertEquals(InterpreterConstants.FUNCTION_SYMBOL_FULLNAME, - declareMethod.getCDParameter(0).getMCType().printType()); - assertEquals("value", declareMethod.getCDParameter(1).getName()); - assertEquals(InterpreterConstants.FUNCTION_VALUE_FULLNAME, - declareMethod.getCDParameter(1).getMCType().printType()); - - Optional optLoadMethod = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("loadFunction")) - .findAny(); - - assertTrue(optLoadMethod.isPresent()); - ASTCDMethod loadMethod = optLoadMethod.get(); - - assertEquals(InterpreterConstants.VALUE_FULLNAME, - loadMethod.getMCReturnType().printType()); - assertEquals(1, loadMethod.getCDParameterList().size()); - assertEquals(InterpreterConstants.FUNCTION_SYMBOL_FULLNAME, - loadMethod.getCDParameter(0).getMCType().printType()); - assertEquals("symbol", - loadMethod.getCDParameter(0).getName()); - } @Test - public void testVariableMethods() { - Optional optDeclareMethod = decoratedClass.getCDMethodList() + public void testScopeCallstackMethod() { + Optional optScopeCallstackMethod = decoratedClass.getCDMethodList() .stream() - .filter(m -> m.getName().equals("declareVariable")) + .filter(m -> m.getName().equals("getScopeCallstack")) .findAny(); - assertTrue(optDeclareMethod.isPresent()); - ASTCDMethod declareMethod = optDeclareMethod.get(); - - assertTrue(declareMethod.getMCReturnType().isPresentMCVoidType()); - assertEquals(2, declareMethod.getCDParameterList().size()); - assertEquals("symbol", declareMethod.getCDParameter(0).getName()); - assertEquals(InterpreterConstants.VARIABLE_SYMBOL_FULLNAME, - declareMethod.getCDParameter(0).getMCType().printType()); - assertEquals("value", declareMethod.getCDParameter(1).getName()); - assertEquals(InterpreterConstants.VALUE_FULLNAME, - declareMethod.getCDParameter(1).getMCType().printType()); - - Optional optStoreMethod = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("storeVariable")) - .findAny(); - - assertTrue(optStoreMethod.isPresent()); - ASTCDMethod storeMethod = optStoreMethod.get(); - - assertTrue(storeMethod.getMCReturnType().isPresentMCVoidType()); - assertEquals(2, storeMethod.getCDParameterList().size()); - assertEquals("symbol", storeMethod.getCDParameter(0).getName()); - assertEquals(InterpreterConstants.VARIABLE_SYMBOL_FULLNAME, - storeMethod.getCDParameter(0).getMCType().printType()); - assertEquals("value", storeMethod.getCDParameter(1).getName()); - assertEquals(InterpreterConstants.VALUE_FULLNAME, - storeMethod.getCDParameter(1).getMCType().printType()); + assertTrue(optScopeCallstackMethod.isPresent()); + ASTCDMethod scopeCallstackMethod = optScopeCallstackMethod.get(); - Optional optLoadMethod = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("loadVariable")) - .findAny(); - - assertTrue(optLoadMethod.isPresent()); - ASTCDMethod loadMethod = optLoadMethod.get(); - - assertEquals(InterpreterConstants.VALUE_FULLNAME, - loadMethod.getMCReturnType().printType()); - assertEquals(1, loadMethod.getCDParameterList().size()); - assertEquals(InterpreterConstants.VARIABLE_SYMBOL_FULLNAME, - loadMethod.getCDParameter(0).getMCType().printType()); - assertEquals("symbol", - loadMethod.getCDParameter(0).getName()); - } - - @Test - public void testScopeMethods() { - Optional optGetCurrentScope = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("getCurrentScope")) - .findAny(); - - assertTrue(optGetCurrentScope.isPresent()); - ASTCDMethod getCurrentScopeMethod = optGetCurrentScope.get(); - - assertTrue(getCurrentScopeMethod.getCDParameterList().isEmpty()); + ASTMCGenericType returnTypeType = (ASTMCGenericType)scopeCallstackMethod.getMCReturnType().getMCType(); + assertEquals("java.util.Stack", returnTypeType.printWithoutTypeArguments()); assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, - getCurrentScopeMethod.getMCReturnType().getMCType().printType()); - - Optional optPushScope = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("pushScope")) - .findAny(); - - assertTrue(optPushScope.isPresent()); - ASTCDMethod pushScopeMethod = optPushScope.get(); - - assertEquals(1, pushScopeMethod.getCDParameterList().size()); - assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, pushScopeMethod.getCDParameter(0).getMCType().printType()); - assertTrue(pushScopeMethod.getMCReturnType().isPresentMCVoidType()); - - Optional optPopScope = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("popScope")) - .findAny(); - - assertTrue(optPopScope.isPresent()); - ASTCDMethod popScopeMethod = optPopScope.get(); - - assertTrue(popScopeMethod.getCDParameterList().isEmpty()); - assertTrue(pushScopeMethod.getMCReturnType().isPresentMCVoidType()); - } - - @Test - @Ignore - public void testInterpretMethods() { - List interpretMethods = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("interpret")) - .collect(Collectors.toList()); - - assertEquals(0, interpretMethods.size()); - ASTCDMethod method = interpretMethods.get(0); - - assertEquals(1, method.getCDParameterList().size()); - assertEquals("node", method.getCDParameter(0).getName()); - assertEquals(InterpreterConstants.VALUE_FULLNAME, method.getMCReturnType().printType()); + returnTypeType.getMCTypeArgument(0).printType()); } @After From 28b696c9a10741d69999a3d86868ae869b45cf33 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Fri, 8 Aug 2025 23:20:27 +0200 Subject: [PATCH 14/37] Remove Class2mc from AbstractTypeVisitorTest --- .../monticore/types3/AbstractTypeVisitorTest.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java index 21bc361bfa..2498e229f8 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java @@ -1,8 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3; -import de.monticore.class2mc.Class2MCResolver; -import de.monticore.class2mc.OOClass2MCResolver; import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.expressions.combineexpressionswithliterals._ast.ASTFoo; import de.monticore.expressions.combineexpressionswithliterals._parser.CombineExpressionsWithLiteralsParser; @@ -18,7 +16,6 @@ import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; -import de.monticore.symbols.oosymbols.OOSymbolsMill; import de.monticore.types.check.IDerive; import de.monticore.types.check.ISynthesize; import de.monticore.types.check.SymTypeExpression; @@ -116,16 +113,6 @@ public void setupDefaultMill() { typeMapTraverser = tc3.getTypeTraverser(); setupSymbolTableCompleter(typeMapTraverser, type4Ast); } - - protected void enableClass2MC() { - BasicSymbolsMill.globalScope().addAdaptedTypeSymbolResolver(new Class2MCResolver()); - } - - protected void enableClass2MC4OO() { - OOClass2MCResolver resolver = new OOClass2MCResolver(); - BasicSymbolsMill.globalScope().addAdaptedTypeSymbolResolver(resolver); - OOSymbolsMill.globalScope().addAdaptedOOTypeSymbolResolver(resolver); - } protected void setupSymbolTableCompleter( ITraverser typeMapTraverser, Type4Ast type4Ast) { From 8a2feb97409922aa5828abd16f3e393c432ca42e Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Sat, 9 Aug 2025 00:10:30 +0200 Subject: [PATCH 15/37] Remove Class2mc from AbstractStatementInterpreterTest --- .../AbstractStatementInterpreterTest.java | 108 ++++++++---------- 1 file changed, 45 insertions(+), 63 deletions(-) diff --git a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java index 822bfc2ac5..8531f765ec 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java @@ -56,69 +56,51 @@ public void init() { } protected MIValue testValidModel(String model) { - return testValidModel(model, Collections.emptyList()); - } - - protected MIValue testValidModel(String model, List imports) { - Log.clearFindings(); - Optional astNodeOpt = Optional.empty(); - try { - astNodeOpt = ((CombineStatementsWithExpressionsParser)parser).parse_String(model); - } catch (IOException e) { - System.out.println(e.getMessage()); - fail(); - } - - if (!Log.getFindings().isEmpty()) { - Log.printFindings(); - fail(); - } - assertTrue(astNodeOpt.isPresent()); - - CombineStatementsWithExpressionsMill.artifactScope().setImportsList(imports); - - OOClass2MCResolver resolver = new OOClass2MCResolver(); - - OOSymbolsMill.reset(); - OOSymbolsMill.init(); - CombineStatementsWithExpressionsMill.reset(); - CombineStatementsWithExpressionsMill.init(); - CombineStatementsWithExpressionsMill.globalScope().clear(); - - DefsTypesForTests.setup(); - - CombineStatementsWithExpressionsMill.globalScope().getSymbolPath().addEntry(OOClass2MCResolver.getJRTPath()); - CombineStatementsWithExpressionsMill.globalScope().addAdaptedTypeSymbolResolver(resolver); - CombineStatementsWithExpressionsMill.globalScope().addAdaptedOOTypeSymbolResolver(resolver); - - CombineStatementsWithExpressionsMill.globalScope().setSymbolPath(new MCPath()); - - ICombineStatementsWithExpressionsArtifactScope rootScope = - CombineStatementsWithExpressionsMill.scopesGenitorDelegator() - .createFromAST(astNodeOpt.get()); - - rootScope.setName("root"); - - astNodeOpt.get().accept(getSymbolTableCompleter()); - - MIValue interpretationResult = astNodeOpt.get().evaluate(interpreter); - - assertNotNull(interpretationResult); - if (!Log.getFindings().isEmpty()) { - Log.printFindings(); - fail(); - } - - assertTrue(interpretationResult.isReturn() || interpretationResult.isVoid()); - if (interpretationResult.isReturn()) { - interpretationResult = interpretationResult.asReturnValue(); - } - - return interpretationResult; - } - - protected void addImports(List imports) { - CombineStatementsWithExpressionsMill.artifactScope().setImportsList(imports); + Log.clearFindings(); + Optional astNodeOpt = Optional.empty(); + try { + astNodeOpt = ((CombineStatementsWithExpressionsParser)parser).parse_String(model); + } catch (IOException e) { + System.out.println(e.getMessage()); + fail(); + } + + if (!Log.getFindings().isEmpty()) { + Log.printFindings(); + fail(); + } + assertTrue(astNodeOpt.isPresent()); + + OOSymbolsMill.reset(); + OOSymbolsMill.init(); + CombineStatementsWithExpressionsMill.reset(); + CombineStatementsWithExpressionsMill.init(); + CombineStatementsWithExpressionsMill.globalScope().clear(); + + DefsTypesForTests.setup(); + + ICombineStatementsWithExpressionsArtifactScope rootScope = + CombineStatementsWithExpressionsMill.scopesGenitorDelegator() + .createFromAST(astNodeOpt.get()); + + rootScope.setName("root"); + + astNodeOpt.get().accept(getSymbolTableCompleter()); + + MIValue interpretationResult = astNodeOpt.get().evaluate(interpreter); + + assertNotNull(interpretationResult); + if (!Log.getFindings().isEmpty()) { + Log.printFindings(); + fail(); + } + + assertTrue(interpretationResult.isReturn() || interpretationResult.isVoid()); + if (interpretationResult.isReturn()) { + interpretationResult = interpretationResult.asReturnValue(); + } + + return interpretationResult; } protected void setupSymbolTableCompleter( From afb73d3d12ae5b79430b913a036777e42e5a17f8 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Sat, 9 Aug 2025 00:46:26 +0200 Subject: [PATCH 16/37] Remove Class2mc-import from AbstractStatementInterpreterTest --- .../monticore/statements/AbstractStatementInterpreterTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java index 8531f765ec..6cc579d056 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java @@ -1,7 +1,6 @@ package de.monticore.statements; import de.monticore.AbstractInterpreterTest; -import de.monticore.class2mc.OOClass2MCResolver; import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsArtifactScope; import de.monticore.expressions.lambdaexpressions._symboltable.LambdaExpressionsSTCompleteTypes2; From 42788b0d325a369c2c3fac0b9e097caefd796da6 Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Mon, 11 Aug 2025 15:23:52 +0200 Subject: [PATCH 17/37] complete assignment-tests & better failed messages --- .../interpreter/InterpreterDecoratorTest.java | 4 - .../interpreter/values/FloatMIValue.java | 2 +- .../interpreter/values/LongMIValue.java | 2 +- .../de/monticore/AbstractInterpreterTest.java | 62 +- .../AbstractExpressionInterpreterTest.java | 37 +- .../AssignmentExpressionsInterpreterTest.java | 650 +++++++++++++----- .../CommonExpressionsInterpreterTest.java | 16 +- .../AbstractStatementInterpreterTest.java | 11 - .../types3/AbstractTypeVisitorTest.java | 1 - 9 files changed, 536 insertions(+), 249 deletions(-) diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index 9e54836c71..83583393a5 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -11,18 +11,14 @@ import de.monticore.codegen.cd2java._visitor.VisitorService; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; -import de.monticore.types.mcbasictypes._ast.ASTMCReturnType; -import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mccollectiontypes._ast.ASTMCGenericType; import de.se_rwth.commons.logging.Log; import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static groovy.test.GroovyTestCase.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java index f409f66e87..5ed19a08aa 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java @@ -38,6 +38,6 @@ public String printType() { @Override public String printValue() { - return String.valueOf(value); + return String.valueOf(value) + "f"; } } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java index 9e2e403564..ae94bfbe02 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java @@ -43,6 +43,6 @@ public String printType() { @Override public String printValue() { - return String.valueOf(value); + return String.valueOf(value) + "L"; } } diff --git a/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java index bc8902c81a..eaff7b2ce4 100644 --- a/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java @@ -59,7 +59,8 @@ public void init() { TypeVisitorOperatorCalculator.init(); DefsTypesForTests.setup(); parser = parserSupplier.get(); - MapBasedTypeCheck3 tc3 = CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); + MapBasedTypeCheck3 tc3 = CombineExpressionsWithLiteralsTypeTraverserFactory + .initTypeCheck3(); type4Ast = tc3.getType4Ast(); typeMapTraverser = tc3.getTypeTraverser(); setupSymbolTableCompleter(typeMapTraverser, type4Ast); @@ -86,61 +87,62 @@ protected static String getAllFindingsAsString() { } public MIValue loadVariable(String name) { - VariableSymbol symbol = BasicSymbolsMill.globalScope().resolveVariable(name).get(); + VariableSymbol symbol = BasicSymbolsMill.globalScope() + .resolveVariable(name).get(); return interpreter.loadVariable(symbol); } public MIValue loadFunction(String name) { - FunctionSymbol symbol = BasicSymbolsMill.globalScope().resolveFunction(name).get(); + FunctionSymbol symbol = BasicSymbolsMill.globalScope() + .resolveFunction(name).get(); return interpreter.loadFunction(symbol); } public void assertValue(MIValue expected, MIValue actual) { if (expected.isVoid()) { - assertTrue(actual.isVoid()); + if (actual.isVoid()) return; } else if (expected.isError()) { - assertTrue(actual.isError()); - assertEquals(expected.asError(), actual.asError()); + if (actual.isError() && expected.asError().equals(actual.asError())) return; } else if (expected.isBreak()) { - assertTrue(actual.isBreak()); + if (actual.isBreak()) return; } else if (expected.isContinue()) { - assertTrue(actual.isContinue()); + if (actual.isContinue()) return; } else if (expected.isReturn()) { - assertTrue(actual.isReturn()); - assertValue(expected.asReturnValue(), actual.asReturnValue()); + if (actual.isReturn()) { + assertValue(expected.asReturnValue(), actual.asReturnValue()); + return; + } } else if (expected.isBoolean()) { - assertTrue(actual.isBoolean()); - assertEquals(expected.asBoolean(), actual.asBoolean()); + if (actual.isBoolean() && expected.asBoolean() == actual.asBoolean()) return; } else if (expected.isByte()) { - assertTrue(actual.isByte()); - Assertions.assertEquals(expected.asByte(), actual.asByte()); + if (actual.isByte() && expected.asByte() == actual.asByte()) return; } else if (expected.isShort()) { - assertTrue(actual.isShort()); - assertEquals(expected.asShort(), actual.asShort()); + if (actual.isShort() && expected.asShort() == actual.asShort()) return; } else if (expected.isChar()) { - assertTrue(actual.isChar()); - assertEquals(expected.asChar(), actual.asChar()); + if (actual.isChar() && expected.asChar() == actual.asChar()) return; } else if (expected.isInt()) { - assertTrue(actual.isInt()); - assertEquals(expected.asInt(), actual.asInt()); + if (actual.isInt() && expected.asInt() == actual.asInt()) return; } else if (expected.isLong()) { - assertTrue(actual.isLong()); - assertEquals(expected.asLong(), actual.asLong()); + if (actual.isLong() && expected.asLong() == actual.asLong()) return; } else if (expected.isFloat()) { - assertTrue(actual.isFloat()); - assertEquals(expected.asFloat(), actual.asFloat()); + if (actual.isFloat() && expected.asFloat() + delta > actual.asFloat() + && expected.asFloat() - delta < actual.asFloat()) return; } else if (expected.isDouble()) { - assertTrue(actual.isDouble()); - assertEquals(expected.asDouble(), actual.asDouble()); + if (actual.isDouble() && expected.asDouble() + delta > actual.asDouble() + && expected.asDouble() - delta < actual.asDouble()) return; } else if (expected.isFunction()) { - assertTrue(actual.isFunction()); + if (actual.isFunction() && expected.asFunction().equals(actual.asFunction())) return; } else if (expected.isObject()) { - assertTrue(actual.isObject()); - assertEquals(expected.asObject(), actual.asObject()); + if (actual.isObject() && expected.asObject().equals(actual.asObject())) return; } else { - Log.error("Trying to compare unsupported MIValue type '" + expected.printType() + "'."); + Log.error("Trying to compare unsupported MIValue type '" + + expected.printType() + "'."); fail(); } + + fail("Expected " + expected.printType() + " (" + expected.printValue() + + ") but got " + actual.printType() + " (" + actual.printValue() + + ")."); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java index 09a26cfde4..1b838973ed 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java @@ -123,34 +123,7 @@ protected void testValidExpression(String expr, MIValue expected) { Log.printFindings(); fail(); } - if (expected.isBoolean()) { - assertTrue(interpretationResult.isBoolean()); - assertEquals(expected.asBoolean(), interpretationResult.asBoolean()); - } else if (expected.isByte()) { - assertTrue(interpretationResult.isByte()); - assertEquals(expected.asByte(), interpretationResult.asByte()); - } else if (expected.isShort()) { - assertTrue(interpretationResult.isShort()); - assertEquals(expected.asShort(), interpretationResult.asShort()); - } else if (expected.isChar()) { - assertTrue(interpretationResult.isChar()); - assertEquals(expected.asChar(), interpretationResult.asChar()); - } else if (expected.isInt()) { - assertTrue(interpretationResult.isInt()); - assertEquals(expected.asInt(), interpretationResult.asInt()); - } else if (expected.isLong()) { - assertTrue(interpretationResult.isLong()); - assertEquals(expected.asLong(), interpretationResult.asLong()); - } else if (expected.isFloat()) { - assertTrue(interpretationResult.isFloat()); - assertEquals(expected.asFloat(), interpretationResult.asFloat(), delta); - } else if (expected.isDouble()) { - assertTrue(interpretationResult.isDouble()); - assertEquals(expected.asDouble(), interpretationResult.asDouble(), delta); - } else if (expected.isObject()) { - assertTrue(interpretationResult.isObject()); - assertEquals(expected.asObject(), interpretationResult.asObject()); - } + assertValue(expected, interpretationResult); assertTrue(Log.getFindings().isEmpty()); } @@ -163,8 +136,14 @@ protected void testInvalidExpression(String expr) { } catch (IOException e) { throw new RuntimeException(e); } - + assertNotNull(interpretationResult); + + if (Log.getFindings().isEmpty() && !interpretationResult.isError()) { + fail("Expected an error but interpretation succeeded with result of " + interpretationResult.printType() + + " (" + interpretationResult.printValue() + ")."); + } + assertFalse(Log.getFindings().isEmpty()); assertTrue(interpretationResult.isError()); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java index a0691523c4..1e6aed375b 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java @@ -72,7 +72,7 @@ protected static Stream andEqualsExpression() { arguments("b &= 2L", null), arguments("b &= 1.5f", null), arguments("b &= 3.14", null), - + arguments("by &= false", null), arguments("by &= (byte)3", createValue((byte)3)), arguments("by &= (short)256", createValue((byte)256)), @@ -81,7 +81,7 @@ protected static Stream andEqualsExpression() { arguments("by &= 2L", createValue((byte)2L)), arguments("by &= 1.5f", null), arguments("by &= 3.14", null), - + arguments("s &= false", null), arguments("s &= (byte)3", createValue((short)0)), arguments("s &= (short)256", createValue((short)256)), @@ -90,7 +90,7 @@ protected static Stream andEqualsExpression() { arguments("s &= 2L", createValue((short)0L)), arguments("s &= 1.5f", null), arguments("s &= 3.14", null), - + arguments("c &= false", null), arguments("c &= (byte)3", createValue((char)1)), arguments("c &= (short)256", createValue((char)0)), @@ -99,7 +99,7 @@ protected static Stream andEqualsExpression() { arguments("c &= 2L", createValue((char)0L)), arguments("c &= 1.5f", null), arguments("c &= 3.14", null), - + arguments("i &= false", null), arguments("i &= (byte)3", createValue(1)), arguments("i &= (short)256", createValue(0)), @@ -119,6 +119,8 @@ protected static Stream andEqualsExpression() { arguments("l &= 3.14", null), arguments("f &= false", null), + arguments("f &= (byte)3", null), + arguments("f &= (short)256", null), arguments("f &= 1", null), arguments("f &= 2L", null), arguments("f &= 1.5f", null), @@ -126,30 +128,66 @@ protected static Stream andEqualsExpression() { arguments("f &= 'a'", null), arguments("d &= false", null), + arguments("d &= (byte)3", null), + arguments("d &= (short)256", null), + arguments("d &= 'a'", null), arguments("d &= 1", null), arguments("d &= 2L", null), arguments("d &= 1.5f", null), - arguments("d &= 3.14", null), - arguments("d &= 'a'", null)); + arguments("d &= 3.14", null) + ); } protected static Stream gTGTEqualsExpression() { return Stream.of( arguments("b >>= false", null), + arguments("b >>= (byte)3", null), + arguments("b >>= (short)256", null), + arguments("b >>= 'a'", null), arguments("b >>= 1", null), arguments("b >>= 2L", null), arguments("b >>= 1.5f", null), arguments("b >>= 3.14", null), - arguments("b >>= 'a'", null), + + arguments("by >>= false", null), + arguments("by >>= (byte)3", createValue((byte)0)), + arguments("by >>= (short)256", createValue((byte)3)), + arguments("by >>= 'a'", createValue((byte)1)), + arguments("by >>= 1", createValue((byte)1)), + arguments("by >>= 2L", createValue((byte)0)), + arguments("by >>= 1.5f", null), + arguments("by >>= 3.14", null), + + arguments("s >>= false", null), + arguments("s >>= (byte)3", createValue((short)32)), + arguments("s >>= (short)256", createValue((short)256)), + arguments("s >>= 'a'", createValue((short)128)), + arguments("s >>= 1", createValue((short)128)), + arguments("s >>= 2L", createValue((short)64)), + arguments("s >>= 1.5f", null), + arguments("s >>= 3.14", null), + + arguments("c >>= false", null), + arguments("c >>= (byte)3", createValue((char)12)), + arguments("c >>= (short)256", createValue('a')), + arguments("c >>= 'a'", createValue((char)48)), + arguments("c >>= 1", createValue((char)48)), + arguments("c >>= 2L", createValue((char)24)), + arguments("c >>= 1.5f", null), + arguments("c >>= 3.14", null), arguments("i >>= false", null), + arguments("i >>= (byte)3", createValue(0)), + arguments("i >>= (short)256", createValue(1)), + arguments("i >>= 'a'", createValue(0)), arguments("i >>= 1", createValue(0)), arguments("i >>= 2L", createValue(0)), arguments("i >>= 1.5f", null), arguments("i >>= 3.14", null), - arguments("i >>= 'a'", createValue(0)), arguments("l >>= false", null), + arguments("l >>= (byte)3", createValue(0L)), + arguments("l >>= (short)256", createValue(5L)), arguments("l >>= 1", createValue(2L)), arguments("l >>= 2L", createValue(1L)), arguments("l >>= 1.5f", null), @@ -157,283 +195,464 @@ protected static Stream gTGTEqualsExpression() { arguments("l >>= 'a'", createValue(0L)), arguments("f >>= false", null), + arguments("f >>= (byte)3", null), + arguments("f >>= (short)256", null), + arguments("f >>= 'a'", null), arguments("f >>= 1", null), arguments("f >>= 2L", null), arguments("f >>= 1.5f", null), arguments("f >>= 3.14", null), - arguments("f >>= 'a'", null), arguments("d >>= false", null), + arguments("d >>= (byte)3", null), + arguments("d >>= (short)256", null), + arguments("d >>= 'a'", null), arguments("d >>= 1", null), arguments("d >>= 2L", null), arguments("d >>= 1.5f", null), - arguments("d >>= 3.14", null), - arguments("d >>= 'a'", null), + arguments("d >>= 3.14", null)); - arguments("c >>= false", null), - arguments("c >>= 1", createValue((char)48)), - arguments("c >>= 2L", createValue((char)24)), - arguments("c >>= 1.5f", null), - arguments("c >>= 3.14", null), - arguments("c >>= 'a'", createValue((char)48))); } protected static Stream gTGTGTEqualsExpression() { return Stream.of( arguments("b >>>= false", null), + arguments("b >>>= (byte)3", null), + arguments("b >>>= (short)256", null), + arguments("b >>>= 'a'", null), arguments("b >>>= 1", null), arguments("b >>>= 2L", null), arguments("b >>>= 1.5f", null), arguments("b >>>= 3.14", null), - arguments("b >>>= 'a'", null), + + arguments("by >>>= false", null), + arguments("by >>>= (byte)3", createValue((byte)0)), + arguments("by >>>= (short)256", createValue((byte)3)), + arguments("by >>>= 'a'", createValue((byte)1)), + arguments("by >>>= 1", createValue((byte)1)), + arguments("by >>>= 2L", createValue((byte)0)), + arguments("by >>>= 1.5f", null), + arguments("by >>>= 3.14", null), + + arguments("s >>>= false", null), + arguments("s >>>= (byte)3", createValue((short)32)), + arguments("s >>>= (short)256", createValue((short)256)), + arguments("s >>>= 'a'", createValue((short)128)), + arguments("s >>>= 1", createValue((short)128)), + arguments("s >>>= 2L", createValue((short)64)), + arguments("s >>>= 1.5f", null), + arguments("s >>>= 3.14", null), + + arguments("c >>>= false", null), + arguments("c >>>= (byte)3", createValue((char)12)), + arguments("c >>>= (short)256", createValue('a')), + arguments("c >>>= 'a'", createValue((char)48)), + arguments("c >>>= 1", createValue((char)48)), + arguments("c >>>= 2L", createValue((char)24)), + arguments("c >>>= 1.5f", null), + arguments("c >>>= 3.14", null), arguments("i >>>= false", null), + arguments("i >>>= (byte)3", createValue(0)), + arguments("i >>>= (short)256", createValue(1)), + arguments("i >>>= 'a'", createValue(0)), arguments("i >>>= 1", createValue(0)), arguments("i >>>= 2L", createValue(0)), arguments("i >>>= 1.5f", null), arguments("i >>>= 3.14", null), - arguments("i >>>= 'a'", createValue(0)), arguments("l >>>= false", null), + arguments("l >>>= (byte)3", createValue(0L)), + arguments("l >>>= (short)256", createValue(5L)), + arguments("l >>>= 'a'", createValue(0L)), arguments("l >>>= 1", createValue(2L)), arguments("l >>>= 2L", createValue(1L)), arguments("l >>>= 1.5f", null), arguments("l >>>= 3.14", null), - arguments("l >>>= 'a'", createValue(0L)), arguments("f >>>= false", null), + arguments("f >>>= (byte)3", null), + arguments("f >>>= (short)256", null), + arguments("f >>>= 'a'", null), arguments("f >>>= 1", null), arguments("f >>>= 2L", null), arguments("f >>>= 1.5f", null), arguments("f >>>= 3.14", null), - arguments("f >>>= 'a'", null), arguments("d >>>= false", null), + arguments("d >>>= (byte)3", null), + arguments("d >>>= (short)256", null), + arguments("d >>>= 'a'", null), arguments("d >>>= 1", null), arguments("d >>>= 2L", null), arguments("d >>>= 1.5f", null), - arguments("d >>>= 3.14", null), - arguments("d >>>= 'a'", null), - - arguments("c >>>= false", null), - arguments("c >>>= 1", createValue((char)48)), - arguments("c >>>= 2L", createValue((char)24)), - arguments("c >>>= 1.5f", null), - arguments("c >>>= 3.14", null), - arguments("c >>>= 'a'", createValue((char)48))); + arguments("d >>>= 3.14", null) + ); } protected static Stream lTLTEqualsExpression() { return Stream.of( arguments("b <<= false", null), + arguments("b <<= (byte)3", null), + arguments("b <<= (short)256", null), + arguments("b <<= 'a'", null), arguments("b <<= 1", null), arguments("b <<= 2L", null), arguments("b <<= 1.5f", null), arguments("b <<= 3.14", null), - arguments("b <<= 'a'", null), + + arguments("by <<= false", null), + arguments("by <<= (byte)3", createValue((byte)24)), + arguments("by <<= (short)256", createValue((byte)3)), + arguments("by <<= 'a'", createValue((byte)6)), + arguments("by <<= 1", createValue((byte)6)), + arguments("by <<= 2L", createValue((byte)12)), + arguments("by <<= 1.5f", null), + arguments("by <<= 3.14", null), + + arguments("s <<= false", null), + arguments("s <<= (byte)3", createValue((short)2048)), + arguments("s <<= (short)256", createValue((short)256)), + arguments("s <<= 'a'", createValue((short)512)), + arguments("s <<= 1", createValue((short)512)), + arguments("s <<= 2L", createValue((short)1024)), + arguments("s <<= 1.5f", null), + arguments("s <<= 3.14", null), + + arguments("c <<= false", null), + arguments("c <<= (byte)3", createValue((char)776)), + arguments("c <<= (short)256", createValue('a')), + arguments("c <<= 'a'", createValue((char)194)), + arguments("c <<= 1", createValue((char)194)), + arguments("c <<= 2L", createValue((char)388)), + arguments("c <<= 1.5f", null), + arguments("c <<= 3.14", null), arguments("i <<= false", null), + arguments("i <<= (byte)3", createValue(8)), + arguments("i <<= (short)256", createValue(1)), + arguments("i <<= 'a'", createValue(2)), arguments("i <<= 1", createValue(2)), arguments("i <<= 2L", createValue(4)), arguments("i <<= 1.5f", null), arguments("i <<= 3.14", null), - arguments("i <<= 'a'", createValue(2)), arguments("l <<= false", null), + arguments("l <<= (byte)3", createValue(40L)), + arguments("l <<= (short)256", createValue(5L)), + arguments("l <<= 'a'", createValue(42949672960L)), arguments("l <<= 1", createValue(10L)), arguments("l <<= 2L", createValue(20L)), arguments("l <<= 1.5f", null), arguments("l <<= 3.14", null), - arguments("l <<= 'a'", createValue(42949672960L)), arguments("f <<= false", null), + arguments("f <<= (byte)3", null), + arguments("f <<= (short)256", null), + arguments("f <<= 'a'", null), arguments("f <<= 1", null), arguments("f <<= 2L", null), arguments("f <<= 1.5f", null), arguments("f <<= 3.14", null), - arguments("f <<= 'a'", null), arguments("d <<= false", null), + arguments("d <<= (byte)3", null), + arguments("d <<= (short)256", null), + arguments("d <<= 'a'", null), arguments("d <<= 1", null), arguments("d <<= 2L", null), arguments("d <<= 1.5f", null), - arguments("d <<= 3.14", null), - arguments("d <<= 'a'", null), - - arguments("c <<= false", null), - arguments("c <<= 1", createValue((char)194)), - arguments("c <<= 2L", createValue((char)388)), - arguments("c <<= 1.5f", null), - arguments("c <<= 3.14", null), - arguments("c <<= 'a'", createValue((char)194))); + arguments("d <<= 3.14", null) + ); } protected static Stream minusEqualsExpression() { return Stream.of( arguments("b -= false", null), + arguments("b -= (byte)3", null), + arguments("b -= (short)256", null), + arguments("b -= 'a'", null), arguments("b -= 1", null), arguments("b -= 2L", null), arguments("b -= 1.5f", null), arguments("b -= 3.14", null), - arguments("b -= 'a'", null), + + arguments("by -= false", null), + arguments("by -= (byte)3", createValue((byte)0)), + arguments("by -= (short)256", createValue((byte)3)), + arguments("by -= 'a'", createValue((byte)-94)), + arguments("by -= 1", createValue((byte)2)), + arguments("by -= 2L", createValue((byte)1)), + arguments("by -= 1.5f", createValue((byte)1)), + arguments("by -= 3.14", createValue((byte)0)), + + arguments("s -= false", null), + arguments("s -= (byte)3", createValue((short)253)), + arguments("s -= (short)256", createValue((short)0)), + arguments("s -= 'a'", createValue((short)159)), + arguments("s -= 1", createValue((short)255)), + arguments("s -= 2L", createValue((short)254)), + arguments("s -= 1.5f", createValue((short)254)), + arguments("s -= 3.14", createValue((short)252)), + + arguments("c -= false", null), + arguments("c -= (byte)3", createValue((char)94)), + arguments("c -= (short)256", createValue((char)-159)), + arguments("c -= 'a'", createValue((char)0)), + arguments("c -= 1", createValue((char)96)), + arguments("c -= 2L", createValue((char)95)), + arguments("c -= 1.5f", createValue((char)95.5f)), + arguments("c -= 3.14", createValue((char)93.86)), arguments("i -= false", null), + arguments("i -= (byte)3", createValue(-2)), + arguments("i -= (short)256", createValue(-255)), + arguments("i -= 'a'", createValue(-96)), arguments("i -= 1", createValue(0)), arguments("i -= 2L", createValue(-1)), arguments("i -= 1.5f", createValue(0)), arguments("i -= 3.14", createValue(-2)), - arguments("i -= 'a'", createValue(-96)), arguments("l -= false", null), + arguments("l -= (byte)3", createValue(2L)), + arguments("l -= (short)256", createValue(-251L)), + arguments("l -= 'a'", createValue(-92L)), arguments("l -= 1", createValue(4L)), arguments("l -= 2L", createValue(3L)), arguments("l -= 1.5f", createValue(3L)), arguments("l -= 3.14", createValue(1L)), - arguments("l -= 'a'", createValue(-92L)), arguments("f -= false", null), + arguments("f -= (byte)3", createValue(-1.5f)), + arguments("f -= (short)256", createValue(-254.5f)), + arguments("f -= 'a'", createValue(-95.5f)), arguments("f -= 1", createValue(0.5f)), arguments("f -= 2L", createValue(-0.5f)), arguments("f -= 1.2f", createValue(.3f)), arguments("f -= 3.14", createValue(-1.64f)), - arguments("f -= 'a'", createValue(-95.5f)), arguments("d -= false", null), + arguments("d -= (byte)3", createValue(0.14)), + arguments("d -= (short)256", createValue(-252.86)), + arguments("d -= 'a'", createValue(-93.86)), arguments("d -= 1", createValue(2.14)), arguments("d -= 2L", createValue(1.14)), arguments("d -= 1.5f", createValue(1.64)), - arguments("d -= 3.04", createValue(.1)), - arguments("d -= 'a'", createValue(-93.86)), - - arguments("c -= false", null), - arguments("c -= 1", createValue((char)96)), - arguments("c -= 2L", createValue((char)95)), - arguments("c -= 1.5f", createValue((char)95.5f)), - arguments("c -= 3.14", createValue((char)93.86)), - arguments("c -= 'a'", createValue((char)0))); + arguments("d -= 3.04", createValue(.1)) + ); } protected static Stream percentEqualsExpression() { return Stream.of( arguments("b %= false", null), + arguments("b %= (byte)3", null), + arguments("b %= (short)256", null), + arguments("b %= 'a'", null), arguments("b %= 1", null), arguments("b %= 2L", null), arguments("b %= 1.5f", null), arguments("b %= 3.14", null), - arguments("b %= 'a'", null), + + arguments("by %= false", null), + arguments("by %= (byte)3", createValue((byte)0)), + arguments("by %= (short)256", createValue((byte)3)), + arguments("by %= 'a'", createValue((byte)3)), + arguments("by %= 1", createValue((byte)0)), + arguments("by %= 2L", createValue((byte)1)), + arguments("by %= 1.5f", createValue((byte)0)), + arguments("by %= 3.14", createValue((byte)3)), + + arguments("s %= false", null), + arguments("s %= (byte)3", createValue((short)1)), + arguments("s %= (short)256", createValue((short)0)), + arguments("s %= 'a'", createValue((short)62)), + arguments("s %= 1", createValue((short)0)), + arguments("s %= 2L", createValue((short)0)), + arguments("s %= 1.5f", createValue((short)1)), + arguments("s %= 3.14", createValue((short)1)), + + arguments("c %= false", null), + arguments("c %= (byte)3", createValue((char)1)), + arguments("c %= (short)256", createValue('a')), + arguments("c %= 'a'", createValue((char)0)), + arguments("c %= 1", createValue((char)0)), + arguments("c %= 2L", createValue((char)1)), + arguments("c %= 1.5f", createValue((char)1)), + arguments("c %= 3.14", createValue((char)2)), arguments("i %= false", null), + arguments("i %= (byte)3", createValue(1)), + arguments("i %= (short)256", createValue(1)), + arguments("i %= 'a'", createValue(1)), arguments("i %= 1", createValue(0)), arguments("i %= 2L", createValue(1)), arguments("i %= 1.5f", createValue(1)), arguments("i %= 3.14", createValue(1)), - arguments("i %= 'a'", createValue(1)), arguments("l %= false", null), + arguments("l %= (byte)3", createValue(2L)), + arguments("l %= (short)256", createValue(5L)), + arguments("l %= 'a'", createValue(5L)), arguments("l %= 1", createValue(0L)), - arguments("l %= 2L", createValue(1L)), + arguments("l %= 4L", createValue(1L)), arguments("l %= 1.5f", createValue(0L)), arguments("l %= 3.14", createValue(1L)), - arguments("l %= 'a'", createValue(5L)), arguments("f %= false", null), + arguments("f %= (byte)3", createValue(1.5f)), + arguments("f %= (short)256", createValue(1.5f)), + arguments("f %= 'a'", createValue(1.5f)), arguments("f %= 1", createValue(0.5f)), arguments("f %= 2L", createValue(1.5f)), - arguments("f %= 1.5f", createValue(0f)), + arguments("f %= 1.5f", createValue(0.0f)), arguments("f %= 3.14", createValue(1.5f)), - arguments("f %= 'a'", createValue(1.5f)), arguments("d %= false", null), + arguments("d %= (byte)3", createValue(0.14)), + arguments("d %= (short)256", createValue(3.14)), + arguments("d %= 'a'", createValue(3.14)), arguments("d %= 1", createValue(0.14)), arguments("d %= 2L", createValue(1.14)), arguments("d %= 1.5f", createValue(0.14)), - arguments("d %= 3.14", createValue(0.)), - arguments("d %= 'a'", createValue(3.14)), - - arguments("c %= false", null), - arguments("c %= 1", createValue((char)0)), - arguments("c %= 2L", createValue((char)1)), - arguments("c %= 1.5f", createValue((char)1)), - arguments("c %= 3.14", createValue((char)2)), - arguments("c %= 'a'", createValue((char)0))); + arguments("d %= 3.04", createValue(0.1)) + ); } protected static Stream pipeEqualsExpression() { return Stream.of( - arguments("b |= false", createValue(true)), + arguments("b |= true", createValue(true)), + arguments("b |= (byte)3", null), + arguments("b |= (short)256", null), + arguments("b |= 'c'", null), arguments("b |= 1", null), arguments("b |= 2L", null), arguments("b |= 1.5f", null), arguments("b |= 3.14", null), - arguments("b |= 'a'", null), + + arguments("by |= false", null), + arguments("by |= (byte)3", createValue((byte)3)), + arguments("by |= (short)256", createValue((byte)259)), + arguments("by |= 'a'", createValue((byte)99)), + arguments("by |= 1", createValue((byte)3)), + arguments("by |= 2L", createValue((byte)3)), + arguments("by |= 1.5f", null), + arguments("by |= 3.14", null), + + arguments("s |= false", null), + arguments("s |= (byte)3", createValue((short)259)), + arguments("s |= (short)256", createValue((short)256)), + arguments("s |= 'a'", createValue((short)353)), + arguments("s |= 1", createValue((short)257)), + arguments("s |= 2L", createValue((short)258)), + arguments("s |= 1.5f", null), + arguments("s |= 3.14", null), + + arguments("c |= false", null), + arguments("c |= (byte)3", createValue((char)99)), + arguments("c |= (short)256", createValue((char)353)), + arguments("c |= 'a'", createValue('a')), + arguments("c |= 1", createValue((char)97)), + arguments("c |= 2L", createValue((char)99)), + arguments("c |= 1.5f", null), + arguments("c |= 3.14", null), arguments("i |= false", null), + arguments("i |= (byte)3", createValue(3)), + arguments("i |= (short)256", createValue(257)), + arguments("i |= 'a'", createValue(97)), arguments("i |= 1", createValue(1)), arguments("i |= 2L", createValue(3)), arguments("i |= 1.5f", null), arguments("i |= 3.14", null), - arguments("i |= 'a'", createValue(97)), arguments("l |= false", null), + arguments("l |= (byte)3", createValue(7L)), + arguments("l |= (short)256", createValue(261L)), + arguments("l |= 'a'", createValue(101L)), arguments("l |= 1", createValue(5L)), - arguments("l |= 2L", createValue(7L)), + arguments("l |= 4L", createValue(5L)), arguments("l |= 1.5f", null), arguments("l |= 3.14", null), - arguments("l |= 'a'", createValue(101L)), arguments("f |= false", null), + arguments("f |= (byte)3", null), + arguments("f |= (short)256", null), + arguments("f |= 'a'", null), arguments("f |= 1", null), arguments("f |= 2L", null), arguments("f |= 1.5f", null), arguments("f |= 3.14", null), - arguments("f |= 'a'", null), arguments("d |= false", null), + arguments("d |= (byte)3", null), + arguments("d |= (short)256", null), + arguments("d |= 'a'", null), arguments("d |= 1", null), arguments("d |= 2L", null), arguments("d |= 1.5f", null), - arguments("d |= 3.14", null), - arguments("d |= 'a'", null), - - arguments("c |= false", null), - arguments("c |= 1", createValue((char)97)), - arguments("c |= 2L", createValue((char)99)), - arguments("c |= 1.5f", null), - arguments("c |= 3.14", null), - arguments("c |= 'a'", createValue((char)97))); + arguments("d |= 3.14", null) + ); } protected static Stream plusEqualsExpression() { return Stream.of( arguments("b += false", null), + arguments("b += (byte)3", null), + arguments("b += (short)256", null), arguments("b += 1", null), arguments("b += 2L", null), arguments("b += 1.5f", null), arguments("b += 3.14", null), arguments("b += 'a'", null), - + arguments("by += false", null), + arguments("by += (byte)3", createValue((byte)6)), + arguments("by += (short)256", createValue((byte)3)), + arguments("by += 'a'", createValue((byte)100)), arguments("by += 1", createValue((byte)4)), arguments("by += 2L", createValue((byte)5)), arguments("by += 1.5f", createValue((byte)4)), arguments("by += 3.14", createValue((byte)6)), - arguments("by += 'a'", createValue((byte)100)), + + arguments("s += false", null), + arguments("s += (byte)3", createValue((short)259)), + arguments("s += (short)256", createValue((short)512)), + arguments("s += 'a'", createValue((short)353)), + arguments("s += 1", createValue((short)257)), + arguments("s += 2L", createValue((short)258)), + arguments("s += 1.5f", createValue((short)257)), + arguments("s += 3.14", createValue((short)259)), + + arguments("c += false", null), + arguments("c += (byte)3", createValue('d')), + arguments("c += (short)256", createValue((char)353)), + arguments("c += 'a'", createValue((char)194)), + arguments("c += 1", createValue((char)98)), + arguments("c += 2L", createValue((char)99)), + arguments("c += 1.5f", createValue((char)98)), + arguments("c += 3.14", createValue((char)100)), arguments("i += false", null), + arguments("i += (byte)3", createValue(4)), + arguments("i += (short)256", createValue(257)), + arguments("i += 'a'", createValue(98)), arguments("i += 1", createValue(2)), arguments("i += 2L", createValue(3)), arguments("i += 1.5f", createValue(2)), arguments("i += 3.14", createValue(4)), - arguments("i += 'a'", createValue(98)), arguments("l += false", null), + arguments("l += (byte)3", createValue(8L)), + arguments("l += (short)256", createValue(261L)), + arguments("l += 'a'", createValue(102L)), arguments("l += 1", createValue(6L)), arguments("l += 2L", createValue(7L)), arguments("l += 1.5f", createValue(6L)), arguments("l += 3.14", createValue(8L)), - arguments("l += 'a'", createValue(102L)), arguments("f += false", null), + arguments("f += (byte)3", createValue(4.5f)), + arguments("f += (short)256", createValue(257.5f)), arguments("f += 1", createValue(2.5f)), arguments("f += 2L", createValue(3.5f)), arguments("f += 1.5f", createValue(3.0f)), @@ -441,153 +660,242 @@ protected static Stream plusEqualsExpression() { arguments("f += 'a'", createValue(98.5f)), arguments("d += false", null), + arguments("d += (byte)3", createValue(6.14)), + arguments("d += (short)256", createValue(259.14)), + arguments("d += 'a'", createValue(100.14)), arguments("d += 1", createValue(4.14)), arguments("d += 2L", createValue(5.14)), arguments("d += 1.5f", createValue(4.64)), - arguments("d += 3.14", createValue(6.28)), - arguments("d += 'a'", createValue(100.14)), - - arguments("c += false", null), - arguments("c += 1", createValue((char)98)), - arguments("c += 2L", createValue((char)99)), - arguments("c += 1.5f", createValue((char)98)), - arguments("c += 3.14", createValue((char)100)), - arguments("c += 'a'", createValue((char)194))); + arguments("d += 3.14", createValue(6.28)) + ); } protected static Stream roofEqualsExpression() { return Stream.of( arguments("b ^= false", createValue(true)), + arguments("b ^= (byte)3", null), + arguments("b ^= (short)256", null), + arguments("b ^= 'c'", null), arguments("b ^= 1", null), arguments("b ^= 2L", null), arguments("b ^= 1.5f", null), arguments("b ^= 3.14", null), - arguments("b ^= 'a'", null), + + arguments("by ^= false", null), + arguments("by ^= (byte)3", createValue((byte)0)), + arguments("by ^= (short)256", createValue((byte)259)), + arguments("by ^= 'a'", createValue((byte)98)), + arguments("by ^= 1", createValue((byte)2)), + arguments("by ^= 2L", createValue((byte)1)), + arguments("by ^= 1.5f", null), + arguments("by ^= 3.14", null), + + arguments("s ^= false", null), + arguments("s ^= (byte)3", createValue((short)259)), + arguments("s ^= (short)256", createValue((short)0)), + arguments("s ^= 'a'", createValue((short)353)), + arguments("s ^= 1", createValue((short)257)), + arguments("s ^= 2L", createValue((short)258)), + arguments("s ^= 1.5f", null), + arguments("s ^= 3.14", null), + + arguments("c ^= false", null), + arguments("c ^= (byte)3", createValue((char)98)), + arguments("c ^= (short)256", createValue((char)353)), + arguments("c ^= 'a'", createValue((char)0)), + arguments("c ^= 1", createValue((char)96)), + arguments("c ^= 2L", createValue((char)99)), + arguments("c ^= 1.5f", null), + arguments("c ^= 3.14", null), arguments("i ^= false", null), - arguments("i ^= 3", createValue(2)), - arguments("i ^= 4L", createValue(5)), + arguments("i ^= (byte)3", createValue(2)), + arguments("i ^= (short)256", createValue(257)), + arguments("i ^= 'a'", createValue(96)), + arguments("i ^= 1", createValue(0)), + arguments("i ^= 2L", createValue(3)), arguments("i ^= 1.5f", null), arguments("i ^= 3.14", null), - arguments("i ^= 'a'", createValue(96)), arguments("l ^= false", null), + arguments("l ^= (byte)3", createValue(6L)), + arguments("l ^= (short)256", createValue(261L)), + arguments("l ^= 'a'", createValue(100L)), arguments("l ^= 1", createValue(4L)), - arguments("l ^= 2L", createValue(7L)), + arguments("l ^= 4L", createValue(1L)), arguments("l ^= 1.5f", null), arguments("l ^= 3.14", null), - arguments("l ^= 'a'", createValue(100L)), arguments("f ^= false", null), + arguments("f ^= (byte)3", null), + arguments("f ^= (short)256", null), + arguments("f ^= 'a'", null), arguments("f ^= 1", null), arguments("f ^= 2L", null), arguments("f ^= 1.5f", null), arguments("f ^= 3.14", null), - arguments("f ^= 'a'", null), arguments("d ^= false", null), + arguments("d ^= (byte)3", null), + arguments("d ^= (short)256", null), + arguments("d ^= 'a'", null), arguments("d ^= 1", null), arguments("d ^= 2L", null), arguments("d ^= 1.5f", null), - arguments("d ^= 3.14", null), - arguments("d ^= 'a'", null), - - arguments("c ^= false", null), - arguments("c ^= 1", createValue((char)96)), - arguments("c ^= 2L", createValue((char)99)), - arguments("c ^= 1.5f", null), - arguments("c ^= 3.14", null), - arguments("c ^= 'a'", createValue((char)0))); + arguments("d ^= 3.14", null) + ); } protected static Stream slashEqualsExpression() { return Stream.of( arguments("b /= false", null), + arguments("b /= (byte)3", null), + arguments("b /= (short)256", null), + arguments("b /= 'a'", null), arguments("b /= 1", null), arguments("b /= 2L", null), arguments("b /= 1.5f", null), arguments("b /= 3.14", null), - arguments("b /= 'a'", null), + + arguments("by /= false", null), + arguments("by /= (byte)3", createValue((byte)1)), + arguments("by /= (short)256", createValue((byte)0)), + arguments("by /= 'a'", createValue((byte)0)), + arguments("by /= 1", createValue((byte)3)), + arguments("by /= 2L", createValue((byte)1)), + arguments("by /= 1.5f", createValue((byte)2)), + arguments("by /= 3.14", createValue((byte)0)), + + arguments("s /= false", null), + arguments("s /= (byte)3", createValue((short)85)), + arguments("s /= (short)256", createValue((short)1)), + arguments("s /= 'a'", createValue((short)2)), + arguments("s /= 1", createValue((short)256)), + arguments("s /= 2L", createValue((short)128)), + arguments("s /= 1.5f", createValue((short)170)), + arguments("s /= 3.14", createValue((short)81)), + + arguments("c /= false", null), + arguments("c /= (byte)3", createValue((char)32)), + arguments("c /= (short)256", createValue((char)0)), + arguments("c /= 'a'", createValue((char)1)), + arguments("c /= 1", createValue('a')), + arguments("c /= 2L", createValue((char)48)), + arguments("c /= 1.5f", createValue((char)64)), + arguments("c /= 3.14", createValue((char)30)), arguments("i /= false", null), - arguments("i /= 0.25f", createValue(4)), - arguments("i /= 0.4", createValue(2)), - arguments("i /= 2", createValue(0)), - arguments("i /= 5L", createValue(0)), - arguments("i /= 'A'", createValue(0)), + arguments("i /= (byte)3", createValue(0)), + arguments("i /= (short)256", createValue(0)), + arguments("i /= 'a'", createValue(0)), + arguments("i /= 1", createValue(1)), + arguments("i /= 2L", createValue(0)), + arguments("i /= 1.5f", createValue(0)), + arguments("i /= 3.14", createValue(0)), arguments("l /= false", null), - arguments("l /= 1.25f", createValue(4L)), - arguments("l /= 0.4", createValue(12L)), - arguments("l /= 2", createValue(2L)), - arguments("l /= 5L", createValue(1L)), - arguments("l /= 'A'", createValue(0L)), + arguments("l /= (byte)3", createValue(1L)), + arguments("l /= (short)256", createValue(0L)), + arguments("l /= 'a'", createValue(0L)), + arguments("l /= 1", createValue(5L)), + arguments("l /= 2L", createValue(2L)), + arguments("l /= 1.5f", createValue(3L)), + arguments("l /= 3.14", createValue(1L)), arguments("f /= false", null), - arguments("f /= 3", createValue(.5f)), + arguments("f /= (byte)3", createValue(0.5f)), + arguments("f /= (short)256", createValue(0.005859375f)), + arguments("f /= 'a'", createValue(0.0154639175f)), + arguments("f /= 1", createValue(1.5f)), arguments("f /= 2L", createValue(0.75f)), - arguments("f /= 0.025f", createValue(60.f)), - arguments("f /= 2.5", createValue(.6f)), - arguments("f /= 'A'", createValue(0.0230769f)), + arguments("f /= 1.5f", createValue(1.0f)), + arguments("f /= 3.14", createValue(0.477707f)), arguments("d /= false", null), + arguments("d /= (byte)3", createValue(1.046666666)), + arguments("d /= (short)256", createValue(0.012265625)), + arguments("d /= 'a'", createValue(0.032371134)), arguments("d /= 1", createValue(3.14)), arguments("d /= 2L", createValue(1.57)), - arguments("d /= 1.57f", createValue(2.)), - arguments("d /= 0.02", createValue(157.)), - arguments("d /= 'A'", createValue(0.048307692307)), - - arguments("c /= false", null), - arguments("c /= 1", createValue((char)97)), - arguments("c /= 97L", createValue((char)1)), - arguments("c /= 0.25f", createValue((char)388)), - arguments("c /= 0.4", createValue((char)242)), - arguments("c /= 'A'", createValue((char)1))); + arguments("d /= 1.5f", createValue(2.09333333)), + arguments("d /= 3.14", createValue(1.0)) + ); } protected static Stream starEqualsExpression() { return Stream.of( arguments("b *= false", null), + arguments("b *= (byte)3", null), + arguments("b *= (short)256", null), + arguments("b *= 'a'", null), arguments("b *= 1", null), arguments("b *= 2L", null), arguments("b *= 1.5f", null), arguments("b *= 3.14", null), - arguments("b *= 'a'", null), + + arguments("by *= false", null), + arguments("by *= (byte)3", createValue((byte)9)), + arguments("by *= (short)256", createValue((byte)0)), + arguments("by *= 'a'", createValue((byte)35)), + arguments("by *= 1", createValue((byte)3)), + arguments("by *= 2L", createValue((byte)6)), + arguments("by *= 1.5f", createValue((byte)4)), + arguments("by *= 3.14", createValue((byte)9)), + + arguments("s *= false", null), + arguments("s *= (byte)3", createValue((short)768)), + arguments("s *= (short)256", createValue((short)0)), + arguments("s *= 'a'", createValue((short)24832)), + arguments("s *= 1", createValue((short)256)), + arguments("s *= 2L", createValue((short)512)), + arguments("s *= 1.5f", createValue((short)384)), + arguments("s *= 3.14", createValue((short)803)), + + arguments("c *= false", null), + arguments("c *= (byte)3", createValue((char)291)), + arguments("c *= (short)256", createValue((char)24832)), + arguments("c *= 'a'", createValue((char)9409)), + arguments("c *= 1", createValue((char)97)), + arguments("c *= 2L", createValue((char)194)), + arguments("c *= 1.5f", createValue((char)145.5f)), + arguments("c *= 3.14", createValue((char)304.58)), arguments("i *= false", null), - arguments("i *= 0.25f", createValue(0)), - arguments("i *= 4.5", createValue(4)), - arguments("i *= 2", createValue(2)), + arguments("i *= (byte)3", createValue(3)), + arguments("i *= (short)256", createValue(256)), + arguments("i *= 'a'", createValue(97)), + arguments("i *= 1", createValue(1)), arguments("i *= 2L", createValue(2)), - arguments("i *= 'A'", createValue(65)), + arguments("i *= 1.5f", createValue(1)), + arguments("i *= 3.14", createValue(3)), arguments("l *= false", null), - arguments("l *= 0.5f", createValue(2L)), - arguments("l *= 0.2", createValue(1L)), - arguments("l *= 2", createValue(10L)), - arguments("l *= 10L", createValue(50L)), - arguments("l *= 'A'", createValue(325L)), + arguments("l *= (byte)3", createValue(15L)), + arguments("l *= (short)256", createValue(1280L)), + arguments("l *= 'a'", createValue(485L)), + arguments("l *= 1", createValue(5L)), + arguments("l *= 2L", createValue(10L)), + arguments("l *= 1.5f", createValue(7L)), + arguments("l *= 3.14", createValue(15L)), arguments("f *= false", null), - arguments("f *= 3", createValue(4.5f)), - arguments("f *= 2L", createValue(3f)), - arguments("f *= 0.5f", createValue(.75f)), - arguments("f *= 0.5", createValue(.75f)), - arguments("f *= 'A'", createValue(97.5f)), + arguments("f *= (byte)3", createValue(4.5f)), + arguments("f *= (short)256", createValue(384.0f)), + arguments("f *= 'a'", createValue(145.5f)), + arguments("f *= 1", createValue(1.5f)), + arguments("f *= 2L", createValue(3.0f)), + arguments("f *= 1.5f", createValue(2.25f)), + arguments("f *= 3.14", createValue(4.71f)), arguments("d *= false", null), + arguments("d *= (byte)3", createValue(9.42)), + arguments("d *= (short)256", createValue(803.84)), + arguments("d *= 'a'", createValue(304.58)), arguments("d *= 1", createValue(3.14)), arguments("d *= 2L", createValue(6.28)), - arguments("d *= 0.5f", createValue(1.57)), - arguments("d *= 0.5", createValue(1.57)), - arguments("d *= 'A'", createValue(204.1)), - - arguments("c *= false", null), - arguments("c *= 2", createValue((char)194)), - arguments("c *= 2L", createValue((char)194)), - arguments("c *= 0.25f", createValue((char)24)), - arguments("c *= 0.5", createValue((char)48)), - arguments("c *= 'A'", createValue((char)6305))); + arguments("d *= 1.5f", createValue(4.71)), + arguments("d *= 3.14", createValue(9.8596)) + ); } @ParameterizedTest @@ -596,13 +904,13 @@ protected static Stream starEqualsExpression() { "decPrefixExpression", "andEqualsExpression", "gTGTEqualsExpression", "gTGTGTEqualsExpression", "lTLTEqualsExpression", "minusEqualsExpression", "percentEqualsExpression", "pipeEqualsExpression", "plusEqualsExpression", - "roofEqualsExpression", "slashEqualsExpression", "starEqualsExpression" + "roofEqualsExpression", "slashEqualsExpression", "starEqualsExpression" }) public void testInterpreter(String expression, MIValue result) { - if (result == null) { - testInvalidExpression(expression); - } else { - testValidExpression(expression, result); - } + if (result == null) { + testInvalidExpression(expression); + } else { + testValidExpression(expression, result); + } } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java index 39041da3d9..3050cffa20 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreterTest.java @@ -62,6 +62,16 @@ public void testInterpretBracketExpression() { testValidExpression("('a')", MIValueFactory.createValue('a')); } + @Test + public void testInterpretMinusPrefixExpression() { + testInvalidExpression("-(true)"); + testValidExpression("-(1)", MIValueFactory.createValue(-1)); + testValidExpression("-(2L)", MIValueFactory.createValue(-2L)); + testValidExpression("-(2.5f)", MIValueFactory.createValue(-2.5f)); + testValidExpression("-(3.14)", MIValueFactory.createValue(-3.14)); + testValidExpression("-('a')", MIValueFactory.createValue(-'a')); + } + @Test public void testInterpretMinusExpression() { testInvalidExpression("true - false"); @@ -76,6 +86,7 @@ public void testInterpretMinusExpression() { testInvalidExpression("true - 'a'"); testInvalidExpression("'a' - false"); + testValidExpression("1 - 2", MIValueFactory.createValue(-1)); testValidExpression("1L - 2", MIValueFactory.createValue(-1L)); testValidExpression("1 - 2L", MIValueFactory.createValue(-1L)); @@ -643,7 +654,10 @@ public void testInterpretLogicalOrOpExpression() { @Test public void testConditionalExpression() { testValidExpression("(true) ? 1 : 2", MIValueFactory.createValue(1)); - testValidExpression("5 <= 10%5 || !true && true ? (3 + 2 * 2) / 14.0 : ((1 > 2L) && ('z' <= 15.243f))", MIValueFactory.createValue(false)); + + // has result of union-type + testValidExpression("5 <= 10%5 || !true && true ? (3 + 2 * 2) / 14.0 : ((1 > 2L) && ('z' <= 15.243f))", + MIValueFactory.createValue(false)); } @Test diff --git a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java index 6cc579d056..9b4958f7db 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java @@ -1,41 +1,30 @@ package de.monticore.statements; import de.monticore.AbstractInterpreterTest; -import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; -import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsArtifactScope; import de.monticore.expressions.lambdaexpressions._symboltable.LambdaExpressionsSTCompleteTypes2; import de.monticore.interpreter.MIValue; -import de.monticore.io.paths.MCPath; import de.monticore.ocl.oclexpressions.symboltable.OCLExpressionsSymbolTableCompleter; import de.monticore.ocl.setexpressions.symboltable.SetExpressionsSymbolTableCompleter; import de.monticore.statements.combinestatementswithexpressions.CombineStatementsWithExpressionsMill; import de.monticore.statements.combinestatementswithexpressions._parser.CombineStatementsWithExpressionsParser; -import de.monticore.statements.combinestatementswithexpressions._symboltable.CombineStatementsWithExpressionsScopesGenitorDelegator; import de.monticore.statements.combinestatementswithexpressions._symboltable.ICombineStatementsWithExpressionsArtifactScope; import de.monticore.statements.combinestatementswithexpressions._visitor.CombineStatementsWithExpressionsInterpreter; import de.monticore.statements.combinestatementswithexpressions._visitor.CombineStatementsWithExpressionsTraverser; import de.monticore.statements.mccommonstatements._symboltable.MCCommonStatementsSymTabCompletion; import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; -import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; import de.monticore.statements.mcvardeclarationstatements._symboltable.MCVarDeclarationStatementsSymTabCompletion; -import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.oosymbols.OOSymbolsMill; -import de.monticore.symboltable.ImportStatement; import de.monticore.types.check.IDerive; import de.monticore.types.check.ISynthesize; -import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.types3wrapper.TypeCheck3AsIDerive; import de.monticore.types.check.types3wrapper.TypeCheck3AsISynthesize; import de.monticore.types3.Type4Ast; -import de.monticore.types3.TypeCheck3; import de.monticore.types3.util.DefsTypesForTests; import de.monticore.visitor.ITraverser; import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.BeforeEach; import java.io.IOException; -import java.util.Collections; -import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; diff --git a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java index 2498e229f8..0abad140b0 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java @@ -6,7 +6,6 @@ import de.monticore.expressions.combineexpressionswithliterals._parser.CombineExpressionsWithLiteralsParser; import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsArtifactScope; import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsTraverser; -import de.monticore.expressions.commonexpressions.types3.util.CommonExpressionsLValueRelations; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaExpression; import de.monticore.expressions.lambdaexpressions._symboltable.LambdaExpressionsSTCompleteTypes2; From 3032dc375afc925a58cbff540841fb232173001d Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Tue, 12 Aug 2025 19:09:49 +0200 Subject: [PATCH 18/37] Doc-Comments --- .../AssignmentExpressionsInterpreter.java | 3 +- .../CommonExpressionsInterpreter.java | 71 +++-- .../interpreter/InterpreterUtils.java | 286 +++++++++++++----- .../values/JavaAttributeMIValue.java | 4 +- .../de/monticore/AbstractInterpreterTest.java | 42 ++- .../AbstractExpressionInterpreterTest.java | 90 ++++-- .../AssignmentExpressionsInterpreterTest.java | 3 + .../AbstractStatementInterpreterTest.java | 10 +- .../CombineStatementsWithExpressionsTest.java | 20 +- 9 files changed, 378 insertions(+), 151 deletions(-) diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java index eed3436688..2833c3df16 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java @@ -261,7 +261,7 @@ public MIValue interpret(ASTAssignmentExpression n) { SymTypeExpression rightType = TypeCheck3.typeOf(n.getRight()); - // no operation + // normal assignment without operation if (operator == EQUALS) { if (leftType.deepEquals(rightType)) { variable.write(rightValue); @@ -401,6 +401,7 @@ public MIValue interpret(ASTAssignmentExpression n) { if (resultValue.isFlowControlSignal()) return resultValue; if (leftType.deepEquals(resultType)) { + // nothing left to do } else if (leftType.isPrimitive() && resultType.isPrimitive()) { resultValue = InterpreterUtils.convertToPrimitiveExplicit(resultType.asPrimitive().getPrimitiveName(), leftType.asPrimitive().getPrimitiveName(), resultValue); diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index 231a4706bd..f910d4fa45 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -43,7 +43,10 @@ public SymTypePrimitive getCompatibleType(SymTypePrimitive type1, SymTypePrimiti : null ); } - + + /** + * Checks whether the left and right value are equal. + */ public MIValue isEqual(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); if (compatibleType == null) { @@ -77,7 +80,10 @@ public MIValue isEqual(SymTypePrimitive leftType, MIValue left, SymTypePrimitive Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + + /** + * Subtracts the right value from the left value while minding the types + */ public MIValue subtract(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); if (compatibleType == null) { @@ -465,30 +471,43 @@ public MIValue interpret(ASTConditionalExpression node) { public MIValue interpret(ASTFieldAccessExpression node) { SymTypeExpression type = TypeCheck3.typeOf(node); Optional symbolOptional = type.getSourceInfo().getSourceSymbol(); + // TODO Definition of Classes with Attributes/Methods in Model if (symbolOptional.isEmpty()) { - + String errorMsg = "0x57018 Field Access operation expected a symbol as source."; + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); } else { + // Java Method/Attribute ISymbol symbol = symbolOptional.get(); if (symbol.getAccessModifier().getDimensionToModifierMap() - .getOrDefault(StaticAccessModifier.DIMENSION, StaticAccessModifier.NON_STATIC) == StaticAccessModifier.STATIC) { // static - if (type.isFunctionType()) { // static function - FunctionSymbol funcSymbol = (FunctionSymbol)symbol; - String funcName = funcSymbol.getName(); - String className = funcSymbol.getFullName().substring(0, funcName.length() + 1); // remove '.funcName' - Class classType; - try { - classType = Class.forName(className); - } catch (ClassNotFoundException e) { - String errorMsg = "0x57018 Failed to load class '" + className + "'."; - Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); - return new ErrorMIValue(errorMsg); - } - return new JavaStaticMethodMIValue(classType, funcName); - } else { // static attribute - // TODO + .getOrDefault(StaticAccessModifier.DIMENSION, + StaticAccessModifier.NON_STATIC) == StaticAccessModifier.STATIC) { + // static + + // get Java-Class from symbol + String fieldName = symbol.getName(); + String fullName = symbol.getFullName(); + String className = fullName.substring(0, (fullName.length() + - fieldName.length() - 1)); + Class classType; + try { + classType = Class.forName(className); + } catch (ClassNotFoundException e) { + String errorMsg = "0x57018 Failed to load class '" + className + "'."; + Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); + } + + if (type.isFunctionType()) { + // static method + return new JavaStaticMethodMIValue(classType, fieldName); + } else { + // static attribute + return InterpreterUtils.getStaticObjectAttribute(classType, fieldName); } - } else { // non-static + } else { + // non-static MIValue leftValue = node.getExpression().evaluate(getRealThis()); if (!leftValue.isObject()) { String errorMsg = "0x57019 The Field Access operation expected an object as left side."; @@ -497,19 +516,17 @@ public MIValue interpret(ASTFieldAccessExpression node) { } // If class-declarations are supported this needs to be expanded - if (type.isFunctionType()) { // method call on object + if (type.isFunctionType()) { + // non-static method FunctionSymbol funcSymbol = (FunctionSymbol)symbol; String name = funcSymbol.getName(); return new JavaNonStaticMethodMIValue(leftValue.asObject(), name); - } else { // non-static attribute access - return InterpreterUtils.getObjectAttribute((ObjectMIValue)leftValue, node.getName(), type); + } else { + // non-static attribute + return InterpreterUtils.getNonStaticObjectAttribute((ObjectMIValue)leftValue, node.getName()); } } } - - String errorMsg = "0x57020 Field Access operation not supported."; - Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); - return new ErrorMIValue(errorMsg); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java index e20d01701f..303642f77d 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java @@ -7,15 +7,23 @@ import de.se_rwth.commons.logging.Log; import java.lang.reflect.Field; +import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import static de.monticore.interpreter.MIValueFactory.createValue; +/** + * Utility class for the interpreter. + * Contains methods for implict/explicit casts, conversion from Object to + * MIValue or MIValue to object, and the calculation of binary operations. + */ public class InterpreterUtils { - public static MIValue calcOpPrimitive(MIValue v1, MIValue v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, - BinaryOperator opFloat, BinaryOperator opDouble, String opName) { + public static MIValue calcOpPrimitive(MIValue v1, MIValue v2, + String resultType, BinaryOperator opInt, + BinaryOperator opLong, BinaryOperator opFloat, + BinaryOperator opDouble, String opName) { switch (resultType) { case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); @@ -28,8 +36,9 @@ public static MIValue calcOpPrimitive(MIValue v1, MIValue v2, String resultType, return new ErrorMIValue(errorMsg); } - public static MIValue calcBitwiseOpPrimitive(MIValue v1, MIValue v2, String resultType, BinaryOperator opInt, BinaryOperator opLong, - String opName) { + public static MIValue calcBitwiseOpPrimitive(MIValue v1, MIValue v2, + String resultType, BinaryOperator opInt, + BinaryOperator opLong, String opName) { switch (resultType) { case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); @@ -39,8 +48,10 @@ public static MIValue calcBitwiseOpPrimitive(MIValue v1, MIValue v2, String resu return new ErrorMIValue(errorMsg); } - public static MIValue calcBitwiseLogicalOpPrimitive(MIValue v1, MIValue v2, String resultType, BinaryOperator opBool, BinaryOperator opInt, - BinaryOperator opLong, String opName) { + public static MIValue calcBitwiseLogicalOpPrimitive(MIValue v1, MIValue v2, + String resultType, BinaryOperator opBool, + BinaryOperator opInt, BinaryOperator opLong, + String opName) { switch (resultType) { case BasicSymbolsMill.BOOLEAN: return createValue((boolean)opBool.apply(v1.asBoolean(), v2.asBoolean())); case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); @@ -51,8 +62,9 @@ public static MIValue calcBitwiseLogicalOpPrimitive(MIValue v1, MIValue v2, Stri return new ErrorMIValue(errorMsg); } - public static MIValue calcShiftPrimitive(MIValue v1, MIValue v2, String resultType, BiFunction opInt, BinaryOperator opLong, - String opName) { + public static MIValue calcShiftPrimitive(MIValue v1, MIValue v2, + String resultType, BiFunction opInt, + BinaryOperator opLong, String opName) { switch (resultType) { case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asLong())); case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); @@ -61,9 +73,25 @@ public static MIValue calcShiftPrimitive(MIValue v1, MIValue v2, String resultTy Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - public static MIValue calcOp(MIValue v1, MIValue v2, SymTypeExpression resultType, BinaryOperator opInt, BinaryOperator opLong, - BinaryOperator opFloat, BinaryOperator opDouble, String opName) { + + /** + * Calculates the result of a binary operation with the given result type by + * using the given lambdas for the calculation. Operation should support + * int, long, float & double. + * @param v1 left operand + * @param v2 right operand + * @param resultType result type of the operation + * @param opInt lambda for int operation + * @param opLong lambda for long operation + * @param opFloat lambda for float operation + * @param opDouble lambda for double operation + * @param opName Name of the operation (for error messages) + * @return Result of the operation or an error value if the type is not supported. + */ + public static MIValue calcOp(MIValue v1, MIValue v2, + SymTypeExpression resultType, BinaryOperator opInt, + BinaryOperator opLong, BinaryOperator opFloat, + BinaryOperator opDouble, String opName) { if (resultType.isPrimitive()) { return calcOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opFloat, opDouble, opName); } @@ -72,9 +100,21 @@ public static MIValue calcOp(MIValue v1, MIValue v2, SymTypeExpression resultTyp Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - public static MIValue calcBitwiseOp(MIValue v1, MIValue v2, SymTypeExpression resultType, BinaryOperator opInt, BinaryOperator opLong, - String opName) { + + /** + * Calculates the result of a bitwise binary operation with the given result type by using + * the given lambdas for the calculation. Operation should support int & long. + * @param v1 left operand + * @param v2 right operand + * @param resultType result type of the operation + * @param opInt lambda for int operation + * @param opLong lambda for long operation + * @param opName Name of the operation (for error messages) + * @return Result of the operation or an error value if the type is not supported. + */ + public static MIValue calcBitwiseOp(MIValue v1, MIValue v2, + SymTypeExpression resultType, BinaryOperator opInt, + BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { return calcBitwiseOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opName); } @@ -83,30 +123,70 @@ public static MIValue calcBitwiseOp(MIValue v1, MIValue v2, SymTypeExpression re Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - public static MIValue calcBitwiseLogicalOp(MIValue v1, MIValue v2, SymTypeExpression resultType, BinaryOperator opBool, BinaryOperator opInt, - BinaryOperator opLong, String opName) { + + /** + * Calculates the result of a bitwise or logical binary operation with the + * given result type by using the given lambdas for the calculation. + * Operation should support boolean, int & long. + * @param v1 left operand + * @param v2 right operand + * @param resultType result type of the operation + * @param opInt lambda for int operation + * @param opLong lambda for long operation + * @param opName Name of the operation (for error messages) + * @return Result of the operation or an error value if the type is not supported. + */ + public static MIValue calcBitwiseLogicalOp(MIValue v1, MIValue v2, + SymTypeExpression resultType, + BinaryOperator opBool, BinaryOperator opInt, + BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { - return calcBitwiseLogicalOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opBool, opInt, opLong, opName); + return calcBitwiseLogicalOpPrimitive(v1, v2, + resultType.asPrimitive().getPrimitiveName(), opBool, opInt, + opLong, opName); } - String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + String errorMsg = opName + " operation with result of type " + resultType + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - public static MIValue calcShift(MIValue v1, MIValue v2, SymTypeExpression resultType, BiFunction opInt, - BinaryOperator opLong, String opName) { + + /** + * Calculates the result of a shift-like operation with the + * given result type by using the given lambdas for the calculation. + * Shift operations always support up to long for the right side. + * @param v1 left operand + * @param v2 right operand + * @param resultType result type of the operation + * @param opInt lambda for int operation + * @param opLong lambda for long operation + * @param opName Name of the operation (for error messages) + * @return Result of the operation or an error value if the type is not supported. + */ + public static MIValue calcShift(MIValue v1, MIValue v2, + SymTypeExpression resultType, + BiFunction opInt, + BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { - return calcShiftPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opName); + return calcShiftPrimitive(v1, v2, + resultType.asPrimitive().getPrimitiveName(), opInt, opLong, + opName); } - String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + String errorMsg = opName + " operation with result of type " + resultType + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - public static MIValue convertToPrimitiveExplicit(String from, String to, MIValue value) { + + /** + * Applies an explicit cast on primitive to target primitive type. + * @return converted MIValue or ErrorMIValue if the cast is not supported or + * not possible. + */ + public static MIValue convertToPrimitiveExplicit(String from, String to, + MIValue value) { if (to.equals(BasicSymbolsMill.BOOLEAN) || from.equals(BasicSymbolsMill.BOOLEAN)) { String errorMsg = "0x57060 Cast to or from boolean is not supported."; Log.error(errorMsg); @@ -170,12 +250,19 @@ public static MIValue convertToPrimitiveExplicit(String from, String to, MIValue return createValue(value.asDouble()); } - String errorMsg = "0x57061 Cast from " + from + " to " + to + " is not supported."; + String errorMsg = "0x57061 Cast from " + from + " to " + to + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - public static MIValue convertToPrimitiveImplicit(String targetType, MIValue value) { + + /** + * Applies an implicit cast on primitive to target primitive type + * @return converted MIValue or ErrorMIValue if the cast is not supported or + * not possible. + */ + public static MIValue convertToPrimitiveImplicit(String targetType, + MIValue value) { if (targetType.equals(BasicSymbolsMill.BYTE)) { return createValue(value.asByte()); } else if (targetType.equals(BasicSymbolsMill.SHORT)) { @@ -192,18 +279,30 @@ public static MIValue convertToPrimitiveImplicit(String targetType, MIValue valu return createValue(value.asDouble()); } - String errorMsg = "0x57062 Implicit cast to " + targetType + " is not supported."; + String errorMsg = "0x57062 Implicit cast to " + targetType + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - public static MIValue convertImplicit(SymTypeExpression targetType, MIValue value) { + + /** + * Applies an implicit cast on value to targetType. + * Allows casts of boxtypes and primitives. + * @return converted MIValue or ErrorMIValue if the cast is not supported or + * not possible. + */ + public static MIValue convertImplicit(SymTypeExpression targetType, + MIValue value) { if (targetType.isPrimitive()) { value = unboxType(value); - return convertToPrimitiveImplicit(targetType.asPrimitive().getPrimitiveName(), value); + return convertToPrimitiveImplicit( + targetType.asPrimitive().getPrimitiveName(), value + ); } else if (isBoxType(targetType)) { SymTypeExpression unboxedType = SymTypeRelations.unbox(targetType); - value = convertToPrimitiveImplicit(unboxedType.asPrimitive().getPrimitiveName(), value); + value = convertToPrimitiveImplicit( + unboxedType.asPrimitive().getPrimitiveName(), value + ); value = boxValue(value, targetType); return value; } else { @@ -214,55 +313,54 @@ public static MIValue convertImplicit(SymTypeExpression targetType, MIValue valu return value; } } - - public static MIValue getObjectAttribute(ObjectMIValue object, String attributeName, SymTypeExpression type) { + + /** + * Creates an AttributeMIValue for a non-static attribute of a java-object. + * @param object Java-Object as MIValue + * @return Value of the attribute as MIValue converted to the given type. + * ErrorMIValue if the attribute does not exist or is not accessible. + */ + public static MIValue getNonStaticObjectAttribute(ObjectMIValue object, + String attributeName) { Field attribute; try { - attribute = object.getClass().getField(attributeName); + attribute = object.asObject().getClass().getField(attributeName); } catch (NoSuchFieldException e) { - String errorMsg = "0x57063 Tried to access attribute '" + attributeName + "' of class '" - + object.getClass().getName() + "'. No such attribute exists."; + String errorMsg = "0x57063 Tried to access attribute '" + attributeName + + "' of class '" + object.getClass().getName() + + "'. No such attribute exists."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + + return new JavaAttributeMIValue(Optional.of(object.asObject()), attribute); + } + + /** + * Creates an AttributeMIValue for a non-static attribute of a java-object. + * @param classObject Java-Class + * @return Value of the attribute as MIValue converted to the given type. + * ErrorMIValue if the attribute does not exist or is not accessible. + */ + public static MIValue getStaticObjectAttribute(Class classObject, + String attributeName) { + Field attribute; try { - if (type.isPrimitive()) { - String typeName = type.asPrimitive().getPrimitiveName(); - if (typeName.equals(BasicSymbolsMill.BOOLEAN)) { - return MIValueFactory.createValue(attribute.getBoolean(object)); - } else if (typeName.equals(BasicSymbolsMill.BYTE)) { - return MIValueFactory.createValue(attribute.getByte(object)); - } else if (typeName.equals(BasicSymbolsMill.SHORT)) { - return MIValueFactory.createValue(attribute.getShort(object)); - } else if (typeName.equals(BasicSymbolsMill.CHAR)) { - return MIValueFactory.createValue(attribute.getChar(object)); - } else if (typeName.equals(BasicSymbolsMill.INT)) { - return MIValueFactory.createValue(attribute.getInt(object)); - } else if (typeName.equals(BasicSymbolsMill.LONG)) { - return MIValueFactory.createValue(attribute.getLong(object)); - } else if (typeName.equals(BasicSymbolsMill.FLOAT)) { - return MIValueFactory.createValue(attribute.getFloat(object)); - } else if (typeName.equals(BasicSymbolsMill.DOUBLE)) { - return MIValueFactory.createValue(attribute.getDouble(object)); - } - - } else if (type.isObjectType()) { - return MIValueFactory.createValue(attribute.get(object)); - } - } catch (IllegalAccessException e) { - String errorMsg = "0x57064 Tried to access attribute '" + attributeName + "' of class '" - + object.getClass().getName() + "'. Attribute is not accessible."; + attribute = classObject.getField(attributeName); + } catch (NoSuchFieldException e) { + String errorMsg = "0x57063 Tried to access attribute '" + attributeName + + "' of class '" + classObject.getName() + + "'. No such attribute exists."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - String errorMsg = "0x57065 Attribute Access operation does not support attributes of type '" - + type.printFullName() + "'."; - Log.error(errorMsg); - return new ErrorMIValue(errorMsg); + + return new JavaAttributeMIValue(Optional.empty(), attribute); } - + + /** + * Gets the corresponding java type for a given MIValue. + */ public static Class typeOfValue(MIValue value) { if (value.isBoolean()) { return boolean.class; @@ -284,11 +382,15 @@ public static Class typeOfValue(MIValue value) { return value.asObject().getClass(); } // Functions are not allowed - String errorMsg = "0x57066 Failed to get java type of " + value.printType() + "."; + String errorMsg = "0x57066 Failed to get java type of " + value.printType() + + "."; Log.error(errorMsg); return null; } - + + /** + * Converts a MIValue to a java object. + */ public static Object valueToObject(MIValue value) { if (value.isBoolean()) { return value.asBoolean(); @@ -310,11 +412,16 @@ public static Object valueToObject(MIValue value) { return value.asObject(); } // Functions are not allowed - String errorMsg = "0x57067 Failed to convert MIValue of type " + value.printType() + " to a java object."; + String errorMsg = "0x57067 Failed to convert MIValue of type " + + value.printType() + " to a java object."; Log.error(errorMsg); return null; } - + + /** + * Converts a java object to a MIValue. + * Boxtypes are converted to their corresponding primitive type. + */ public static MIValue objectToValue(Object object) { if (object instanceof Boolean) { return new BooleanMIValue((Boolean)object); @@ -336,11 +443,20 @@ public static MIValue objectToValue(Object object) { return new ObjectMIValue(object); } - + + /** + * Checks if SymTypeExpression is a boxtype + */ public static boolean isBoxType(SymTypeExpression type) { - return !type.isPrimitive() && (SymTypeRelations.isNumericType(type) || SymTypeRelations.isBoolean(type)); + return !type.isPrimitive() && ( + SymTypeRelations.isNumericType(type) + || SymTypeRelations.isBoolean(type) + ); } - + + /** + * Unboxes a value if it is a boxtype. + */ public static MIValue unboxType(MIValue value) { if (!value.isObject()) return value; @@ -363,7 +479,11 @@ public static MIValue unboxType(MIValue value) { return value; } - + + + /** + * Converts a MIValue into its equivalent Boxtype + */ public static MIValue boxValue(MIValue value) { if (!value.isPrimitive()) { return value; @@ -389,7 +509,11 @@ public static MIValue boxValue(MIValue value) { return value; } - + + /** + * Converts a value to the given box type. + * @return Boxed value wrapped in an ObjectMIValue + */ public static MIValue boxValue(MIValue value, SymTypeExpression boxType) { if (SymTypeRelations.isInt(boxType)) { return MIValueFactory.createValue(Integer.valueOf(value.asInt())); diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java index 5f3e1c4eab..883c655588 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java @@ -14,8 +14,8 @@ public class JavaAttributeMIValue extends WriteableMIValue { Optional innerValue = Optional.empty(); - public JavaAttributeMIValue(Object obj, Field attribute) { - this.obj = obj; + public JavaAttributeMIValue(Optional obj, Field attribute) { + this.obj = obj.orElse(null); this.attribute = attribute; } diff --git a/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java index eaff7b2ce4..8b43af7c46 100644 --- a/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/AbstractInterpreterTest.java @@ -4,7 +4,6 @@ import de.monticore.antlr4.MCConcreteParser; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.ModelInterpreter; -import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; @@ -15,7 +14,6 @@ import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import java.util.function.Supplier; @@ -23,6 +21,12 @@ import static org.junit.jupiter.api.Assertions.*; +/** + * Abstract class for interpreter tests. + * Supplies utils for comparing MIValues and loading functions/variables. + * Implementations need to initialize the parserSupplier, resetMill and + * initMill-attributes and implement the setupSymbolTableCompleter method. + */ public abstract class AbstractInterpreterTest { protected static final double delta = 0.00001; @@ -85,22 +89,41 @@ protected static String getAllFindingsAsString() { .collect(Collectors.joining(System.lineSeparator())) ; } - + + + /** + * Loads variable by full qualified name. + * @param name full qualified name + * @return stored MIValue or ErrorMIValue if not declared/initialized + */ public MIValue loadVariable(String name) { VariableSymbol symbol = BasicSymbolsMill.globalScope() .resolveVariable(name).get(); return interpreter.loadVariable(symbol); } - + + /** + * Loads function by full qualified name. + * @param name full qualified name + * @return stored FunctionMIValue or ErrorMIValue if not declared + */ public MIValue loadFunction(String name) { FunctionSymbol symbol = BasicSymbolsMill.globalScope() .resolveFunction(name).get(); return interpreter.loadFunction(symbol); } - - public void assertValue(MIValue expected, MIValue actual) { + + /** + * Compares two MIValues based on type and value. + * @param expected + * @param actual + */ + public void assertValueEquals(MIValue expected, MIValue actual) { + // if you join the ifs with && you can't tell missing comparison implementations for a new value + // from value mismatches apart if (expected.isVoid()) { if (actual.isVoid()) return; + } else if (expected.isError()) { if (actual.isError() && expected.asError().equals(actual.asError())) return; } else if (expected.isBreak()) { @@ -109,9 +132,10 @@ public void assertValue(MIValue expected, MIValue actual) { if (actual.isContinue()) return; } else if (expected.isReturn()) { if (actual.isReturn()) { - assertValue(expected.asReturnValue(), actual.asReturnValue()); + assertValueEquals(expected.asReturnValue(), actual.asReturnValue()); return; } + } else if (expected.isBoolean()) { if (actual.isBoolean() && expected.asBoolean() == actual.asBoolean()) return; } else if (expected.isByte()) { @@ -124,16 +148,19 @@ public void assertValue(MIValue expected, MIValue actual) { if (actual.isInt() && expected.asInt() == actual.asInt()) return; } else if (expected.isLong()) { if (actual.isLong() && expected.asLong() == actual.asLong()) return; + } else if (expected.isFloat()) { if (actual.isFloat() && expected.asFloat() + delta > actual.asFloat() && expected.asFloat() - delta < actual.asFloat()) return; } else if (expected.isDouble()) { if (actual.isDouble() && expected.asDouble() + delta > actual.asDouble() && expected.asDouble() - delta < actual.asDouble()) return; + } else if (expected.isFunction()) { if (actual.isFunction() && expected.asFunction().equals(actual.asFunction())) return; } else if (expected.isObject()) { if (actual.isObject() && expected.asObject().equals(actual.asObject())) return; + } else { Log.error("Trying to compare unsupported MIValue type '" + expected.printType() + "'."); @@ -143,6 +170,7 @@ public void assertValue(MIValue expected, MIValue actual) { fail("Expected " + expected.printType() + " (" + expected.printValue() + ") but got " + actual.printType() + " (" + actual.printValue() + ")."); + } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java index 1b838973ed..eb3fea2533 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java @@ -35,6 +35,19 @@ import static de.monticore.types3.util.DefsTypesForTests.variable; import static org.junit.jupiter.api.Assertions.*; +/** + * Abstract class for tests that use CombineExpressionsWithLiterals and + * only contain expressions. + * Creates a variable for each primitive type:
+ * boolean b = true;
+ * char c = 'a';
+ * byte by = 3;
+ * short s = 256;
+ * int i = 1;
+ * long l = 5L;
+ * float f = 1.5f;
+ * double d = 3.14;
+ */ public class AbstractExpressionInterpreterTest extends AbstractInterpreterTest { @Override @@ -63,53 +76,67 @@ public void init() { } protected void initBool() throws IOException { - VariableSymbol varSymbol = variable("b", SymTypeExpressionFactory.createPrimitive("boolean")); + VariableSymbol varSymbol = variable("b", SymTypeExpressionFactory + .createPrimitive("boolean")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, Optional.of(createValue(true))); } protected void initChar() throws IOException { - VariableSymbol varSymbol = variable("c", SymTypeExpressionFactory.createPrimitive("char")); + VariableSymbol varSymbol = variable("c", SymTypeExpressionFactory + .createPrimitive("char")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, Optional.of(createValue('a'))); } protected void initByte() throws IOException { - VariableSymbol varSymbol = variable("by", SymTypeExpressionFactory.createPrimitive("byte")); + VariableSymbol varSymbol = variable("by", SymTypeExpressionFactory + .createPrimitive("byte")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, Optional.of(createValue((byte)3))); } protected void initShort() throws IOException { - VariableSymbol varSymbol = variable("s", SymTypeExpressionFactory.createPrimitive("short")); + VariableSymbol varSymbol = variable("s", SymTypeExpressionFactory + .createPrimitive("short")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, Optional.of(createValue((short)256))); } protected void initInt() throws IOException { - VariableSymbol varSymbol = variable("i", SymTypeExpressionFactory.createPrimitive("int")); + VariableSymbol varSymbol = variable("i", SymTypeExpressionFactory + .createPrimitive("int")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, Optional.of(createValue(1))); } protected void initLong() throws IOException { - VariableSymbol varSymbol = variable("l", SymTypeExpressionFactory.createPrimitive("long")); + VariableSymbol varSymbol = variable("l", SymTypeExpressionFactory + .createPrimitive("long")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, Optional.of(createValue(5L))); } protected void initFloat() throws IOException { - VariableSymbol varSymbol = variable("f", SymTypeExpressionFactory.createPrimitive("float")); + VariableSymbol varSymbol = variable("f", SymTypeExpressionFactory + .createPrimitive("float")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, Optional.of(createValue(1.5f))); } protected void initDouble() throws IOException { - VariableSymbol varSymbol = variable("d", SymTypeExpressionFactory.createPrimitive("double")); + VariableSymbol varSymbol = variable("d", SymTypeExpressionFactory + .createPrimitive("double")); inScope(CombineExpressionsWithLiteralsMill.globalScope(), varSymbol); interpreter.declareVariable(varSymbol, Optional.of(createValue(3.14))); } - + + /** + * Interprets expression and checks if the result is as expected. + * Fails if parsing, interpretation or comparison fails. + * @param expr Expression to interpret + * @param expected Expected result of expression + */ protected void testValidExpression(String expr, MIValue expected) { Log.clearFindings(); MIValue interpretationResult = null; @@ -123,10 +150,15 @@ protected void testValidExpression(String expr, MIValue expected) { Log.printFindings(); fail(); } - assertValue(expected, interpretationResult); + assertValueEquals(expected, interpretationResult); assertTrue(Log.getFindings().isEmpty()); } - + + /** + * Tries to parse and interpret invalid expression. + * Fails if parsing and interpretation succeed. + * @param expr Invalid expression to check + */ protected void testInvalidExpression(String expr) { Log.clearFindings(); MIValue interpretationResult; @@ -140,14 +172,21 @@ protected void testInvalidExpression(String expr) { assertNotNull(interpretationResult); if (Log.getFindings().isEmpty() && !interpretationResult.isError()) { - fail("Expected an error but interpretation succeeded with result of " + interpretationResult.printType() + fail("Expected an error but interpretation succeeded with result of " + + interpretationResult.printType() + " (" + interpretationResult.printValue() + ")."); } assertFalse(Log.getFindings().isEmpty()); assertTrue(interpretationResult.isError()); } - + + /** + * Parses and interprets an expression. + * @param expr Expression to parse and interpret + * @return result of interpretation + * @throws IOException if parsing throws IOException + */ protected MIValue parseExpressionAndInterpret(String expr) throws IOException { final ASTExpression ast = parseExpr(expr); generateScopes(ast); @@ -159,19 +198,26 @@ protected MIValue parseExpressionAndInterpret(String expr) throws IOException { } return ast.evaluate(interpreter); } - + + /** + * Parses an expression and returns the resulting ASTExpression. + * @param exprStr Expression to parse + * @return resulting ASTExpression + * @throws IOException if parsing throws IOException + */ protected ASTExpression parseExpr(String exprStr) throws IOException { - Optional astExpression = parseStringExpr(exprStr); + Optional astExpression = + ((CombineExpressionsWithLiteralsParser)parser) + .parse_StringExpression(exprStr); Assertions.assertTrue(astExpression.isPresent(), getAllFindingsAsString()); return astExpression.get(); } - - // Parse a String expression of the according language - protected Optional parseStringExpr(String exprStr) - throws IOException { - return ((CombineExpressionsWithLiteralsParser)parser).parse_StringExpression(exprStr); - } - + + /** + * Generates Model for a single Expression so the Symboltable and + * scopes are build correctly + * @param expr Expression to generate model for + */ protected void generateScopes(ASTExpression expr) { // create a root ASTFoo rootNode = CombineExpressionsWithLiteralsMill.fooBuilder() diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java index 1e6aed375b..381bf5645a 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreterTest.java @@ -12,6 +12,9 @@ import static org.junit.jupiter.params.provider.Arguments.arguments; import static de.monticore.interpreter.MIValueFactory.createValue; +/** + * Tests for all AssignmentExpressions with primitive types + */ public class AssignmentExpressionsInterpreterTest extends AbstractExpressionInterpreterTest { protected static Stream incSuffixExpression() { diff --git a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java index 9b4958f7db..3589a8f764 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java @@ -29,6 +29,9 @@ import static org.junit.jupiter.api.Assertions.*; +/** + * Abstract class for tests that use CombineStatementsWithExpressions. + */ public abstract class AbstractStatementInterpreterTest extends AbstractInterpreterTest { @Override @@ -42,7 +45,12 @@ public void init() { interpreter = new CombineStatementsWithExpressionsInterpreter(); } - + + /** + * Parses and interprets a given model. + * @param model model to parse and interpret + * @return result of interpretation + */ protected MIValue testValidModel(String model) { Log.clearFindings(); Optional astNodeOpt = Optional.empty(); diff --git a/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java b/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java index 1aace4ad93..752263d43c 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java @@ -13,11 +13,11 @@ public class CombineStatementsWithExpressionsTest extends AbstractStatementInter @Test public void testVarDeclarationStatement() { testValidModel("int i = 0;"); - assertValue(createValue(0), loadVariable("i")); + assertValueEquals(createValue(0), loadVariable("i")); testValidModel("int j = 1, k = 2;"); - assertValue(createValue(1), loadVariable("j")); - assertValue(createValue(2), loadVariable("k")); + assertValueEquals(createValue(1), loadVariable("j")); + assertValueEquals(createValue(2), loadVariable("k")); } @Test @@ -34,7 +34,7 @@ public void testJavaBlockStatement() { " return [i, j]; \n" + "} " ); - assertValue(createValue(List.of(0, 42)), result); + assertValueEquals(createValue(List.of(0, 42)), result); } @Test @@ -49,7 +49,7 @@ public void testCommonWhileStatement() { " return count; \n" + "} " ); - assertValue(createValue(8), result); + assertValueEquals(createValue(8), result); } @Test @@ -64,7 +64,7 @@ public void testCommonDoWhileStatement() { " return count; \n" + "} " ); - assertValue(createValue(1), result); + assertValueEquals(createValue(1), result); } @Test @@ -78,7 +78,7 @@ public void testCommonForStatement() { " return count; \n" + "} " ); - assertValue(createValue(10), result); + assertValueEquals(createValue(10), result); } @Test @@ -92,7 +92,7 @@ public void testForEachStatement() { " return sum; \n" + "}" ); - assertValue(createValue(10), result); + assertValueEquals(createValue(10), result); } @Test @@ -107,7 +107,7 @@ public void testContinueStatement() { " return count; \n" + "} " ); - assertValue(createValue(5), result); + assertValueEquals(createValue(5), result); } @Test @@ -122,7 +122,7 @@ public void testBreakStatement() { " return count; \n" + "} " ); - assertValue(createValue(7), result); + assertValueEquals(createValue(7), result); } @Test From bc9752789b6f95800f357647d60b934ffa5e62de Mon Sep 17 00:00:00 2001 From: Samuel Thesing Date: Tue, 12 Aug 2025 19:45:06 +0200 Subject: [PATCH 19/37] More MCCommonStatement- & SetExpressions-Tests --- .../CommonExpressionsInterpreter.java | 2 + .../MCCommonStatementsInterpreter.java | 14 +++++- .../AbstractExpressionInterpreterTest.java | 25 ++++------- .../SetExpressionsInterpreterTest.java | 43 +++++++++++++++++++ .../AbstractStatementInterpreterTest.java | 42 ++++++++++++++++++ ...ementsWithExpressionsInterpreterTest.java} | 22 ++++++++-- 6 files changed, 125 insertions(+), 23 deletions(-) create mode 100644 monticore-grammar/src/test/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreterTest.java rename monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/{CombineStatementsWithExpressionsTest.java => CombineStatementsWithExpressionsInterpreterTest.java} (89%) diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index f910d4fa45..ec7b56f113 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -557,6 +557,8 @@ public MIValue interpret(ASTCallExpression node) { MIValue returnValue = value.asFunction().execute(getRealThis(), args); return InterpreterUtils.convertImplicit(returnType, returnValue); } + + } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java index 97979cb7d4..d99d1295be 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java @@ -75,7 +75,12 @@ public MIValue interpret(ASTWhileStatement node) { } popScope(); - if (condition.isFlowControlSignal()) { + if (!condition.isBoolean()) { + String errorMsg = "0x57009 While condition must be of type boolean. Got " + condition.printType() + + " (" + condition.printValue() + ")."; + Log.error(errorMsg, node.getCondition().get_SourcePositionStart(), node.getCondition().get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); + } else if (condition.isFlowControlSignal()) { return condition; } else { return new VoidMIValue(); @@ -101,7 +106,12 @@ public MIValue interpret(ASTDoWhileStatement node) { } popScope(); - if (condition.isFlowControlSignal()) { + if (!condition.isBoolean()) { + String errorMsg = "0x57009 While condition must be of type boolean. Got " + condition.printType() + + " (" + condition.printValue() + ")."; + Log.error(errorMsg, node.getCondition().get_SourcePositionStart(), node.getCondition().get_SourcePositionEnd()); + return new ErrorMIValue(errorMsg); + } else if (condition.isFlowControlSignal()) { return condition; } else { return new VoidMIValue(); diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java index eb3fea2533..cc1bc19642 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractExpressionInterpreterTest.java @@ -165,8 +165,8 @@ protected void testInvalidExpression(String expr) { try { interpretationResult = parseExpressionAndInterpret(expr); - } catch (IOException e) { - throw new RuntimeException(e); + } catch (IOException | AssertionError e) { + return; } assertNotNull(interpretationResult); @@ -188,7 +188,12 @@ protected void testInvalidExpression(String expr) { * @throws IOException if parsing throws IOException */ protected MIValue parseExpressionAndInterpret(String expr) throws IOException { - final ASTExpression ast = parseExpr(expr); + Optional astExpression = + ((CombineExpressionsWithLiteralsParser)parser) + .parse_StringExpression(expr); + assertTrue(astExpression.isPresent(), getAllFindingsAsString()); + + ASTExpression ast = astExpression.get(); generateScopes(ast); SymTypeExpression type = TypeCheck3.typeOf(ast); if (type.isObscureType()) { @@ -199,20 +204,6 @@ protected MIValue parseExpressionAndInterpret(String expr) throws IOException { return ast.evaluate(interpreter); } - /** - * Parses an expression and returns the resulting ASTExpression. - * @param exprStr Expression to parse - * @return resulting ASTExpression - * @throws IOException if parsing throws IOException - */ - protected ASTExpression parseExpr(String exprStr) throws IOException { - Optional astExpression = - ((CombineExpressionsWithLiteralsParser)parser) - .parse_StringExpression(exprStr); - Assertions.assertTrue(astExpression.isPresent(), getAllFindingsAsString()); - return astExpression.get(); - } - /** * Generates Model for a single Expression so the Symboltable and * scopes are build correctly diff --git a/monticore-grammar/src/test/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreterTest.java new file mode 100644 index 0000000000..3f4337cd9a --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/ocl/setexpressions/_visitor/SetExpressionsInterpreterTest.java @@ -0,0 +1,43 @@ +package de.monticore.ocl.setexpressions._visitor; + +import de.monticore.expressions.AbstractExpressionInterpreterTest; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Set; + +import static de.monticore.interpreter.MIValueFactory.createValue; + +public class SetExpressionsInterpreterTest extends AbstractExpressionInterpreterTest { + + @Test + public void testInterpretSetEnumerationExpression() { + testInvalidExpression("1..2"); + + testValidExpression("[1..7]", + createValue(List.of(1, 2, 3, 4, 5, 6, 7))); + testValidExpression("{1..10}", + createValue(Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); + } + + @Test + public void testInterpretSetComprehensionExpression() { + testInvalidExpression("{| x in [1..2]}"); + testInvalidExpression("{x | }"); + testInvalidExpression("{x | x in [1..2], x = x}"); + + testValidExpression("{x | x in [1..3]}", createValue(Set.of(1, 2, 3))); + testValidExpression("[x * x | x in [1..3]]", + createValue(List.of(1, 4, 9))); + + testValidExpression("{x | x in [1..3], x % 2 == 1}", + createValue(Set.of(1, 3))); + + testValidExpression("{x * y | x in [1..3], y in [1..2], x != y}", + createValue(Set.of(2, 3, 6))); + + testValidExpression("{y | x in [1..3], int y = x * x * x}", + createValue(Set.of(1, 8, 27))); + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java index 3589a8f764..066fef2ea7 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/AbstractStatementInterpreterTest.java @@ -136,5 +136,47 @@ protected void setupSymbolTableCompleter( symbolTableCompleter = combinedScopesCompleter; scopeGenitor = combinedScopesCompleter; } + + protected void testInvalidModel(String model) { + Log.clearFindings(); + Optional astNodeOpt = Optional.empty(); + try { + astNodeOpt = ((CombineStatementsWithExpressionsParser)parser).parse_String(model); + } catch (IOException e) { + System.out.println(e.getMessage()); + return; + } + + if (!Log.getFindings().isEmpty() || !astNodeOpt.isPresent()) { + return; + } + + OOSymbolsMill.reset(); + OOSymbolsMill.init(); + CombineStatementsWithExpressionsMill.reset(); + CombineStatementsWithExpressionsMill.init(); + CombineStatementsWithExpressionsMill.globalScope().clear(); + + DefsTypesForTests.setup(); + + ICombineStatementsWithExpressionsArtifactScope rootScope = + CombineStatementsWithExpressionsMill.scopesGenitorDelegator() + .createFromAST(astNodeOpt.get()); + + rootScope.setName("root"); + + astNodeOpt.get().accept(getSymbolTableCompleter()); + + MIValue interpretationResult = astNodeOpt.get().evaluate(interpreter); + + assertNotNull(interpretationResult); // this should not happen even if the model is invalid + if (!Log.getFindings().isEmpty()) { + return; + } + + fail("Expected an error but interpretation succeeded with result of " + + interpretationResult.printType() + " (" + + interpretationResult.printValue() + ")."); + } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java b/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsInterpreterTest.java similarity index 89% rename from monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java rename to monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsInterpreterTest.java index 752263d43c..bef7f503a8 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/combinestatementswithexpressions/_visitor/CombineStatementsWithExpressionsInterpreterTest.java @@ -8,7 +8,8 @@ import static de.monticore.interpreter.MIValueFactory.createValue; -public class CombineStatementsWithExpressionsTest extends AbstractStatementInterpreterTest { +public class CombineStatementsWithExpressionsInterpreterTest + extends AbstractStatementInterpreterTest { @Test public void testVarDeclarationStatement() { @@ -50,6 +51,8 @@ public void testCommonWhileStatement() { "} " ); assertValueEquals(createValue(8), result); + + testInvalidModel("while (2);"); } @Test @@ -65,6 +68,8 @@ public void testCommonDoWhileStatement() { "} " ); assertValueEquals(createValue(1), result); + + testInvalidModel("do; while (2);"); } @Test @@ -79,6 +84,8 @@ public void testCommonForStatement() { "} " ); assertValueEquals(createValue(10), result); + + testInvalidModel("for (;);"); } @Test @@ -93,6 +100,8 @@ public void testForEachStatement() { "}" ); assertValueEquals(createValue(10), result); + + testInvalidModel("for (int i : 1);"); } @Test @@ -101,13 +110,16 @@ public void testContinueStatement() { "{ \n" + " int count = 0; \n" + " for (int i = 0; i < 10; i++) { \n" + - " if (i % 2 != 0) continue; \n" + + " if (i % 2 != 0) { \n" + + " continue; \n" + + " } \n" + " count++; \n" + " } \n" + " return count; \n" + "} " ); assertValueEquals(createValue(5), result); + } @Test @@ -117,7 +129,9 @@ public void testBreakStatement() { " int count = 0; \n" + " for (int i = 0; i < 10; i++) { \n" + " count++; \n" + - " if (i > 5) break; \n" + + " if (i > 5) { \n" + + " break; \n" + + " } \n" + " } \n" + " return count; \n" + "} " @@ -132,7 +146,7 @@ public void testLeibnizEfficiency() { "{ \n" + " double pi = 1; \n" + " double x = 1; \n" + - " for (int i = 2; i < 10000002; i++) { \n" + + " for (int i = 2; i < 100002; i++) { \n" + " x = x * -1; \n" + " pi = pi + x / (2 * i - 1); \n" + " } \n" + From 4b935b817b3ab0e2f83d4f736d286980890087e0 Mon Sep 17 00:00:00 2001 From: SE-FDr <88034434+SE-FDr@users.noreply.github.com> Date: Wed, 13 Aug 2025 18:38:02 +0200 Subject: [PATCH 20/37] add Interpreter documentation --- .../de/monticore/interpreter/Interpreter.md | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/Interpreter.md diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/Interpreter.md b/monticore-grammar/src/main/java/de/monticore/interpreter/Interpreter.md new file mode 100644 index 0000000000..d875c9ab66 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/Interpreter.md @@ -0,0 +1,188 @@ + + + + +An Interpreter evaluates a model without the need of compilation. +E.g., an expression interpreter will evaluate the expression `1 + 3` +to the value `4`. + +In MontiCore an Interpreter can be used for, e.g., +* Read-eval-print loop (REPL) +* Custom interactions with model elements at runtime, e.g., + filtering a list of car objects to only display red cars. + +## Given infrastructure in MontiCore + +* [IModelInterpreter](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java) + (offers `interpret` to evaluate an `ASTNode` to a value) + * [ModelInterpreter](ModelInterpreter.java) + (default Implementation; + allows storing/loading of variables and functions) +* [MIValue](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java) + (represents values as a result of interpretation) + * [MIValueFactory](MIValueFactory.java) + (Factory to create MIValues) + * [BooleanMIValue](values/BooleanMIValue.java) + (represents a `boolean` value) + * [ByteMIValue](values/ByteMIValue.java) + (represents a `byte` value) + * [ShortMIValue](values/ShortMIValue.java) + (represents a `short` value) + * [CharMIValue](values/CharMIValue.java) + (represents a `char` value) + * [IntMIValue](values/IntMIValue.java) + (represents an `int` value) + * [LongMIValue](values/LongMIValue.java) + (represents a `long` value) + * [FloatMIValue](values/FloatMIValue.java) + (represents a `float` value) + * [DoubleMIValue](values/DoubleMIValue.java) + (represents a `double` value) + * [ObjectMIValue](values/ObjectMIValue.java) + (represents a Java `Object` value, including subclasses) + * [FunctionMIValue](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java) + (represents function values, they can be executed) + * [ModelFunctionMIValue](values/ModelFunctionMIValue.java) + (represents a function defined by an ASTNode) + * [JavaNonStaticMethodMIValue](values/JavaNonStaticMethodMIValue.java) + (represents a non-static method of a Java class) + * [JavaStaticMethodMIValue](values/JavaStaticMethodMIValue.java) + (represents a static method of a Java class) + * [WriteableMIValue](values/WriteableMIValue.java) + (represents an LValue; a value can be assigned, e.g., `a` in `a = 2;`) + * [VariableMIValue](values/VariableMIValue.java) + (represents the value of a VariableSymbol) + * [JavaAttributeMIValue](values/JavaAttributeMIValue.java) + (represents the value of a Java `Object`'s attribute, e.g, `p.name`) + * [VoidMIValue](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java) + (represents the lack of a value, e.g., interpretation of a statement) + * [ErrorMIValue](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java) + (represents an error during execution, e.g., interpretation of `1/0`) + * [MIFlowControlSignal](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java) + (represents transfer of control in the execution flow) + * [ReturnMIValue](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java) + (represents transfer of control due to a `return` statement, + contains the value returned) + * [BreakMIValue](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java) + (represents transfer of control due to a `break` statement) + * [ContinueMIValue](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java) + (represents transfer of control due to a `continue` statement) +* [IMIScope](../../../../../../../monticore-runtime/src/main/java/de/monticore/interpreter/IMIScope.java) + (represents a scope of execution of the interpreter) + * [MIScope](MIScope.java) + (implementation; contains local variables/functions) +* [MIForIterator](iterators/MIForIterator.java) + (internal representation of an iterator of a for-loop, + can execute the body of the loop) + * [MICommonForIterator](iterators/MICommonForIterator.java) + (represents the common for iterator, e.g, `int i = 5; i < 10; i++`) + * [MIForEachIterator](iterators/MIForEachIterator.java) + (represents the iterator of a for-each loop, e.g, `Person p : persons`) +* [InterpreterUtils](InterpreterUtils.java) + (internal utility class for interpreter visitors; offers, e.g., casting of values) +* Interpreter Visitors contain the evaluation logic for each type of `ASTNode` + of their corresponding grammar component. + * Expressions + * [AssignmentExpressionsInterpreter](../expressions/assignmentexpressions/_visitor/AssignmentExpressionsInterpreter.java) + * BitExpressionsInterpreter is currently not implemented. + * [CommonExpressionsInterpreter](../expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java) + * [ExpressionBasisInterpreter](../expressions/expressionsbasis/_visitor/ExpressionsBasisInterpreter.java) + * JavaClassExpressionsInterpreter is currently not implemented. + * [LambdaExpressionsInterpreter](../expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java) + * [OCLExpressionsInterpreter](../ocl/oclexpressions/_visitor/OCLExpressionsInterpreter.java) + is mostly unimplemented. + * OptionalOperatorsInterpreter is currently not implemented. + * RegularExpressionsInterpreter is currently not implemented. + * [SetExpressionsInterpreter](../ocl/setexpressions/_visitor/SetExpressionsInterpreter.java) + * StreamExpressionsInterpreter is currently no implemented. + * TupleExpressionsInterpreter is currently not implemented. + * [UglyExpressionsInterpreter](../expressions/uglyexpressions/_visitor/UglyExpressionsInterpreter.java) + is currently not implemented fully. + * Literals + * [MCCommonLiteralsInterpreter](../literals/mccommonliterals/_visitor/MCCommonLiteralsInterpreter.java) + * JavaLiteralsInterpreter is currently not implemented. + * Statements + * MCArrayStatementsInterpreter is currently not implemented. + * [MCCommonStatementsInterpreter](../statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java) + * [MCLowLevelStatementsInterpreter](../statements/mclowlevelstatements/_visitor/MCLowLevelStatementsInterpreter.java) + is mostly unimplemented + * [MCReturnStatementsInterpreter](../statements/mcreturnstatements/_visitor/MCReturnStatementsInterpreter.java) + * [MCVarDeclarationStatemensInterpreter](../statements/mcvardeclarationstatements/_visitor/MCVarDeclarationStatementsInterpreter.java) + +## How to Interpret a Model + +The interpreter is a collection of visitors traversing the AST. +The [ModelInterpreter](ModelInterpreter.java) +can be used to evaluate an `ASTNode`; +The `ASTNode` has to have a corresponding symbol table, +and has to be of a valid model (check using CoCos). + +Create a new Interpreter of your language and use +`ASTNode::evaluate` to calculate a value; +```java +ASTNode expr = parseAndCreateSymTabAndRunCoCos("1 + 3"); +ModelInterpreter interpreter = new MyLangInterpreter(); +MIValue result = expr.evaluate(interpreter); +// check that no error occured with isError() +if (result.isInt()) { + System.out.println("1 + 3 = " + result.asInt()); +} +``` + +## How to store/load variables/functions (to be) used in the interpreter + +To use custom values during interpretation, +first, add the corresponding symbols (VariableSymbol/FunctionSymbol) +to the symbol table, as they have to be available for the CoCos to pass. + +Afterwards, set the values in the interpreter accordingly; +```java +// add j to the symbol table +ModelInterpreter interpreter = new MyLangInterpreter(); +// add the variable to the interpreters current scope +interpreter.declareVariable(jSymbol, MIValueFactory.createValue(2)); +ASTNode statement = parseAndCreateSymTabAndRunCoCos("int i = j++;"); +statement.evaluate(interpreter); // simply returns void +VariableSymbol iSymbol = // resolve for "i" in the model's scope +int i = interpreter.loadVariable(iSymbol).asInt(); // i == 2 +int j = interpreter.loadVariable(jSymbol).asInt(); // j == 3 +// j is already in the interpreter's scope, use 'store' to set a new value +interpreter.storeVariable(jSymbol, MIValueFactory.createValue(4)); +``` + +## How to use Java Classes in the Interpreter + +Simply initialize Class2MC and Java classes can be used with the interpreter. + +_But is it safe?_ +__No! Adding Class2MC allows the execution of arbitrary code!__ + +One should consider +* setting the predicate of the Class2MCResolver + to filter out all classes not explicitly allowed. + * currently, this cannot filter attributes/methods +* Use a CoCo to check for whether all model elements are allowed. + +A safer Approach is to +1. _NOT_ initialize Class2MC +2. add all allowed symbols to the symbol table +3. use `declareVariable`/`declareFunction` to set the values +4. interpret using this limited, but safe(r), set of symbols + +Regarding static symbols; +If JavaInteroperability is used with static variables/methods, +then global values can be changed, +which in turn can influence the execution of the current program, +or different interpreters might influence each other. +In most cases, it is recommended to not allow access to static symbols. + +## Further Information + +* [Project root: MontiCore @github](https://github.com/MontiCore/monticore) +* [MontiCore documentation](https://www.monticore.de/) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [TypeSystem documentation](../types3/TypeSystem3.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) +* [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) From a3fbfb09676a1bc8f8efe9879127481398266595 Mon Sep 17 00:00:00 2001 From: SE-FDr <88034434+SE-FDr@users.noreply.github.com> Date: Thu, 14 Aug 2025 11:19:16 +0200 Subject: [PATCH 21/37] Interpreter.md small edits --- .../src/main/java/de/monticore/interpreter/Interpreter.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/Interpreter.md b/monticore-grammar/src/main/java/de/monticore/interpreter/Interpreter.md index d875c9ab66..a073051dd6 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/Interpreter.md +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/Interpreter.md @@ -123,7 +123,8 @@ Create a new Interpreter of your language and use ASTNode expr = parseAndCreateSymTabAndRunCoCos("1 + 3"); ModelInterpreter interpreter = new MyLangInterpreter(); MIValue result = expr.evaluate(interpreter); -// check that no error occured with isError() +// check that no error occurred with isError(), +// error will be logged already if (result.isInt()) { System.out.println("1 + 3 = " + result.asInt()); } @@ -146,11 +147,12 @@ statement.evaluate(interpreter); // simply returns void VariableSymbol iSymbol = // resolve for "i" in the model's scope int i = interpreter.loadVariable(iSymbol).asInt(); // i == 2 int j = interpreter.loadVariable(jSymbol).asInt(); // j == 3 -// j is already in the interpreter's scope, use 'store' to set a new value +// j is already in the interpreter's scope, +// use 'store' to set a new value interpreter.storeVariable(jSymbol, MIValueFactory.createValue(4)); ``` -## How to use Java Classes in the Interpreter +## Sandboxing – How to use Java Classes in the Interpreter Simply initialize Class2MC and Java classes can be used with the interpreter. From c5b7beea71b6534b6801df418285848038559a1f Mon Sep 17 00:00:00 2001 From: SE-FDr <88034434+SE-FDr@users.noreply.github.com> Date: Thu, 14 Aug 2025 12:05:26 +0200 Subject: [PATCH 22/37] interpreter initial cleanup --- .../CommonExpressionsInterpreter.java | 442 +++++++------ .../LambdaExpressionsInterpreter.java | 12 +- .../interpreter/InterpreterUtils.java | 588 +++++++++++------- .../monticore/interpreter/MIForIterator.java | 9 - .../de/monticore/interpreter/MIScope.java | 39 +- .../monticore/interpreter/MIValueFactory.java | 14 +- .../interpreter/ModelInterpreter.java | 21 +- .../{ => iterators}/MICommonForIterator.java | 70 ++- .../{ => iterators}/MIForEachIterator.java | 36 +- .../interpreter/iterators/MIForIterator.java | 12 + .../interpreter/values/BooleanMIValue.java | 10 +- .../interpreter/values/ByteMIValue.java | 26 +- .../interpreter/values/CharMIValue.java | 8 +- .../interpreter/values/DoubleMIValue.java | 8 +- .../interpreter/values/FloatMIValue.java | 6 +- .../interpreter/values/IntMIValue.java | 6 +- .../values/JavaAttributeMIValue.java | 38 +- .../values/JavaNonStaticMethodMIValue.java | 27 +- .../values/JavaStaticMethodMIValue.java | 24 +- .../interpreter/values/LongMIValue.java | 6 +- .../values/ModelFunctionMIValue.java | 31 +- .../interpreter/values/ObjectMIValue.java | 5 +- .../interpreter/values/ShortMIValue.java | 24 +- .../interpreter/values/VariableMIValue.java | 16 +- .../interpreter/values/WriteableMIValue.java | 69 +- .../MCCommonStatementsInterpreter.java | 141 +++-- .../LambdaExpressionsInterpreterTest.java | 7 +- .../interpreter/IModelInterpreter.java | 11 +- .../de/monticore/interpreter/MIValue.java | 80 ++- .../interpreter/values/ErrorMIValue.java | 44 +- .../interpreter/values/FunctionMIValue.java | 15 +- .../interpreter/values/MIBreakSignal.java | 9 +- .../interpreter/values/MIContinueSignal.java | 8 +- .../values/MIFlowControlSignal.java | 5 +- .../interpreter/values/MIReturnSignal.java | 16 +- .../interpreter/values/VoidMIValue.java | 7 +- 36 files changed, 1113 insertions(+), 777 deletions(-) delete mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/MIForIterator.java rename monticore-grammar/src/main/java/de/monticore/interpreter/{ => iterators}/MICommonForIterator.java (72%) rename monticore-grammar/src/main/java/de/monticore/interpreter/{ => iterators}/MIForEachIterator.java (65%) create mode 100644 monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MIForIterator.java diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java index ec7b56f113..27dfa4f0f0 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/_visitor/CommonExpressionsInterpreter.java @@ -5,9 +5,12 @@ import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.expressions.expressionsbasis._ast.ASTLiteralExpression; import de.monticore.interpreter.InterpreterUtils; -import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; -import de.monticore.interpreter.values.*; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.JavaNonStaticMethodMIValue; +import de.monticore.interpreter.values.JavaStaticMethodMIValue; +import de.monticore.interpreter.values.ObjectMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symboltable.ISymbol; @@ -33,96 +36,16 @@ public CommonExpressionsInterpreter() { public CommonExpressionsInterpreter(ModelInterpreter realThis) { super(realThis); } - - public SymTypePrimitive getCompatibleType(SymTypePrimitive type1, SymTypePrimitive type2) { - return SymTypeRelations.isCompatible(type1, type2) - ? type1 - : ( - SymTypeRelations.isCompatible(type2, type1) - ? type2 - : null - ); - } - - /** - * Checks whether the left and right value are equal. - */ - public MIValue isEqual(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { - SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); - if (compatibleType == null) { - String errorMsg = "0x57000 Equality operation with operands ot type '" + leftType.print() - + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); - return new ErrorMIValue(errorMsg); - } - - String primitive = compatibleType.getPrimitiveName(); - if (primitive.equals(BasicSymbolsMill.BOOLEAN)) { - return createValue(left.asBoolean() == right.asBoolean()); - } else if (primitive.equals(BasicSymbolsMill.BYTE)) { - return createValue(left.asByte() == right.asByte()); - } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - return createValue(left.asShort() == right.asShort()); - } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - return createValue(left.asChar() == right.asChar()); - } else if (primitive.equals(BasicSymbolsMill.INT)) { - return createValue(left.asInt() == right.asInt()); - } else if (primitive.equals(BasicSymbolsMill.LONG)) { - return createValue(left.asLong() == right.asLong()); - } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - return createValue(left.asFloat() == right.asFloat()); - } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - return createValue(left.asDouble() == right.asDouble()); - } - - String errorMsg = "0x57001 Equality operator with operands of type '" + leftType.print() - + "' and '" + rightType.print() + "' is not implemented."; - Log.error(errorMsg); - return new ErrorMIValue(errorMsg); - } - - /** - * Subtracts the right value from the left value while minding the types - */ - public MIValue subtract(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { - SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); - if (compatibleType == null) { - String errorMsg = "0x57002 Greater or Lesser operation with operands ot type '" + leftType.print() - + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); - return new ErrorMIValue(errorMsg); - } - - String primitive = compatibleType.getPrimitiveName(); - if (primitive.equals(BasicSymbolsMill.BYTE)) { - return createValue(left.asByte() - right.asByte()); - } else if (primitive.equals(BasicSymbolsMill.SHORT)) { - return createValue(left.asShort() - right.asShort()); - } else if (primitive.equals(BasicSymbolsMill.CHAR)) { - return createValue(left.asChar() - right.asChar()); - } else if (primitive.equals(BasicSymbolsMill.INT)) { - return createValue(left.asInt() - right.asInt()); - } else if (primitive.equals(BasicSymbolsMill.LONG)) { - return createValue(left.asLong() - right.asLong()); - } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { - return createValue(left.asFloat() - right.asFloat()); - } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { - return createValue(left.asDouble() - right.asDouble()); - } - - String errorMsg = "0x57003 Greater or Lesser operation with operands of type '" + leftType.print() - + "' and '" + rightType.print() + "' is not supported."; - Log.error(errorMsg); - return new ErrorMIValue(errorMsg); - } @Override public MIValue interpret(ASTPlusExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, Integer::sum, Long::sum, Float::sum, Double::sum, "0x57037 Plus"); } @@ -131,9 +54,11 @@ public MIValue interpret(ASTPlusExpression node) { public MIValue interpret(ASTMinusExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a - b, (a, b) -> a - b, (a, b) -> a - b, (a, b) -> a - b, "0x57038 Minus"); @@ -143,9 +68,11 @@ public MIValue interpret(ASTMinusExpression node) { public MIValue interpret(ASTMultExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a * b, (a, b) -> a * b, (a, b) -> a * b, (a, b) -> a * b, "0x57039 Multiplication"); @@ -155,24 +82,26 @@ public MIValue interpret(ASTMultExpression node) { public MIValue interpret(ASTDivideExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression type = TypeCheck3.typeOf(node); if (type.isPrimitive()) { String resultPrimitive = type.asPrimitive().getPrimitiveName(); - + if (right.asDouble() == 0.0) { String errorMsg = "0x57004 Division by zero is undefined"; Log.error(errorMsg, node.getRight().get_SourcePositionStart(), node.getRight().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - + return InterpreterUtils.calcOpPrimitive(left, right, resultPrimitive, (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, (a, b) -> a / b, "0x57040 Division"); } - + String errorMsg = "0x57005 Division operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); @@ -182,9 +111,11 @@ public MIValue interpret(ASTDivideExpression node) { public MIValue interpret(ASTModuloExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression type = TypeCheck3.typeOf(node); return InterpreterUtils.calcOp(left, right, type, (a, b) -> a % b, (a, b) -> a % b, (a, b) -> a % b, (a, b) -> a % b, "0x57041 Modulo"); @@ -193,29 +124,36 @@ public MIValue interpret(ASTModuloExpression node) { @Override public MIValue interpret(ASTMinusPrefixExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isFlowControlSignal()) return value; - + if (value.isFlowControlSignal()) + return value; + SymTypeExpression type = TypeCheck3.typeOf(node); if (type.isPrimitive()) { String primitive = type.asPrimitive().getPrimitiveName(); - + if (primitive.equals(BasicSymbolsMill.BYTE)) { return createValue(-value.asByte()); - } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + } + else if (primitive.equals(BasicSymbolsMill.SHORT)) { return createValue(-value.asShort()); - } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + } + else if (primitive.equals(BasicSymbolsMill.CHAR)) { return createValue(-value.asChar()); - } else if (primitive.equals(BasicSymbolsMill.INT)) { + } + else if (primitive.equals(BasicSymbolsMill.INT)) { return createValue(-value.asInt()); - } else if (primitive.equals(BasicSymbolsMill.LONG)) { + } + else if (primitive.equals(BasicSymbolsMill.LONG)) { return createValue(-value.asLong()); - } else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + } + else if (primitive.equals(BasicSymbolsMill.FLOAT)) { return createValue(-value.asFloat()); - } else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + } + else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { return createValue(-value.asDouble()); } } - + String errorMsg = "0x57006 Minus Prefix operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); @@ -224,13 +162,14 @@ public MIValue interpret(ASTMinusPrefixExpression node) { @Override public MIValue interpret(ASTPlusPrefixExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isFlowControlSignal()) return value; - + if (value.isFlowControlSignal()) + return value; + SymTypeExpression type = TypeCheck3.typeOf(node); if (type.isPrimitive() && (type.asPrimitive().isNumericType() || type.asPrimitive().isIntegralType())) { return value; } - + String errorMsg = "0x57007 Minus Prefix operation with result of type '" + type.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); @@ -240,15 +179,17 @@ public MIValue interpret(ASTPlusPrefixExpression node) { public MIValue interpret(ASTEqualsExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { return isEqual(leftType.asPrimitive(), left, rightType.asPrimitive(), right); } - + String errorMsg = "0x57008 Equality operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); @@ -259,18 +200,21 @@ public MIValue interpret(ASTEqualsExpression node) { public MIValue interpret(ASTNotEqualsExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = isEqual(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isFlowControlSignal()) return result; - + if (result.isFlowControlSignal()) + return result; + return createValue(!result.asBoolean()); } - + String errorMsg = "0x57009 Inequality operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); @@ -281,18 +225,21 @@ public MIValue interpret(ASTNotEqualsExpression node) { public MIValue interpret(ASTGreaterThanExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isFlowControlSignal()) return result; - + if (result.isFlowControlSignal()) + return result; + return createValue(result.asDouble() > 0.0); } - + String errorMsg = "0x57010 Greater than operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); @@ -303,18 +250,21 @@ public MIValue interpret(ASTGreaterThanExpression node) { public MIValue interpret(ASTLessThanExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isFlowControlSignal()) return result; - + if (result.isFlowControlSignal()) + return result; + return createValue(result.asDouble() < 0.0); } - + String errorMsg = "0x57011 Less than operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); @@ -325,18 +275,21 @@ public MIValue interpret(ASTLessThanExpression node) { public MIValue interpret(ASTGreaterEqualExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isFlowControlSignal()) return result; - + if (result.isFlowControlSignal()) + return result; + return createValue(result.asDouble() >= 0.0); } - + String errorMsg = "0x57012Greater equal operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); @@ -347,18 +300,21 @@ public MIValue interpret(ASTGreaterEqualExpression node) { public MIValue interpret(ASTLessEqualExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (leftType.isPrimitive() && rightType.isPrimitive()) { MIValue result = subtract(leftType.asPrimitive(), left, rightType.asPrimitive(), right); - if (result.isFlowControlSignal()) return result; - + if (result.isFlowControlSignal()) + return result; + return createValue(result.asDouble() <= 0.0); } - + String errorMsg = "0x57013 Less equal operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); @@ -369,24 +325,29 @@ public MIValue interpret(ASTLessEqualExpression node) { @Override public MIValue interpret(ASTBooleanNotExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isFlowControlSignal()) return value; + if (value.isFlowControlSignal()) + return value; SymTypeExpression type = TypeCheck3.typeOf(node.getExpression()); if (type.isPrimitive() && type.asPrimitive().isIntegralType()) { String primitive = type.asPrimitive().getPrimitiveName(); if (primitive.equals(BasicSymbolsMill.BYTE)) { return createValue(~value.asByte()); - } else if (primitive.equals(BasicSymbolsMill.SHORT)) { + } + else if (primitive.equals(BasicSymbolsMill.SHORT)) { return createValue(~value.asShort()); - } else if (primitive.equals(BasicSymbolsMill.CHAR)) { + } + else if (primitive.equals(BasicSymbolsMill.CHAR)) { return createValue(~value.asChar()); - } else if (primitive.equals(BasicSymbolsMill.INT)) { + } + else if (primitive.equals(BasicSymbolsMill.INT)) { return createValue(~value.asInt()); - } else if (primitive.equals(BasicSymbolsMill.LONG)) { + } + else if (primitive.equals(BasicSymbolsMill.LONG)) { return createValue(~value.asLong()); } } - + String errorMsg = "0x57014 Bitwise Not operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); @@ -399,14 +360,15 @@ public MIValue interpret(ASTBooleanNotExpression node) { @Override public MIValue interpret(ASTLogicalNotExpression node) { MIValue value = node.getExpression().evaluate(getRealThis()); - if (value.isFlowControlSignal()) return value; - + if (value.isFlowControlSignal()) + return value; + SymTypeExpression type = TypeCheck3.typeOf(node.getExpression()); - + if (value.isBoolean()) { return createValue(!value.asBoolean()); } - + String errorMsg = "0x57015 Logical Not operation with operand of type '" + type.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); @@ -416,16 +378,18 @@ public MIValue interpret(ASTLogicalNotExpression node) { public MIValue interpret(ASTBooleanAndOpExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); if (left.isBoolean() && right.isBoolean()) { return createValue(left.asBoolean() && right.asBoolean()); } - + String errorMsg = "0x57016 Logical And operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); @@ -436,16 +400,18 @@ public MIValue interpret(ASTBooleanAndOpExpression node) { public MIValue interpret(ASTBooleanOrOpExpression node) { MIValue left = node.getLeft().evaluate(getRealThis()); MIValue right = node.getRight().evaluate(getRealThis()); - if (left.isFlowControlSignal()) return left; - if (right.isFlowControlSignal()) return right; - + if (left.isFlowControlSignal()) + return left; + if (right.isFlowControlSignal()) + return right; + SymTypeExpression leftType = TypeCheck3.typeOf(node.getLeft()); SymTypeExpression rightType = TypeCheck3.typeOf(node.getRight()); - + if (left.isBoolean() && right.isBoolean()) { return createValue(left.asBoolean() || right.asBoolean()); } - + String errorMsg = "0x57017 Logical Or operation with operands of type '" + leftType.print() + "' and '" + rightType.print() + "' is not supported."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); @@ -460,8 +426,9 @@ public MIValue interpret(ASTBracketExpression node) { @Override public MIValue interpret(ASTConditionalExpression node) { MIValue condition = node.getCondition().evaluate(getRealThis()); - if (condition.isFlowControlSignal()) return condition; - + if (condition.isFlowControlSignal()) + return condition; + return condition.asBoolean() ? node.getTrueExpression().evaluate(getRealThis()) : node.getFalseExpression().evaluate(getRealThis()); @@ -476,23 +443,25 @@ public MIValue interpret(ASTFieldAccessExpression node) { String errorMsg = "0x57018 Field Access operation expected a symbol as source."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); - } else { + } + else { // Java Method/Attribute ISymbol symbol = symbolOptional.get(); if (symbol.getAccessModifier().getDimensionToModifierMap() - .getOrDefault(StaticAccessModifier.DIMENSION, - StaticAccessModifier.NON_STATIC) == StaticAccessModifier.STATIC) { + .getOrDefault(StaticAccessModifier.DIMENSION, + StaticAccessModifier.NON_STATIC) == StaticAccessModifier.STATIC) { // static // get Java-Class from symbol String fieldName = symbol.getName(); String fullName = symbol.getFullName(); String className = fullName.substring(0, (fullName.length() - - fieldName.length() - 1)); - Class classType; + - fieldName.length() - 1)); + Class classType; try { classType = Class.forName(className); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { String errorMsg = "0x57018 Failed to load class '" + className + "'."; Log.error(errorMsg, node.get_SourcePositionStart(), node.get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); @@ -501,12 +470,14 @@ public MIValue interpret(ASTFieldAccessExpression node) { if (type.isFunctionType()) { // static method return new JavaStaticMethodMIValue(classType, fieldName); - } else { + } + else { // static attribute return InterpreterUtils.getStaticObjectAttribute(classType, fieldName); } - - } else { + + } + else { // non-static MIValue leftValue = node.getExpression().evaluate(getRealThis()); if (!leftValue.isObject()) { @@ -514,16 +485,17 @@ public MIValue interpret(ASTFieldAccessExpression node) { Log.error(errorMsg, node.getExpression().get_SourcePositionStart(), node.getExpression().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - + // If class-declarations are supported this needs to be expanded if (type.isFunctionType()) { // non-static method - FunctionSymbol funcSymbol = (FunctionSymbol)symbol; + FunctionSymbol funcSymbol = (FunctionSymbol) symbol; String name = funcSymbol.getName(); return new JavaNonStaticMethodMIValue(leftValue.asObject(), name); - } else { + } + else { // non-static attribute - return InterpreterUtils.getNonStaticObjectAttribute((ObjectMIValue)leftValue, node.getName()); + return InterpreterUtils.getNonStaticObjectAttribute((ObjectMIValue) leftValue, node.getName()); } } } @@ -533,7 +505,7 @@ public MIValue interpret(ASTFieldAccessExpression node) { public MIValue interpret(ASTLiteralExpression node) { return node.getLiteral().evaluate(getRealThis()); } - + @Override public MIValue interpret(ASTCallExpression node) { // evaluate expression that gives lambda/function @@ -546,19 +518,113 @@ public MIValue interpret(ASTCallExpression node) { Log.error(errorMsg, node.getExpression().get_SourcePositionStart(), node.getExpression().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - + List args = new ArrayList<>(); for (ASTExpression argument : node.getArguments().getExpressionList()) { args.add(argument.evaluate(getRealThis())); } - + // cast needed in case of subtyping SymTypeExpression returnType = TypeCheck3.typeOf(node); MIValue returnValue = value.asFunction().execute(getRealThis(), args); return InterpreterUtils.convertImplicit(returnType, returnValue); } + // helper + + protected SymTypePrimitive getCompatibleType(SymTypePrimitive type1, SymTypePrimitive type2) { + return SymTypeRelations.isCompatible(type1, type2) + ? type1 + : ( + SymTypeRelations.isCompatible(type2, type1) + ? type2 + : null + ); + } + + /** + * Checks whether the left and right value are equal. + */ + protected MIValue isEqual(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { + SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); + if (compatibleType == null) { + String errorMsg = "0x57000 Equality operation with operands ot type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + String primitive = compatibleType.getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BOOLEAN)) { + return createValue(left.asBoolean() == right.asBoolean()); + } + else if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(left.asByte() == right.asByte()); + } + else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(left.asShort() == right.asShort()); + } + else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(left.asChar() == right.asChar()); + } + else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(left.asInt() == right.asInt()); + } + else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(left.asLong() == right.asLong()); + } + else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(left.asFloat() == right.asFloat()); + } + else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(left.asDouble() == right.asDouble()); + } + + String errorMsg = "0x57001 Equality operator with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not implemented."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + /** + * Subtracts the right value from the left value while minding the types + */ + protected MIValue subtract(SymTypePrimitive leftType, MIValue left, SymTypePrimitive rightType, MIValue right) { + SymTypePrimitive compatibleType = getCompatibleType(leftType, rightType); + if (compatibleType == null) { + String errorMsg = "0x57002 Greater or Lesser operation with operands ot type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } + + String primitive = compatibleType.getPrimitiveName(); + if (primitive.equals(BasicSymbolsMill.BYTE)) { + return createValue(left.asByte() - right.asByte()); + } + else if (primitive.equals(BasicSymbolsMill.SHORT)) { + return createValue(left.asShort() - right.asShort()); + } + else if (primitive.equals(BasicSymbolsMill.CHAR)) { + return createValue(left.asChar() - right.asChar()); + } + else if (primitive.equals(BasicSymbolsMill.INT)) { + return createValue(left.asInt() - right.asInt()); + } + else if (primitive.equals(BasicSymbolsMill.LONG)) { + return createValue(left.asLong() - right.asLong()); + } + else if (primitive.equals(BasicSymbolsMill.FLOAT)) { + return createValue(left.asFloat() - right.asFloat()); + } + else if (primitive.equals(BasicSymbolsMill.DOUBLE)) { + return createValue(left.asDouble() - right.asDouble()); + } + + String errorMsg = "0x57003 Greater or Lesser operation with operands of type '" + leftType.print() + + "' and '" + rightType.print() + "' is not supported."; + Log.error(errorMsg); + return new ErrorMIValue(errorMsg); + } - - } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java index 076ed631a5..471eca2500 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_visitor/LambdaExpressionsInterpreter.java @@ -3,8 +3,8 @@ import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaExpression; import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaExpressionBody; import de.monticore.expressions.lambdaexpressions._ast.ASTLambdaParameter; -import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.values.ModelFunctionMIValue; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; @@ -12,20 +12,20 @@ import java.util.List; public class LambdaExpressionsInterpreter extends LambdaExpressionsInterpreterTOP { - + public LambdaExpressionsInterpreter() { super(); } - + public LambdaExpressionsInterpreter(ModelInterpreter realThis) { super(realThis); } - + @Override public MIValue interpret(ASTLambdaExpressionBody node) { return node.getExpression().evaluate(getRealThis()); } - + @Override public MIValue interpret(ASTLambdaExpression node) { List parameterSymbols = new ArrayList<>(); @@ -34,5 +34,5 @@ public MIValue interpret(ASTLambdaExpression node) { } return new ModelFunctionMIValue(getRealThis().getCurrentScope(), parameterSymbols, node.getLambdaBody()); } - + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java index 303642f77d..4de627f1d8 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java @@ -1,6 +1,16 @@ package de.monticore.interpreter; -import de.monticore.interpreter.values.*; +import de.monticore.interpreter.values.BooleanMIValue; +import de.monticore.interpreter.values.ByteMIValue; +import de.monticore.interpreter.values.CharMIValue; +import de.monticore.interpreter.values.DoubleMIValue; +import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.FloatMIValue; +import de.monticore.interpreter.values.IntMIValue; +import de.monticore.interpreter.values.JavaAttributeMIValue; +import de.monticore.interpreter.values.LongMIValue; +import de.monticore.interpreter.values.ObjectMIValue; +import de.monticore.interpreter.values.ShortMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.SymTypeRelations; @@ -19,55 +29,77 @@ * MIValue or MIValue to object, and the calculation of binary operations. */ public class InterpreterUtils { - + + // todo use SymTypeExpression, not string for resultType + // todo opName is not the name, but errorcode+name -> split! public static MIValue calcOpPrimitive(MIValue v1, MIValue v2, - String resultType, BinaryOperator opInt, - BinaryOperator opLong, BinaryOperator opFloat, - BinaryOperator opDouble, String opName) { - - switch (resultType) { - case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); - case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); - case BasicSymbolsMill.FLOAT: return createValue((float)opFloat.apply(v1.asFloat(), v2.asFloat())); - case BasicSymbolsMill.DOUBLE: return createValue((double)opDouble.apply(v1.asDouble(), v2.asDouble())); + String resultType, BinaryOperator opInt, + BinaryOperator opLong, BinaryOperator opFloat, + BinaryOperator opDouble, String opName) { + + try { + switch (resultType) { + case BasicSymbolsMill.INT: + return createValue((int) opInt.apply(v1.asInt(), v2.asInt())); + case BasicSymbolsMill.LONG: + return createValue((long) opLong.apply(v1.asLong(), v2.asLong())); + case BasicSymbolsMill.FLOAT: + return createValue((float) opFloat.apply(v1.asFloat(), v2.asFloat())); + case BasicSymbolsMill.DOUBLE: + return createValue((double) opDouble.apply(v1.asDouble(), v2.asDouble())); + } + } + catch (Exception e) { + // e.g., ArithmeticException 1/0 + Log.error("0x58110 exception occured during interpretation of the " + + opName + " operator", e); + return new ErrorMIValue(e); } + String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + public static MIValue calcBitwiseOpPrimitive(MIValue v1, MIValue v2, - String resultType, BinaryOperator opInt, - BinaryOperator opLong, String opName) { + String resultType, BinaryOperator opInt, + BinaryOperator opLong, String opName) { switch (resultType) { - case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); - case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); + case BasicSymbolsMill.INT: + return createValue((int) opInt.apply(v1.asInt(), v2.asInt())); + case BasicSymbolsMill.LONG: + return createValue((long) opLong.apply(v1.asLong(), v2.asLong())); } String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + public static MIValue calcBitwiseLogicalOpPrimitive(MIValue v1, MIValue v2, - String resultType, BinaryOperator opBool, - BinaryOperator opInt, BinaryOperator opLong, - String opName) { + String resultType, BinaryOperator opBool, + BinaryOperator opInt, BinaryOperator opLong, + String opName) { switch (resultType) { - case BasicSymbolsMill.BOOLEAN: return createValue((boolean)opBool.apply(v1.asBoolean(), v2.asBoolean())); - case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asInt())); - case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); + case BasicSymbolsMill.BOOLEAN: + return createValue((boolean) opBool.apply(v1.asBoolean(), v2.asBoolean())); + case BasicSymbolsMill.INT: + return createValue((int) opInt.apply(v1.asInt(), v2.asInt())); + case BasicSymbolsMill.LONG: + return createValue((long) opLong.apply(v1.asLong(), v2.asLong())); } String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + public static MIValue calcShiftPrimitive(MIValue v1, MIValue v2, - String resultType, BiFunction opInt, - BinaryOperator opLong, String opName) { + String resultType, BiFunction opInt, + BinaryOperator opLong, String opName) { switch (resultType) { - case BasicSymbolsMill.INT: return createValue((int)opInt.apply(v1.asInt(), v2.asLong())); - case BasicSymbolsMill.LONG: return createValue((long)opLong.apply(v1.asLong(), v2.asLong())); + case BasicSymbolsMill.INT: + return createValue((int) opInt.apply(v1.asInt(), v2.asLong())); + case BasicSymbolsMill.LONG: + return createValue((long) opLong.apply(v1.asLong(), v2.asLong())); } String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; Log.error(errorMsg); @@ -78,25 +110,28 @@ public static MIValue calcShiftPrimitive(MIValue v1, MIValue v2, * Calculates the result of a binary operation with the given result type by * using the given lambdas for the calculation. Operation should support * int, long, float & double. - * @param v1 left operand - * @param v2 right operand + * + * @param v1 left operand + * @param v2 right operand * @param resultType result type of the operation - * @param opInt lambda for int operation - * @param opLong lambda for long operation - * @param opFloat lambda for float operation - * @param opDouble lambda for double operation - * @param opName Name of the operation (for error messages) + * @param opInt lambda for int operation + * @param opLong lambda for long operation + * @param opFloat lambda for float operation + * @param opDouble lambda for double operation + * @param opName Name of the operation (for error messages) * @return Result of the operation or an error value if the type is not supported. */ public static MIValue calcOp(MIValue v1, MIValue v2, - SymTypeExpression resultType, BinaryOperator opInt, - BinaryOperator opLong, BinaryOperator opFloat, - BinaryOperator opDouble, String opName) { + SymTypeExpression resultType, BinaryOperator opInt, + BinaryOperator opLong, BinaryOperator opFloat, + BinaryOperator opDouble, String opName) { if (resultType.isPrimitive()) { return calcOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opFloat, opDouble, opName); } - - String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + + String errorMsg = opName + " operation with result of type " + + resultType.printFullName() + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -104,22 +139,25 @@ public static MIValue calcOp(MIValue v1, MIValue v2, /** * Calculates the result of a bitwise binary operation with the given result type by using * the given lambdas for the calculation. Operation should support int & long. - * @param v1 left operand - * @param v2 right operand + * + * @param v1 left operand + * @param v2 right operand * @param resultType result type of the operation - * @param opInt lambda for int operation - * @param opLong lambda for long operation - * @param opName Name of the operation (for error messages) + * @param opInt lambda for int operation + * @param opLong lambda for long operation + * @param opName Name of the operation (for error messages) * @return Result of the operation or an error value if the type is not supported. */ public static MIValue calcBitwiseOp(MIValue v1, MIValue v2, - SymTypeExpression resultType, BinaryOperator opInt, - BinaryOperator opLong, String opName) { + SymTypeExpression resultType, BinaryOperator opInt, + BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { return calcBitwiseOpPrimitive(v1, v2, resultType.asPrimitive().getPrimitiveName(), opInt, opLong, opName); } - - String errorMsg = opName + " operation with result of type " + resultType + " is not supported."; + + String errorMsg = opName + " operation with result of type " + + resultType.printFullName() + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -128,26 +166,27 @@ public static MIValue calcBitwiseOp(MIValue v1, MIValue v2, * Calculates the result of a bitwise or logical binary operation with the * given result type by using the given lambdas for the calculation. * Operation should support boolean, int & long. - * @param v1 left operand - * @param v2 right operand + * + * @param v1 left operand + * @param v2 right operand * @param resultType result type of the operation - * @param opInt lambda for int operation - * @param opLong lambda for long operation - * @param opName Name of the operation (for error messages) + * @param opInt lambda for int operation + * @param opLong lambda for long operation + * @param opName Name of the operation (for error messages) * @return Result of the operation or an error value if the type is not supported. */ public static MIValue calcBitwiseLogicalOp(MIValue v1, MIValue v2, - SymTypeExpression resultType, - BinaryOperator opBool, BinaryOperator opInt, - BinaryOperator opLong, String opName) { + SymTypeExpression resultType, + BinaryOperator opBool, BinaryOperator opInt, + BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { return calcBitwiseLogicalOpPrimitive(v1, v2, - resultType.asPrimitive().getPrimitiveName(), opBool, opInt, - opLong, opName); + resultType.asPrimitive().getPrimitiveName(), opBool, opInt, + opLong, opName); } - + String errorMsg = opName + " operation with result of type " + resultType - + " is not supported."; + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -156,37 +195,39 @@ public static MIValue calcBitwiseLogicalOp(MIValue v1, MIValue v2, * Calculates the result of a shift-like operation with the * given result type by using the given lambdas for the calculation. * Shift operations always support up to long for the right side. - * @param v1 left operand - * @param v2 right operand + * + * @param v1 left operand + * @param v2 right operand * @param resultType result type of the operation - * @param opInt lambda for int operation - * @param opLong lambda for long operation - * @param opName Name of the operation (for error messages) + * @param opInt lambda for int operation + * @param opLong lambda for long operation + * @param opName Name of the operation (for error messages) * @return Result of the operation or an error value if the type is not supported. */ public static MIValue calcShift(MIValue v1, MIValue v2, - SymTypeExpression resultType, - BiFunction opInt, - BinaryOperator opLong, String opName) { + SymTypeExpression resultType, + BiFunction opInt, + BinaryOperator opLong, String opName) { if (resultType.isPrimitive()) { return calcShiftPrimitive(v1, v2, - resultType.asPrimitive().getPrimitiveName(), opInt, opLong, - opName); + resultType.asPrimitive().getPrimitiveName(), opInt, opLong, + opName); } - + String errorMsg = opName + " operation with result of type " + resultType - + " is not supported."; + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } /** * Applies an explicit cast on primitive to target primitive type. + * * @return converted MIValue or ErrorMIValue if the cast is not supported or - * not possible. + * not possible. */ public static MIValue convertToPrimitiveExplicit(String from, String to, - MIValue value) { + MIValue value) { if (to.equals(BasicSymbolsMill.BOOLEAN) || from.equals(BasicSymbolsMill.BOOLEAN)) { String errorMsg = "0x57060 Cast to or from boolean is not supported."; Log.error(errorMsg); @@ -194,93 +235,136 @@ public static MIValue convertToPrimitiveExplicit(String from, String to, } if (to.equals(BasicSymbolsMill.BYTE)) { switch (from) { - case BasicSymbolsMill.DOUBLE: return createValue((byte) value.asDouble()); - case BasicSymbolsMill.FLOAT: return createValue((byte) value.asFloat()); - case BasicSymbolsMill.LONG: return createValue((byte) value.asLong()); - case BasicSymbolsMill.INT: return createValue((byte) value.asInt()); - case BasicSymbolsMill.SHORT: return createValue((byte) value.asShort()); - case BasicSymbolsMill.CHAR: return createValue((byte) value.asChar()); - default: return createValue(value.asByte()); + case BasicSymbolsMill.DOUBLE: + return createValue((byte) value.asDouble()); + case BasicSymbolsMill.FLOAT: + return createValue((byte) value.asFloat()); + case BasicSymbolsMill.LONG: + return createValue((byte) value.asLong()); + case BasicSymbolsMill.INT: + return createValue((byte) value.asInt()); + case BasicSymbolsMill.SHORT: + return createValue((byte) value.asShort()); + case BasicSymbolsMill.CHAR: + return createValue((byte) value.asChar()); + default: + return createValue(value.asByte()); } - - } else if (to.equals(BasicSymbolsMill.SHORT)) { + + } + else if (to.equals(BasicSymbolsMill.SHORT)) { switch (from) { - case BasicSymbolsMill.DOUBLE: return createValue((short) value.asDouble()); - case BasicSymbolsMill.FLOAT: return createValue((short) value.asFloat()); - case BasicSymbolsMill.LONG: return createValue((short) value.asLong()); - case BasicSymbolsMill.INT: return createValue((short) value.asInt()); - case BasicSymbolsMill.CHAR: return createValue((short) value.asChar()); - default: return createValue(value.asShort()); + case BasicSymbolsMill.DOUBLE: + return createValue((short) value.asDouble()); + case BasicSymbolsMill.FLOAT: + return createValue((short) value.asFloat()); + case BasicSymbolsMill.LONG: + return createValue((short) value.asLong()); + case BasicSymbolsMill.INT: + return createValue((short) value.asInt()); + case BasicSymbolsMill.CHAR: + return createValue((short) value.asChar()); + default: + return createValue(value.asShort()); } - - } else if (to.equals(BasicSymbolsMill.CHAR)) { + + } + else if (to.equals(BasicSymbolsMill.CHAR)) { switch (from) { - case BasicSymbolsMill.DOUBLE: return createValue((char) value.asDouble()); - case BasicSymbolsMill.FLOAT: return createValue((char) value.asFloat()); - case BasicSymbolsMill.LONG: return createValue((char) value.asLong()); - case BasicSymbolsMill.INT: return createValue((char) value.asInt()); - case BasicSymbolsMill.SHORT: return createValue((char) value.asShort()); - case BasicSymbolsMill.BYTE: return createValue((char) value.asByte()); - default: return createValue(value.asChar()); + case BasicSymbolsMill.DOUBLE: + return createValue((char) value.asDouble()); + case BasicSymbolsMill.FLOAT: + return createValue((char) value.asFloat()); + case BasicSymbolsMill.LONG: + return createValue((char) value.asLong()); + case BasicSymbolsMill.INT: + return createValue((char) value.asInt()); + case BasicSymbolsMill.SHORT: + return createValue((char) value.asShort()); + case BasicSymbolsMill.BYTE: + return createValue((char) value.asByte()); + default: + return createValue(value.asChar()); } - - } else if (to.equals(BasicSymbolsMill.INT)) { + + } + else if (to.equals(BasicSymbolsMill.INT)) { switch (from) { - case BasicSymbolsMill.DOUBLE: return createValue((int) value.asDouble()); - case BasicSymbolsMill.FLOAT: return createValue((int) value.asFloat()); - case BasicSymbolsMill.LONG: return createValue((int) value.asLong()); - default: return createValue(value.asInt()); + case BasicSymbolsMill.DOUBLE: + return createValue((int) value.asDouble()); + case BasicSymbolsMill.FLOAT: + return createValue((int) value.asFloat()); + case BasicSymbolsMill.LONG: + return createValue((int) value.asLong()); + default: + return createValue(value.asInt()); } - - } else if (to.equals(BasicSymbolsMill.LONG)) { + + } + else if (to.equals(BasicSymbolsMill.LONG)) { if (from.equals(BasicSymbolsMill.DOUBLE)) { - return createValue((long)value.asDouble()); - } else if (from.equals(BasicSymbolsMill.FLOAT)) { - return createValue((long)value.asFloat()); + return createValue((long) value.asDouble()); + } + else if (from.equals(BasicSymbolsMill.FLOAT)) { + return createValue((long) value.asFloat()); } return createValue(value.asLong()); - - } else if (to.equals(BasicSymbolsMill.FLOAT)) { + + } + else if (to.equals(BasicSymbolsMill.FLOAT)) { if (from.equals(BasicSymbolsMill.DOUBLE)) { - return createValue((float)value.asDouble()); + return createValue((float) value.asDouble()); } return createValue(value.asFloat()); - - } else if (to.equals(BasicSymbolsMill.DOUBLE)) { + + } + else if (to.equals(BasicSymbolsMill.DOUBLE)) { return createValue(value.asDouble()); } - + String errorMsg = "0x57061 Cast from " + from + " to " + to - + " is not supported."; + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } /** * Applies an implicit cast on primitive to target primitive type + * * @return converted MIValue or ErrorMIValue if the cast is not supported or - * not possible. + * not possible. + * + * todo replace String with SymTypeExpression for targetType */ public static MIValue convertToPrimitiveImplicit(String targetType, - MIValue value) { - if (targetType.equals(BasicSymbolsMill.BYTE)) { + MIValue value) { + if (value.isError()) { + return value; + } + else if (targetType.equals(BasicSymbolsMill.BYTE)) { return createValue(value.asByte()); - } else if (targetType.equals(BasicSymbolsMill.SHORT)) { + } + else if (targetType.equals(BasicSymbolsMill.SHORT)) { return createValue(value.asShort()); - } else if (targetType.equals(BasicSymbolsMill.CHAR)) { + } + else if (targetType.equals(BasicSymbolsMill.CHAR)) { return createValue(value.asChar()); - } else if (targetType.equals(BasicSymbolsMill.INT)) { + } + else if (targetType.equals(BasicSymbolsMill.INT)) { return createValue(value.asInt()); - } else if (targetType.equals(BasicSymbolsMill.LONG)) { + } + else if (targetType.equals(BasicSymbolsMill.LONG)) { return createValue(value.asLong()); - } else if (targetType.equals(BasicSymbolsMill.FLOAT)) { + } + else if (targetType.equals(BasicSymbolsMill.FLOAT)) { return createValue(value.asFloat()); - } else if (targetType.equals(BasicSymbolsMill.DOUBLE)) { + } + else if (targetType.equals(BasicSymbolsMill.DOUBLE)) { return createValue(value.asDouble()); } - + String errorMsg = "0x57062 Implicit cast to " + targetType - + " is not supported."; + + " is not supported."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -288,24 +372,30 @@ public static MIValue convertToPrimitiveImplicit(String targetType, /** * Applies an implicit cast on value to targetType. * Allows casts of boxtypes and primitives. + * * @return converted MIValue or ErrorMIValue if the cast is not supported or - * not possible. + * not possible. */ public static MIValue convertImplicit(SymTypeExpression targetType, - MIValue value) { - if (targetType.isPrimitive()) { + MIValue value) { + if (value.isError()) { + return value; + } + else if (targetType.isPrimitive()) { value = unboxType(value); return convertToPrimitiveImplicit( - targetType.asPrimitive().getPrimitiveName(), value + targetType.asPrimitive().getPrimitiveName(), value ); - } else if (isBoxType(targetType)) { + } + else if (isBoxType(targetType)) { SymTypeExpression unboxedType = SymTypeRelations.unbox(targetType); value = convertToPrimitiveImplicit( - unboxedType.asPrimitive().getPrimitiveName(), value + unboxedType.asPrimitive().getPrimitiveName(), value ); value = boxValue(value, targetType); return value; - } else { + } + else { // value may be primitive with targetType Object; int -> Integer -> Object if (value.isPrimitive()) { value = boxValue(value); @@ -316,19 +406,21 @@ public static MIValue convertImplicit(SymTypeExpression targetType, /** * Creates an AttributeMIValue for a non-static attribute of a java-object. + * * @param object Java-Object as MIValue * @return Value of the attribute as MIValue converted to the given type. - * ErrorMIValue if the attribute does not exist or is not accessible. + * ErrorMIValue if the attribute does not exist or is not accessible. */ public static MIValue getNonStaticObjectAttribute(ObjectMIValue object, - String attributeName) { + String attributeName) { Field attribute; try { attribute = object.asObject().getClass().getField(attributeName); - } catch (NoSuchFieldException e) { + } + catch (NoSuchFieldException e) { String errorMsg = "0x57063 Tried to access attribute '" + attributeName - + "' of class '" + object.getClass().getName() - + "'. No such attribute exists."; + + "' of class '" + object.getClass().getName() + + "'. No such attribute exists."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -338,19 +430,21 @@ public static MIValue getNonStaticObjectAttribute(ObjectMIValue object, /** * Creates an AttributeMIValue for a non-static attribute of a java-object. + * * @param classObject Java-Class * @return Value of the attribute as MIValue converted to the given type. - * ErrorMIValue if the attribute does not exist or is not accessible. + * ErrorMIValue if the attribute does not exist or is not accessible. */ public static MIValue getStaticObjectAttribute(Class classObject, - String attributeName) { + String attributeName) { Field attribute; try { attribute = classObject.getField(attributeName); - } catch (NoSuchFieldException e) { + } + catch (NoSuchFieldException e) { String errorMsg = "0x57063 Tried to access attribute '" + attributeName - + "' of class '" + classObject.getName() - + "'. No such attribute exists."; + + "' of class '" + classObject.getName() + + "'. No such attribute exists."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } @@ -364,26 +458,34 @@ public static MIValue getStaticObjectAttribute(Class classObject, public static Class typeOfValue(MIValue value) { if (value.isBoolean()) { return boolean.class; - } else if (value.isChar()) { + } + else if (value.isChar()) { return char.class; - } else if (value.isByte()) { + } + else if (value.isByte()) { return byte.class; - } else if (value.isShort()) { + } + else if (value.isShort()) { return short.class; - } else if (value.isInt()) { + } + else if (value.isInt()) { return int.class; - } else if (value.isLong()) { + } + else if (value.isLong()) { return long.class; - } else if (value.isFloat()) { + } + else if (value.isFloat()) { return float.class; - } else if (value.isDouble()) { + } + else if (value.isDouble()) { return double.class; - } else if (value.isObject()) { + } + else if (value.isObject()) { return value.asObject().getClass(); } // Functions are not allowed String errorMsg = "0x57066 Failed to get java type of " + value.printType() - + "."; + + "."; Log.error(errorMsg); return null; } @@ -394,26 +496,34 @@ public static Class typeOfValue(MIValue value) { public static Object valueToObject(MIValue value) { if (value.isBoolean()) { return value.asBoolean(); - } else if (value.isChar()) { + } + else if (value.isChar()) { return value.asChar(); - } else if (value.isByte()) { + } + else if (value.isByte()) { return value.asByte(); - } else if (value.isShort()) { + } + else if (value.isShort()) { return value.asShort(); - } else if (value.isInt()) { + } + else if (value.isInt()) { return value.asInt(); - } else if (value.isLong()) { + } + else if (value.isLong()) { return value.asLong(); - } else if (value.isFloat()) { + } + else if (value.isFloat()) { return value.asFloat(); - } else if (value.isDouble()) { + } + else if (value.isDouble()) { return value.asDouble(); - } else if (value.isObject()) { + } + else if (value.isObject()) { return value.asObject(); } // Functions are not allowed String errorMsg = "0x57067 Failed to convert MIValue of type " - + value.printType() + " to a java object."; + + value.printType() + " to a java object."; Log.error(errorMsg); return null; } @@ -424,23 +534,30 @@ public static Object valueToObject(MIValue value) { */ public static MIValue objectToValue(Object object) { if (object instanceof Boolean) { - return new BooleanMIValue((Boolean)object); - } else if (object instanceof Character) { - return new CharMIValue((Character)object); - } else if (object instanceof Byte) { - return new ByteMIValue((Byte)object); - } else if (object instanceof Short) { - return new ShortMIValue((Short)object); - } else if (object instanceof Integer) { - return new IntMIValue((Integer)object); - } else if (object instanceof Long) { - return new LongMIValue((Long)object); - } else if (object instanceof Float) { - return new FloatMIValue((Float)object); - } else if (object instanceof Double) { - return new DoubleMIValue((Double)object); - } - + return new BooleanMIValue((Boolean) object); + } + else if (object instanceof Character) { + return new CharMIValue((Character) object); + } + else if (object instanceof Byte) { + return new ByteMIValue((Byte) object); + } + else if (object instanceof Short) { + return new ShortMIValue((Short) object); + } + else if (object instanceof Integer) { + return new IntMIValue((Integer) object); + } + else if (object instanceof Long) { + return new LongMIValue((Long) object); + } + else if (object instanceof Float) { + return new FloatMIValue((Float) object); + } + else if (object instanceof Double) { + return new DoubleMIValue((Double) object); + } + return new ObjectMIValue(object); } @@ -449,7 +566,7 @@ public static MIValue objectToValue(Object object) { */ public static boolean isBoxType(SymTypeExpression type) { return !type.isPrimitive() && ( - SymTypeRelations.isNumericType(type) + SymTypeRelations.isNumericType(type) || SymTypeRelations.isBoolean(type) ); } @@ -458,29 +575,35 @@ public static boolean isBoxType(SymTypeExpression type) { * Unboxes a value if it is a boxtype. */ public static MIValue unboxType(MIValue value) { - if (!value.isObject()) return value; - + if (!value.isObject()) + return value; + Object obj = value.asObject(); if (obj instanceof Integer) { - return new IntMIValue((Integer)obj); - } else if (obj instanceof Long) { - return new LongMIValue((Long)obj); - } else if (obj instanceof Float) { + return new IntMIValue((Integer) obj); + } + else if (obj instanceof Long) { + return new LongMIValue((Long) obj); + } + else if (obj instanceof Float) { return new FloatMIValue((Float) obj); - } else if (obj instanceof Double) { - return new DoubleMIValue((Double)obj); - } else if (obj instanceof Character) { - return new CharMIValue((Character)obj); - } else if (obj instanceof Byte) { - return new ByteMIValue((Byte)obj); - } else if (obj instanceof Short) { - return new ShortMIValue((Short)obj); - } - + } + else if (obj instanceof Double) { + return new DoubleMIValue((Double) obj); + } + else if (obj instanceof Character) { + return new CharMIValue((Character) obj); + } + else if (obj instanceof Byte) { + return new ByteMIValue((Byte) obj); + } + else if (obj instanceof Short) { + return new ShortMIValue((Short) obj); + } + return value; } - /** * Converts a MIValue into its equivalent Boxtype */ @@ -488,54 +611,69 @@ public static MIValue boxValue(MIValue value) { if (!value.isPrimitive()) { return value; } - + if (value.isBoolean()) { - return MIValueFactory.createValue((Boolean)value.asBoolean()); - } else if (value.isChar()) { - return MIValueFactory.createValue((Character)value.asChar()); - } else if (value.isByte()) { - return MIValueFactory.createValue((Byte)value.asByte()); - } else if (value.isShort()) { - return MIValueFactory.createValue((Short)value.asShort()); - } else if (value.isInt()) { - return MIValueFactory.createValue((Integer)value.asInt()); - } else if (value.isLong()) { - return MIValueFactory.createValue((Long)value.asLong()); - } else if (value.isFloat()) { - return MIValueFactory.createValue((Float)value.asFloat()); - } else if (value.isDouble()) { - return MIValueFactory.createValue((Double)value.asDouble()); - } - + return MIValueFactory.createValue((Boolean) value.asBoolean()); + } + else if (value.isChar()) { + return MIValueFactory.createValue((Character) value.asChar()); + } + else if (value.isByte()) { + return MIValueFactory.createValue((Byte) value.asByte()); + } + else if (value.isShort()) { + return MIValueFactory.createValue((Short) value.asShort()); + } + else if (value.isInt()) { + return MIValueFactory.createValue((Integer) value.asInt()); + } + else if (value.isLong()) { + return MIValueFactory.createValue((Long) value.asLong()); + } + else if (value.isFloat()) { + return MIValueFactory.createValue((Float) value.asFloat()); + } + else if (value.isDouble()) { + return MIValueFactory.createValue((Double) value.asDouble()); + } + return value; } /** * Converts a value to the given box type. + * * @return Boxed value wrapped in an ObjectMIValue */ public static MIValue boxValue(MIValue value, SymTypeExpression boxType) { if (SymTypeRelations.isInt(boxType)) { return MIValueFactory.createValue(Integer.valueOf(value.asInt())); - } else if (SymTypeRelations.isLong(boxType)) { + } + else if (SymTypeRelations.isLong(boxType)) { return MIValueFactory.createValue(Long.valueOf(value.asLong())); - } else if (SymTypeRelations.isFloat(boxType)) { + } + else if (SymTypeRelations.isFloat(boxType)) { return MIValueFactory.createValue(Float.valueOf(value.asFloat())); - } else if (SymTypeRelations.isDouble(boxType)) { + } + else if (SymTypeRelations.isDouble(boxType)) { return MIValueFactory.createValue(Double.valueOf(value.asDouble())); - } else if (SymTypeRelations.isChar(boxType)) { + } + else if (SymTypeRelations.isChar(boxType)) { return MIValueFactory.createValue(Character.valueOf(value.asChar())); - } else if (SymTypeRelations.isByte(boxType)) { + } + else if (SymTypeRelations.isByte(boxType)) { return MIValueFactory.createValue(Byte.valueOf(value.asByte())); - } else if (SymTypeRelations.isShort(boxType)) { + } + else if (SymTypeRelations.isShort(boxType)) { return MIValueFactory.createValue(Short.valueOf(value.asShort())); - } else if (SymTypeRelations.isBoolean(boxType)) { + } + else if (SymTypeRelations.isBoolean(boxType)) { return MIValueFactory.createValue(Boolean.valueOf(value.asBoolean())); } - + String errorMsg = "0x57084 Tried to convert to unknown boxed type."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIForIterator.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIForIterator.java deleted file mode 100644 index 20a4f8ae07..0000000000 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIForIterator.java +++ /dev/null @@ -1,9 +0,0 @@ -package de.monticore.interpreter; - -import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; - -public interface MIForIterator { - - public MIValue execute(ModelInterpreter interpreter, ASTMCStatement body); - -} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java index 3532539036..b110fcf4f0 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java @@ -11,20 +11,20 @@ import java.util.Optional; public class MIScope implements IMIScope { - + protected Map functionMap = new HashMap<>(); protected Map> variableMap = new HashMap<>(); - + protected Optional parent; - + public MIScope() { this.parent = Optional.empty(); } - + public MIScope(MIScope parent) { this.parent = Optional.of(parent); } - + public MIScope clone() { MIScope clone = new MIScope(); clone.parent = parent; @@ -32,64 +32,67 @@ public MIScope clone() { clone.functionMap = new HashMap<>(functionMap); return clone; } - + public void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { if (functionMap.containsKey(symbol)) { Log.error("0x57068 Function was already declared"); } this.functionMap.put(symbol, value); } - + public MIValue loadFunction(FunctionSymbol symbol) { if (functionMap.containsKey(symbol)) { return functionMap.get(symbol); } - + if (parent.isPresent()) { return parent.get().loadFunction(symbol); } - + String errorMsg = "0x57069 Failed to load Function by Symbol. Could not find Symbol in the current or any parent scope"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + public void declareVariable(VariableSymbol symbol, Optional value) { if (variableMap.containsKey(symbol)) { Log.error("0x57070 Variable was already declared"); } this.variableMap.put(symbol, value); } - + public MIValue loadVariable(VariableSymbol symbol) { Optional value = variableMap.get(symbol); if (value != null) { if (value.isPresent()) { return value.get(); - } else { + } + else { String errorMsg = "0x57087 Failed to load Variable by Symbol. Variable was declared but never initialized."; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } } - + if (parent.isPresent()) { return parent.get().loadVariable(symbol); } - + String errorMsg = "0x57071 Failed to load Variable by Symbol. Could not find Symbol in the current or any parent scope"; Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + public void storeVariable(VariableSymbol symbol, MIValue value) { if (variableMap.containsKey(symbol)) { variableMap.put(symbol, Optional.of(value)); - } else if (parent.isPresent()){ + } + else if (parent.isPresent()) { parent.get().storeVariable(symbol, value); - } else { + } + else { Log.error("0x57072 Failed to store Value in Symbol. Could not find Symbol in the current or any parent scope"); } } - + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIValueFactory.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIValueFactory.java index 142df5ce9f..7b5e344309 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIValueFactory.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIValueFactory.java @@ -1,10 +1,18 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter; -import de.monticore.interpreter.values.*; +import de.monticore.interpreter.values.BooleanMIValue; +import de.monticore.interpreter.values.ByteMIValue; +import de.monticore.interpreter.values.CharMIValue; +import de.monticore.interpreter.values.DoubleMIValue; +import de.monticore.interpreter.values.FloatMIValue; +import de.monticore.interpreter.values.IntMIValue; +import de.monticore.interpreter.values.LongMIValue; +import de.monticore.interpreter.values.ObjectMIValue; +import de.monticore.interpreter.values.ShortMIValue; public class MIValueFactory { - + public static MIValue createValue(short value) { return new ShortMIValue(value); } @@ -32,7 +40,7 @@ public static MIValue createValue(boolean value) { public static MIValue createValue(char value) { return new CharMIValue(value); } - + public static MIValue createValue(byte value) { return new ByteMIValue(value); } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java index ddb91380d9..e7df6fe2f8 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java @@ -1,7 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.interpreter; -import de.monticore.ast.ASTNode; import de.monticore.interpreter.values.FunctionMIValue; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; @@ -10,17 +9,17 @@ import java.util.Stack; public interface ModelInterpreter extends IModelInterpreter { - + void setRealThis(ModelInterpreter realThis); ModelInterpreter getRealThis(); - + Stack getScopeCallstack(); default MIScope getCurrentScope() { return getRealThis().getScopeCallstack().peek(); } - + /* TODO Explicit cast is needed because: Short version: Dependencies between symbols, scopes, functions & interpreter @@ -41,9 +40,9 @@ default MIScope getCurrentScope() { IMIscope cant access Variable-/FunctionSymbol -> explicit cast */ default void pushScope(IMIScope scope) { - getRealThis().getScopeCallstack().push((MIScope)scope); + getRealThis().getScopeCallstack().push((MIScope) scope); } - + default void popScope() { getRealThis().getScopeCallstack().pop(); } @@ -51,21 +50,21 @@ default void popScope() { default void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { getCurrentScope().declareFunction(symbol, value); } - + default MIValue loadFunction(FunctionSymbol symbol) { return getCurrentScope().loadFunction(symbol); } - + default void declareVariable(VariableSymbol symbol, Optional value) { getCurrentScope().declareVariable(symbol, value); } - + default MIValue loadVariable(VariableSymbol symbol) { return getCurrentScope().loadVariable(symbol); } - default void storeVariable(VariableSymbol symbol, MIValue value){ + default void storeVariable(VariableSymbol symbol, MIValue value) { getCurrentScope().storeVariable(symbol, value); } - + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MICommonForIterator.java b/monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MICommonForIterator.java similarity index 72% rename from monticore-grammar/src/main/java/de/monticore/interpreter/MICommonForIterator.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MICommonForIterator.java index d21ba77741..b2dc319fc0 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MICommonForIterator.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MICommonForIterator.java @@ -1,6 +1,9 @@ -package de.monticore.interpreter; +package de.monticore.interpreter.iterators; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.MIValueFactory; +import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.values.VoidMIValue; import de.monticore.statements.mccommonstatements._ast.ASTForInit; import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; @@ -9,33 +12,19 @@ import java.util.Optional; public class MICommonForIterator implements MIForIterator { - - Optional initNode; - Optional condition; - List expressions; - + + protected Optional initNode; + + protected Optional condition; + + protected List expressions; + public MICommonForIterator(Optional initNode, Optional condition, List expressions) { this.initNode = initNode; this.condition = condition; this.expressions = expressions; } - - public MIValue checkCondition(ModelInterpreter interpreter) { - if (condition.isPresent()) { - return condition.get().evaluate(interpreter); - } else { - return MIValueFactory.createValue(true); - } - } - - public MIValue increment(ModelInterpreter interpreter) { - for (ASTExpression expression : expressions) { - MIValue result = expression.evaluate(interpreter); - if (result.isError()) return result; - } - return new VoidMIValue(); - } - + @Override public MIValue execute(ModelInterpreter interpreter, ASTMCStatement body) { if (initNode.isPresent()) { @@ -43,21 +32,44 @@ public MIValue execute(ModelInterpreter interpreter, ASTMCStatement body) { if (result.isFlowControlSignal()) return result; } - + MIValue conditionResult = checkCondition(interpreter); while (conditionResult.isBoolean() && conditionResult.asBoolean()) { MIValue statementResult = body.evaluate(interpreter); - if (statementResult.isBreak()) break; - if (statementResult.isFlowControlSignal() && !statementResult.isContinue()) return statementResult; - + if (statementResult.isBreak()) + break; + if (statementResult.isFlowControlSignal() && !statementResult.isContinue()) + return statementResult; + MIValue incrementResult = increment(interpreter); if (incrementResult.isFlowControlSignal()) { return incrementResult; } - + conditionResult = checkCondition(interpreter); } - + return conditionResult.isFlowControlSignal() ? conditionResult : new VoidMIValue(); } + + // helper + + protected MIValue checkCondition(ModelInterpreter interpreter) { + if (condition.isPresent()) { + return condition.get().evaluate(interpreter); + } + else { + return MIValueFactory.createValue(true); + } + } + + protected MIValue increment(ModelInterpreter interpreter) { + for (ASTExpression expression : expressions) { + MIValue result = expression.evaluate(interpreter); + if (result.isError()) + return result; + } + return new VoidMIValue(); + } + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIForEachIterator.java b/monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MIForEachIterator.java similarity index 65% rename from monticore-grammar/src/main/java/de/monticore/interpreter/MIForEachIterator.java rename to monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MIForEachIterator.java index 74640fe197..8cd5b898f4 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIForEachIterator.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MIForEachIterator.java @@ -1,5 +1,9 @@ -package de.monticore.interpreter; +package de.monticore.interpreter.iterators; +import de.monticore.interpreter.InterpreterUtils; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.MIValueFactory; +import de.monticore.interpreter.ModelInterpreter; import de.monticore.interpreter.values.VoidMIValue; import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; @@ -9,32 +13,38 @@ import java.util.Optional; public class MIForEachIterator implements MIForIterator { - - VariableSymbol symbol; - Iterator iterator; - + + protected VariableSymbol symbol; + + protected Iterator iterator; + public MIForEachIterator(VariableSymbol symbol, Iterator iterator) { this.symbol = symbol; this.iterator = iterator; } - + @Override public MIValue execute(ModelInterpreter interpreter, ASTMCStatement body) { - if (!iterator.hasNext()) return new VoidMIValue(); - + if (!iterator.hasNext()) + return new VoidMIValue(); + interpreter.declareVariable(symbol, Optional.empty()); do { SymTypeExpression targetType = symbol.getType(); Object nextValue = iterator.next(); MIValue convertedValue = InterpreterUtils.convertImplicit(targetType, MIValueFactory.createValue(nextValue)); interpreter.storeVariable(symbol, convertedValue); - + MIValue statementResult = body.evaluate(interpreter); - if (statementResult.isContinue()) continue; - if (statementResult.isBreak()) break; - if (statementResult.isFlowControlSignal()) return statementResult; + if (statementResult.isContinue()) + continue; + if (statementResult.isBreak()) + break; + if (statementResult.isFlowControlSignal()) + return statementResult; } while (iterator.hasNext()); - + return new VoidMIValue(); } + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MIForIterator.java b/monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MIForIterator.java new file mode 100644 index 0000000000..a952834d07 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/iterators/MIForIterator.java @@ -0,0 +1,12 @@ +package de.monticore.interpreter.iterators; + +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.statements.mcstatementsbasis._ast.ASTMCStatement; + +@FunctionalInterface +public interface MIForIterator { + + MIValue execute(ModelInterpreter interpreter, ASTMCStatement body); + +} diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java index bef968eec6..f1bea9eae1 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/BooleanMIValue.java @@ -7,7 +7,7 @@ public class BooleanMIValue implements MIValue { protected boolean value; - public BooleanMIValue(boolean value){ + public BooleanMIValue(boolean value) { this.value = value; } @@ -15,22 +15,22 @@ public BooleanMIValue(boolean value){ public boolean isBoolean() { return true; } - + @Override public boolean isPrimitive() { return true; } - + @Override public boolean asBoolean() { return value; } - + @Override public String printType() { return "Boolean"; } - + @Override public String printValue() { return String.valueOf(value); diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ByteMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ByteMIValue.java index 087ca8fa6c..068a355578 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ByteMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ByteMIValue.java @@ -3,61 +3,61 @@ import de.monticore.interpreter.MIValue; public class ByteMIValue implements MIValue { - + protected byte value; - + public ByteMIValue(byte value) { this.value = value; } - + @Override public boolean isPrimitive() { return true; } - + @Override public boolean isByte() { return true; } - + @Override public byte asByte() { return value; } - + @Override public short asShort() { return value; } - + @Override public int asInt() { return value; } - + @Override public long asLong() { return value; } - + @Override public float asFloat() { return value; } - + @Override public double asDouble() { return value; } - + @Override public String printType() { return "Byte"; } - + @Override public String printValue() { return String.valueOf(value); } - + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/CharMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/CharMIValue.java index f0c3abe739..f15c9ff43f 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/CharMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/CharMIValue.java @@ -7,10 +7,10 @@ public class CharMIValue implements MIValue { protected char value; - public CharMIValue(char value){ + public CharMIValue(char value) { this.value = value; } - + @Override public boolean isPrimitive() { return true; @@ -45,12 +45,12 @@ public long asLong() { public float asFloat() { return value; } - + @Override public String printType() { return "Char"; } - + @Override public String printValue() { return String.valueOf(value); diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java index bda87a63c8..4be5aff72d 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/DoubleMIValue.java @@ -10,7 +10,7 @@ public class DoubleMIValue implements MIValue { public DoubleMIValue(double value) { this.value = value; } - + @Override public boolean isPrimitive() { return true; @@ -25,15 +25,15 @@ public boolean isDouble() { public double asDouble() { return value; } - + @Override public String printType() { return "Double"; } - + @Override public String printValue() { return String.valueOf(value); } - + } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java index 5ed19a08aa..2ced7647e9 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/FloatMIValue.java @@ -10,7 +10,7 @@ public class FloatMIValue implements MIValue { public FloatMIValue(float value) { this.value = value; } - + @Override public boolean isPrimitive() { return true; @@ -30,12 +30,12 @@ public double asDouble() { public float asFloat() { return value; } - + @Override public String printType() { return "Float"; } - + @Override public String printValue() { return String.valueOf(value) + "f"; diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/IntMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/IntMIValue.java index 567248a84f..f5a9d1160e 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/IntMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/IntMIValue.java @@ -10,7 +10,7 @@ public class IntMIValue implements MIValue { public IntMIValue(int value) { this.value = value; } - + @Override public boolean isPrimitive() { return true; @@ -40,12 +40,12 @@ public long asLong() { public float asFloat() { return value; } - + @Override public String printType() { return "Integer"; } - + @Override public String printValue() { return String.valueOf(value); diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java index 883c655588..9e76102afa 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaAttributeMIValue.java @@ -8,37 +8,45 @@ import java.util.Optional; public class JavaAttributeMIValue extends WriteableMIValue { - - Object obj; // null -> static attribute (that's how java does it) + + /** + * if null, this represents a static attribute; + * concept taken from Java Reflection API + */ + Object obj; + Field attribute; - + Optional innerValue = Optional.empty(); - + public JavaAttributeMIValue(Optional obj, Field attribute) { this.obj = obj.orElse(null); this.attribute = attribute; } - + @Override public void write(MIValue value) { try { attribute.set(obj, InterpreterUtils.valueToObject(value)); innerValue = Optional.of(value); - } catch (IllegalAccessException e) { - String errorMsg = "0x57094 Failed to assign value " + value.printType() - + "(" + value.printValue() + ") to attribute '" + attribute.getName() - + "' of class '" + attribute.getDeclaringClass().getName() + "'."; + } + catch (IllegalAccessException e) { + String errorMsg = "0x57094 Failed to assign value " + + value.printType() + "(" + value.printValue() + ")" + + " to attribute '" + attribute.getName() + "'" + + " of class '" + attribute.getDeclaringClass().getName() + "'."; Log.error(errorMsg); } } - + @Override public MIValue getMIValue() { if (!innerValue.isPresent()) { try { innerValue = Optional.of( InterpreterUtils.objectToValue(attribute.get(obj))); - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { String errorMsg = "0x57093 Failed to access attribute '" + attribute.getName() + "' of class '" + attribute.getDeclaringClass().getName() + "'."; @@ -46,15 +54,15 @@ public MIValue getMIValue() { innerValue = Optional.of(new ErrorMIValue(errorMsg)); } } - + return innerValue.get(); } - + @Override public String printType() { - return "Attribute"; + return "Java-Field"; } - + @Override public String printValue() { return getMIValue().printType() + " (" + getMIValue().printValue() + ")"; diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaNonStaticMethodMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaNonStaticMethodMIValue.java index 2b1110e3a0..511580ab73 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaNonStaticMethodMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaNonStaticMethodMIValue.java @@ -3,7 +3,6 @@ import de.monticore.interpreter.IModelInterpreter; import de.monticore.interpreter.InterpreterUtils; import de.monticore.interpreter.MIValue; -import de.monticore.interpreter.ModelInterpreter; import de.se_rwth.commons.logging.Log; import java.lang.reflect.InvocationTargetException; @@ -13,24 +12,26 @@ // TODO change to getting method by SymType public class JavaNonStaticMethodMIValue implements FunctionMIValue { + Object object; String methodName; - + public JavaNonStaticMethodMIValue(Object object, String methodName) { this.object = object; this.methodName = methodName; } - + @Override public MIValue execute(IModelInterpreter interpreter, List arguments) { List> argumentTypes = arguments.stream() .map(InterpreterUtils::typeOfValue) .collect(Collectors.toList()); - + Method method; try { method = object.getClass().getDeclaredMethod(methodName, argumentTypes.toArray(new Class[0])); - } catch (NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { StringBuilder sb = new StringBuilder(); sb.append("0x57059 Failed to find method '") .append(methodName) @@ -47,30 +48,32 @@ public MIValue execute(IModelInterpreter interpreter, List arguments) { Log.error(sb.toString()); return new ErrorMIValue(sb.toString()); } - + Object[] argumentObjects = arguments.stream().map(InterpreterUtils::valueToObject).toArray(); - + Object returnObject; try { returnObject = method.invoke(object, argumentObjects); - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { String errorMsg = e.getMessage(); Log.error(errorMsg); return new ErrorMIValue(errorMsg); - } catch (InvocationTargetException e) { + } + catch (InvocationTargetException e) { String errorMsg = e.getMessage(); Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + return InterpreterUtils.objectToValue(returnObject); } - + @Override public String printType() { return "Java-Method"; } - + @Override public String printValue() { return object.getClass().getName() + "." + methodName; diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaStaticMethodMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaStaticMethodMIValue.java index b0ee4935c6..e013f8b472 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaStaticMethodMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/JavaStaticMethodMIValue.java @@ -12,25 +12,26 @@ // TODO change to getting method by SymType public class JavaStaticMethodMIValue implements FunctionMIValue { - + Class classType; String functionName; - + public JavaStaticMethodMIValue(Class classType, String methodName) { this.classType = classType; this.functionName = methodName; } - + @Override public MIValue execute(IModelInterpreter interpreter, List arguments) { List> argumentTypes = arguments.stream() .map(InterpreterUtils::typeOfValue) .collect(Collectors.toList()); - + Method function; try { function = classType.getDeclaredMethod(functionName, argumentTypes.toArray(new Class[0])); - } catch (NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { StringBuilder sb = new StringBuilder(); sb.append("0x57058 Failed to find static function '") .append(functionName) @@ -47,13 +48,14 @@ public MIValue execute(IModelInterpreter interpreter, List arguments) { Log.error(sb.toString()); return new ErrorMIValue(sb.toString()); } - + Object[] argumentObjects = arguments.stream().map(InterpreterUtils::valueToObject).toArray(); - + Object returnObject; try { returnObject = function.invoke(null, argumentObjects); - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { @@ -61,15 +63,15 @@ public MIValue execute(IModelInterpreter interpreter, List arguments) { Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - + return InterpreterUtils.objectToValue(returnObject); } - + @Override public String printType() { return "Java-Function"; } - + @Override public String printValue() { return classType.getName() + "." + functionName; diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java index ae94bfbe02..875ec87b36 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/LongMIValue.java @@ -10,7 +10,7 @@ public class LongMIValue implements MIValue { public LongMIValue(long value) { this.value = value; } - + @Override public boolean isPrimitive() { return true; @@ -35,12 +35,12 @@ public long asLong() { public float asFloat() { return value; } - + @Override public String printType() { return "Long"; } - + @Override public String printValue() { return String.valueOf(value) + "L"; diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ModelFunctionMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ModelFunctionMIValue.java index e51372e67f..9eff449deb 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ModelFunctionMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ModelFunctionMIValue.java @@ -1,8 +1,10 @@ package de.monticore.interpreter.values; import de.monticore.ast.ASTNode; -import de.monticore.interpreter.*; - +import de.monticore.interpreter.IModelInterpreter; +import de.monticore.interpreter.InterpreterUtils; +import de.monticore.interpreter.MIScope; +import de.monticore.interpreter.MIValue; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.types.check.SymTypeExpression; @@ -10,47 +12,48 @@ import java.util.Optional; public class ModelFunctionMIValue implements FunctionMIValue { - + protected MIScope parentScope; protected List parameterSymbols; protected ASTNode body; - + public ModelFunctionMIValue(MIScope parentScope, List parameterSymbols, ASTNode body) { this.parentScope = parentScope; this.parameterSymbols = parameterSymbols; this.body = body; } - + @Override public MIValue execute(IModelInterpreter interpreter, List arguments) { MIScope newScope = new MIScope(parentScope); - + for (int i = 0; i < parameterSymbols.size(); i++) { VariableSymbol parameterSymbol = parameterSymbols.get(i); SymTypeExpression paramType = parameterSymbol.getType(); - + MIValue argument = arguments.get(i); argument = InterpreterUtils.convertImplicit(paramType, argument); - if (argument.isError()) return argument; - + if (argument.isError()) + return argument; + newScope.declareVariable(parameterSymbol, Optional.of(argument)); } - + interpreter.pushScope(newScope); MIValue result = body.evaluate(interpreter); interpreter.popScope(); - + return result; } - + @Override public String printType() { return "Model-Function"; } - + @Override public String printValue() { - return ""; + return "implemenation(" + body.get_SourcePositionStart().toString() + ")"; } } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java index 0c24fd39f8..156764ce6b 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ObjectMIValue.java @@ -23,7 +23,10 @@ public Object asObject() { @Override public String printType() { - return "Object"; + String typeStr = value != null + ? value.getClass().getTypeName() + : "null"; + return "Object(" + typeStr + ")"; } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ShortMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ShortMIValue.java index daf0232e3a..3848937484 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/ShortMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/ShortMIValue.java @@ -3,53 +3,53 @@ import de.monticore.interpreter.MIValue; public class ShortMIValue implements MIValue { - + protected short value; - + public ShortMIValue(short value) { this.value = value; } - + @Override public boolean isPrimitive() { return true; } - + @Override public boolean isShort() { return true; } - + @Override public short asShort() { return value; } - + @Override public int asInt() { return value; } - + @Override public long asLong() { return value; } - + @Override public float asFloat() { return value; } - + @Override public double asDouble() { return value; } - + @Override public String printType() { - return "Short"; + return "short"; } - + @Override public String printValue() { return String.valueOf(value); diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/VariableMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/VariableMIValue.java index 39033a0b56..0fc640fe78 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/VariableMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/VariableMIValue.java @@ -7,37 +7,37 @@ import java.util.Optional; public class VariableMIValue extends WriteableMIValue { - + protected MIScope scope; protected VariableSymbol symbol; - + protected Optional innerValue = Optional.empty(); - + public VariableMIValue(MIScope scope, VariableSymbol symbol) { this.scope = scope; this.symbol = symbol; } - + @Override public void write(MIValue value) { scope.storeVariable(symbol, value); innerValue = Optional.of(value); } - + @Override public MIValue getMIValue() { if (!innerValue.isPresent()) { innerValue = Optional.of(scope.loadVariable(symbol)); } - + return innerValue.get(); } - + @Override public String printType() { return "Variable"; } - + @Override public String printValue() { return getMIValue().printType() + " (" + getMIValue().printValue() + ")"; diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/values/WriteableMIValue.java b/monticore-grammar/src/main/java/de/monticore/interpreter/values/WriteableMIValue.java index 2627b314d4..ef462f491d 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/values/WriteableMIValue.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/values/WriteableMIValue.java @@ -3,164 +3,165 @@ import de.monticore.interpreter.MIValue; public abstract class WriteableMIValue implements MIValue { - + @Override public boolean isWriteable() { return true; } - + public abstract void write(MIValue value); - + public abstract MIValue getMIValue(); - + @Override public boolean isPrimitive() { - + return getMIValue().isPrimitive(); } - + @Override public boolean isBoolean() { return getMIValue().isBoolean(); } - + @Override public boolean isByte() { return getMIValue().isByte(); } - + @Override public boolean isChar() { return getMIValue().isChar(); } - + @Override public boolean isShort() { return getMIValue().isShort(); } - + @Override public boolean isInt() { return getMIValue().isInt(); } - + @Override public boolean isLong() { return getMIValue().isLong(); } - + @Override public boolean isFloat() { return getMIValue().isFloat(); } - + @Override public boolean isDouble() { return getMIValue().isDouble(); } - + @Override public boolean isObject() { return getMIValue().isObject(); } - + @Override public boolean isFunction() { return getMIValue().isFunction(); } - + @Override public boolean isVoid() { return getMIValue().isVoid(); } - + @Override public boolean isSIUnit() { return getMIValue().isSIUnit(); } - + @Override public boolean isFlowControlSignal() { return getMIValue().isFlowControlSignal(); } - + @Override public boolean isError() { return getMIValue().isError(); } - + @Override public boolean isBreak() { return getMIValue().isBreak(); } - + @Override public boolean isContinue() { return getMIValue().isContinue(); } - + @Override public boolean isReturn() { return getMIValue().isReturn(); } - + @Override public boolean asBoolean() { return getMIValue().asBoolean(); } - + @Override public byte asByte() { return getMIValue().asByte(); } - + @Override public char asChar() { return getMIValue().asChar(); } - + @Override public short asShort() { return getMIValue().asShort(); } - + @Override public int asInt() { return getMIValue().asInt(); } - + @Override public long asLong() { return getMIValue().asLong(); } - + @Override public float asFloat() { return getMIValue().asFloat(); } - + @Override public double asDouble() { return getMIValue().asDouble(); } - + @Override public FunctionMIValue asFunction() { return getMIValue().asFunction(); } - + @Override public Object asObject() { return getMIValue().asObject(); } - + @Override public MIValue asReturnValue() { return getMIValue().asReturnValue(); } - + @Override public String asError() { return getMIValue().asError(); } + } diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java index d99d1295be..fdbb164b78 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/_visitor/MCCommonStatementsInterpreter.java @@ -1,11 +1,29 @@ package de.monticore.statements.mccommonstatements._visitor; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; -import de.monticore.interpreter.*; +import de.monticore.interpreter.MIScope; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.MIValueFactory; +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.iterators.MICommonForIterator; +import de.monticore.interpreter.iterators.MIForEachIterator; +import de.monticore.interpreter.iterators.MIForIterator; import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.interpreter.values.MIBreakSignal; import de.monticore.interpreter.values.VoidMIValue; -import de.monticore.statements.mccommonstatements._ast.*; +import de.monticore.statements.mccommonstatements._ast.ASTBreakStatement; +import de.monticore.statements.mccommonstatements._ast.ASTCommonForControl; +import de.monticore.statements.mccommonstatements._ast.ASTDoWhileStatement; +import de.monticore.statements.mccommonstatements._ast.ASTEmptyStatement; +import de.monticore.statements.mccommonstatements._ast.ASTEnhancedForControl; +import de.monticore.statements.mccommonstatements._ast.ASTExpressionStatement; +import de.monticore.statements.mccommonstatements._ast.ASTForInit; +import de.monticore.statements.mccommonstatements._ast.ASTForInitByExpressions; +import de.monticore.statements.mccommonstatements._ast.ASTForStatement; +import de.monticore.statements.mccommonstatements._ast.ASTFormalParameter; +import de.monticore.statements.mccommonstatements._ast.ASTIfStatement; +import de.monticore.statements.mccommonstatements._ast.ASTMCJavaBlock; +import de.monticore.statements.mccommonstatements._ast.ASTWhileStatement; import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.se_rwth.commons.logging.Log; @@ -15,20 +33,20 @@ import java.util.Optional; public class MCCommonStatementsInterpreter extends MCCommonStatementsInterpreterTOP { - + public MCCommonStatementsInterpreter() { super(); } - + public MCCommonStatementsInterpreter(ModelInterpreter realThis) { super(realThis); } - + @Override public MIValue interpret(ASTMCJavaBlock node) { MIScope scope = new MIScope(getRealThis().getCurrentScope()); pushScope(scope); - + for (ASTMCBlockStatement statement : node.getMCBlockStatementList()) { MIValue result = statement.evaluate(getRealThis()); if (result.isFlowControlSignal()) { @@ -36,118 +54,131 @@ public MIValue interpret(ASTMCJavaBlock node) { return result; } } - + popScope(); return new VoidMIValue(); } - + @Override public MIValue interpret(ASTIfStatement node) { MIValue condition = node.getCondition().evaluate(getRealThis()); - if (condition.isFlowControlSignal()) return condition; - + if (condition.isFlowControlSignal()) + return condition; + if (condition.asBoolean()) { MIValue result = node.getThenStatement().evaluate(getRealThis()); - if (result.isFlowControlSignal()) return result; - } else if (node.isPresentElseStatement()) { + if (result.isFlowControlSignal()) + return result; + } + else if (node.isPresentElseStatement()) { MIValue result = node.getElseStatement().evaluate(getRealThis()); - if (result.isFlowControlSignal()) return result; + if (result.isFlowControlSignal()) + return result; } return new VoidMIValue(); } - + @Override public MIValue interpret(ASTWhileStatement node) { MIScope scope = new MIScope(getRealThis().getCurrentScope()); pushScope(scope); - + MIValue condition = node.getCondition().evaluate(getRealThis()); while (condition.isBoolean() && condition.asBoolean()) { MIValue result = node.getMCStatement().evaluate(getRealThis()); - if (result.isBreak()) break; - if (result.isContinue()) continue; + if (result.isBreak()) + break; + if (result.isContinue()) + continue; if (result.isFlowControlSignal()) { popScope(); return result; } - + condition = node.getCondition().evaluate(getRealThis()); } - + popScope(); if (!condition.isBoolean()) { String errorMsg = "0x57009 While condition must be of type boolean. Got " + condition.printType() - + " (" + condition.printValue() + ")."; + + " (" + condition.printValue() + ")."; Log.error(errorMsg, node.getCondition().get_SourcePositionStart(), node.getCondition().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); - } else if (condition.isFlowControlSignal()) { + } + else if (condition.isFlowControlSignal()) { return condition; - } else { + } + else { return new VoidMIValue(); } } - + @Override public MIValue interpret(ASTDoWhileStatement node) { MIScope scope = new MIScope(getRealThis().getCurrentScope()); pushScope(scope); - + MIValue condition = MIValueFactory.createValue(true); while (condition.isBoolean() && condition.asBoolean()) { MIValue result = node.getMCStatement().evaluate(getRealThis()); - if (result.isBreak()) break; - if (result.isContinue()) continue; + if (result.isBreak()) + break; + if (result.isContinue()) + continue; if (result.isFlowControlSignal()) { popScope(); return result; } - + condition = node.getCondition().evaluate(getRealThis()); } - + popScope(); if (!condition.isBoolean()) { String errorMsg = "0x57009 While condition must be of type boolean. Got " + condition.printType() - + " (" + condition.printValue() + ")."; + + " (" + condition.printValue() + ")."; Log.error(errorMsg, node.getCondition().get_SourcePositionStart(), node.getCondition().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); - } else if (condition.isFlowControlSignal()) { + } + else if (condition.isFlowControlSignal()) { return condition; - } else { + } + else { return new VoidMIValue(); } } - + @Override public MIValue interpret(ASTEmptyStatement node) { return new VoidMIValue(); } - + @Override public MIValue interpret(ASTExpressionStatement node) { MIValue result = node.getExpression().evaluate(getRealThis()); - if (result.isFlowControlSignal()) return result; + if (result.isFlowControlSignal()) + return result; return new VoidMIValue(); } - + @Override public MIValue interpret(ASTForStatement node) { MIScope scope = new MIScope(getRealThis().getCurrentScope()); pushScope(scope); - + MIValue control = node.getForControl().evaluate(getRealThis()); if (control.isFlowControlSignal()) { popScope(); return control; } - - MIForIterator controlIterator = (MIForIterator)control.asObject(); - + + MIForIterator controlIterator = (MIForIterator) control.asObject(); + MIValue result = controlIterator.execute(getRealThis(), node.getMCStatement()); popScope(); return result.isFlowControlSignal() ? result : new VoidMIValue(); } - + @Override public MIValue interpret(ASTCommonForControl node) { Optional initNode = node.isPresentForInit() ? Optional.of(node.getForInit()) : Optional.empty(); @@ -156,55 +187,59 @@ public MIValue interpret(ASTCommonForControl node) { MICommonForIterator iterator = new MICommonForIterator(initNode, condition, expressions); return MIValueFactory.createValue(iterator); } - + @Override public MIValue interpret(ASTForInit node) { if (node.isPresentForInitByExpressions()) { return node.getForInitByExpressions().evaluate(getRealThis()); - } else if (node.isPresentLocalVariableDeclaration()) { + } + else if (node.isPresentLocalVariableDeclaration()) { return node.getLocalVariableDeclaration().evaluate(getRealThis()); } - + return new VoidMIValue(); } - + @Override public MIValue interpret(ASTForInitByExpressions node) { for (ASTExpression expression : node.getExpressionList()) { MIValue result = expression.evaluate(getRealThis()); - if (result.isFlowControlSignal()) return result; + if (result.isFlowControlSignal()) + return result; } return new VoidMIValue(); } - + @Override public MIValue interpret(ASTEnhancedForControl node) { MIValue collectionValue = node.getExpression().evaluate(getRealThis()); - if (collectionValue.isFlowControlSignal()) return collectionValue; - + if (collectionValue.isFlowControlSignal()) + return collectionValue; + if (!(collectionValue.asObject() instanceof Collection)) { String errorMsg = "0x57082 Expected a collection in for-each loop. Got " + collectionValue.printType() + " (" + collectionValue.printValue() + ")."; Log.error(errorMsg, node.getExpression().get_SourcePositionStart(), node.getExpression().get_SourcePositionEnd()); return new ErrorMIValue(errorMsg); } - - Collection collection = (Collection)(collectionValue.asObject()); + + Collection collection = (Collection) (collectionValue.asObject()); VariableSymbol symbol = node.getFormalParameter().getDeclarator().getSymbol(); MIForIterator iterator = new MIForEachIterator(symbol, collection.iterator()); return MIValueFactory.createValue(iterator); } - + @Override public MIValue interpret(ASTFormalParameter node) { MIValue result = node.getDeclarator().evaluate(getRealThis()); if (result.isFlowControlSignal()) { return result; - } else { + } + else { return new VoidMIValue(); } } - + @Override public MIValue interpret(ASTBreakStatement node) { return new MIBreakSignal(); diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java index c796f23d21..77ab303bbb 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java @@ -1,17 +1,16 @@ package de.monticore.expressions.lambdaexpressions; -import de.monticore.AbstractInterpreterTest; import de.monticore.expressions.AbstractExpressionInterpreterTest; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import org.junit.jupiter.api.Test; -import java.io.IOException; - import static de.monticore.interpreter.MIValueFactory.createValue; public class LambdaExpressionsInterpreterTest extends AbstractExpressionInterpreterTest { @Test - public void testSimpleLambda() throws IOException { + public void testSimpleLambda() { + testValidExpression("(() -> \"a\"+1)()", createValue(1)); testValidExpression("(() -> 1)()", createValue(1)); testValidExpression("(() -> () -> 2)()()", createValue(2)); testValidExpression("((long a) -> a + 1)(41L)", createValue(42L)); diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java b/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java index cad6659098..7a7f4959ed 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/IModelInterpreter.java @@ -5,14 +5,15 @@ import de.se_rwth.commons.logging.Log; public interface IModelInterpreter { - + default MIValue interpret(ASTNode n) { String errorMsg = "0x57073 No implementation of ASTNode of type " + n.toString(); Log.error(errorMsg); return new ErrorMIValue(errorMsg); } - - public void popScope(); - public void pushScope(IMIScope scope); - + + void popScope(); + + void pushScope(IMIScope scope); + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java index 338b585703..28ca221588 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/MIValue.java @@ -5,27 +5,31 @@ import de.se_rwth.commons.logging.Log; public interface MIValue { - - default boolean isWriteable() { return false; } - - default boolean isPrimitive() { return false; } + + default boolean isWriteable() { + return false; + } + + default boolean isPrimitive() { + return false; + } default boolean isBoolean() { return false; } - + default boolean isByte() { return false; } - + default boolean isChar() { return false; } - + default boolean isShort() { return false; } - + default boolean isInt() { return false; } @@ -45,104 +49,116 @@ default boolean isDouble() { default boolean isObject() { return false; } - + default boolean isFunction() { return false; } - + default boolean isVoid() { return false; } - + default boolean isSIUnit() { return false; } - - default boolean isFlowControlSignal() { return false;} - + + default boolean isFlowControlSignal() { + return false; + } + default boolean isError() { return false; } - + default boolean isBreak() { return false; } - + default boolean isContinue() { return false; } - + default boolean isReturn() { return false; } - + default boolean asBoolean() { Log.error("0x31251 Type boolean is not applicable for " + printType() + " (" + printValue() + ")."); return false; } - + default byte asByte() { Log.error("0x31252 Type byte is not applicable for " + printType() + " (" + printValue() + ")."); return 0; } - + default char asChar() { Log.error("0x31253 Type char is not applicable for " + printType() + " (" + printValue() + ")."); return '\0'; } - + default short asShort() { Log.error("0x31254 Type short is not applicable for " + printType() + " (" + printValue() + ")."); return 0; } - + default int asInt() { Log.error("0x31255 Type int is not applicable for " + printType() + " (" + printValue() + ")."); return 0; } - + default long asLong() { Log.error("0x31256 Type long is not applicable for " + printType() + " (" + printValue() + ")."); return 0L; } - + default float asFloat() { Log.error("0x31257 Type float is not applicable for " + printType() + " (" + printValue() + ")."); return 0.0f; } - + default double asDouble() { Log.error("0x31258 Type double is not applicable for " + printType() + " (" + printValue() + ")."); return 0.0; } - + default FunctionMIValue asFunction() { Log.error("0x57099 Type function is not applicable for " + printType() + " (" + printValue() + ")."); return null; } - + default Object asObject() { Log.error("0x31259 Type object is not applicable for " + printType() + " (" + printValue() + ")."); return null; } + default String asError() { Log.error("0x57092 Type Error is not applicable for " + printType() + " (" + printValue() + ")."); return null; } - + default MIValue asReturnValue() { - Log.error("0x57083 Type ReturnValue is not applicable for " + printType() + " (" + printValue() + ")."); + Log.error("0x57083 Type ReturnValue is not applicable for " + + printType() + + " (" + printValue() + ")." + ); return null; } - + + /** + * Print the type of the MIValue in human-readable form + */ default String printType() { Log.error("0x31260 printType is not applicable for '" + getClass().getName() + "'."); return "UnknownType"; } - + + /** + * Print the value in human-readable form + */ default String printValue() { Log.error("0x31261 printValue is not applicable for '" + getClass().getName() + "'."); return "UnknownValue"; } - + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java index 25b832a43e..f4c967cc98 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/ErrorMIValue.java @@ -1,31 +1,53 @@ package de.monticore.interpreter.values; +import java.util.Optional; + public class ErrorMIValue implements MIFlowControlSignal { - - String message; - + + protected Optional message; + + protected Optional exception; + public ErrorMIValue(String message) { - this.message = message; + this.message = Optional.of(message); + this.exception = Optional.empty(); } - + + public ErrorMIValue(Exception exception) { + this.message = Optional.empty(); + this.exception = Optional.of(exception); + } + @Override public boolean isError() { return true; } - + @Override public String asError() { - return message; + return getMessage(); } - + @Override public String printType() { return "Error"; } - + @Override public String printValue() { - return message; + return getMessage(); } - + + // helper + + protected String getMessage() { + if (message.isPresent()) { + return message.get(); + } + else { + return exception.get().getClass().getTypeName() + + " occured: " + exception.get().getMessage(); + } + } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java index 4aa3294033..56b372d64c 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/FunctionMIValue.java @@ -5,18 +5,19 @@ import java.util.List; +@FunctionalInterface public interface FunctionMIValue extends MIValue { - + @Override - public default boolean isFunction() { + default boolean isFunction() { return true; } - + @Override - public default FunctionMIValue asFunction() { + default FunctionMIValue asFunction() { return this; } - - public MIValue execute(IModelInterpreter interpreter, List arguments); - + + MIValue execute(IModelInterpreter interpreter, List arguments); + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java index 729081c70a..01364e8c63 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIBreakSignal.java @@ -1,19 +1,20 @@ package de.monticore.interpreter.values; public class MIBreakSignal implements MIFlowControlSignal { - + @Override public boolean isBreak() { return true; } - + @Override public String printType() { - return "Break"; + return "Break-Signal"; } - + @Override public String printValue() { return ""; } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java index 8246694f20..1fcc5aab79 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIContinueSignal.java @@ -1,20 +1,20 @@ package de.monticore.interpreter.values; public class MIContinueSignal implements MIFlowControlSignal { - + @Override public boolean isContinue() { return true; } - + @Override public String printType() { return "Continue"; } - + @Override public String printValue() { return ""; } - + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java index 91337db4b5..ee57a0bb93 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIFlowControlSignal.java @@ -3,9 +3,10 @@ import de.monticore.interpreter.MIValue; public interface MIFlowControlSignal extends MIValue { - + @Override - public default boolean isFlowControlSignal() { + default boolean isFlowControlSignal() { return true; } + } diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java index 8857a0b646..4500c2070d 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/MIReturnSignal.java @@ -3,32 +3,32 @@ import de.monticore.interpreter.MIValue; public class MIReturnSignal implements MIFlowControlSignal { - + MIValue value; - + public MIReturnSignal() { this.value = new VoidMIValue(); } - + public MIReturnSignal(MIValue value) { this.value = value; } - + @Override public boolean isReturn() { return true; } - + @Override public MIValue asReturnValue() { return value; } - + @Override public String printType() { - return "Return"; + return "Return-Signal"; } - + @Override public String printValue() { return value.printType() + "(" + value.printValue() + ")"; diff --git a/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java b/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java index 9165c37f0b..970378b336 100644 --- a/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java +++ b/monticore-runtime/src/main/java/de/monticore/interpreter/values/VoidMIValue.java @@ -3,19 +3,20 @@ import de.monticore.interpreter.MIValue; public class VoidMIValue implements MIValue { - + @Override public boolean isVoid() { return true; } - + @Override public String printType() { return "Void"; } - + @Override public String printValue() { return ""; } + } From 9d2626f29d108ee6f581b5a2a893124da6cfe742 Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Mon, 2 Feb 2026 20:35:28 +0100 Subject: [PATCH 23/37] Merge branch 'dev' into interpreter --- .gitattributes | 4 +- .github/workflows/deploy_pages.yml | 77 + .github/workflows/deploy_release_mc.yml | 2 +- .github/workflows/deploy_snapshot_mc.yml | 12 +- .github/workflows/gradle_mc.yml | 30 +- .github/workflows/prepare_pages.yml | 48 - .gitignore | 4 +- 00.org/Explanations/CHANGELOG.md | 93 +- 00.org/Explanations/FAQ.md | 6 +- 00.org/Explanations/StatusOfGrammars.md | 6 +- README.md | 85 +- build.gradle | 92 +- docs/BestPractices-CLI.md | 6 +- docs/BestPractices-Errors.md | 6 +- docs/BestPractices-Language-Design.md | 6 +- docs/BestPractices-Symbols-Scopes.md | 6 +- docs/BestPractices-Syntax-Design.md | 6 +- docs/BestPractices-Testing.md | 243 ++++ docs/BestPractices.md | 8 +- docs/BuildMontiCore.md | 20 +- docs/CI.md | 2 + docs/DevelopedLanguages.md | 6 +- docs/Download.md | 6 +- docs/GettingStarted.md | 40 +- docs/Gradle.md | 4 +- docs/JavaDocs.md | 19 + docs/Languages.md | 26 +- docs/MontiCoreSymposium.md | 18 +- docs/README.md | 11 + docs/docs/MC_Symp_Banner.png | Bin 37780 -> 0 bytes ...ing-and-Testing--Usage-of-UML-Diagrams.png | Bin docs/{docs => img}/Bild6.png | Bin docs/{docs => img}/Eclipse.png | Bin docs/{docs => img}/GenAutomataAST.png | Bin docs/{docs => img}/GenAutomataParser.png | Bin docs/{docs => img}/GenAutomataScopes.png | Bin docs/{docs => img}/GenAutomataSymbols.png | Bin docs/{docs => img}/GenAutomataVisitors.png | Bin docs/{docs => img}/IntelliJ-IDEA.png | Bin docs/img/MC_Symp_Banner.png | Bin 0 -> 38582 bytes .../MontiCore--Selected-Languages.png | Bin docs/{ => img}/MontiCoreHandbook2021.gif | Bin docs/{docs => img}/Notational-Conventions.png | Bin {img => docs/img}/favicon.ico | Bin mc-logo.png => docs/img/mc-logo.png | Bin docs/{docs => img}/small_bulb.png | Bin docs/overrides/extensions/docsnippet.py | 287 ++++ docs/overrides/landingpage.html | 366 +++++ docs/scripts/preprocessing.sh | 91 +- docs/stylesheets/extra.css | 5 + gradle.properties | 12 +- mkdocs.yml | 25 +- monticore-generator/build.gradle | 228 +-- .../gradle-plugin/build.gradle | 92 ++ .../main/java/de/monticore/IncChecker.java | 0 .../java/de/monticore/MCMillBuildService.java | 0 .../src/main/java/de/monticore/MCPlugin.java | 0 .../src/main/java/de/monticore/MCTask.java | 7 +- .../main/java/de/monticore/MCTaskError.java | 0 .../java/de/monticore/MontiTransExec.java | 0 .../monticore/gradle/GradleTaskStatistic.java | 0 .../gradle/MCGeneratorBasePlugin.java | 3 + .../gradle/MCGeneratorExtension.java | 0 .../monticore/gradle/MCGeneratorPlugin.java | 5 + .../gradle/MCGeneratorWithTRPlugin.java | 0 .../de/monticore/gradle/StatisticData.java | 4 +- .../monticore/gradle/StatisticListener.java | 0 .../dependencies/MCDependenciesPlugin.java | 1 - .../dependencies/MCPublishingPlugin.java | 104 +- .../gradle/dependencies/MCSourceSets.java | 0 .../MCToolDependenciesPlugin.java | 57 + .../de/monticore/gradle/gen/MCGenTask.java | 0 .../de/monticore/gradle/gen/MCToolAction.java | 2 +- .../sources/MCGrammarsSourceDirectorySet.java | 0 .../gradle/sources/MCSourcesPlugin.java | 0 .../java/de/monticore/IncCheckerTest.java | 75 +- .../de/monticore/gradle/MCGenPluginTest.java | 271 ++-- monticore-generator/gradle.properties | 14 +- monticore-generator/settings.gradle | 6 +- .../de/monticore/DelegatingClassLoader.java | 12 +- .../java/de/monticore/MontiCoreScript.java | 10 +- .../java/de/monticore/cli/MontiCoreTool.java | 28 +- .../codegen/cd2java/AbstractService.java | 54 +- .../de/monticore/codegen/cd2java/JavaDoc.java | 2 - .../symbol/ASTReferencedSymbolDecorator.java | 2 +- .../_ast/builder/BuilderDecorator.java | 8 + .../_parser/ParserForSuperDecorator.java | 62 +- .../scope/ArtifactScopeClassDecorator.java | 2 + .../scope/GlobalScopeClassDecorator.java | 4 + .../scopesgenitor/ScopesGenitorDecorator.java | 65 +- .../_symboltable/symbol/SymbolDecorator.java | 17 + .../symbol/SymbolSurrogateDecorator.java | 47 +- .../cd2java/_tagging/TaggerDecorator.java | 4 +- .../_visitor/TraverserClassDecorator.java | 2 +- .../codegen/cd2java/cli/CLIDecorator.java | 14 + .../typecd2java/TypeCD2JavaDecorator.java | 2 +- .../mc2cd/MC2CD4CodeSymbolTableCompleter.java | 2 +- .../codegen/mc2cd/MC2CDStereotypes.java | 7 +- .../codegen/mc2cd/TransformationHelper.java | 2 +- .../JavaAndCdConformNameManipulation.java | 2 +- ...RemoveRedundantAttributesManipulation.java | 81 +- .../codegen/mc2cd/transl/NameTranslation.java | 3 + .../codegen/parser/MCGrammarInfo.java | 2 +- .../codegen/parser/ParserGenerator.java | 7 +- .../codegen/parser/ParserGeneratorHelper.java | 34 +- .../parser/antlr/Grammar2ParseVisitor.java | 4 +- .../codegen/prettyprint/MC2PPTranslation.java | 10 +- ...ava => NonTermAccessorVisitorHandler.java} | 85 +- .../PrettyPrinterGenerationVisitor.java | 94 +- .../PrettyPrinterReplaceKeywordFinder.java | 4 +- .../codegen/prettyprint/data/AltData.java | 45 +- .../codegen/prettyprint/data/BlockData.java | 18 + .../prettyprint/data/PPGuardComponent.java | 32 +- .../Grammar_WithConceptsPhasedSTCFix.java | 41 + .../DSL2TransformationLanguageVisitor.java | 74 +- .../PostprocessPatternAttributesVisitor.java | 2 +- .../ProductionFactory.java | 19 +- .../TFLanguageOverrideVisitor.java | 16 +- .../CollectGrammarInformationVisitor.java | 18 +- .../DSTLGenInheritanceHelper.java | 6 +- .../dstlgen/util/DSTLPrettyPrinter.java | 161 +-- .../monticore/gradle/gen/MCToolInvoker.java | 5 +- .../tagging/TagLanguageOverrideVisitor.java | 16 +- .../src/main/resources/_cli/Init.ftl | 4 +- .../src/main/resources/_cli/Main.ftl | 19 +- .../resources/_prettyprinter/pp/Block.ftl | 4 +- .../ConstructorArtifactScope.ftl | 4 +- .../globalscope/ConstructorGlobalScope.ftl | 4 +- .../iglobalscope/CalculateModelNamesFor.ftl | 2 +- .../_symboltable/iscope/GetSymbolSize.ftl | 2 +- .../scopesgenitor/CreateFromAST.ftl | 2 +- .../_symboltable/scopesgenitor/PutOnStack.ftl | 2 +- .../scopeDeSer/DeserializeSymbols.ftl | 2 +- .../resources/_symboltable/symbol/Equals.ftl | 10 + .../_symboltable/symbolsurrogate/Equals.ftl | 12 + .../GetSpannedScopeSymbolSurrogate.ftl | 6 + .../_symboltable/symbolsurrogate/GetThis.ftl | 7 + .../SetSpannedScopeSymbolSurrogate.ftl | 5 + .../src/main/resources/dstlgen/MainClass.ftl | 21 +- .../dstlgen/cocos/CoCoVisitorBuilder.ftl | 2 +- .../cocos/CollectRHSVariablesVisitor.ftl | 1 - .../cocos/DiffSchemaVarTypeVisitor.ftl | 4 +- .../src/main/resources/mill/GetMillMethod.ftl | 5 +- .../src/main/resources/mill/InitMeMethod.ftl | 8 + .../src/main/resources/parser/Lexer.ftl | 2 +- .../src/main/resources/parser/ParserInfo.ftl | 6 +- ...CGrammarLanguageFamilySymbolTableTest.java | 13 +- .../de/monticore/MontiCoreScriptTest.java | 430 +++--- .../de/monticore/cli/MontiCoreToolTest.java | 44 +- .../cli/UpdateCheckerRunnableTest.java | 25 +- .../codegen/cd2java/DecoratorAssert.java | 24 +- .../codegen/cd2java/DecoratorTestCase.java | 8 +- .../codegen/cd2java/DecoratorTestUtil.java | 20 +- .../codegen/cd2java/DeprecatedTest.java | 10 +- .../cd2java/GeneratedErrorCodeTest.java | 6 +- .../ASTConstantsDecoratorTest.java | 12 +- .../ASTInterfaceDecoratorTest.java | 12 +- .../ASTLanguageInterfaceDecoratorTest.java | 14 +- .../FullASTInterfaceDecoratorTest.java | 12 +- .../_ast/ast_new/ASTCDDecoratorTest.java | 13 +- .../_ast/ast_new/ASTDecoratorTest.java | 12 +- .../_ast/ast_new/ASTFullDecoratorTest.java | 11 +- .../_ast/ast_new/ASTScopeDecoratorTest.java | 10 +- .../cd2java/_ast/ast_new/ASTServiceTest.java | 10 +- .../_ast/ast_new/ASTSymbolDecoratorTest.java | 10 +- .../reference/ASTReferenceDecoratorTest.java | 10 +- ...ReferencedDefinitionDecoratorListTest.java | 12 +- ...encedDefinitionDecoratorMandatoryTest.java | 12 +- ...rencedDefinitionDecoratorOptionalTest.java | 12 +- .../ASTReferencedSymbolDecoratorListTest.java | 12 +- ...eferencedSymbolDecoratorMandatoryTest.java | 12 +- ...ReferencedSymbolDecoratorOptionalTest.java | 14 +- .../_ast/builder/ASTBuilderDecoratorTest.java | 12 +- .../_ast/builder/BuilderDecoratorTest.java | 8 +- .../_ast/enums/LiteralsEnumDecoratorTest.java | 12 +- .../_ast_emf/ASTEmfCDDecoratorTest.java | 12 +- .../ast_class/ASTEmfDecoratorTest.java | 16 +- .../ast_class/ASTFullEmfDecoratorTest.java | 11 +- .../ast_class/DataEmfDecoratorTest.java | 12 +- .../emf_package/PackageImplDecoratorTest.java | 12 +- .../PackageInterfaceDecoratorTest.java | 12 +- .../_cocos/CoCoCheckerDecoratorTest.java | 15 +- .../cd2java/_cocos/CoCoDecoratorTest.java | 12 +- .../_cocos/CoCoInterfaceDecoratorTest.java | 12 +- .../cd2java/_cocos/CoCoServiceTest.java | 10 +- .../codegen/cd2java/_od/ODDecoratorTest.java | 12 +- .../_parser/ParserCDDecoratorTest.java | 10 +- .../_parser/ParserClassDecoratorTest.java | 12 +- .../_parser/ParserForSuperDecoratorTest.java | 12 +- .../cd2java/_parser/ParserServiceTest.java | 10 +- .../SymbolTableCDDecoratorTest.java | 10 +- .../_symboltable/SymbolTableServiceTest.java | 10 +- .../_symboltable/Symbols2JsonTest.java | 10 +- .../ArtifactScopeClassDecoratorTest.java | 12 +- .../ArtifactScopeInterfaceDecoratorTest.java | 10 +- .../scope/GlobalScopeClassDecoratorTest.java | 10 +- .../GlobalScopeInterfaceDecoratorTest.java | 10 +- .../scope/ScopeClassDecoratorTest.java | 18 +- .../scope/ScopeInterfaceDecoratorTest.java | 12 +- .../ScopesGenitorDecoratorTest.java | 12 +- .../ScopesGenitorDelegatorDecoratorTest.java | 12 +- .../ScopeDeSerDecoratorTest.java | 14 +- .../SymbolDeSerDecoratorTest.java | 14 +- .../Symbols2JsonDecoratorTest.java | 16 +- .../CommonSymbolInterfaceDecoratorTest.java | 12 +- .../symbol/SymbolBuilderDecoratorTest.java | 12 +- .../symbol/SymbolDecoratorTest.java | 30 +- .../SymbolResolverInterfaceDecoratorTest.java | 10 +- .../SymbolSurrogateBuilderDecoratorTest.java | 12 +- .../symbol/SymbolSurrogateDecoratorTest.java | 44 +- .../_visitor/CDTraverserDecoratorTest.java | 10 +- .../_visitor/HandlerDecoratorTest.java | 12 +- .../InheritanceHandlerDecoratorTest.java | 10 +- .../_visitor/TraverserClassDecoratorTest.java | 12 +- .../TraverserInterfaceDecoratorTest.java | 10 +- .../_visitor/Visitor2DecoratorTest.java | 12 +- .../cd2java/_visitor/VisitorServiceTest.java | 10 +- .../cd2java/cli/CDCLIDecoratorTest.java | 12 +- .../codegen/cd2java/cli/CLIDecoratorTest.java | 12 +- .../cd2java/data/DataDecoratorTest.java | 14 +- .../data/DataInterfaceDecoratorTest.java | 12 +- .../cd2java/data/FullConstructorTest.java | 14 +- .../cd2java/data/ListSuffixDecoratorTest.java | 17 +- .../interpreter/InterpreterDecoratorTest.java | 140 +- .../InterpreterInterfaceDecoratorTest.java | 26 +- .../accessor/ListAccessorDecoratorTest.java | 10 +- .../MandatoryAccessorDecoratorTest.java | 6 +- .../OptionalAccessorDecoratorTest.java | 15 +- .../mutator/ListMutatorDecoratorTest.java | 10 +- .../MandatoryMutatorDecoratorTest.java | 10 +- .../mutator/OptionalMutatorDecoratorTest.java | 10 +- .../mill/CDAuxiliaryDecoratorTest.java | 13 +- .../cd2java/mill/CDMillDecoratorTest.java | 13 +- .../cd2java/mill/MillDecoratorTest.java | 10 +- .../mill/MillForSuperDecoratorTest.java | 10 +- .../cd2java/mill/MillWithInheritanceTest.java | 12 +- .../cd2java/typecd2java/TypeCD2JavaTest.java | 25 +- ...veRedundantReferencesManipulationTest.java | 15 +- .../scopeTransl/CDScopeTranslationTest.java | 47 +- .../symbolTransl/CDSymbolTranslationTest.java | 82 +- .../mc2cd/symbolTransl/SpanningScopeTest.java | 62 +- .../mc2cd/transl/AbstractProdTest.java | 51 +- .../mc2cd/transl/AstRuleInheritanceTest.java | 113 +- .../codegen/mc2cd/transl/AstRuleTest.java | 15 +- .../AttributeInASTMultiplicityTest.java | 17 +- .../transl/AttributeInASTOverridingTest.java | 17 +- .../mc2cd/transl/AttributeInASTTypeTest.java | 9 +- .../mc2cd/transl/ComponetTranslationTest.java | 17 +- .../transl/DerivedAttributeNameTest.java | 71 +- .../DirectLeftRecursionDetectorTest.java | 14 +- .../codegen/mc2cd/transl/EnumProdTest.java | 9 +- .../transl/ExternalImplementationTest.java | 10 +- .../ExternalInterfaceTranslationTest.java | 12 +- .../codegen/mc2cd/transl/InheritanceTest.java | 41 +- .../InheritedAttributesTranslationTest.java | 42 +- .../mc2cd/transl/InterfaceProdTest.java | 23 +- .../transl/LeftRecursiveTranslationTest.java | 12 +- .../transl/NonTerminalMultiplicityTest.java | 49 +- .../mc2cd/transl/OverridingClassProdTest.java | 11 +- .../transl/StarImportSuperGrammarTest.java | 11 +- .../transl/StartProdTranslationTest.java | 34 +- .../transl/SymbolAndScopeTranslationTest.java | 222 +-- .../transl/TerminalWithUsageNameTest.java | 11 +- .../mc2cd/transl/TokenMultiplicityTest.java | 9 +- .../codegen/mc2cd/transl/TokenTypeTest.java | 48 +- .../codegen/mc2cd/transl/UsageNameTest.java | 13 +- .../codegen/parser/MCGrammarParserTest.java | 101 +- .../codegen/parser/ParserGeneratorTest.java | 41 +- .../MCGrammarPrettyPrinterTest.java | 65 +- .../monticore/runtime/junit/MCAssertions.java | 63 + .../de/monticore/inherited/Supergrammar.mc4 | 4 + .../de/monticore/inherited/sub/Subgrammar.mc4 | 3 + .../inherited/subsub/Subsubgrammar.mc4 | 4 + monticore-grammar-emf/build.gradle | 8 +- monticore-grammar/build.gradle | 100 +- .../main/grammars/de/monticore/Grammars.md | 6 +- .../main/grammars/de/monticore/JavaLight.md | 8 +- .../main/grammars/de/monticore/MCBasics.mlc | 1 + .../de/monticore/expressions/Expressions.md | 6 +- .../de/monticore/literals/Literals.md | 6 +- .../de/monticore/ocl/OCLExpressions.mc4 | 2 +- .../grammars/de/monticore/siunit/SIUnits.md | 12 +- .../de/monticore/symbols/CompSymbols.mc4 | 3 +- .../de/monticore/symbols/OOSymbols.mc4 | 1 + .../main/grammars/de/monticore/types/Types.md | 6 +- .../AssignmentExpressionsCTTIVisitor.java | 4 +- .../types3/CommonExpressionsCTTIVisitor.java | 6 +- ...essionsTypeIdAsConstructorCTTIVisitor.java | 83 ++ ...essionsTypeIdAsConstructorTypeVisitor.java | 3 + .../types3/CommonExpressionsTypeVisitor.java | 15 +- ...onBasisTypeIdAsConstructorCTTIVisitor.java | 57 + ...onBasisTypeIdAsConstructorTypeVisitor.java | 3 + .../LambdaExpressionsSTCompleteTypes.java | 4 + .../LambdaExpressionsSTCompleteTypes2.java | 23 +- .../types3/TupleExpressionsCTTIVisitor.java | 79 + .../types3/TupleExpressionsTypeVisitor.java | 4 +- .../grammar/DirectLeftRecursionDetector.java | 2 +- .../java/de/monticore/grammar/LexNamer.java | 8 +- .../grammar/MCGrammarSymbolTableHelper.java | 5 +- .../grammar/cocos/ExternalNTNoASTRule.java | 4 +- .../grammar/cocos/InheritedModiOverwrite.java | 4 +- ...tImplementationOnlyInComponentGrammar.java | 2 +- .../grammar/cocos/NoASTExtendsForClasses.java | 10 +- ...NoExtensionOfSymbolThatOnlySpansScope.java | 2 +- .../grammar/cocos/NoForbiddenGrammarName.java | 4 +- .../cocos/NoForbiddenProdAndSymbolName.java | 2 +- .../grammar/cocos/NoForbiddenProdName.java | 4 +- .../cocos/NoForbiddenProdNameAddon.java | 2 +- .../grammar/cocos/NoForbiddenSymbolName.java | 12 +- .../cocos/NoForbiddenSymbolNameAddon.java | 2 +- ...oNestedGenericsInAdditionalAttributes.java | 18 +- .../cocos/OverridingAdditionalAttributes.java | 2 +- .../grammar/cocos/OverridingEnumNTs.java | 4 +- .../grammar/cocos/OverridingInterfaceNTs.java | 2 +- .../ReferenceSymbolSameAttributeVisitor.java | 4 +- .../cocos/RuleComponentsCompatible.java | 4 +- .../cocos/ScopeProdOverwrittenByScope.java | 2 +- .../cocos/SymbolProdOverwrittenBySymbol.java | 2 +- .../grammar/cocos/UniqueProdNamesForComp.java | 12 +- .../grammar/_symboltable/MCGrammarSymbol.java | 4 +- .../_symboltable/MCGrammarSymbolBuilder.java | 6 +- .../grammar/_symboltable/ProdSymbol.java | 11 +- .../_parser/GrammarTransformer.java | 10 +- .../Grammar_WithConceptsPhasedSTC.java | 24 + .../Grammar_WithConceptsScopesGenitor.java | 3 +- .../ConstructorNoAccessModifierPair.java | 2 +- .../cocos/ConstructorNoDuplicateModifier.java | 6 +- .../cocos/MethodExceptionThrows.java | 2 +- .../MethodFormalParametersDifferentName.java | 4 +- .../cocos/MethodNoDuplicateModifier.java | 6 +- .../monticore/literals/MCLiteralsDecoder.java | 22 +- .../cocos/BasicDoubleLiteralRangeCoCo.java | 4 +- .../cocos/BasicFloatLiteralRangeCoCo.java | 4 +- .../cocos/BasicLongLiteralRangeCoCo.java | 4 +- .../cocos/NatLiteralRangeCoCo.java | 4 +- .../NoLineBreaksInStringLiteralCoCo.java | 4 +- .../SignedBasicDoubleLiteralRangeCoCo.java | 4 +- .../SignedBasicFloatLiteralRangeCoCo.java | 4 +- .../SignedBasicLongLiteralRangeCoCo.java | 4 +- .../cocos/SignedNatLiteralRangeCoCo.java | 4 +- .../_visitor/MCJavaLiteralsInterpreter.java | 38 + .../cocos/DoubleLiteralRangeCoCo.java | 4 +- .../cocos/FloatLiteralRangeCoCo.java | 4 +- .../cocos/IntLiteralRangeCoCo.java | 4 +- .../cocos/LongLiteralRangeCoCo.java | 4 +- .../cocos/SetComprehensionHasGenerator.java | 4 +- .../SetExpressionsSymbolTableCompleter.java | 91 +- .../types3/SetExpressionsTypeVisitor.java | 20 +- .../cocos/AssertIsValid.java | 49 +- .../cocos/CatchIsValid.java | 29 +- .../cocos/DoWhileConditionHasBooleanType.java | 28 +- .../cocos/ExpressionStatementIsValid.java | 28 +- .../cocos/ForConditionHasBooleanType.java | 31 +- .../cocos/ForEachIsValid.java | 26 +- .../cocos/IfConditionHasBooleanType.java | 29 +- .../ResourceInTryStatementCloseable.java | 30 +- .../cocos/SwitchStatementValid.java | 31 +- .../cocos/SynchronizedArgIsReftype.java | 29 +- .../cocos/ThrowIsValid.java | 32 +- .../cocos/WhileConditionHasBooleanType.java | 27 +- ...clarationInitializationHasCorrectType.java | 71 +- ...rDeclarationNameAlreadyDefinedInScope.java | 49 + .../_symboltable/IBasicSymbolsScope.java | 2 +- .../ComponentType2TypeSymbolAdapter.java | 69 + .../_symboltable/ComponentTypeSymbol.java | 48 +- .../ComponentTypeSymbolBuilder.java | 83 ++ .../ComponentTypeSymbolDeSer.java | 9 +- .../ComponentTypeSymbolSurrogate.java | 30 + .../_symboltable/Port2VariableAdapter.java | 88 ++ .../compsymbols/_symboltable/PortSymbol.java | 12 +- .../Subcomponent2VariableAdapter.java | 84 ++ .../oosymbols/_symboltable/FieldSymbol.java | 1 + .../types3/OOSymbolsSymTypeRelations.java | 258 ++++ .../monticore/tagging/SimpleSymbolTagger.java | 4 +- .../de/monticore/tagging/TagRepository.java | 6 +- .../monticore/tagging/conforms/TagData.java | 2 +- .../tagging/conforms/TagSchemaData.java | 10 +- .../tagschema/TagSchemaAfterParseTrafo.java | 10 +- .../CollectCoCoInformationState.java | 6 +- .../_ast/ASTTransformationStructure.java | 37 +- .../tf/odrules/DifferenceFinder.java | 2 +- .../monticore/tf/odrules/HierarchyHelper.java | 12 +- .../de/monticore/tf/odrules/ODBuildOrder.java | 8 +- .../tf/odrules/ODRuleCodeGenerator.java | 10 +- .../AddSuffixToOptionalsVisitor.java | 4 +- .../subConstraints/FindDependVarsVisitor.java | 4 +- .../subConstraints/FindOptionalsVisitor.java | 4 +- .../FindSubExpressionVisitor.java | 2 +- .../InsertIsPresentChecksVisitor.java | 4 +- .../subConstraints/ODSubConstraint.java | 4 +- .../ruletranslation/ODRuleNameGenerator.java | 6 +- .../monticore/types/check/AbstractDerive.java | 5 + .../check/AbstractDeriveFromExpression.java | 5 + .../types/check/AbstractSynthesize.java | 5 + .../check/AbstractSynthesizeFromType.java | 5 + .../types/check/CompKindExpression.java | 42 +- .../types/check/CompKindOfComponentType.java | 10 + .../check/CompKindOfGenericComponentType.java | 36 +- .../DeriveSymTypeOfAssignmentExpressions.java | 3 + .../DeriveSymTypeOfBSCommonExpressions.java | 13 +- .../check/DeriveSymTypeOfBitExpressions.java | 3 + .../DeriveSymTypeOfCommonExpressions.java | 3 + .../check/DeriveSymTypeOfExpression.java | 3 + .../DeriveSymTypeOfJavaClassExpressions.java | 3 + .../DeriveSymTypeOfLambdaExpressions.java | 3 + .../types/check/DeriveSymTypeOfLiterals.java | 3 + .../DeriveSymTypeOfMCCommonLiterals.java | 3 + .../check/DeriveSymTypeOfMCJavaLiterals.java | 5 + .../check/DeriveSymTypeOfUglyExpressions.java | 3 + .../check/FullSynthesizeFromMCArrayTypes.java | 5 + .../check/FullSynthesizeFromMCBasicTypes.java | 5 + .../FullSynthesizeFromMCCollectionTypes.java | 5 + .../FullSynthesizeFromMCFullGenericTypes.java | 5 + .../FullSynthesizeFromMCFunctionTypes.java | 5 + ...ullSynthesizeFromMCSimpleGenericTypes.java | 5 + .../types/check/ISynthesizeComponent.java | 9 +- .../monticore/types/check/ITypeRelations.java | 6 +- .../de/monticore/types/check/SIUnitBasic.java | 5 +- .../monticore/types/check/SymTypeArray.java | 9 +- .../types/check/SymTypeExpression.java | 143 +- .../types/check/SymTypeExpressionFactory.java | 106 +- .../types/check/SymTypeInferenceVariable.java | 13 +- .../types/check/SymTypeOfFunction.java | 33 +- .../types/check/SymTypeOfGenerics.java | 71 +- .../types/check/SymTypeOfIntersection.java | 12 +- .../check/SymTypeOfIntersectionDeSer.java | 4 +- .../check/SymTypeOfNumericWithSIUnit.java | 5 +- .../types/check/SymTypeOfObject.java | 20 +- .../types/check/SymTypeOfObjectDeSer.java | 2 +- .../monticore/types/check/SymTypeOfRegEx.java | 4 +- .../types/check/SymTypeOfSIUnit.java | 4 +- .../monticore/types/check/SymTypeOfTuple.java | 3 +- .../monticore/types/check/SymTypeOfUnion.java | 12 +- .../types/check/SymTypeOfUnionDeSer.java | 4 +- .../types/check/SymTypeOfWildcard.java | 2 +- .../types/check/SymTypePrimitive.java | 44 +- .../types/check/SymTypeVariable.java | 13 +- .../SynthesizeCompKindFromMCBasicTypes.java | 3 - ...esizeCompKindFromMCSimpleGenericTypes.java | 29 +- .../SynthesizeSymTypeFromMCArrayTypes.java | 3 + .../SynthesizeSymTypeFromMCBasicTypes.java | 3 + ...ynthesizeSymTypeFromMCCollectionTypes.java | 3 + ...nthesizeSymTypeFromMCFullGenericTypes.java | 3 + .../SynthesizeSymTypeFromMCFunctionTypes.java | 3 + ...hesizeSymTypeFromMCSimpleGenericTypes.java | 3 + .../de/monticore/types/check/TypeCheck.md | 17 +- .../monticore/types/check/TypeRelations.java | 6 +- .../mcbasictypes/_ast/ASTMCReturnType.java | 2 +- .../types/mcbasictypes/_ast/ASTMCType.java | 2 +- .../_ast/ASTMCTypeArgument.java | 2 +- .../types3/MCCollectionSymTypeRelations.java | 3 +- .../MCSimpleGenericTypesTypeVisitor.java | 23 +- .../types3/MCStructuralTypesTypeVisitor.java | 2 +- .../TypeParametersSTCompleteTypes.java | 15 +- .../TypeParameterNoCyclicInheritance.java | 2 +- .../cocos/TypeParametersHaveUniqueNames.java | 6 +- .../monticore/types3/ISymTypeRelations.java | 20 +- .../de/monticore/types3/SymTypeRelations.java | 23 +- .../java/de/monticore/types3/Type4Ast.java | 8 +- .../de/monticore/types3/TypeCalculator3.java | 7 +- .../java/de/monticore/types3/TypeCheck3.java | 9 +- .../java/de/monticore/types3/TypeSystem3.md | 12 +- .../de/monticore/types3/generics/Generics.md | 5 + .../generics/TypeParameterRelations.java | 11 +- .../types3/generics/bounds/Bound.java | 43 +- .../generics/bounds/BoundComparator.java | 163 +++ .../types3/generics/bounds/CaptureBound.java | 24 +- .../generics/bounds/SubTypingBound.java | 5 + .../bounds/TypeCompatibilityBound.java | 5 + .../generics/bounds/TypeEqualityBound.java | 5 + .../generics/bounds/UnsatisfiableBound.java | 5 + .../constraints/BoundWrapperConstraint.java | 10 +- .../generics/constraints/Constraint.java | 43 +- .../constraints/ConstraintComparator.java | 255 ++++ .../ExpressionCompatibilityConstraint.java | 12 +- .../constraints/SubTypingConstraint.java | 5 + .../TypeCompatibilityConstraint.java | 5 + .../constraints/TypeEqualityConstraint.java | 5 + .../context/InferenceContext4Ast.java | 6 +- .../generics/context/InferenceResult.java | 4 +- .../generics/util/BoundIncorporation.java | 18 +- .../types3/generics/util/BoundResolution.java | 156 +- .../util/CompileTimeTypeCalculator.java | 122 +- .../generics/util/ConstraintReduction.java | 5 +- .../generics/util/PartialFunctionInfo.java | 10 +- .../SymTypeFreeVariableReplaceVisitor.java | 6 +- ...ymTypeInferenceVariableReplaceVisitor.java | 8 +- .../util/SymTypeVariableReplaceVisitor.java | 10 +- .../generics/util/WildcardCapturer.java | 4 +- .../streams/StreamSymTypeRelations.java | 3 +- .../types3/util/FunctionRelations.java | 3 +- .../types3/util/LValueRelations.java | 3 +- .../types3/util/MapBasedTypeCheck3.java | 7 +- .../util/NominalSuperTypeCalculator.java | 4 +- .../OOWithinTypeBasicSymbolsResolver.java | 41 +- .../types3/util/SIUnitTypeRelations.java | 19 +- .../types3/util/SymTypeBoxingVisitor.java | 18 +- .../types3/util/SymTypeCollectionVisitor.java | 4 +- .../util/SymTypeCompatibilityCalculator.java | 23 +- .../types3/util/SymTypeDeepCloneVisitor.java | 4 +- .../util/SymTypeExpressionComparator.java | 469 +++--- .../types3/util/SymTypeLubCalculator.java | 26 +- .../types3/util/SymTypeNormalizeVisitor.java | 59 +- .../types3/util/SymTypeUnboxingVisitor.java | 18 +- .../types3/util/TypeContextCalculator.java | 11 +- .../types3/util/TypeVisitorLifting.java | 9 +- .../util/TypeVisitorOperatorCalculator.java | 13 +- .../util/WithinScopeBasicSymbolsResolver.java | 154 +- .../util/WithinTypeBasicSymbolsResolver.java | 406 ++++-- .../ComponentSymbolsWithMCBasicTypesTest.mc4 | 10 + .../java/de/monticore/MCCommonUnitTest.java | 181 +-- .../java/de/monticore/SymbolImportTest.java | 15 +- .../aggregation/AggregationTest.java | 31 +- .../monticore/comments/CommentsOnASTTest.java | 66 +- .../expressions/AbstractInterpreterTest.java | 262 ++++ ...xpressionsOnlyAssignToLValuesCoCoTest.java | 14 +- ...ignmentMatchesRegExExpressionCoCoTest.java | 15 +- .../cocos/ExpressionValidTest.java | 12 +- .../ParserTest.java | 23 +- .../TestNoClassExpressionForGenerics.java | 24 +- .../CommonExpressionsBuilderTest.java | 22 + ...tionCallArgumentsMatchesRegExCoCoTest.java | 13 +- .../AssignmentExpressionsJavaPrinterTest.java | 162 +-- .../BitExpressionsJavaPrinterTest.java | 77 +- .../CommonExpressionsJavaPrinterTest.java | 245 ++-- .../JavaClassExpressionsJavaPrinterTest.java | 93 +- .../UglyExpressionsJavaPrinterTest.java | 24 - ...ssignmentExpressionsPrettyPrinterTest.java | 162 +-- .../BitExpressionsPrettyPrinterTest.java | 82 +- .../CommonExpressionsPrettyPrinterTest.java | 235 +-- ...JavaClassExpressionsPrettyPrinterTest.java | 125 +- .../LambdaExpressionsPrettyPrinterTest.java | 29 +- .../StreamExpressionsPrettyPrinterTest.java | 16 +- .../CombinedStreamsExpressionsParserTest.java | 7 +- .../grammar/MCGrammarParserTest.java | 101 +- .../grammar/MCGrammarPrettyPrinterTest.java | 65 +- .../de/monticore/grammar/cocos/CocoTest.java | 29 +- .../cocos/GrammarInheritanceCycleTest.java | 11 +- .../cocos/GrammarNameEqualsFileNameTest.java | 13 +- .../cocos/KeywordAlternativeNameTest.java | 11 +- .../grammar/cocos/NTUniqueIgnoreCaseTest.java | 11 +- .../cocos/NoForbiddenSymbolNameTest.java | 14 +- .../cocos/NoNTInheritanceCycleTest.java | 13 +- .../grammar/cocos/UsedNTNotDefinedTest.java | 9 +- .../symboltable/IGrammarScopeTest.java | 189 ++- ...ontiCoreGrammarSymbolTableCreatorTest.java | 371 ++--- ...ctorFormalParametersDifferentNameTest.java | 6 +- .../cocos/ConstructorModifiersValidTest.java | 5 +- .../ConstructorNoAccessModifierPairTest.java | 5 +- .../ConstructorNoDuplicateModifierTest.java | 5 +- .../javalight/cocos/JavaLightCocoTest.java | 22 +- .../MethodAbstractAndOtherModifiersTest.java | 5 +- .../cocos/MethodBodyAbsenceTest.java | 5 +- .../cocos/MethodBodyPresenceTest.java | 5 +- .../cocos/MethodExceptionThrowsTest.java | 10 +- ...thodFormalParametersDifferentNameTest.java | 5 +- .../cocos/MethodNoNativeAndStrictfpTest.java | 5 +- .../ReturnTypeAssignmentIsValidTest.java | 17 +- .../DoubleCommonLiteralsTest.java | 17 +- .../FloatCommonLiteralsTest.java | 19 +- .../IntCommonLiteralsTest.java | 33 +- .../LongCommonLiteralsTest.java | 17 +- .../NoLineBreaksInStringLiteralTest.java | 16 +- .../mccommonliterals/RangeCoCosTest.java | 39 +- .../DoubleJavaLiteralsTest.java | 11 +- .../mcjavaliterals/FloatJavaLiteralsTest.java | 12 +- .../mcjavaliterals/IntJavaLiteralsTest.java | 10 +- .../mcjavaliterals/LongJavaLiteralsTest.java | 10 +- .../MCJavaLiteralsTestHelper.java | 5 +- .../mcjavaliterals/RangeCoCosTest.java | 43 +- .../mcliterals/CharLiteralsTest.java | 10 +- .../mcliterals/MCLiteralsTestHelper.java | 7 +- .../mcliterals/MCLiteralsUnitTest.java | 165 ++- .../monticore/mcliterals/NatLiteralsTest.java | 15 +- .../NullAndBooleanLiteralsTest.java | 21 +- .../mcliterals/SignedNatLiteralsTest.java | 15 +- .../mcliterals/StringLiteralsTest.java | 5 +- .../CardinalityPrettyPrinterTest.java | 41 +- .../CompletenessPrettyPrinterTest.java | 55 +- .../prettyprint/GrammarPrettyPrinterTest.java | 19 +- .../JavaLightPrettyPrinterTest.java | 185 ++- .../MCCommonLiteralsPrettyPrinterTest.java | 149 +- .../MCHexNumbersPrettyPrinterTest.java | 41 +- .../MCJavaLiteralsPrettyPrinterTest.java | 53 +- .../MCNumbersPrettyPrinterTest.java | 53 +- .../StringLiteralsPrettyPrinterTest.java | 41 +- .../UMLModifierPrettyPrinterTest.java | 31 +- .../UMLStereotypePrettyPrinterTest.java | 30 +- .../cocos/RangeHasLowerOrUpperBoundTest.java | 13 +- .../statements/cocos/AssertIsValidTest.java | 108 +- .../statements/cocos/CatchIsValidTest.java | 191 +-- .../DoWhileConditionHasBooleanTypeTest.java | 116 +- .../cocos/ExpressionStatementIsValidTest.java | 103 +- .../cocos/ForConditionHasBooleanTypeTest.java | 110 +- .../statements/cocos/ForEachIsValidTest.java | 170 ++- .../cocos/IfConditionHasBooleanTypeTest.java | 118 +- .../ResourceInTryStatementCloseableTest.java | 173 ++- .../cocos/SwitchStatementValidTest.java | 193 ++- .../cocos/SynchronizedArgIsReftypeTest.java | 119 +- .../statements/cocos/ThrowIsValidTest.java | 160 ++- ...ationInitializationHasCorrectTypeTest.java | 114 +- ...larationNameAlreadyDefinedInScopeTest.java | 104 ++ .../WhileConditionHasBooleanTypeTest.java | 111 +- .../MCArrayStatementsPrettyPrinterTest.java | 29 +- .../MCCommonStatementsPrettyPrinterTest.java | 257 ++-- ...CExceptionStatementsPrettyPrinterTest.java | 89 +- ...MCLowLevelStatementsPrettyPrinterTest.java | 53 +- .../MCReturnStatementsPrettyPrinterTest.java | 17 +- ...nchronizedStatementsPrettyPrinterTest.java | 17 +- ...eclarationStatementsPrettyPrinterTest.java | 17 +- .../TrailingSpacesPrettyPrinterTest.java | 15 +- .../BasicSymbolsSymbols2JsonTest.java | 74 +- .../_symboltable/TypeSymbolSurrogateTest.java | 425 ++++++ .../_symboltable/TypeSymbolTest.java | 101 ++ .../CompKindOfComponentTypeTest.java | 30 - .../CompKindOfGenericComponentTypeTest.java | 35 - .../ComponentSymbolDeSerTest.java | 343 ----- .../_symboltable/ComponentSymbolTest.java | 46 - .../ComponentType2TypeSymbolAdapterTest.java | 64 + .../ComponentTypeSymbolBuilderTest.java | 189 +++ .../ComponentTypeSymbolDeSerTest.java | 429 ++++++ .../ComponentTypeSymbolSurrogateTest.java | 799 ++++++++++ .../_symboltable/ComponentTypeSymbolTest.java | 257 ++++ .../Port2VariableAdapterTest.java | 116 ++ .../Subcomponent2VariableAdapterTest.java | 116 ++ .../oosymbols/_symboltable/CloneTest.java | 50 +- .../oosymbols/_symboltable/ModifierTest.java | 39 +- .../_symboltable/OOSymbolsModifierTest.java | 100 +- .../OOSymbolsSymbols2JsonTest.java | 51 +- .../types3/OOSymbolsSymTypeRelationsTest.java | 239 +++ .../de/monticore/testsymtabmill/MillTest.java | 10 +- .../typepersistence/TypePersistenceTest.java | 7 +- .../monticore/types/AlwaysTheSameASTTest.java | 461 +++--- .../de/monticore/types/MCBasicTypesTest.java | 55 +- .../types/MCCollectionTypesTest.java | 167 +-- .../types/MCFullGenericTypesTest.java | 15 +- .../monticore/types/MCFunctionTypesTest.java | 88 +- .../monticore/types/MCGenericsTypesTest.java | 63 +- .../types/MCSimpleGenericsTypesTest.java | 137 +- .../de/monticore/types/MCTypeFacadeTest.java | 489 +++---- .../MCollectionTypesCorrectStateTest.java | 105 +- .../types/check/AbstractDeriveTest.java | 54 +- .../check/CompKindOfComponentTypeTest.java | 212 +++ .../CompKindOfGenericComponentTypeTest.java | 445 ++++++ .../types/check/DefiningSymbolsTest.java | 91 +- .../check/DeriveSymTypeAbstractTest.java | 25 +- ...riveSymTypeOfAssignmentExpressionTest.java | 23 +- .../DeriveSymTypeOfBitExpressionsTest.java | 18 +- .../DeriveSymTypeOfCommonExpressionTest.java | 57 +- .../check/DeriveSymTypeOfExpressionTest.java | 22 +- ...riveSymTypeOfJavaClassExpressionsTest.java | 58 +- .../DeriveSymTypeOfLambdaExpressionsTest.java | 10 +- .../check/DeriveSymTypeOfLiteralsTest.java | 9 +- .../DeriveSymTypeOfMCCommonLiteralsTest.java | 37 +- ...ynthesizeCompKindFromMCBasicTypesTest.java | 69 + .../check/SymTypeExpressionDeSerTest.java | 134 +- .../types/check/SymTypeExpressionTest.java | 1013 +++++++------ ...nthesizeComponentFromMCBasicTypesTest.java | 140 ++ ...ComponentFromMCSimpleGenericTypesTest.java | 287 ++++ ...SynthesizeSymTypeFromMCArrayTypesTest.java | 25 +- ...SynthesizeSymTypeFromMCBasicTypesTest.java | 21 +- ...esizeSymTypeFromMCCollectionTypesTest.java | 77 +- ...sizeSymTypeFromMCFullGenericTypesTest.java | 37 +- ...zeSymTypeFromMCSimpleGenericTypesTest.java | 35 +- ...hesizeSymTypeFromMCcFunctionTypesTest.java | 34 +- .../types/check/TypeCalculatorTest.java | 241 ++-- ...ingSymbolSetter4CommonExpressionsTest.java | 19 +- .../SubExprNameExtractionResultTest.java | 143 +- ...prNameExtractor4CommonExpressionsTest.java | 39 +- .../MCArrayTypesNodeIdentHelperTest.java | 12 +- .../types/helper/MCBasicTypesHelperTest.java | 27 +- .../MCBasicTypesNodeIdentHelperTest.java | 31 +- .../MCCollectionTypesNodeIdentHelperTest.java | 27 +- ...MCFullGenericTypesNodeIdentHelperTest.java | 11 +- ...SimpleGenericTypesNodeIdentHelperTest.java | 25 +- .../helper/MCType2SymTypeExpressionTest.java | 244 ++-- .../QualifiedTypeHasNoTypeParametersTest.java | 2 +- .../util/MCCollectionSymTypeFactoryTest.java | 108 +- .../util/MCCollectionTypeRelationsTest.java | 174 ++- .../MCArrayTypesPrettyPrinterTest.java | 18 +- .../MCBasicTypesPrettyPrinterTest.java | 115 +- .../MCCollectionTypesPrettyPrinterTest.java | 77 +- .../MCFullGenericTypesPrettyPrinterTest.java | 41 +- .../MCFunctionTypesPrettyPrinterTest.java | 17 +- ...MCSimpleGenericTypesPrettyPrinterTest.java | 53 +- .../PrintTypeAstExtensionTests.java | 61 +- .../TypeParametersPrettyPrinterTest.java | 31 +- .../types/printer/BasicTypesPrinterTest.java | 31 +- .../printer/CollectionTypesPrinterTest.java | 31 +- .../printer/FullGenericTypesPrinterTest.java | 23 +- .../SimpleGenericTypesPrinterTest.java | 15 +- .../TypeParametersHaveUniqueNamesTest.java | 15 +- ...TypeParametersNoCyclicInheritanceTest.java | 19 +- .../de/monticore/types3/AbstractTypeTest.java | 44 +- .../types3/AbstractTypeVisitorTest.java | 149 +- .../types3/CallGenericFunctionsTest.java | 13 +- .../CommonExpressionTypeVisitorTest.java | 195 +-- .../types3/CommonLiteralsTypeVisitorTest.java | 8 +- .../JavaClassExpressionsTypeVisitorTest.java | 2 + .../types3/MCArrayTypesTypeVisitorTest.java | 4 + .../types3/MCBasicTypesTypeVisitorTest.java | 21 +- .../MCCollectionTypesTypeVisitorTest.java | 67 +- .../MCSimpleGenericTypesTypeVisitorTest.java | 2 +- .../types3/MapBasedTypeCheck3Test.java | 3 +- .../types3/OCLExpressionsTypeVisitorTest.java | 3 +- .../OptionalOperatorsTypeVisitorTest.java | 2 +- .../ResolveTypeIdAsConstructorTest.java | 85 +- .../types3/ResolveWithinOOTypeTest.java | 112 +- .../types3/ResolveWithinTypeTest.java | 118 +- .../SIUnitTypes4MathTypeVisitorTest.java | 5 +- .../types3/SetExpressionsTypeVisitorTest.java | 4 +- .../monticore/types3/SourceSymbolsTest.java | 10 +- .../StreamExpressionsTypeVisitorTest.java | 2 +- .../types3/SymTypeBoxingVisitorTest.java | 21 +- .../types3/SymTypeCompatibilityTest.java | 765 +++++----- .../SymTypeExpressionComparatorTest.java | 57 + .../types3/SymTypeLeastUpperBoundTest.java | 23 +- .../types3/SymTypeNormalizeVisitorTest.java | 13 +- .../types3/SymTypeUnboxingVisitorTest.java | 15 +- .../TupleExpressionsTypeVisitorTest.java | 12 +- .../UglyExpressionsTypeVisitorTest.java | 10 +- .../streams/StreamSymTypeFactoryTest.java | 15 +- .../streams/StreamTypeRelationsTest.java | 26 +- ...sionsWithLiteralsTypeTraverserFactory.java | 44 +- .../types3/util/DefsTypesForTests.java | 371 ++--- .../types3/util/DefsVariablesForTests.java | 50 +- .../util/SymTypeExpressionGenerator.java | 170 +++ .../umlmodifier/ModifierBuilderTest.java | 23 +- .../umlmodifier/ModifierPrettyPrintTest.java | 33 +- .../umlstereotype/StereoValueContentTest.java | 20 +- .../cocos/StereoValueIsStringLiteralTest.java | 12 +- .../grammar/cocos/invalid/A4099/A4099.mc4 | 11 + .../compsymbols/_symboltable/WithField.json | 18 + .../compsymbols/_symboltable/WithInner.json | 14 + .../{WithParent.json => WithRefinement.json} | 4 +- .../types3/util/DefsTypesForTests.java | 1280 +++++++++++++++++ .../types3/util/DefsVariablesForTests.java | 276 ++++ .../stream-symbols-it/build.gradle | 4 +- .../symbols/library/StreamTypeTest.java | 55 +- .../stream-symbols/build.gradle | 3 +- .../EventStream.symtabdefinition | 2 +- .../symtabdefinition/Stream.symtabdefinition | 3 +- .../SyncStream.symtabdefinition | 6 +- .../ToptStream.symtabdefinition | 4 +- .../UntimedStream.symtabdefinition | 6 +- monticore-runtime-emf/build.gradle | 6 +- .../de/monticore/emf/util/AST2ModelFiles.java | 4 +- monticore-runtime/build.gradle | 111 +- .../de/monticore/antlr4/MCBuildVisitor.java | 2 +- .../de/monticore/antlr4/MCConcreteParser.java | 4 +- .../de/monticore/antlr4/MCErrorListener.java | 16 +- .../main/java/de/monticore/ast/ASTNode.java | 46 +- .../monticore/generating/GeneratorEngine.java | 15 +- .../monticore/generating/GeneratorSetup.java | 9 +- .../GlobalExtensionManagement.java | 5 +- .../templateengine/TemplateController.java | 10 +- .../freemarker/FreeMarkerTemplateEngine.java | 7 +- .../freemarker/MontiCoreTemplateLoader.java | 3 +- .../freemarker/SimpleHashFactory.java | 17 +- .../reporting/artifacts/ArtifactReporter.java | 4 +- .../artifacts/ReportingNameHelper.java | 2 +- .../artifacts/formatter/GMLFormatter.java | 12 +- .../artifacts/formatter/GVFormatter.java | 6 +- .../reporting/artifacts/model/APkg.java | 6 +- .../reporting/artifacts/model/Element.java | 6 +- .../reporting/artifacts/model/Pkg.java | 2 +- .../reporting/artifacts/model/RootPkg.java | 4 +- .../commons/IReportEventHandler.java | 2 +- .../reporting/commons/Layouter.java | 7 +- .../reporting/commons/ReportCreator.java | 10 +- .../reporting/commons/ReportLogHook.java | 4 +- .../reporting/commons/ReportManager.java | 3 +- .../commons/ReportingRepository.java | 6 +- .../reporting/commons/StatisticsHandler.java | 2 +- .../reporting/reporter/DetailedReporter.java | 2 +- .../reporting/reporter/HookPointReporter.java | 6 +- .../reporting/reporter/IncGenReporter.java | 4 +- .../reporter/InstantiationsReporter.java | 8 +- .../reporter/InvolvedFilesReporter.java | 2 +- .../reporter/NodeTreeDecoratedReporter.java | 7 +- .../reporting/reporter/NodeTreeReporter.java | 11 +- .../reporting/reporter/NodeTypesReporter.java | 15 +- .../reporter/StatisticsReporter.java | 2 +- .../reporting/reporter/SummaryReporter.java | 48 +- .../reporter/TemplateTreeReporter.java | 6 +- .../reporting/reporter/TemplatesReporter.java | 29 +- .../de/monticore/io/FileReaderWriter.java | 9 +- .../de/monticore/io/MontiCoreClassLoader.java | 2 +- .../io/paths/GlobExpressionEvaluator.java | 4 +- .../java/de/monticore/io/paths/MCPath.java | 4 +- .../monticore/prettyprint/IndentPrinter.java | 1 - .../java/de/monticore/symboltable/IScope.java | 19 +- .../SymbolWithScopeOfUnknownKindBuilder.java | 5 +- .../SymbolWithScopeOfUnknownKindDeSer.java | 4 +- .../de/monticore/symboltable/Symboltable.md | 6 +- .../modifiers/CompoundAccessModifier.java | 4 +- .../symboltable/serialization/IDeSer.java | 4 - .../symboltable/serialization/JsonDeSers.java | 1 - .../serialization/JsonPrinter.java | 2 +- .../json/TraceableJsonObject.java | 8 +- .../tf/rule2od/Variable2AttributeMap.java | 4 +- .../monticore/tf/runtime/FastLookupList.java | 78 + .../java/de/monticore/tf/runtime/ODRule.java | 2 - .../tf/runtime/SuccessfulReporter.java | 5 - .../monticore/tf/runtime/ValueComparator.java | 2 +- .../matching/CommentBasedModelTraversal.java | 62 + .../CommentBasedModelTraversalFactory.java | 33 + .../CommentBasedModelTraversalVisitor.java | 11 + .../tf/runtime/matching/ModelTraversal.java | 6 +- .../matching/ModelTraversalVisitor.java | 2 +- .../de/monticore/tf/odrules/ClassMatch.ftl | 8 +- .../de/monticore/tf/odrules/ConstantCode.ftl | 24 +- .../tf/odrules/DoPatternMatching.ftl | 24 +- .../tf/odrules/DoPatternMatchingList.ftl | 24 +- .../tf/odrules/DoPatternMatchingOptional.ftl | 15 +- .../de/monticore/tf/odrules/DoReplacement.ftl | 1 + .../monticore/tf/odrules/FastLookupList.ftl | 13 + .../monticore/tf/odrules/FindSearchPlan.ftl | 2 +- .../tf/odrules/OptimizeSearchPlan.ftl | 61 + .../monticore/tf/odrules/ResetOptionals.ftl | 11 + .../tf/odrules/TransformationClass.ftl | 6 + .../tf/odrules/TransformationUnit.ftl | 4 +- .../dopatternmatching/HandleListObject.ftl | 5 +- .../dopatternmatching/HandleNormalObject.ftl | 8 +- .../dopatternmatching/HandleNotObject.ftl | 9 +- .../dopatternmatching/HandleOptObject.ftl | 4 +- .../odrules/doreplacement/CreateObjects.ftl | 4 + .../de/monticore/ast/CommentBuilderTest.java | 16 +- .../de/monticore/cocos/helper/Assert.java | 19 +- .../generating/GeneratorEngineTest.java | 36 +- ...obalExtensionManagementGlobalVarsTest.java | 19 +- .../templateengine/ObjectFactoryTest.java | 25 +- .../templateengine/TemplateAliasingTest.java | 113 +- .../TemplateControllerHookPointsTest.java | 222 +-- .../TemplateControllerSignatureUsageTest.java | 36 +- .../TemplateControllerTest.java | 56 +- .../templateengine/TemplateLoggerTest.java | 7 +- .../commons/ReportingStringHelperTest.java | 13 +- .../commons/StatisticsHandlerTest.java | 9 +- .../java/de/monticore/io/FileFinderTest.java | 61 +- .../de/monticore/io/FileReaderWriterTest.java | 11 +- .../de/monticore/io/paths/MCPathTest.java | 111 +- .../serialization/JsonLexerTest.java | 98 +- .../serialization/JsonParserTest.java | 32 +- .../JsonPrinterSecurityTest.java | 32 +- .../serialization/JsonPrinterTest.java | 89 +- .../serialization/JsonStringEscapeTest.java | 13 +- .../TemplateEngineBenchmark.java | 2 +- .../runtime/junit/AbstractMCTest.java | 49 + .../monticore/runtime/junit/MCAssertions.java | 234 +++ .../junit/MCLanguageTestExtension.java | 64 + .../runtime/junit/PrettyPrinterTester.java | 117 ++ .../runtime/junit/TestWithMCLanguage.java | 27 + .../src/main/java/automata/AutomataTool.java | 26 +- .../src/test/java/AutomataParseTest.java | 36 +- .../src/test/java/AutomataToolTest.java | 38 +- .../test/java/TransitionSourceExistsTest.java | 43 +- monticore-test/01.experiments/build.gradle | 12 +- .../builderAtm/src/main/grammars/G1.mc4 | 20 + .../src/test/java/Builders4Test.java | 35 +- .../src/test/java/BuildersG1G2Test.java | 43 +- .../src/test/java/BuildersTest.java | 34 +- .../src/test/java/G1TerminalBuildersTest.java | 85 ++ .../ch17/src/test/java/HAutomataTest.java | 21 +- .../ch17/src/test/java/IAutomataTest.java | 24 +- .../ch17/src/test/java/SAutomataTest.java | 27 +- .../composition/src/main/grammars/A.mc4 | 8 +- .../composition/src/main/grammars/B.mc4 | 5 +- .../composition/src/main/grammars/C.mc4 | 4 +- .../composition/src/main/grammars/D.mc4 | 5 +- .../main/java/composition/MyInterface.java | 6 + .../src/test/java/Automata3ToolTest.java | 28 +- .../composition/src/test/java/GTest.java | 18 +- .../test/java/HierInvAutomataToolTest.java | 23 +- .../01.experiments/demonstrator/build.gradle | 37 +- .../src/main/java/automata/AutomataTool.java | 8 +- .../src/productTest/java/PingPongTest.java | 22 +- .../src/test/java/AutomataParseTest.java | 24 +- .../src/test/java/AutomataToolTest.java | 19 +- .../test/java/TransitionSourceExistsTest.java | 51 +- .../test/java/minimalexample/ParserTest.java | 15 +- .../src/test/java/sm2/SM2ToolTest.java | 29 +- .../forMill/src/test/java/MillTest.java | 15 +- .../01.experiments/forParser/build.gradle | 4 + .../test/java/GenerateAutomataParserTest.java | 12 +- .../src/test/java/HierAutomataTest.java | 26 +- .../src/test/java/SuperLexerTest.java | 18 +- .../src/test/java/SuperParserTest.java | 14 +- .../glex/src/test/java/GlexTest.java | 41 +- .../glex/src/test/java/HookTest.java | 74 +- monticore-test/01.experiments/hooks/ReadMe.md | 6 +- .../01.experiments/hooks/build.gradle | 40 +- .../src/productTest/java/PingPongTest.java | 36 +- .../src/test/java/automata/HooksToolTest.java | 20 +- .../ColoredGraphSTCompleteTypes.java | 4 +- .../src/test/java/ColoredGraphToolTest.java | 23 +- .../SimpleEquationsInterpreterTest.java | 48 + .../src/test/java/LexicalModesParseTest.java | 29 +- .../test/java/automata/AutomataParseTest.java | 21 +- .../test/java/automata/AutomataToolTest.java | 31 +- .../automata/TransitionSourceExistsTest.java | 45 +- .../de/monticore/TestPrettyPrinters.mc4 | 33 + .../prettyprint/KeywordAddingTest.java | 14 +- .../prettyprint/KeywordReplacingTest.java | 30 +- .../de/monticore/prettyprint/PPTestClass.java | 10 +- .../prettyprint/PrettyPrinterMillTest.java | 30 +- .../SuperTestPrettyPrinterTest.java | 16 +- .../prettyprint/TestPrettyPrinterTest.java | 212 ++- .../01.experiments/runtimeOnly/build.gradle | 11 + .../runtimeOnly/src/main/grammars/a/b/XY.mc4 | 13 + .../src/test/java/CheckScannerlessTest.java | 129 +- .../src/test/java/sm2/SM2ToolTest.java | 27 +- .../src/test/java/CheckSpaceOnOffTest.java | 82 +- .../src/test/java/SomeTest.java | 112 +- .../src/test/java/ParserTest.java | 23 +- .../src/test/java/SymTabTest.java | 26 +- .../src/test/java/BasicJavaToolTest.java | 32 +- .../src/test/java/CDAndAutTest.java | 20 +- .../src/test/java/CDAutTest.java | 36 +- .../src/test/java/STRulesToolTest.java | 16 +- .../01.experiments/tagging/build.gradle | 9 +- .../tagging/src/test/java/GrammarTagTest.java | 38 +- .../tagging/src/test/java/TagTest.java | 61 +- .../src/withGen/java/AutomataSchemaTest.java | 73 +- .../tagging/src/withGen/java/CDTest.java | 25 +- .../java/FQNEnhancedAutomataSchemaTest.java | 32 +- .../src/withGen/java/FQNInheritedTagTest.java | 63 +- .../tagging/src/withGen/java/FQNTagTest.java | 59 +- .../withGen/java/InvalidTagSchemaTest.java | 18 +- .../withGen/java/NotQuiteAutomataTest.java | 25 +- .../java/TagSchemaSerializationTest.java | 20 +- .../01.experiments/templates/ReadMe.md | 6 +- .../01.experiments/templates/build.gradle | 39 +- .../src/main/java/automata/TemplatesTool.java | 8 +- .../src/productTest/java/PingPongTest.java | 21 +- .../src/test/java/automata/GeneratorTest.java | 18 +- .../src/test/java/AutomataToolTest.java | 42 +- monticore-test/02.experiments/build.gradle | 8 +- .../configTemplate/build.gradle | 2 +- .../src/test/java/CustomTemplateTest.java | 18 +- .../test/java/GetDispatcherFromMillTest.java | 5 +- .../src/test/java/AutomataParseTest.java | 14 +- .../src/test/java/AutomataToolTest.java | 13 +- .../parser/src/main/grammars/QuoteTest.mc4 | 12 + .../parser/src/test/java/ParseErrorTest.java | 8 +- .../parser/src/test/java/QuoteTest.java | 64 + .../de/monticore/simplecd/CoCoHelper.java | 4 +- .../de/monticore/simplecd/ResolvingTest.java | 31 +- .../scopes/src/test/java/GlobalScopeTest.java | 5 +- .../traverser/src/test/java/TreesTest.java | 23 +- .../typecheck/src/test/java/MyLangTest.java | 24 +- .../src/test/java/UnknownScopeDeSerTests.java | 19 +- .../test/java/automata/AutomatonToolTest.java | 2 +- monticore-test/it/build.gradle | 8 +- .../mc/feature/scopes/ScopeInheritance.mc4 | 43 + .../mc/examples/automaton/TestAutomaton.java | 15 +- .../mc/examples/coord/TestCoordinates.java | 109 +- .../test/java/mc/examples/lwc/TestEDL.java | 48 +- .../test/java/mc/examples/lwc/TestODL.java | 46 +- .../test/java/mc/feature/abc/EmbedTest.java | 22 +- .../abstractgrammar/AbstractGrammarTest.java | 22 +- .../abstractprod/AbstractProdTest.java | 22 +- .../feature/addkeywords/AddKeywordsTest.java | 41 +- .../src/test/java/mc/feature/ast/ASTTest.java | 24 +- .../feature/ast/ParserForInterfaceTest.java | 10 +- .../test/java/mc/feature/ast/ParserTest.java | 54 +- .../mc/feature/astident/TestASTIdent.java | 14 +- .../mc/feature/astlist/CollectionTest.java | 71 +- .../java/mc/feature/astlist/TestLists.java | 10 +- .../aststring/ASTStringParserTest.java | 37 +- .../automaton/SubclassParsingTest.java | 12 +- .../classgenwithingrammar/ParserTest.java | 25 +- .../feature/cocochecker/CoCoCheckerTest.java | 19 +- .../java/mc/feature/comments/CommentTest.java | 40 +- .../mc/feature/comments/CommentTypesTest.java | 26 +- .../mc/feature/comments/CommentsTest.java | 22 +- .../feature/compilationunit/ParserTest.java | 22 +- .../ConstantsShortFormTest.java | 14 +- .../deepclone/DeepCloneNotEqualTest.java | 257 ++-- .../feature/deepclone/NoDoubleAddingTest.java | 17 +- .../java/mc/feature/embedding/EmbedTest.java | 24 +- .../mc/feature/embedding/EmbeddingTest.java | 15 +- .../feature/expression/Expression3Test.java | 73 +- .../feature/expression/Expression4Test.java | 73 +- .../feature/expression/Expression5Test.java | 31 +- .../mc/feature/expression/ExpressionTest.java | 75 +- .../filefindertest/FileFinderTest.java | 33 +- .../followoption/FollowOptionTest.java | 18 +- .../grammarinherit/TestGrammarInherit.java | 9 +- .../java/mc/feature/hwc/BuildersTest.java | 19 +- .../TestInheritedBuilder.java | 8 +- .../inheritence/CloneInheritenceTest.java | 5 +- .../feature/inheritence/InheritenceTest.java | 46 +- .../mc/feature/interfaces/InterfacesTest.java | 12 +- .../feature/interfaces/ListInterfaceTest.java | 49 +- .../interfaces/MethodInterfaceTest.java | 53 +- .../interfaces/OptionalInterfacesTest.java | 45 +- .../java/mc/feature/javasql/JavaSQLTest.java | 11 +- .../java/mc/feature/keyrule/KeyRuleTest.java | 29 +- .../feature/lexerformat/KleenePlusTest.java | 109 +- .../lexerformat/LexRulesOrderTest.java | 11 +- .../mc/feature/lexerformat/LexerTest.java | 64 +- .../embedding/AutomatonOverallParserTest.java | 13 +- .../mc/feature/listrule/ListRuleTest.java | 42 +- .../test/java/mc/feature/mcenum/EnumTest.java | 99 +- .../StatechartResolvingTest.java | 23 +- .../feature/options/MultipleOptionTest.java | 14 +- .../ComponentGrammarParserInfoTest.java | 2 +- .../mc/feature/parserinfo/ParserInfoTest.java | 34 +- .../replacekeyword/ReplaceRuleTest.java | 25 +- .../mc/feature/scoperules/ScoperuleTest.java | 33 +- .../feature/scopes/ScopeInheritanceTest.java | 147 ++ .../java/mc/feature/scopes/ScopesTest.java | 22 +- .../SemPredWithInterfaceParserTest.java | 20 +- .../ExpressionSourcePositionsTest.java | 21 +- .../feature/symbolrules/SymbolruleTest.java | 157 +- .../symboltable/AutomatonWithSTInfo1Test.java | 9 +- .../symboltable/AutomatonWithSTInfo2Test.java | 11 +- .../symboltable/AutomatonWithSTInfo3Test.java | 12 +- .../symboltable/AutomatonWithSTInfo4Test.java | 11 +- .../symboltable/AutomatonWithSTInfo5Test.java | 13 +- .../symboltable/AutomatonWithSTInfo6Test.java | 13 +- .../java/mc/feature/visitor/VisitorTest.java | 26 +- .../inheritance/InheritanceVisitorTest.java | 9 +- .../visitor/inheritance/VisitorTest.java | 15 +- .../delegator/ComposeSimpleTest.java | 27 +- .../test/java/mc/feature/wiki/WikiTest.java | 10 +- .../test/java/mc/grammar/MCParserTest.java | 9 +- .../test/java/mc/tfcs/ast/TestVisitor.java | 5 +- .../feature/scopes/ScopeInheritanceModel.st | 10 + .../mc/emf/east/GeneratedAstClassesTest.java | 16 +- .../java/mc/emf/emethods/EGeterSeterTest.java | 8 +- .../emf/emethods/FeatureIDConversionTest.java | 13 +- .../mc/emf/eobjects/CreateEObjectsTest.java | 11 +- .../test_emf/java/mc/emf/epackage/IDTest.java | 4 +- .../java/mc/emf/epackage/MetaObjectTest.java | 10 +- .../java/mc/emf/etools/EcoreUtilTest.java | 17 +- .../java/mc/emf/etools/EmfDiffTest.java | 15 +- .../java/mc/emf/generator/ASTNodeTest.java | 8 +- .../mc/emf/generator/GrammarDiffsTest.java | 19 +- .../mc/emf/generator/GrammarSerDeserTest.java | 22 +- .../java/mc/emf/modularity/ExternalTest.java | 10 +- .../ASTInstanceSerialDeserialTest.java | 23 +- .../ASTModelSerialDeserialTest.java | 8 +- .../monticore-grammar-it/build.gradle | 16 +- .../test/java/mc/typechecktest/CoCoTests.java | 35 +- .../java/mc/typescalculator/CD2EHelper.java | 10 +- .../CombineExpressionsWithLiteralsTest.java | 39 +- ...ynthesizeSymTypeFromMyOwnLanguageTest.java | 13 +- monticore-test/montitrans/build.gradle | 48 +- .../montitrans/test-dstl-gen/build.gradle | 174 +-- .../mc/testcases/odname/ODNameBasis.mc4 | 8 + .../mc/testcases/odname/ODNameReport.mc4 | 17 + .../rule/_cocos/NoOptOnRHSCoCoTest.java | 11 +- .../rule/_cocos/NoOptWithinNotCoCoTest.java | 12 +- ...AutomatonTransformationRuleParserTest.java | 33 +- ...RuleState_PatternMCConcreteParserTest.java | 12 +- ...ansistion_PatternMCConcreteParserTest.java | 10 +- ...ionRuleTransitionMCConcreteParserTest.java | 10 +- ...ition_ReplacementMCConcreteParserTest.java | 10 +- .../translation/AutomatonRule2ODToolTest.java | 4 +- .../ExpressionDSLTRParseTest.java | 33 +- .../TFLanguageOverrideTest.java | 13 +- ...ertiesThanAutomatonRule2ODVisitorTest.java | 13 +- .../mc/tfcs/TransformationRuleParserTest.java | 13 +- .../test-generated-dstls/build.gradle | 50 +- .../mc/testcases/statechart/Statechart.mc4 | 90 -- .../java/expressiondsl/ExpressionDSLTest.java | 37 +- .../social/DeleteAllEntriesFromUserTest.java | 10 +- .../Test01_ParsePedestrianLightTest.java | 12 +- .../java/trafo/Test02_EliminateDoTest.java | 28 +- .../java/trafo/Test08_InsertStatesTest.java | 12 +- .../java/trafo/Test09_CopyTransitionTest.java | 12 +- .../trafo/Test10_DeleteTransitionTest.java | 12 +- .../java/trafo/Test11_SetInitialTest.java | 12 +- .../montitrans/test-odrules/build.gradle | 57 +- .../de/monticore/tf/AtMostOneStateTest.java | 9 +- .../monticore/tf/AtMostOneSubstateTest.java | 9 +- .../de/monticore/tf/ChangeFixNameTest.java | 11 +- .../de/monticore/tf/ChangeMarkerTest.java | 13 +- .../tf/ConstraintAlongOptionalTest.java | 9 +- .../monticore/tf/ConstraintEmbeddingTest.java | 11 +- .../tf/ConstraintForOptionalTest.java | 9 +- .../tf/CopySubListDefInListTest.java | 12 +- .../java/de/monticore/tf/CopySubListTest.java | 13 +- .../de/monticore/tf/CopyTransitionsTest.java | 11 +- .../de/monticore/tf/CreateInOptionalTest.java | 10 +- .../java/de/monticore/tf/CreateStateTest.java | 11 +- .../monticore/tf/DeleteOptionalStateTest.java | 9 +- .../de/monticore/tf/DeleteStateListTest.java | 14 +- .../java/de/monticore/tf/DeleteStateTest.java | 14 +- .../tf/DeleteSubListDefInListTest.java | 12 +- .../de/monticore/tf/DeleteSubListTest.java | 11 +- .../monticore/tf/DeleteTransitionsTest.java | 12 +- .../java/de/monticore/tf/DoBlockTest.java | 11 +- .../de/monticore/tf/ExpandInitialTest.java | 12 +- .../de/monticore/tf/FlattenStateTest.java | 9 +- ...lattenStateWithAtMostTwoSubstatesTest.java | 13 +- .../monticore/tf/FoldListStateRuleTest.java | 10 +- .../de/monticore/tf/FoldStateRuleTest.java | 12 +- .../tf/ForwardTransitionRuleTest.java | 11 +- .../monticore/tf/ListPrototypeCopyTest.java | 13 +- .../de/monticore/tf/ListPrototypeTest.java | 15 +- .../java/de/monticore/tf/ListStateTest.java | 12 +- .../java/de/monticore/tf/ListThenNotTest.java | 12 +- .../de/monticore/tf/ListWithAssignTest.java | 12 +- .../monticore/tf/ListWithConstraintTest.java | 11 +- .../tf/MoveSubListDefInListTest.java | 13 +- .../java/de/monticore/tf/MoveSubListTest.java | 12 +- .../java/de/monticore/tf/MoveSubTest.java | 11 +- .../de/monticore/tf/MoveSubstateTest.java | 12 +- .../de/monticore/tf/MoveTransitionsTest.java | 11 +- .../de/monticore/tf/NonEmptyListTest.java | 9 +- .../java/de/monticore/tf/NotInListTest.java | 9 +- .../java/de/monticore/tf/NotStateTest.java | 9 +- .../tf/NotStateWithConditionsTest.java | 9 +- .../java/de/monticore/tf/OptInListTest.java | 9 +- .../tf/OptStateWithOptSubstateTest.java | 9 +- .../tf/OptionalChangeFixNameTest.java | 10 +- .../de/monticore/tf/OptionalListTest.java | 10 +- .../tf/SetInitialToFalseInListTest.java | 12 +- .../monticore/tf/SetInitialToFalseTest.java | 10 +- .../0001-use-next-snapshot.patch | 57 + .../PreparingTheNextRelease.md | 44 + prepare-next-release/applyPatches.sh | 34 + prepare-next-release/buildPatches.sh | 21 + settings.gradle | 29 +- 1127 files changed, 26935 insertions(+), 15508 deletions(-) create mode 100644 .github/workflows/deploy_pages.yml delete mode 100644 .github/workflows/prepare_pages.yml create mode 100644 docs/BestPractices-Testing.md create mode 100644 docs/JavaDocs.md create mode 100644 docs/README.md delete mode 100644 docs/docs/MC_Symp_Banner.png rename docs/{docs => img}/Agile-use-of-Models-for-Coding-and-Testing--Usage-of-UML-Diagrams.png (100%) rename docs/{docs => img}/Bild6.png (100%) rename docs/{docs => img}/Eclipse.png (100%) rename docs/{docs => img}/GenAutomataAST.png (100%) rename docs/{docs => img}/GenAutomataParser.png (100%) rename docs/{docs => img}/GenAutomataScopes.png (100%) rename docs/{docs => img}/GenAutomataSymbols.png (100%) rename docs/{docs => img}/GenAutomataVisitors.png (100%) rename docs/{docs => img}/IntelliJ-IDEA.png (100%) create mode 100644 docs/img/MC_Symp_Banner.png rename docs/{docs => img}/MontiCore--Selected-Languages.png (100%) rename docs/{ => img}/MontiCoreHandbook2021.gif (100%) rename docs/{docs => img}/Notational-Conventions.png (100%) rename {img => docs/img}/favicon.ico (100%) rename mc-logo.png => docs/img/mc-logo.png (100%) rename docs/{docs => img}/small_bulb.png (100%) create mode 100644 docs/overrides/extensions/docsnippet.py create mode 100644 docs/overrides/landingpage.html create mode 100644 monticore-generator/gradle-plugin/build.gradle rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/IncChecker.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/MCMillBuildService.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/MCPlugin.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/MCTask.java (98%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/MCTaskError.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/MontiTransExec.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/GradleTaskStatistic.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/MCGeneratorBasePlugin.java (94%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/MCGeneratorExtension.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/MCGeneratorPlugin.java (95%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/MCGeneratorWithTRPlugin.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/StatisticData.java (96%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/StatisticListener.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/dependencies/MCDependenciesPlugin.java (98%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/dependencies/MCPublishingPlugin.java (79%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/dependencies/MCSourceSets.java (100%) create mode 100644 monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCToolDependenciesPlugin.java rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/gen/MCGenTask.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/gen/MCToolAction.java (97%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/sources/MCGrammarsSourceDirectorySet.java (100%) rename monticore-generator/{ => gradle-plugin}/src/main/java/de/monticore/gradle/sources/MCSourcesPlugin.java (100%) rename monticore-generator/{ => gradle-plugin}/src/test/java/de/monticore/IncCheckerTest.java (61%) rename monticore-generator/{ => gradle-plugin}/src/test/java/de/monticore/gradle/MCGenPluginTest.java (51%) rename monticore-generator/src/main/java/de/monticore/codegen/prettyprint/{NonTermAccessorVisitor.java => NonTermAccessorVisitorHandler.java} (67%) create mode 100644 monticore-generator/src/main/java/de/monticore/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsPhasedSTCFix.java create mode 100644 monticore-generator/src/main/resources/_symboltable/symbol/Equals.ftl create mode 100644 monticore-generator/src/main/resources/_symboltable/symbolsurrogate/Equals.ftl create mode 100644 monticore-generator/src/main/resources/_symboltable/symbolsurrogate/GetSpannedScopeSymbolSurrogate.ftl create mode 100644 monticore-generator/src/main/resources/_symboltable/symbolsurrogate/GetThis.ftl create mode 100644 monticore-generator/src/main/resources/_symboltable/symbolsurrogate/SetSpannedScopeSymbolSurrogate.ftl create mode 100644 monticore-generator/src/test/java/de/monticore/runtime/junit/MCAssertions.java create mode 100644 monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeIdAsConstructorCTTIVisitor.java create mode 100644 monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/types3/ExpressionBasisTypeIdAsConstructorCTTIVisitor.java create mode 100644 monticore-grammar/src/main/java/de/monticore/expressions/tupleexpressions/types3/TupleExpressionsCTTIVisitor.java create mode 100644 monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/_visitor/MCJavaLiteralsInterpreter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_cocos/VarDeclarationNameAlreadyDefinedInScope.java create mode 100644 monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentType2TypeSymbolAdapter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolBuilder.java create mode 100644 monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolSurrogate.java create mode 100644 monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/Port2VariableAdapter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/Subcomponent2VariableAdapter.java create mode 100644 monticore-grammar/src/main/java/de/monticore/symbols/oosymbols/types3/OOSymbolsSymTypeRelations.java create mode 100644 monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/BoundComparator.java create mode 100644 monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/ConstraintComparator.java create mode 100644 monticore-grammar/src/test/grammars/de/monticore/types/ComponentSymbolsWithMCBasicTypesTest.mc4 create mode 100644 monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/CommonExpressionsBuilderTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/statements/cocos/VarDeclarationNameAlreadyDefinedInScopeTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolSurrogateTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolTest.java delete mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/CompKindOfComponentTypeTest.java delete mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/CompKindOfGenericComponentTypeTest.java delete mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentSymbolDeSerTest.java delete mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentSymbolTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentType2TypeSymbolAdapterTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolBuilderTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolDeSerTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolSurrogateTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/Port2VariableAdapterTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/Subcomponent2VariableAdapterTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/types3/OOSymbolsSymTypeRelationsTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/types/check/CompKindOfComponentTypeTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/types/check/CompKindOfGenericComponentTypeTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/types/check/FullSynthesizeCompKindFromMCBasicTypesTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeComponentFromMCBasicTypesTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeComponentFromMCSimpleGenericTypesTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/types3/SymTypeExpressionComparatorTest.java create mode 100644 monticore-grammar/src/test/java/de/monticore/types3/util/SymTypeExpressionGenerator.java create mode 100644 monticore-grammar/src/test/resources/de/monticore/grammar/cocos/invalid/A4099/A4099.mc4 create mode 100644 monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithField.json create mode 100644 monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithInner.json rename monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/{WithParent.json => WithRefinement.json} (76%) create mode 100644 monticore-grammar/src/testFixtures/java/de/monticore/types3/util/DefsTypesForTests.java create mode 100644 monticore-grammar/src/testFixtures/java/de/monticore/types3/util/DefsVariablesForTests.java create mode 100644 monticore-runtime/src/main/java/de/monticore/tf/runtime/FastLookupList.java create mode 100644 monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversal.java create mode 100644 monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversalFactory.java create mode 100644 monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversalVisitor.java create mode 100644 monticore-runtime/src/main/resources/de/monticore/tf/odrules/FastLookupList.ftl create mode 100644 monticore-runtime/src/main/resources/de/monticore/tf/odrules/OptimizeSearchPlan.ftl create mode 100644 monticore-runtime/src/main/resources/de/monticore/tf/odrules/ResetOptionals.ftl create mode 100644 monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/AbstractMCTest.java create mode 100644 monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java create mode 100644 monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCLanguageTestExtension.java create mode 100644 monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/PrettyPrinterTester.java create mode 100644 monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/TestWithMCLanguage.java create mode 100644 monticore-test/01.experiments/builderAtm/src/test/java/G1TerminalBuildersTest.java create mode 100644 monticore-test/01.experiments/composition/src/main/java/composition/MyInterface.java create mode 100644 monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java create mode 100644 monticore-test/01.experiments/runtimeOnly/build.gradle create mode 100644 monticore-test/01.experiments/runtimeOnly/src/main/grammars/a/b/XY.mc4 create mode 100644 monticore-test/02.experiments/parser/src/main/grammars/QuoteTest.mc4 create mode 100644 monticore-test/02.experiments/parser/src/test/java/QuoteTest.java create mode 100644 monticore-test/it/src/main/grammars/mc/feature/scopes/ScopeInheritance.mc4 create mode 100644 monticore-test/it/src/test/java/mc/feature/scopes/ScopeInheritanceTest.java create mode 100644 monticore-test/it/src/test/resources/mc/feature/scopes/ScopeInheritanceModel.st create mode 100644 monticore-test/montitrans/test-dstl-gen/src/main/grammars/mc/testcases/odname/ODNameBasis.mc4 create mode 100644 monticore-test/montitrans/test-dstl-gen/src/main/grammars/mc/testcases/odname/ODNameReport.mc4 delete mode 100644 monticore-test/montitrans/test-generated-dstls/src/main/grammars/mc/testcases/statechart/Statechart.mc4 create mode 100644 prepare-next-release/0001-use-next-snapshot.patch create mode 100644 prepare-next-release/PreparingTheNextRelease.md create mode 100644 prepare-next-release/applyPatches.sh create mode 100644 prepare-next-release/buildPatches.sh diff --git a/.gitattributes b/.gitattributes index bf50152bce..2ec3ba24dc 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,5 @@ # All files (*) that git considers to be text (auto) # will have normalized (LF) line-endings in the repository. -* text=auto eol=lf +* text=auto eol=lf +*.jar -text +*.png -text diff --git a/.github/workflows/deploy_pages.yml b/.github/workflows/deploy_pages.yml new file mode 100644 index 0000000000..2ed54c7ee0 --- /dev/null +++ b/.github/workflows/deploy_pages.yml @@ -0,0 +1,77 @@ +# (c) https://github.com/MontiCore/monticore +name: Build MKDocs + + +on: + push: # run this test pipeline on every push (if markdown and/or the docs directory was changed) + paths: + - "**.md" + - "docs/**" + pull_request: # and pull request (Note: We can skip pull request events IFF the PR is not done from a fork) + paths: + - "**.md" + - "docs/**" + workflow_run: # and when the javadocs have been updated + workflows: [ "Gradle Deploy Snapshot" ] + types: + - completed + + +permissions: + contents: read # This action may run somewhat unsafe code + + +jobs: + build_pages: + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/dev' + steps: + - name: Checkout project sources + uses: actions/checkout@v4 + - name: Download Javadoc artifact + uses: dawidd6/action-download-artifact@ac66b43f0e6a346234dd65d4d0c8fbb31cb316e5 + continue-on-error: true # the javadocs are sometimes not present (e.g., when the artifact is expired) + with: + workflow: deploy_snapshot_mc.yml + workflow_conclusion: success + branch: dev + name: javadoc + - name: Setup Python + uses: actions/setup-python@v4 + with: + python-version: '3.9' + - name: Install python packages + env: + GITLAB_TOKEN: ${{ secrets.GITLAB_TOKEN }} + run: | + python -m pip install --upgrade pip + pip install mkdocs mkdocs-material + git clone https://monticore:$GITLAB_TOKEN@git.rwth-aachen.de/se/infrastructure/monticore-pygments-highlighting.git + pip install -r ./monticore-pygments-highlighting/requirements.txt + pip install ./monticore-pygments-highlighting + - name: Preprocess the docs + run: sh docs/scripts/preprocessing.sh inplace + - name: Build the docs into a site directory + run: mkdocs build --verbose --clean --strict + - name: Upload static files as artifact + id: deployment + uses: actions/upload-pages-artifact@v3 # or specific "vX.X.X" version tag for this action + with: + path: site/ + + deploy: + # Deploy to the github-pages environment + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/dev' # only for the dev branch! + needs: build_pages + # Grant GITHUB_TOKEN the permissions required to make a Pages deployment + permissions: + pages: write # to deploy to Pages + id-token: write # to verify the deployment originates from an appropriate source + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/deploy_release_mc.yml b/.github/workflows/deploy_release_mc.yml index 24fe2e3d96..b515adf84f 100644 --- a/.github/workflows/deploy_release_mc.yml +++ b/.github/workflows/deploy_release_mc.yml @@ -11,7 +11,7 @@ permissions: packages: write env: - GRADLE_VERSION: 7.4 # Gradle version used + GRADLE_VERSION: 7.6 # Gradle version used GRADLE_CLI_OPTS: "-Pci" # CLI option passed to Gradle jobs: diff --git a/.github/workflows/deploy_snapshot_mc.yml b/.github/workflows/deploy_snapshot_mc.yml index db4ed688a5..c07e046983 100644 --- a/.github/workflows/deploy_snapshot_mc.yml +++ b/.github/workflows/deploy_snapshot_mc.yml @@ -18,7 +18,7 @@ permissions: packages: write env: - GRADLE_VERSION: 7.4 # Gradle version used + GRADLE_VERSION: 7.6 # Gradle version used GRADLE_CLI_OPTS: "-Pci" # CLI option passed to Gradle jobs: @@ -36,6 +36,16 @@ jobs: arguments: deployMC ${{env.GRADLE_CLI_OPTS}} -PmavenPassword=${{secrets.SE_NEXUS_PASSWORD}} -PmavenUser=${{secrets.SE_NEXUS_USER}} -PgenEMF=true -PgenTR=true -PgenTagging=true env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Upload Javadoc + uses: actions/upload-artifact@v4 + # uploads the Javadocs to be used + with: + name: javadoc + path: | + monticore-runtime/target/docs/javadoc/ + monticore-runtime/target/docs/testFixturesJavadoc/ + monticore-grammar/target/docs/javadoc/ + monticore-grammar/target/docs/testFixturesJavadoc/ # Trigger GitHub downstream projects (without reporting the pipeline result) trigger-github-downstream: diff --git a/.github/workflows/gradle_mc.yml b/.github/workflows/gradle_mc.yml index ad6879b05a..d88185a8da 100644 --- a/.github/workflows/gradle_mc.yml +++ b/.github/workflows/gradle_mc.yml @@ -9,16 +9,16 @@ concurrency: # run this test workflow only once per "branch" on: push: # run this test pipeline on every push paths-ignore: - - "*.md" + - "**.md" pull_request: # and pull request (Note: We can skip pull request events IFF the PR is not done from a fork) paths-ignore: - - "*.md" + - "**.md" repository_dispatch: # and on request of upstream projects types: [ trigger_after_upstream_deploy ] env: - GRADLE_VERSION: 7.4 # Gradle version used + GRADLE_VERSION: 7.6 # Gradle version used GRADLE_CLI_OPTS: "-Pci --build-cache " # CLI option passed to Gradle GRADLE_BUILD_ACTION_CACHE_KEY_JOB: "test-cache-${{ github.head_ref }}.${{ github.sha }}" @@ -180,6 +180,29 @@ jobs: with: report_paths: '**/target/test-results/test/TEST-*.xml' + # Look ahead in time to check if this would break the next MC release + test-for-breaking-changes: + if: (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name ) && github.ref_name != github.event.repository.default_branch # do not run duplicate jobs on PRs or on dev branch + runs-on: ubuntu-latest + steps: + - name: Checkout project sources + uses: actions/checkout@v4 + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: ${{env.GRADLE_VERSION}} + - name: Setup git + run: git config --global user.email "ci@monticore.de" && git config --global user.name "ci" + - name: Apply patches to look into the future + run: sh ./prepare-next-release/applyPatches.sh + - name: Build a subset of the monticore project + run: gradle monticore-generator:build monticore-grammar:build monticore-test:check ${{env.GRADLE_CLI_OPTS}} + - name: Publish Test Report + uses: mikepenz/action-junit-report@a451de5ac1ff45e46508b6150cb4f51a287d0309 + if: always() # always run even if the previous step fails + with: + report_paths: '**/target/test-results/test/TEST-*.xml' + # Run the MontiVerse pipeline (tests this change on a suite of projects) trigger-montiverse: if: github.event_name == 'pull_request' # only run on PRs @@ -203,7 +226,6 @@ jobs: grep -riEno "\"(0x[0-9a-zA-Z]{3,})" --include="*.java" --exclude-dir="test" . | awk -F '\"' '{if($2 in x){if(x[$2]) print x[$2]; print $1substr($2,1);x[$2]=""} else x[$2]=$1substr($2,1)}' | awk -F ":" '{print "::warning file="$1",line="$2",title=ErrorCodeDuplicate::Duplicate error code "$3" (" $1 ":" $2 ")";}' - # TODO: FIX to specific version instead of @v3 # TODO: check-links diff --git a/.github/workflows/prepare_pages.yml b/.github/workflows/prepare_pages.yml deleted file mode 100644 index 17e37ed27e..0000000000 --- a/.github/workflows/prepare_pages.yml +++ /dev/null @@ -1,48 +0,0 @@ -# (c) https://github.com/MontiCore/monticore -name: Prepare And Deploy Pages - -# Preprocess the docs, build a site directory and push its contents to the gh-pages branch - -on: - push: - branches: - - dev - -jobs: - build: - runs-on: ubuntu-latest - env: - GITLAB_TOKEN: ${{ secrets.GITLAB_TOKEN }} - name: Build and Push - steps: - - name: Checkout repo - uses: actions/checkout@v3 - - - name: Setup Python - uses: actions/setup-python@v4 - with: - python-version: '3.9' - - - name: Install python packages - run: | - python -m pip install --upgrade pip - pip install mkdocs mkdocs-material - git clone https://monticore:$GITLAB_TOKEN@git.rwth-aachen.de/se/infrastructure/monticore-pygments-highlighting.git - pip install -r ./monticore-pygments-highlighting/requirements.txt - pip install ./monticore-pygments-highlighting - - - name: Preprocess the docs - run: sh docs/scripts/preprocessing.sh - - - name: Build the docs into a site directory - run: mkdocs build --verbose --clean --strict - - - name: Push - uses: s0/git-publish-subdir-action@develop - env: - REPO: self - BRANCH: gh-pages # The branch name where you want to push the assets - FOLDER: site # The directory where your assets are generated - SQUASH_HISTORY: true - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - MESSAGE: "Deploy contents of GitHub pages to gh-pages branch" # The commit message diff --git a/.gitignore b/.gitignore index e049ed742e..622c7cdae5 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,6 @@ build *.bak out target-emf/ -.DS_Store \ No newline at end of file +.DS_Store +#mkdocs local build +docs_wd/ \ No newline at end of file diff --git a/00.org/Explanations/CHANGELOG.md b/00.org/Explanations/CHANGELOG.md index 718ed3a4e5..d744d7ed72 100644 --- a/00.org/Explanations/CHANGELOG.md +++ b/00.org/Explanations/CHANGELOG.md @@ -2,6 +2,91 @@ # Release Notes +## MontiCore 7.8.0 +released: TBD + +### Additions: + +- Test Framework (#141, #159) +- Reproducible Gradle tasks (#139, #96) +- Publish reports of a grammar (#94, #102) +- FieldSymbols have isEnumConstant-field (#176) +- Stream symbol library (#163) +- TypeCheck: + - OOSymbolsSymTypeRelations (#176) + - Stream support (#93) + - Passthrough expression CTTI (#110) + - CompKind sourceNode (#124, #127) +- Interpreter: + - Add MCJavaLiteralsInterpreter (#175) +- Documentation: + - Improve generated JavaDocs (#164) + - Host JavaDocs online (#178) +- StringLiteral Linebreak CoCo (#106) +- Stereotype Symbols (#132) + +### Changes: + +- Mills: + - don't override the logger during init (#89, #100) + - Mills now have to be explicitly initialized (#141, #161) + - do not have one delegate per partial grammar (#91) + - cleans the global scope during init (#101) +- Gradle Compability (#160, #147) +- Updated FreeMarker to 2.3.34 (#130) +- Use \`src/main/configtemplates\` instead of \`src/main/resources\` as the template path (#108) +- The MavenPublication type must be now specified explicitly (#182) +- TypeCheck: + - String conversions are more strict (#118) +- SymbolDeSer: + - replace hand-written DeSers with generated ones (#90, #115) + - Add scope param to CompKindDeserialization (#103) +- Allow any expressions in stereotype values (#87) + +### Removals: + +- continue to deprecate TypeCheck 1 (#83, #166, #170, #177) + +### Fixes: + +- Handling of filepaths with spaces of the FileReaderWriter (#140) +- Escaping of quotation symbols ' and " in implicit tokens (#165) +- (generated) PrettyPrinter: + - properly respecting optionals in alts (#179) + - properly handle cascading conditions (#150) +- Surrogates - fix NPE (#117) +- Extending NonTerminals: + - astextends support for non DSL-classes (#183, #188) +- TypeCheck + - partial replacement TC1 with TC3 (#85, #169, #172) + - add null checks (#189) + - generic constructor fixes (#186, #187) + - fix resolving (#154) + - Fix ilvaluerelations package (#152) + - LuB of numbers (#146) + - RegEx types for string literals (#86) + - fix RegEx-String SubTyping (#92) + - More consistent static delegates (#88) + - Variable selection depending on scopes (#142) + - Minor fixes (#121) +- MontiTrans: + - fix replacements within nested opts (#145) + - DSTL-Generation: + - properly Override annotation (#185) + - handling of empty productions (#184) +- OCLExpressions.mc4 make ASCII-128 compatible (#151) +- Performance: + - of the type dispatcher class loading (#122) + - of the Groovy Engine (#95) + - of the Templating Engine (#128) +- Parser: + - Single Quotation Mark in Terminals (#105) + - LSP support for inlined interfaces (#112) +- Transitive Mill Delegation (#107) +- Escape Stereo-Value content (#116, #125) +- Incorrect AST-present, overridden Terminals (#167, #168) + + ## MontiCore 7.7.0 released: 20.01.2025 @@ -463,7 +548,7 @@ released: 11.11.2020 ### Changes * MontiCore now uses Gradle as build tool - * some tasks have been introduced for the comfortable control of frequent activities, e.g., `buildMC`, `assembleMC` that can be found in the [`build.gradle`](https://github.com/MontiCore/monticore/blob/opendev/build.gradle) + * some tasks have been introduced for the comfortable control of frequent activities, e.g., `buildMC`, `assembleMC` that can be found in the root projects build.gradle * relocated the EMF related subprojects: * `monticore-emf-grammar` to `monticore-grammar-emf` * `monticore-emf-runtime` to `monticore-runtime-emf` @@ -734,9 +819,9 @@ released: 07.05.2020 * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../../monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/00.org/Explanations/FAQ.md b/00.org/Explanations/FAQ.md index 9b3ca30fdf..61aa0f8f9b 100644 --- a/00.org/Explanations/FAQ.md +++ b/00.org/Explanations/FAQ.md @@ -39,9 +39,9 @@ Remember that all Maven modules are independent units. By default, they are not * [MontiCore project](../../README.md) - MontiCore * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../../monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/00.org/Explanations/StatusOfGrammars.md b/00.org/Explanations/StatusOfGrammars.md index e626acfdf6..6c7cb8ba69 100644 --- a/00.org/Explanations/StatusOfGrammars.md +++ b/00.org/Explanations/StatusOfGrammars.md @@ -63,9 +63,9 @@ A comment of the following form within the grammar defines this status: * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../../monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/README.md b/README.md index 845f226b43..79d8297f90 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,16 @@ + +
-
+
MontiCore logo
# MontiCore - Language Workbench and Development Tool Framework - -**NEWS**: - - -* ISW Stuttgart and RWTH Aachen organize the third **[MontiCore Symposium 2025](docs/MontiCoreSymposium.md)** March 23 - March 26 in Gemünd, Germany - * Deadline for submission of papers or abstracts: January, 10th. - ---- ---> [MontiCore](https://www.monticore.de) is a language workbench for the efficient development of domain-specific languages (DSLs). It processes an extended @@ -52,24 +42,26 @@ grammar languages are comfortable to use. To show a little of MontiCore's capabilities, the following (incomplete) grammar might help: - grammar MyStatemachine extends Automata, // MontiCore grammar - MCBasicTypes, SetExpressions, MCCommonLiterals { - start Automaton; - - // overriding a nonterminal (to add optional conditions): - Transition = from:Name@State ":" Expression? "->" to:Name@State; +```monticore title="MyStatemachine.mc4" +grammar MyStatemachine extends Automata, // MontiCore grammar + MCBasicTypes, SetExpressions, MCCommonLiterals { + start Automaton; - // add new variants of expressions - LogicalNotExpr implements Expression = "!" Expression; + // overriding a nonterminal (to add optional conditions): + Transition = from:Name@State ":" Expression? "->" to:Name@State; - XorExpr implements Expression = - left:Expression "xor" right:Expression; + // add new variants of expressions + LogicalNotExpr implements Expression = "!" Expression; - scope LetExpr implements Expression = - "let" (VarDeclaration || ",")+ "in" Expression; + XorExpr implements Expression = + left:Expression "xor" right:Expression; - symbol VarDeclaration = MCType? Name "=" Expression ; - } + scope LetExpr implements Expression = + "let" (VarDeclaration || ",")+ "in" Expression; + + symbol VarDeclaration = MCType? Name "=" Expression ; +} +``` The grammar language has a variety of mechanisms to define new nonterminals using constants `"!"`, @@ -95,10 +87,12 @@ frontend and a larger part of the backend of a statemachine processor. We now can write statemachines like: - statemachine PingPong { // MyStatemachine - state Ping, Pong; - Ping : (speed > 14km/h && !missedBall) -> Pong - } +```statemachine title="PingPong.sm" +statemachine PingPong { // MyStatemachine + state Ping, Pong; + Ping : (speed > 14km/h && !missedBall) -> Pong +} +``` MontiCore provides versions of expressions that use SI Units like `240km/h` or `14.2 m/s^2`, but also Java @@ -119,16 +113,8 @@ Please also note that `PlusExpr` is mutually left-recursive. ## Quick Start -``` -$ cd /usr/local -$ wget www.monticore.de/download/aut.tar.gz -$ tar -xf aut.tar.gz -$ cd mc-workspace -$ wget www.monticore.de/download/monticore-cli.jar -$ java -jar monticore-cli.jar -g Automata.mc4 -hcp hwc/ -mp monticore-cli.jar -$ javac -cp monticore-cli.jar -sourcepath "src/;out/;hwc/" src/automata/AutomataTool.java -$ java -cp "src/;out/;hwc/;monticore-cli.jar" automata.AutomataTool example/PingPong.aut PingPong.autsym -``` +You can follow the [Getting Started](https://monticore.github.io/monticore/docs/GettingStarted/) +or follow a more [in-depth tutorial](https://github.com/MontiCore/tutorial/). ## MontiCore has a Relaxed 3-Level License @@ -192,15 +178,16 @@ For details see [Licenses](00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md). ## Further Information * see also [**MontiCore handbook**](https://www.monticore.de/handbook.pdf) -* [MontiCore Reference Languages](https://monticore.github.io/monticore/docs/DevelopedLanguages/) - Languages Built Using MontiCore -* [Build MontiCore](https://monticore.github.io/monticore/docs/BuildMontiCore/) - How to Build MontiCore -* [Getting Started](https://monticore.github.io/monticore/docs/GettingStarted/) - How to start using MontiCore +* [MontiCore Reference Languages](docs/DevelopedLanguages.md) - Languages Built Using MontiCore +* [Build MontiCore](docs/BuildMontiCore.md) - How to Build MontiCore +* [Getting Started](docs/GettingStarted.md) - How to Start Using MontiCore * [Changelog](00.org/Explanations/CHANGELOG.md) - Release Notes -* [FAQ](00.org/Explanations/FAQ.md) - FAQ +* [JavaDocs](docs/JavaDocs.md) - JavaDocs +* [FAQ](00.org/Explanations/FAQ.md) - FAQ * [Licenses](00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) - MontiCore 3-Level License * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) -* [**List of languages**](https://monticore.github.io/monticore/docs/Languages/) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://monticore.github.io/monticore/docs/BestPractices/) +* [**List of languages**](docs/Languages.md) +* [**MontiCore Core Grammar Library**](monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) diff --git a/build.gradle b/build.gradle index 8966047f98..991a256cde 100644 --- a/build.gradle +++ b/build.gradle @@ -8,7 +8,7 @@ plugins { id "io.github.themrmilchmann.ecj" version "0.2.0" apply false id "org.sonarqube" version "3.0" id "jacoco" - id 'org.barfuin.gradle.jacocolog' version '1.2.3' + id 'org.barfuin.gradle.jacocolog' version '3.1.0' } sonarqube { @@ -32,9 +32,9 @@ allprojects { mavenLocal() } maven { - credentials.username mavenUser - credentials.password mavenPassword - url repo + credentials.username = mavenUser + credentials.password = mavenPassword + url = repo } mavenCentral() } @@ -64,11 +64,11 @@ subprojects { useJUnitPlatform() testLogging { // controls whether test output is shown - showStandardStreams= ("false").equals(getProperty('showTestOutput'))? false : true - showExceptions true - showCauses true - showStackTraces true - exceptionFormat TestExceptionFormat.FULL + showStandardStreams = ("false").equals(getProperty('showTestOutput'))? false : true + showExceptions = true + showCauses = true + showStackTraces = true + exceptionFormat = TestExceptionFormat.FULL info { events TestLogEvent.FAILED, TestLogEvent.PASSED, @@ -91,11 +91,11 @@ subprojects { } } - tasks.withType(JavaCompile) { + tasks.withType(JavaCompile).configureEach { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 options.encoding = "UTF-8" - options.deprecation false + options.deprecation = false options.warnings = false options.forkOptions.jvmArgs += ["-Xmx4G"] } @@ -113,9 +113,9 @@ subprojects { * Builds the core projects, i.e. the generator, runtime and grammar library. * Executes JUnit tests and assembles the jars. */ -task buildMC { - group("build") - description('Builds the core projects, i.e. the generator, runtime and grammar library.') +tasks.register("buildMC") { + group = "build" + description ='Builds the core projects, i.e. the generator, runtime and grammar library.' dependsOn ":monticore-grammar:build" dependsOn ":monticore-runtime:build" if(("true").equals(getProperty('genEMF'))) { @@ -130,9 +130,9 @@ buildMC.dependsOn(gradle.includedBuilds*.task(':build')) * Assembles the core projects, i.e. the generator, runtime and grammar library. * Assembles the jars but does not execute JUnit tests. */ -task assembleMC { - group("build") - description('Assembles the core projects, i.e. the generator, runtime and grammar library.') +tasks.register("assembleMC") { + group = "build" + description ='Assembles the core projects, i.e. the generator, runtime and grammar library.' dependsOn ":monticore-grammar:assemble" dependsOn ":monticore-runtime:assemble" if(("true").equals(getProperty('genEMF'))) { @@ -146,9 +146,9 @@ assembleMC.dependsOn(gradle.includedBuilds*.task(':assemble')) /** * Executes JUnit tests of the core projects, i.e. the generator, runtime and grammar library. */ -task testMC { - group("build") - description('Tests the core projects, i.e. the generator, runtime and grammar library.') +tasks.register("testMC") { + group = "build" + description ='Tests the core projects, i.e. the generator, runtime and grammar library.' dependsOn ":monticore-grammar:test" dependsOn ":monticore-runtime:test" @@ -165,12 +165,13 @@ testMC.dependsOn(gradle.includedBuilds*.task(':test')) * to the nexus repository. * Assembles the jars and publishes them, but does not execute JUnit tests. */ -task deployMC { - group("build") - description('Publishes the core projects, i.e. the generator, runtime and grammar library.') +tasks.register("deployMC") { + group = "build" + description = 'Publishes the core projects, i.e. the generator, runtime and grammar library.' dependsOn ":monticore-grammar:publish" dependsOn ":monticore-runtime:publish" + dependsOn ":monticore-libraries:stream-symbols:publish" if(("true").equals(getProperty('genEMF'))) { dependsOn ":monticore-runtime-emf:publish" dependsOn ":monticore-grammar-emf:publish" @@ -185,12 +186,13 @@ deployMC.dependsOn(gradle.includedBuilds*.task(':publish')) * to the local m2 repository. Typically this should not be needed. * Assembles the jars and publishes them, but does not execute JUnit tests. */ -task publishMCToMavenLocal { - group("build") - description('Publishes the core projects, i.e. the generator, runtime and grammar library' + - 'to the local maven repository.') +tasks.register("publishMCToMavenLocal") { + group = "build" + description = 'Publishes the core projects, i.e. the generator, runtime and grammar library' + + 'to the local maven repository.' dependsOn ":monticore-grammar:publishToMavenLocal" dependsOn ":monticore-runtime:publishToMavenLocal" + dependsOn ":monticore-libraries:stream-symbols:publishToMavenLocal" if(("true").equals(getProperty('genEMF'))) { dependsOn ":monticore-runtime-emf:publishToMavenLocal" dependsOn ":monticore-grammar-emf:publishToMavenLocal" @@ -203,9 +205,9 @@ publishMCToMavenLocal.dependsOn(gradle.includedBuilds*.task(':publishToMavenLoca * Build the test projects, i.e. integration tests and experiments. * This includes code generation for these projects and JUnit tests. */ -task testIT { - group("build") - description('Build the test projects, i.e. integration tests and experiments.') +tasks.register("testIT") { + group = "build" + description = 'Build the test projects, i.e. integration tests and experiments.' dependsOn( project(":monticore-test").subprojects.collect { @@ -214,30 +216,8 @@ task testIT { ) } - - -task buildAll(type: GradleBuild) { - dependsOn(subprojects.collect { getTasksByName("build", false) }) -} - -task cleanMC { - dependsOn ":monticore-grammar:clean" - dependsOn ":monticore-runtime:clean" - if(("true").equals(getProperty('genEMF'))) { - dependsOn ":monticore-runtime-emf:clean" - dependsOn ":monticore-grammar-emf:clean" - } -} - -cleanMC.dependsOn( - project(":monticore-test").subprojects.collect { - it.tasks.getByName "clean" - } -) - - -task sonarMC (type: GradleBuild) { - description('Generates code coverage') +tasks.register("sonarMC", GradleBuild) { + description = 'Generates code coverage' dependsOn( ":testMC" ) @@ -266,8 +246,8 @@ configure(projectsToConfigure){ repositories { maven { name = "SE-Nexus" - credentials.username mavenUser - credentials.password mavenPassword + credentials.username = mavenUser + credentials.password = mavenPassword def releasesRepoUrl = "https://nexus.se.rwth-aachen.de/content/repositories/monticore-releases/" def snapshotsRepoUrl = "https://nexus.se.rwth-aachen.de/content/repositories/monticore-snapshots/" url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl diff --git a/docs/BestPractices-CLI.md b/docs/BestPractices-CLI.md index d3f80dcb43..c11a240916 100644 --- a/docs/BestPractices-CLI.md +++ b/docs/BestPractices-CLI.md @@ -161,9 +161,9 @@ might a good argument to do it differently. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/BestPractices-Errors.md b/docs/BestPractices-Errors.md index bd12af6d40..0f8c6ee499 100644 --- a/docs/BestPractices-Errors.md +++ b/docs/BestPractices-Errors.md @@ -39,9 +39,9 @@ they could be taken for something else). * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/BestPractices-Language-Design.md b/docs/BestPractices-Language-Design.md index d94b826585..951a871517 100644 --- a/docs/BestPractices-Language-Design.md +++ b/docs/BestPractices-Language-Design.md @@ -236,9 +236,9 @@ of which has its own advantages and disadvantages: * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/BestPractices-Symbols-Scopes.md b/docs/BestPractices-Symbols-Scopes.md index cdd412952e..35aa7bffbe 100644 --- a/docs/BestPractices-Symbols-Scopes.md +++ b/docs/BestPractices-Symbols-Scopes.md @@ -138,9 +138,9 @@ intermediate step between the tools providing and reading the symbol tables. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/BestPractices-Syntax-Design.md b/docs/BestPractices-Syntax-Design.md index 4c3351d965..1c942aeef6 100644 --- a/docs/BestPractices-Syntax-Design.md +++ b/docs/BestPractices-Syntax-Design.md @@ -307,9 +307,9 @@ vs: * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/BestPractices-Testing.md b/docs/BestPractices-Testing.md new file mode 100644 index 0000000000..11eba90108 --- /dev/null +++ b/docs/BestPractices-Testing.md @@ -0,0 +1,243 @@ + + +# MontiCore Best Practices - Testing a Language + +!!! note "This Best Practice is still under development" + + +Defining a new grammar is a task as complex and error prone as writing arbitrary software. +Much can be said about how to assure the quality of a grammar. +To ensure the quality of a grammar, + a comprehensive set of parsable model, as well as negative examples are useful. +It is necessary to + +- review the grammar thoroughly +- use a comprehensive set of input models to be parsed, and +- identify a set of negative (not parseable) models to prevent false positives. + +However, languages consist of more than just syntax; +they also include context conditions and additional tools, which have to be tested. + +Unit tests are among the most helpful and efficient techniques to check a grammar + respectively its outcome for the desired behavior. +Therefore, we use a JUnit 5 infrastructure to check the desired behavior of a grammar's result. + +## Testing the Syntax of a Language + +A typical testing class, such as `CheckScannerlessTest` + is annotated as a test class for the language under test (here Scannerless). +The following code contains a positive and a negative test. + Both use the parsing from a String functionality. +In the first case a `Type` is parsed and in the second case an `Expression` + (here types are also expressions like in OCL, but the comparison `">>"` contains an erroneous space). + +``` { .java .annotate linenums="1" } +@TestWithMCLanguage(ScannerlessMill.class) // Initializes a language's mill in addition to the AbstractMCTest hooks +public class CheckScannerlessTest { + // The @TestWithMCLanguage ensures, that before each test: + // - a side effect free log variant is newly initialized + // - quickFail is disabled + // - the specified Mill is initialized + @Test + public void testType2() throws IOException { + // A positive test + ASTType ast = ScannerlessMill.parser().parse_StringType( " List < Theo > " ) + .orElseGet(MCAssertions::failAndPrintFindings); + assertEquals("List", ast.getName()); + ASTTypeArguments ta = ast.getTypeArguments(); + assertEquals("Theo", ta.getType(0).getName()); + // MCAssertions.assertNoFindings(); is implicitly called due to @TestWithMCLanguage + } + + @Test + public void testType8() throws IOException { + // This cannot be parsed as a Type >> wert + // This cannot be parsed because of the illegal space in ">>" + var parser = ScannerlessMill.parser(); + parser.parse_StringExpression("List>> >wert" ); + assertTrue(parser.hasErrors()); // check that the parser has errors + + // assert a findings is present & remove it from the log + // We ignore the content of the finding, as it is a parser error + MCAssertions.assertHasFinding(); + } + // The @TestWithMCLanguage ensures, that after each test: + // - no more findings are present + // - the mill is torn down +} +``` + +The `@TestWithMCLanguage` annotation sets-up the test for a language. +Before each test, + + 1. the logger is replaced with a side effect free stub that collects, + 2. the previous findings cleared, + 3. and the given mill initialized. + +After each test, the log must not have any findings present. +If no Mill setup is desired, +the [`AbstractMCTest`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/AbstractMCTest.java) class provides the same functionality. + +In addition to jUnits [`Assertions`](https://docs.junit.org/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html), +MontiCore provides a [`MCAssertions`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java) +class for e.g., Log assertions: + +The notable methods are: + +* [`MCAssertions#assertNoFindings()`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java#assertHasFinding()) - + Ensure no findings are present (always called after each test) +* [`MCAssertions#assertHasFindingStartingWith(String expectedPrefix, String message)`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java#assertHasFindingStartingWith(java.lang.String,java.lang.String)) - + Ensures that at least one finding starts with the prefix and removes & returns + that one finding +* [`MCAssertions#assertHasFindingsStartingWith(String expectedPrefix, String message)`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java#assertHasFindingsStartingWith(java.lang.String,java.lang.String)) - + Ensures that at least one finding starts with the prefix and removes & returns + all matching findings +* [`MCAssertions#assertHasFinding(Predicate predicate, String message)`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java#assertHasFinding(java.util.function.Predicate,java.lang.String)) - + Ensures that at least one finding matches the predicate and removes & returns + that one finding +* [`MCAssertions#assertHasFindings(Predicate predicate, String message)`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java#assertHasFindings(java.util.function.Predicate,java.lang.String)) - + Ensures that at least one finding matches the predicate and removes & returns + all matching findings + +When the generated pretty printer is customized via the TOP-mechanism, + the `PrettyPrinterTester` class provides functionality for quickly writing a bunch of tests for the pretty printer. + +The test functionality of MontiCore is provided by the [test fixture](https://docs.gradle.org/current/userguide/java_testing.html#sec:java_test_fixtures) +`testImplementation testFixtures("de.monticore:monticore-grammar:$mc_version")` dependency. + +```groovy +// build.gradle +dependencies { + testImplementation testFixtures("de.monticore:monticore-grammar:$mc_version") +} +``` + +For smaller examples of parsing, pretty printing, etc., models can be written within the test class and +external model files are not needed. + +## Testing the Symbol Table of a Language + +!!! note "This Best Practice is still under development" + + The testing of symbol table creation, the resolving of symbols, possible adapters, and DeSers is WIP + + +## Testing Context Conditions + +As a best practice for testing context conditions, one should test both, valid and invalid models. +The former make sure that valid models do not violate the context condition (i.e. true positives and no false negatives), +whereas the latter ensure that invalid models do violate the context condition +(i.e. true negatives and no false positives). +Consequently, two different kinds of tests should exist for every context condition. + +Similar to parser tests, the [`@TestWithMCLanguage`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/TestWithMCLanguage.java) +annotation or [`AbstractMCTest`](../monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/AbstractMCTest.java) class can be used to set up tests. + +### Testing a Context Condition on a Valid Model + +Testing a context condition on a *valid model* consists of the following three steps: + + * Parse the model, obtain the AST, and create its symbol table. + * Check the context condition on that AST. + * Verify that no errors were found. + +``` { .java .annotate linenums="1" } +@TestWithMCLanguage(AutomataMill.class) // Sets up the log, initializes the AutomataMill, and tests that no findings are present after each test (1)! +public class TransitionSourceExistsTest { + @Test + public void testOnValidModel() throws IOException { + ASTAutomaton ast = AutomataMill.parser().parse_String( + "automaton Simple { state A; state B; A -x> A; B -y> A; }" // Parses an automaton model from the given String (2)! + ).orElseGet(MCAssertions::failAndPrintFindings); // and stores the AST - in case the parsing fails, the findings are printed (3)! + + // set up the symbol table + IAutomataArtifactScope modelTopScope = createSymbolTable(ast); + + // set up context condition infrastructure & check + AutomataCoCoChecker checker = new AutomataCoCoChecker(); + checker.addCoCo(new TransitionSourceExists()); + + checker.checkAll(ast); + + // MCAssertions.assertNoFindings(); // only necessary when TestWithMCLanguage is not used + } +} +``` + +1. Sets up the log, initializes the AutomataMill, and tests that no findings are present after each test +2. Parses an automaton model from the given String +3. and stores the AST - in case the parsing fails, the findings are printed + +The shown test case demonstrates this by testing the context condition _TransitionSourceExists_. +First of all, the model is specified in ll. 5f. +An ArtifactScope that contains the symboltable of the model is created from this +model (cf. l. 10). +For more information about ArtifactScopes, see [Chapter 9 of the handbook](https://www.monticore.de/handbook.pdf). +The context condition is instantiated and added to a checker. +Next, the checker is executed on the model (cf. ll. 13f). +Finally, if the `@TestWithMCLanguage` is not used, the test verifies that no errors occurred in l. 18. + + +### Testing a Context Condition on an Invalid Model + +Testing a context condition on an *invalid model* is similar to the above check, +but at the end checks for the expected errors. + +The following listing shows a test on an invalid model that does not define the source state of a transition. +Again, the model is specified (cf. l. 3) and the symbol table for this model is created in l. 9. +This model uses a state that has not been defined. +A checker is configured with the context condition under test and executed on the invalid model (cf. ll. 12f). +This example expects exactly one error with a given text. +Checking that all expected findings occurred (cf. ll. 18) ensures that the context condition identifies the invalid model as such + + +``` { .java .annotate linenums="1" } + @Test + public void testOnInvalidModel() throws IOException { + ASTAutomaton ast = AutomataMill.parser().parse_String( + "automaton Simple { " + + " state A; state B; A - x > A; Blubb - y > A; }" + ).orElseGet(MCAssertions::failAndPrintFindings); + + // setup the symbol table + IAutomataArtifactScope modelTopScope = createSymbolTable(ast); + + // setup context condition infrastructure & check + AutomataCoCoChecker checker = new AutomataCoCoChecker(); + checker.addCoCo(new TransitionSourceExists()); + + checker.checkAll(ast); + + // we expect one error in the findings + MCAssertions.assertHasFindingsStartingWith(TransitionSourceExists.ERROR_CODE); + } +``` + +It is possible to check the source position of the error in the invalid model +or complete error message as well. +However, it is often useful to reduce the assertion to checking the error code (`0xADD03`), +because error messages are relatively often modified. + +### Uniqueness of Error Codes + +!!! note "This Best Practice is still under development" + Check the `check-error-codes` GitHub action for now + + +## Testing the Command Line Interface of a Language + +!!! note "This Best Practice is still under development" + + +The handbook describes testing of language features in [Sections 10.3 and 21.5](https://www.monticore.de/handbook.pdf). + +## Further Information + +* [Project root: MontiCore @github](https://github.com/MontiCore/monticore) +* [MontiCore documentation](https://www.monticore.de/) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) +* [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) +* [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) + diff --git a/docs/BestPractices.md b/docs/BestPractices.md index 97b1025823..838a8e565f 100644 --- a/docs/BestPractices.md +++ b/docs/BestPractices.md @@ -30,6 +30,8 @@ of the handbook. * [**Designing Symbols, Scopes and SymbolTables**](BestPractices-Symbols-Scopes.md) +* [**Testing a Language**](BestPractices-Testing.md) + * [**Designing Tools for Command Line Interfaces**](BestPractices-CLI.md) * **Generating Code with Templates** (no practice defined here yet) @@ -39,9 +41,9 @@ of the handbook. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/BuildMontiCore.md b/docs/BuildMontiCore.md index 971e99b5bc..5dba6a198c 100644 --- a/docs/BuildMontiCore.md +++ b/docs/BuildMontiCore.md @@ -1,6 +1,6 @@
-
+
# MontiCore - Language Workbench And Development Tool Framework @@ -66,14 +66,24 @@ lasting tasks. * cleaning integration tests: * using gradle `gradle clean` within the corresponding subproject (see above) - +## Build the website + +The website is built using mkdocs. + +* Install mkdocs: `pip install mkdocs mkdocs-material` +* Build the website's files: `./docs/scripts/preprocessing.sh symlink` +* Serve locally: `mkdocs serve` +* (optional) use Gradle to build the javadocs + +(A GitHub workflow deploys the website similarly to GitHub pages.) + ## Further Information * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/CI.md b/docs/CI.md index 6b701af099..254bce68db 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -36,5 +36,7 @@ In addition, the tutorial tar.gz is packaged and added as an artifact (TODO). | GITLAB_TOKEN | Checks out the monticore-pygments-highlighting project from GitLab | prepare_pages | | MONTIVERSE_TRIGGER_TOKEN | Triggers the MontiVerse IT-Pipeline on GitLab [more](https://github.com/digital-blueprint/gitlab-pipeline-trigger-action) | gradle_mc | | MONTIVERSE_ACCESS_TOKEN | Reads the MontiVerse IT-Pipeline status from GitLab [more](https://github.com/digital-blueprint/gitlab-pipeline-trigger-action), must have access to [montiverseciprojects](https://git.rwth-aachen.de/monticore/montiverseciprojects) | gradle_mc | +| EMA_GITLAB_TOKEN | Grants access to the internal GitLab EMA project structure | +EMA only | diff --git a/docs/DevelopedLanguages.md b/docs/DevelopedLanguages.md index 88ff7f5e8e..60d95d6ea3 100644 --- a/docs/DevelopedLanguages.md +++ b/docs/DevelopedLanguages.md @@ -160,9 +160,9 @@ development. See language definition and usage method in * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/Download.md b/docs/Download.md index db192c092e..bc48c0139d 100644 --- a/docs/Download.md +++ b/docs/Download.md @@ -16,6 +16,10 @@ related tooling are currently available for download: .md-typeset table:not([class]) td { padding:.3em .7em; } +/*Hide sidebar/navigation to gain even more space*/ +.md-sidebar--primary { + display: none; +} | Artifact | Description | Download | @@ -51,6 +55,6 @@ Please note the [MontiCore 3-Level License](../00.org/Licenses/LICENSE-MONTICORE * [Licenses](../00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) - MontiCore 3-Level License * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [**List of languages**](https://monticore.github.io/monticore/docs/Languages/) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) * [Best Practices](https://monticore.github.io/monticore/docs/BestPractices/) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md index 9d0a7a79fa..f69a10698e 100644 --- a/docs/GettingStarted.md +++ b/docs/GettingStarted.md @@ -194,7 +194,7 @@ grammar. In this example, the `Automata` grammar extends the grammar
- + Tip 2.4 MontiCore Key Feature: Composition

The MontiCore language workbench allows to compose language components @@ -309,7 +309,7 @@ extending part from `E` is generated.

- + Tip 2.6 Infrastructure Generated by MontiCore
MontiCore itself as well as the infrastructure generated by the @@ -464,7 +464,7 @@ corresponding generated builder class. Parts of the AST data structure generated for the `Automata` grammar. -![](https://github.com/MontiCore/monticore/raw/opendev/docs/docs/GenAutomataAST.png) +![](https://github.com/MontiCore/monticore/raw/dev/docs/img/GenAutomataAST.png)
Figure 2.7: Parts of the AST data structure generated for the Automata grammar.
The contents of the AST and builder classes are generated systematically @@ -493,7 +493,7 @@ found in [Chapter 9 of the MontiCore handbook](https://www.monticore.de/handbook
- + Tip 2.8 Generated Symbols and Scopes in the AST

Each AST class contains access to the enclosingScope.

@@ -524,7 +524,7 @@ analogously.
- + Tip 2.9 Handwritten AST Class Extensions

If the generator detects that an AST class for a nonterminal is @@ -560,7 +560,7 @@ Details about the generated parsers and their uses are described in Parts of the class `AutomataParser` generated from the `Automata` grammar. -![](https://github.com/MontiCore/monticore/raw/opendev/docs/docs/GenAutomataParser.png) +![](https://github.com/MontiCore/monticore/raw/dev/docs/img/GenAutomataParser.png)

Figure 2.10: Parts of the class AutomataParser generated from the Automata grammar.
Parts of the generated class `AutomataParser` are depicted in Figure 2.10. The @@ -573,7 +573,7 @@ object with the fully qualified name of the file as input.
- + Tip 2.11 Methods for Parsing

The class AutomataParser contains the methods

@@ -601,12 +601,12 @@ cross-references concerning information defined in different model elements that are potentially defined in different models stored in different files. -![](https://github.com/MontiCore/monticore/raw/opendev/docs/docs/GenAutomataScopes.png) +![](https://github.com/MontiCore/monticore/raw/dev/docs/img/GenAutomataScopes.png)
Figure 2.12: The scope classes generated from the `Automata` grammar.
- + Tip 2.13 Scope Classes

For the Automata grammar, the generator produces the classes

@@ -625,7 +625,7 @@ classes and interfaces are depicted in Figure 2.12.

AutomataScopes represent scopes spanned inside of models.

-![](https://github.com/MontiCore/monticore/raw/opendev/docs/docs/GenAutomataSymbols.png) +![](https://github.com/MontiCore/monticore/raw/dev/docs/img/GenAutomataSymbols.png)
Figure 2.14: Parts of the symbol classes generated from the Automata grammar.
Figure 2.14 depicts parts of the symbol classes generated for the `Automata` @@ -641,7 +641,7 @@ symbol classes, the MontiCore generator also produces builder classes
- + Tip 2.15 Extending Symbol Classes

It is possible to add further methods and attributes in two ways:

@@ -711,7 +711,7 @@ to call for the (de)serialization. #### Visitor -![](https://github.com/MontiCore/monticore/raw/opendev/docs/docs/GenAutomataVisitors.png) +![](https://github.com/MontiCore/monticore/raw/dev/docs/img/GenAutomataVisitors.png)
Figure 2.17: Parts of the visitor infrastructure generated from the Automata grammar
The infrastructure is generated into the directory `out/automata/_visitor`. @@ -737,7 +737,7 @@ more detailed explanation consider reading
- + Tip 2.18 Visitors

MontiCore provides the visitor pattern in a detangled and thus flexible @@ -832,7 +832,7 @@ singleton.

- + Tip 2.20 Mill Use and Automatic Initialization

A mill is a factory for builders and other commonly used functions, such @@ -873,7 +873,7 @@ of the `AutomataMill`.

- + Tip 2.22 Mill Methods

A mill provides public static methods for retrieving the instances of @@ -1331,7 +1331,7 @@ This makes Eclipse execute the MontiCore Gradle plugin as described in After installing and executing MontiCore in Eclipse, your workspace should look similar to Figure 2.28. -![](https://github.com/MontiCore/monticore/raw/opendev/docs/docs/Eclipse.png) +![](https://github.com/MontiCore/monticore/raw/dev/docs/img/Eclipse.png)

Figure 2.28: Eclipse after importing the example project and executing MontiCore
## Using MontiCore in IntelliJ IDEA @@ -1380,7 +1380,7 @@ Projects menu should occur on the right side and you can follow the above mentioned steps for the execution. After installing and executing MontiCore in IntelliJ IDEA, your workspace should look similar to Figure 2.29. -![](https://github.com/MontiCore/monticore/raw/opendev/docs/docs/IntelliJ-IDEA.png) +![](https://github.com/MontiCore/monticore/raw/dev/docs/img/IntelliJ-IDEA.png)
Figure 2.29: IntelliJ IDEA after importing the example project and executing MontiCore
@@ -1421,9 +1421,9 @@ the project again. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/Gradle.md b/docs/Gradle.md index e90470e541..2881b57b7d 100644 --- a/docs/Gradle.md +++ b/docs/Gradle.md @@ -51,11 +51,13 @@ java { } dependencies { - // Depend on the MontiCore language library (which in term depends on the runtime) + // Depend on the MontiCore language library (which in turn depends on the runtime) grammar "de.monticore:monticore-grammar:$mc_version" // and depend on the junit dependencies testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + // and add the test fixtures (used to set-up tests) + testImplementation testFixtures("de.monticore:monticore-grammar:$mc_version") } // Where can we find the dependencies? diff --git a/docs/JavaDocs.md b/docs/JavaDocs.md new file mode 100644 index 0000000000..f4b7a534bc --- /dev/null +++ b/docs/JavaDocs.md @@ -0,0 +1,19 @@ + + +# JavaDocs + +We publish and provide JavaDocs for some of our artifacts. +Your IDE may be able to download these JavaDocs from our repository. + +| Artifact | Description | JavaDoc | +|--------------------------------|---------------------------------------------------------------|:-----------------------------------------------------------------------------------------:| +| MontiCore Runtime | MontiCore's runtime library. | [JavaDoc](../../monticore-runtime/javadoc) | +| MontiCore Runtime TestFixtures | TextFixtures for testing against MontiCore's runtime. | [JavaDoc](../../monticore-runtime/testFixturesJavadoc) [Usage](BestPractices-Testing.md) | +| MontiCore Grammar | MontiCore's grammar library. | [JavaDoc](../../monticore-grammar/javadoc) | +| MontiCore Grammar TestFixtures | TextFixtures for testing against MontiCore's grammar library. | [JavaDoc](../../monticore-grammar/testFixturesJavadoc) [Usage](BestPractices-Testing.md) | + +Please note +the [MontiCore 3-Level License](../00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) +of these artifacts. + + diff --git a/docs/Languages.md b/docs/Languages.md index 6f2ec32b11..1f4a0974e8 100644 --- a/docs/Languages.md +++ b/docs/Languages.md @@ -97,11 +97,11 @@ classdiagram MyLife2 { map any kind of source models to a class/attribute/method/association based intermediate structure, before it is printed e.g. as Java code. For example a transformation sequence could be: - * [MontiCoreCLI](https://github.com/MontiCore/monticore/blob/opendev/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecorator.java): + * [MontiCoreCLI](https://github.com/MontiCore/monticore/blob/dev/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecorator.java): Grammar -> - [Grammar AST encoded in CD4Code](https://github.com/MontiCore/monticore/blob/opendev/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CDTransformation.java) -> - [Decoration for custom behavior](https://github.com/MontiCore/monticore/tree/opendev/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecorator.java) -> - [Java code](https://github.com/MontiCore/monticore/tree/opendev/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecorator.java) + [Grammar AST encoded in CD4Code](https://github.com/MontiCore/monticore/blob/dev/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CDTransformation.java) -> + [Decoration for custom behavior](https://github.com/MontiCore/monticore/tree/dev/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecorator.java) -> + [Java code](https://github.com/MontiCore/monticore/tree/dev/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecorator.java) * Statechart -> State pattern encoded in CD4Code -> Decoration by monitoring methods -> Java code. * Main grammar [`de.monticore.cd.CD4Code`](https://github.com/MontiCore/cd4analysis/tree/master/cdlang/src/main/grammars/de/monticore/CD4Code.mc4) @@ -169,7 +169,7 @@ and [*documentation*](https://git.rwth-aachen.de/monticore/languages/gui-dsl/wikis/home). -### [MontiCore Grammar](https://github.com/MontiCore/monticore/tree/opendev/monticore-grammar/src/main/grammars/de/monticore/grammar) (MontiCore Stable) +### [MontiCore Grammar](https://github.com/MontiCore/monticore/tree/dev/monticore-grammar/src/main/grammars/de/monticore/grammar) (MontiCore Stable) * Language for MontiCore Grammars itself. It can be understood as *meta language*, but also used as ordinary language. * Its main use currently: A MontiCore grammar defines the @@ -195,9 +195,9 @@ and * Additional elements, such as **enum productions** and comfortable operations for grammar definitions exist. * Main grammars - [`de.monticore.grammar.Grammar`](https://github.com/MontiCore/monticore/tree/opendev/monticore-grammar/src/main/grammars/de/monticore/grammar/Grammar.mc4) + [`de.monticore.grammar.Grammar`](https://github.com/MontiCore/monticore/tree/dev/monticore-grammar/src/main/grammars/de/monticore/grammar/Grammar.mc4) defines the language with some open parameters and - [`de.monticore.grammar.Grammar_WithConcepts`](https://github.com/MontiCore/monticore/tree/opendev/monticore-grammar/src/main/grammars/de/monticore/grammar/Grammar_WithConcepts.mc4) + [`de.monticore.grammar.Grammar_WithConcepts`](https://github.com/MontiCore/monticore/tree/dev/monticore-grammar/src/main/grammars/de/monticore/grammar/Grammar_WithConcepts.mc4) binds the external, imported expressions, method bodies, etc. * [*Detailed description*](https://www.monticore.de/handbook.pdf) in the MontiCore Handbook. @@ -608,7 +608,7 @@ usecasediagram Example { [*detailed description*](https://github.com/MontiCore/xml/blob/master/src/main/grammars/de/monticore/lang/xml.md) -### [JavaLight](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/JavaLight.md) (MontiCore Stable) +### [JavaLight](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/JavaLight.md) (MontiCore Stable) * This is a reduced version of the **Java language**. JavaLight is meant to be used to integrate simplified Java-like parts in modeling languages but not to parse complete Java implementations. @@ -623,9 +623,9 @@ public void print(String name) { System.out.println("Hello " + name); } ``` -* [Main grammar `de.monticore.JavaLight`](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/JavaLight.mc4) +* [Main grammar `de.monticore.JavaLight`](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/JavaLight.mc4) and - [*detailed description*](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/JavaLight.md). + [*detailed description*](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/JavaLight.md). @@ -640,9 +640,9 @@ public void print(String name) { * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](https://github.com/MontiCore/monticore/blob/dev/docs/Languages.md) +* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/dev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](https://github.com/MontiCore/monticore/blob/dev/docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/docs/MontiCoreSymposium.md b/docs/MontiCoreSymposium.md index 10050c6934..07494b0a4d 100644 --- a/docs/MontiCoreSymposium.md +++ b/docs/MontiCoreSymposium.md @@ -1,6 +1,6 @@ -## Third MontiCore Symposium 23. March - 26. March 2025 +## Fourth MontiCore Symposium 28. September - 01. October 2025 ![](https://github.com/MontiCore/monticore/raw/dev/docs/docs/MC_Symp_Banner.png) @@ -27,16 +27,16 @@ solutions in the context of DSLs and model-based development. ### Location -The MontiCore symposium will be located in Gemünd, Germany. +The MontiCore symposium will be located in Köln-Riehl, Germany. ### Participation Participation is based on acceptance of an abstract or a full paper and -requires registration until **07th of March**. +requires registration until **12th of September**. Registration costs are 660€ and include accommodation, conference fees, and meals during the symposium. -~~You can register via this link~~ Registration is closed. +~~Register now~~ (registration is closed) ### Submission @@ -46,16 +46,16 @@ be found [here](https://www.acm.org/publications/proceedings-template). We ask f [1] Research papers: 8 pages, [2] Vision abstracts: 1 page. -Submissions must be uploaded through [EasyChair via this link](https://easychair.org/conferences/?conf=mcs25). +Submissions must be uploaded via EasyChair (submissions are closed). It is planned to produce post-proceedings with extended and improved versions of the papers as result of the symposium. ### Important Dates (deadlines extended) - * **10.01.2025**: Paper Submission Deadline - * **28.02.2025**: Acceptance Notification - * **07.03.2025**: Registration Deadline - * **23.03.2025-26.03.2025**: MontiCore Symposium + * **25.07.2025**: Paper Submission Deadline + * **22.08.2025**: Acceptance Notification + * **12.09.2025**: Registration Deadline + * **28.09.2025-01.10.2025**: MontiCore Symposium ### Call for Papers diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000..5e024dcb83 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,11 @@ +--- +template: landingpage.html +title: MontiCore - Language Workbench and Development Tool Framework +hide: + - footer +--- + + + + +--8<-- "README.md:11" diff --git a/docs/docs/MC_Symp_Banner.png b/docs/docs/MC_Symp_Banner.png deleted file mode 100644 index 0e4f77772a0ddab8eb559c46cca5603dd00079b1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 37780 zcmY&=1z3~q7xzFhCaFvsL|;@Il8LL77gLa>fgT9cFE|hUY_rHEK2n1qpXZ&I6 z_A9>w0zDHqyrOFz=Cs%nwctjK!p>?-LVeo%T9jq`O{UUc55mv&fU{oMf7wkyrAtT@ zXW6_tz5e~dKMx)Ubssl8FZ?vJ9nz^=V(!Z&TibIiZucE6`&UouuUoyGcf($?-o1X9 zIWTl-b2t z7ahWh{~k#Ak)`=Lmu)eHceyT4L@B{>;xUGDum5pM-dOE^C$WtCJzaE;q0NJzSY18B z44O5Pj$`ufB|wx(vL3;JP78rPHwprvH8LmcP5;6;yx_*HrWO4TC;&vSnOl zE$fwvjiGeTEhP)^g}DZTsB(D(87yQ&ANs3VK7`8yEk}hCXlmg#B5=2wG*K{ zZXe~zRB<%k>3>UrcmRpVYus`=b2o+Dn$uP$XLrmTCWFvY_4{@-0reXO$W zy9U2fp``fZMfT`#>7bh_yt9C=YziGfyZZm%M}P5{=CV;!+)>EU$9`c1)*xE*PTirI z6;634&HTfa?El|3fg`IP&Ph+ngMN&hH`(qxQ*Q`mg7sYKP*AMX(3#*|`|o_;e>1nu zvC&sM>l;Gp8`40SlQXX#}T_{p3q3lOi!7O97bp4i2A1HlI_o*o%uJcg`j-61tfQq zyI*1u>L1zNI?Gcyv^zVK?DvRXWTR3s{VHM#P0anP$s&crEh&9Y0o!lx#tP6j9Fu#e zL#8FM`|VVr@!pBn@Q7b6R(>+gT1)sRge*FC3X;D3(_-qAm0o6ShRF7wX9R z_jwON^)1{MOn@sxDr9u~4lUDmW6b9rYl0J$O7$zIM?wtno1rt+-M5_~EzU92-=6cc zgoz4|Dgh6HB&{=ZEU^}se#DY3UAL(Q5`SN*@J94$#RNGeX!Eb}7V(Ximb=;YEZZkG zXwmBx3!1l!m!1F16L00i&>a26s6|o+^zTc{ zuR+a8%bp#osLai;c^i2je301_A@3aw$fbu{Oj(LWQ#~kBy32BJPu!d1XKWTiFILWy z7(Wkv^1rR-4M)wnt=21i&mRj}ZNKZDhr~sV2TVMhQNt-+n1ix-A9Ed1GA5`C&bRU5 z9sq`UEe_}TikhLp?EFWF*wrtb*GYcv9gPtTq!s(5Bf)i~FUhL9SXR+FpRA%#yRV6t zgBcKDeI*}C%s(3^`{&8`H+_d!E4CH7Dlu=n2F3BZsE^Rek(o)CHM0m z-CUlafACCyH#O-Q6|*shziD$EwhGQ0y5`~E`tbjuC=`mln)?+wQx% z0r0JMkNbHWog&yF`w$^`_m{LMf=kcRzG`Jnz~{uu<{LEJQna3YBa&iM z94mh}-f>l(k*9)X+xJ?A>>tm9+|)qM%9GXmSn!cI~NaiFdig8N3d(X>Wap1!|5Sa!xbuP1gRiSnu)L<97HbT(ft0M6p?+i(OVTbjC`S7T4XOt6Dn?4~g8f z=H|#VR+DAc%H1S73Yh>gvcEWF-HFO_ggB@LCOG+^GDyX6T-2Aq-7|Jr4=wn^3i4Zt zRQ)yOP26Dh&bqxQb|yfyI{h69vh*%J0WWxOVe6GKK~nLErj8-tGH>~FuJ~>Mz7>!{SVG-}<^oUXiWnTgWGSA{KlBg}l)Y8U*v9 zI zwd;P4T5l`sh%=-xcfaAJ=LCb#R!klGdlGJImG9P@cmvpx-)*Mm>~(!$P%&@xJ2R^U zr^JU~78=fuT_@eZ3F*lut=G;Cy&IJK7}Hv=69)0 zkb;9&vo!Oty0H$773DZrx&Zgx=lJE%dY~IDa4(Nt;cNLgaJX!X2cGY19ki#GG+giU zv+Rs*Oi&W^H9gd7`W|nk{iLURgOE!(pRd6U6~rRzzibihRQqBdb2mR|NuawC0mZ4_ zk=w8A&TA~Dw#L(;aBkT$!xqr|H9@tNPD*b-6+UAxQyuh2!*VvbUlB@B>b0cx` zk?r9H;<{MHt^oGQz`Xv=eCUT$i%sSXoZG2`!^7>B&0g*NiFvVzVi{@l#QPMhjcS;P z{GpMPNJ)3E0-D_U-|v|FaYeO%uGt!&K6iRN^AiKwNt-yq6d&qO@=vq?j3KN z?#f?QZQ3UEpw1o2L>krjDyY<~$okCso?Tb^Rzl$frg1H`%@%B^+U>Mu7gSwCY#|hf41=O#YuN=~l0x z>IQNvk|*F1^6SQH+Qv&JA8}dyVr=6QoKIlqW-;RTj%&A)$@aa8-8>@d9s;$O2L0fh zQtLZ0GAu4>4K-8wG)> z{F|9|9n*}NbQo==na={AK>Mwy)60`PH=!uf8d#w{)6$X8HZd3c1oFvqhl11@0=w3- zqfXqDZU={71?*85l?AI!bIB%>aC&V>XJ=X%%@0Z=S5wp90c%^eC^G*zSlDIioAFFC zf7X+L$iG`nB{;qoPp#2uHt#E9yl&>&?$@S2hUg^^c--9k^>ed@8s;UuST^&7zVELl z-Q$dXR;28-?#`5X2tdjjyV>l<8;Mf0mR}@l`Cm(C6@e<=#0PMd-F6mT=0t_NdHyUj zSHAM$4b;sZ(yL?vokqeh4yJY5ZJ1 zVTv81I_yAxLXZRt^JUj-!z&a|U;2ZW_q=E3I>k{3SjqX|?U8KPCm9rv_ZKcUC+6Bf z(Kb+IVyPE@sO@A45}HTYa39IcFS3=mpU&n0zh99FRZ1kf5NI=o$NNyoaJT-gSMMY; znXe}TZaw0vBN!%fdk77LlUB9Adjhpz;YfzzJ-EugrAHPnNdFM>RK)fk->bM~Z6{h{ zrHdeTR_d80=GZ8A!#y3GS#qP@sW^p=`g2!^jeCK2ZV+gL(e9D$m83<3G5MdwkOw`4 zDs0}wVo+Fr%>+F!3*k`_UZ6S~*>6cap$cTPI(`JV)d;uzqkneGdnw}jFkSPpN(cn! zbiX~}?nO$XK6<7gL9|L&>UGfmuu2%(Xsi@d%%zW@CRzjjvxsM|I$Y)C#vh;Zp7S7=36=V8_c!6zsgp#^ zNTYCfG5q^V3W8)CM?u(tsFER6_ASGt3))XLwm+-=&}~MFXxg}c%-KC@0m$01{oH@?K_?`9CoS7_ zR5fBUvpvVFkv%gKdmDWNk8PdylS`oHeUE)gkUY16sw=kNJjFfg`efxl3x87nSa{I) z!Mqtin+|#4VOz^Sm<_zMLMAWBoKsL8BYV4G?c*_dhVb_mM)qHCF(tNJnkCO4Rs6d$ z&fK+bJr5Efg}MBrB)49j=on=54Ko z9#gqX=36mBhBs|a-ZPU*k6vC@f|Dz%!q=7428;41R;4x9`Tj0}lVf8IKb>QT!%K((jpIiAgUsYWGSfbAP=fiUXP^p`E3$A1;r=AmZ z)lD%FK`-MPyw`% zUK5smk5$ZwM>secjugGMH($>ax)3?O^Yg`9m>o!Hi&@%uMO>>ww-SuJU;Rq`}5%3$)xx;(Wd{BEeEnFu{mXRV^F{k zt)$n>#4P$jYV(#mI@m7)0kb-m&NvLy}!xO6U2J8zuWbKvvUFb?^^@y z@VZ>&MNa*3aqCqZmX_}{Ga=>Ks(!WY=yBZQAPsfjkNBkH-v9WE zIQ-XVxo1RVR7c00#q<;>HCyp9o`!%gp||voM|{>JsGBVhZSGLPAcg_oP?%FEHm_Qn z!T!42=ieCY0A7=eJP8!aNBCAg0kVH8EwUZmC4}~dNBwz)Gf|7<46x}lC!itrB62EG ze#5H^)c=)j7j;J6aih%u%5gPfEz>=G(?a*Fms55gPPyzCNa*VcP3+ZcpanmV2Ue1@*xb ztPE!9DdBeoDH+^v#?nRpD_w;!E~Yo-V@*6o6pq8(sA6K9mRc=aryFJG>%SlMS@mrczCz zer%_*ao4p@rU=R_@Y3A5>b zn55)zhOA%YeA(@(e-8>2YdvWEd|mxil`-U%eKD1@W#(1;j8^J!Y3#<_=AQ5RCsl4= z`oPDbB3nmA*hL*17IYSR-v+v!1nDG&wb`73@yNgiU=$CQkB3`$jW+uj{@4Q026Vh? zd5Z{T23h@hVe52rG<>$;F&b7cQ|CQg9Y$^%uQhC`3!3fk{PM=YHt0YYg@Z7$e4|6A zIb;gKh_d4~6Qdbb6mEjVXpJ7Z60CH74sCBkRB5!S#Xv0tL;l^-oN_9~LtRWnj*OBN zo)+=w&$se1ApD3?E@)rp6mxt4x{-~-;6Aa2O3OBUizhl9=(F#qx#~uVo)b%%O_7>) z{j%DfrJkX*Djh5S!!En^!*sWh3p{6ogft0w;WUbbFzcBkA$R%Hs_c=h3uFzuQj8-Y=tkOG{(Ju`huDb1Tx&mh*t81?=PUm<7^tBLO$YZzliqtf(zLP4^(}_=DO=8Zv zq#|Q)k(rP){U8qAM)K!3P8+7VN~^Oz*>y`^MN#JEdWj0Y^vXv=G1AZfA91BM93NM$ zBr=Z_1>AxR`cmrpSUIe$FIHsc5b9Z7IU*o>;tc_!rm5gq?zM|Qww7XX+DKGxh1K>O zf8*6d&#x?J?Ei>q`rN#PTtHRZQcB^7+#$5O?c$qp{rcrd-`Zdh=wj!TY`#K_^Vux_ z3ejaT<>;Q#LIm$Af*RWQx#KbZcln%&ZzmP9`q>q5-~7 zHZdaJc`?G%=5+DlxWE$q5%hys_8hy(pKY3fT+fmQ4DqrIH)If?wb4G*KP z!!@lgoD$Z20`KxiX3zznt7oASPXRJxRhhC|^c75MG) z_@U)j!^?HU^LWfYN4vXbjbMKQujH8W=TiXKAjJfs^54(Zk#knF81Z4XC^a@~ps%rW*jv3aP=H5GRB2>2%YR;6EI zG<}|UT9?(8Eh6Yp`T6x=cww+b$*}=_atZTiB+ZHZ#7R=K&fD}Oond&MOCj#sHB$AX z@DXU}AP5u$WCg~E%*}&}n`(E!yS1A1jTY6<*V_>T+m@aRf!!4|+8lSuVDEM1K0j$P zU&zFQYagsuvkjaSg${^gfxe#`Rr&puii}ld#DTn`TpkMYC<{oh&WCdMNJ13q+sW^u zbD9%clAA{9eY6t;=ceOgpE|O6rP|kz+U$SKw2Hcc~d(*Y`QKe;-LG~%>D#~VM z%8Q=)M^SF!>!G9U6?Nd;Gk?~`QJS1G==M;W64U!CFh z(DOF*aMLuK;h#NI8luR>h7X#9kTWlQ;++r@u*XBwbDR0`B>!ILU096S@vs6Le^|X> z%jp$>0ucxrG4Jc)ZLzyBwbl=S3#5{vzM<(Ct#eSk{O&lM#N*)q;X4wAu}_~BNH5v` zB#AvR-=W5!*+4a~J#JC<`0+l8Au2yq6Sw~2k7BaeBRUxlJE_5@1ie>ERxp7L!f`NP z0mx|-#ltHPaLIVu`g3zW5NHKRMI6dbu6$C3uAaTUdC7Enhmj(N0%vdBw9mIKZk%%g z9yggK4a=Iuw2ksA6fnDZ-K_c=6(ksRJi>}u2s#pC@@WI5?yRH@ZElxMI7NMJ z6J)F{hTF30dt5@~IRQ$B@Zw^Xvz1(y3qr>m?ZJcc*+rWhQJ-JNU@ZqiuYPJM8~HpK zl{i1y?~@AHjTJV?Ik83z=YTzNpJA+US&!YUD-|nLGcEa-nYK<51JOa+TwIi}g&#DO znSIV7z++cF5V0M4aS#?i-CA;YaM0##{?#S$Mly_MZnq$-Y=aibeF-qWmR%jv@+5bN z_}G9%*x5N200n}s1WKu75L^h29DVv=*#Zru(<_AKtF+L6UQYu(KP5z_EmCcG#P&*u z($}8v&5X^tDK1M#zEafY=ArWvO1Z=kSTGM@vs_Je{X94Oke8(T0DLHt-R6;xjz@ebpzwB|UYoI5 zMe1q8HGp2^oXDYH;R<9s3yow`KBqAK%$rPLbQBi8d z6xn{L={m}O$QrJTUP42Q9bOxIK~20g?Mopfr?APy9sq!jiR=0CPEP>b@WkCTf>xo< z3f?B5VofMzGQPD@a7sDSxMlANg z->cCQ5^1?m%T9~N;^!4NTZtMVg0$zeN??O(W&A5Zb(-SX12~?zBA#0_<@jh?0;sB{ zY&^^hPGoxC4QS5#{mVzpb}Svx$+A5R85M8e5(0$LoK?ESgTAY}RWtQjuvw_BquY_z zpc4^RO@1V*N&V@P~zge_3hw)tNMD7kW&Ycw`s-nPm9X}3mpY&|9#6l48 znIoC@_ZHSI^nAQ-)ORm6E3@1KFIi5==8j8WxQh0xa4&>c1U8{Ih?lr+vYO3Qxnm_* zYwN6H2E3r62+Z`*whhI%YAmw0FVbK&1g^~-`_2w8!ZmHJ&nVT;hM*&UJz(Ska;|GX zDsTanTE{qzd$Lc=os{(VUU?sP2-P@cVeTa@slfUKvV)8u<<@-~3`nijR%P;Yx0~0f z2Tu3FHY^p~U{nmKt==$^J$*DvI`M?**orY~SMny5C$hQ1+@SdG!ziNC+ay0n;VB7M zJr9-$U;23nsI=()KwsW>UX)yIA7Xi$8@~IT_5N5O&02^5^*1H4;Pqv=_}d5niqABM zG8OSf@agveZEua?%+03)c(R^MccocNHC&`_r{7*kwJh>TgESfG$%7Bm_j|(^etGk@&>Ew`n;7pjAK5+@O(j}UE zMK8?tp{vu_B8bz~iZL)^=h}dowq{R}vf@7%zZ8^7bd0X#vL;l>B-BZ8o4%NPtqNU? zq)Z7#Ht!VKPUdV!8d|lDw=%<>6KN*F@ZFN;3-`OZ-_MU?r<$qxwNdVE(kR1Z;phG_ z#ugNQB54ZR44RSk#lP76k|M7iDq__uc^L$s_fZ?g&mV@{+s9w9?k z)QmM24#|ZMPUWmqxMrsT;yM5RN7Qap$dq`{J{MP$d8dVZ6IPqPzOq+I{Bk%J+ec87^sbf3}=f^f2G6q{c_<5a^p! z{X#ftXE$Zle6kFuP}lZFoMGP^(k+txz&t?gOCV*!z#L;hKIZ0mBL$UKOx^;w6UI-H zSXvy@dSGqE1f}~%LLxOLn+4)89+Q5*ab)ok^*NL$W1US#u!?e5d*hNwRb%qq^(fkB zlfu^$Zpk+&R1#*b`%QXhAEg%8O8v;E4V%^3{90)X+J%wL`&&$V4#$T4)S=)1OIzOx zHez^FT4u=5fy=oZA`&s&Jb!LOd`e#jY^J@tR-Jb{%^*+U=cg00&Hgu!Q<6jvw-{sy zE0&2o(l5U9`?=*81h^$%#$3_N2wn(XABGZU-gqi1#~??vB(1-+x;LsiuF;jCZAov1 zv8{t}a|6oMbJrXGBc1En^rFPe7b+K?4ZdQ&58s1pwb8~BpZQ>D`I%n<@kg){!BUo} zH|S(HsbJ}nq?M|kBOn1FT9ySJ4;KR%!v-0?YkqWwr#XfU54cE;I|QnN(`+tFNufyt zN&r?#Sam1WVjBV1rmm&$^nn2Xfijglf$d&G z6LO>IvlsG%OULn}_Z?xj&{y=I`oAj;Pa!zI|2RAY@@HpAO!18#V!c{+o*}hqhMUH7 z_9=kWx^)dG^z@&W{i_rA2Ev_XJz3H=Yzee;Aq_~&;o^Nfqtb$QFRe=iGT-d8B13A- zf5UEjPZpb>y>G;J_jcE1HbVqI27DWLY~;RWn|s-YWLcYPnI}~D#wXm!;VR2*5;yO( z;N_PCkXrxM?($t(LmslTFUwZuzm0WPBDXmsWZ#b3<|D|7dDt}YwRNX}W#?Tobc+@x zjT-ktY|f5)QU;URZ;SXcfdodRW~L$a+MY?Tt)2sEi$hrkK9h9fbSjVn$G-Guv;)$F z0~}Yx4&f@&p_K>;C_KpFX&t3vaplmswSrbv?Wmd+8S#GD-n2r$*!uT#{+te*@rQ#& zuO)gH&bqG}qB*Tqo&^f(S#BDXTA!Pdnm~Xgl&nqB$Ffy9P8?H?NkzmtopN-DQJun2 zThy#ACur4udvp9Ih%4~YX1_6w#+e60TH<53>d`eOja{{lpv;V<-&N7--`Dc3K1Tjx zaaGAGv$xjJ-zFjej#=(h*rn6Sr8utS@PVrY8uR$cF$Gx7@XSfq!?VGZif>9U z@^yw)xs4Ld5H5~JL^~sM3!X>8Ts5lJCbKh-6~%&UKOXP2Wd1rhHQjr>)KY(C)c(`A!i3lCGWgvdT-YNP~|hr z2Knja(V(z^FYxVN^WaAZ7MZ0qG!G1f$sHQxz{8&zIMgE*lDEFPUBy~g+T)PQp?MUW z6}1{cuPvzWaJ8G_J+(%cW%G*=t&*g4@w6Rr-9+uv-q(3_^UjH-X8B0Y3WA|ymt51t z*2DfCrMBl+N*`7BOD#F{MFxXMu(aT08x~Wmd}>kW)^!t}yUxuR)^@a(XvLm{B|2ZF z&i+@wr>n4qj&A>`&>J`Q-N_0U&4)i}B&s zM#`vymM<!#K6sH|gC-B#x|N-{&9h7WWODMX{L^Ceh2R+7G4CCprBE4P$jrhVjl zqZs1dJ2*u=uVelGN7gAXcHePc%0k9f9`eNV`0;$NGc&>`^{EN`mrg53Ju2z9__S_; zY$Hj_UhA4?aqr$V!~5)obo`10rb~K!Q_(uXNZ$$gM~%}dDN)8%eKkNoD@Vn8^?N3i zEJ_#USbh7si2QOOt;(!l$?Mh0AJ#)zb8Yr7zL2U>f?%=svO#2Tjy%7WgiT%+`6}Uj zATzRVtdIUSU7layQkgKeju?x8zEEulca;)K2?^LW5uY=Oaxb=qHh-Lt&{Vn;GSH3O z45Dm4JvW^z2^Ct*;&FB4UTL)Xkx}c^A5#GQGGyCYzWb9}I6s&bdYbnyl3no4>tZ%Dq;)WQ@4=buvr9 z%Ucndr$u@?dGC|{nX1ji^Ol%ZOWNU_%MrXeRS{)>tiIR^I%ef1b(>~)<}5~k#JP-d z=nsHk-(3{_zWu%-8<+7*fsN86H29ry@i&sa!HW`!hd>wN=}1(NWBC(HQNdHMLbz%k z4#paFm;ZyHWw6n4YEIC%7}+w3kv;*}g@8vTkEdQnEV%(@bCvo_oVeR~4!&C@T9T*L zWjS`?@!+pOvZ$`C4xe@So!#h;U*YQ)3Ui1J%`1$VjtrKw-*MLRyf=6N-5m#Xm);4q z=4x@COiFK-k`=qqI2jwACbyo`mv7yG&-NFf6g!^ruVwM(k)QB4WZ5h0F5k3l^24A$ z8S`x_otK+C>wXF`6`94ZY}wvARD?xML9bHjfnA%yt6jX2`M2l4hn2pH99GC$$6Xhi z#jX9uAZ9OYL@ktNRQ*uQ9vOJACKV+MD6nY*@4g4f%9ty<$Ft%YqbOVj*WlzLmuOkJ z;DEq&gPX0=cWjU=dG3J1aEMjmzMWNm#FR~+%(qs0WRwwqJ^MpA*ItR$HccacU9>`d zxs6l@!qpXOAS5aKA4S4LH2(rM4EhA86+hlwWXsM~?^Bf}IBWk_xF<)xD-qD%Q?dg! zr<;~p#8V_lZQD9^uhrQOFBWr4Cum~>l6 zl%N6NU`Ad&4Gz!<>Ti(}dYbj#2Ubx6AlMblp&XSehHV^82GIcmxk!rDP|*nzX0JQ< zd@N%3kTo!1e2aL-Oi`rKGgcor08z|qqDZQaytA-2cJ_Lr4OnOxAd_m%CwaY z8eQ`0wNGoLIr&`*spyy4fWDQUC)nvy!xWWW{&qw*KS&3 zQT=c+;p*>y2F2dxUATsClT*A{hl{S8^K`b#HYRutbO!(sDPI&f6=tdP^tm6rr*cGDV#CH*zNl9pjSEW@_2e5Hn6tHn0O70WK0|O zl8q^w^q=`!dlNK_alfrP(fG&>fc=bpSnTQ4Rr#R`N#i+_Jt`jwWfMH1>-SE-`0-D} zw*W_Y)J%NUp7Gq?;$+2%lI>{HqHrbn4w99lm3c z-II(t?F522>Q>X8?7sT@i^H9TQJa3_$7==Yo5ei)5nDJ#XQcj#2>jmQFCr=b>V93R zq}v3oN3oe*k1;vW^KBJq%IB{*R6ng{ohd*JH%Lu zQV9N((_S8y2^MMRgcA-BKAM@}r0LG7q{FNezND?!zL&|Er0hKtOl6FF&iwlLi_u}p zkKRs3NsiAjhCC0bxZ@FJTx;~X5nkhOw5k1qqI&fg0`CqxaLIKmj6R}^{~@gj-Ng#1R@ZTffcQDyOApOPj?69CxlZ)LD-j|bPe)?QtW zdy{vevy#butYPsHae1lbFycdbX~qW=5!ZjcFsNOo*nkg*mfC|cj!LNbVKrgZaiDYC zeUZkf#yFwTupa)W z2k_{T&&P`PRE7@#T>UM*pRPyC&WtJR3siiQ?~*^dHvvbw?3~LqyFMAeIX;0ThT={}xssTIxG2&#pOV z(jo(xW$EKCzM5#W@AN_5S{qI^H{;OZiltm3n;g^`ySQcRCf{o??K!lXS;UY9IrTF^ zGBRohALJM^i`kXMq)XjkW1zUma~!tueCu^`gDDZhqa$Mj;DI-OeDFP#V$Te4q;m!} zd9q!D;9D$w;tVLqh0MoF*S@~2M411-QZ}iFviqbChVIj6dlxIJgWc|b(m#J`gB~={ zZMTv;u+cc(rP2|Q$5bSE!L+5Z0l0fGvuw0LMrm(7;Co=|2#5LzWjO32$F!Jbm}>)g zPpzr#dO*3HsKv1|YrppU;ll-MZ&e%_j;JlDd+S@f$H#1T_XLPWmr7DmC=i8b)R2Q~ zVrS-R4cYu|_wl*bprWAu)R~9!A*rKwmYb4FXK3`1V}=Zss#<0*3R*($QMEeKp9nmL z`Bqdp8Z^zjN`?28Xt`U_BaX(pR0Cs%Gk(SkfQxVnoT>*9{0Yf`hmW;wbNX|P$F9Fw z;fqNcaOUkgCXjY}EKSSak(oAOV>ic*MF#`26d6RvlqDT+~+DyzHr~9XO&z$ zJvU)9jYPiL1>4rkP7ZYeFDMwf=Ht~MRUj!O>m|H@e{Ldo0*J3Zq}qKa z_3MnrNIcaSsQnz(#>zR2VifXnW4S3naVwu;3&vAD>juzi_m z&+Oe_a#Y5~U()tp{Sva>^BmC1u21dHL#q2>cE7s^yLbB#QJ4|gVsgb9f-}CqI5FMO zdx$10%c>>4E9XGlbRJN&sW&5qY;l~idqDHIS!_DyygIx38Qy?ryeb??@^b9HG@Fxp za~%vG02(Z}nB|n%OieVOuw{M%2y%}jfM2QZFA7~AZ<$e}4r=%`P?4zKX_6{8j(v5o za&ku6!`p6tfY>T=F=(~J9!VJjfjb5k|`0zOQ(V z3m*?Im0LBnAB_!oQyg0{ku#JAR#!AdLy}CPi_4756;l>^l5YbcZ=sNffJ%}{*l)(z zEn*tDZKqOlXY4guF{38l(dUiR3H^4ti|YX~0}(>@b#-PmaF(Sv+W{2?>~<60Z0UaE)Kqf& zh^cZ$dW(7?PPk@&DU7~-@|8i1z=QOcrC%m?X`d_i zX{j28PE<@!6Q)~Bms}A#7vP1KT}PLuMt&MPI+KC$(llf$rdY8it?65nq2~^zQAHDQ zu?n+s4^KLpd2QGD_`Z}c)hM5wc~~_V_2G%V*w{2MH`IP5ZD=iml#yN7cmW0^P*9e4 za493CPA|CqL0efRj=;eTG2g-(0(x;#Io(f7zTd`iUJ;!kqPP8_;%ED{d8{o{(SB~m zb{<})k7g!9m8GbiE@nU`Q+D(k!gZ3+xZ=F}*`Q%rtv>x{t;FuM;v#-6BM#3VQ&^FF zWM}<1Ij7BBDB&k=;F4f;EOMTz_w6U{7KZNFDh8uwtGGcAb|k(vu#mo&CVa+QUxfI@ zaljzQ7Pmc9P`I_>`L9QCBUV)uW@FI-$-Jo{rn6)X~8 zPOH;ck2}s%5pK^iH+97ps6eR%wGzELYEpg{~d;|hRDnK z6@Xt^8}cT#g8$ti{LAqM82Fd$eIEUhnw$iU38hosO2GDOap6&;6FWtwqOZ~op((VZ z2sK~u9W?0kyz8zeD_hj=>UZoL--+F*s`R`Pe6!r|nzhd;JbN-mBqpLv+nM-_4gQ<< z3xz~&RLR_5uRk~H3>?#*hRr%U2D5`#HxhnU+~XfU05mmk{aA>Z*^y;Uv3jzUSC$a( zsC~@Z4&e`lAjPh;IqSQ2&q8SI5kW|A=zRW3%q&okC+ms0I8i_n3iVASnN7tD<{nn^ z$Rcq?Ze#R=zn~M*^+U+iT@~qmX9C4qcluDiSy>MNYM9hv5nQ6>nEN(@K1UbPuMFSr=tY;_3o(&{RL^ZaaBX-E)- zTswK)(b<%c7m?1Lo(*oHtGoi+1!44^`> zSjPqZ(V*&N%zUM7w>_nJN;*h{!~|SfgPd|y%MS2$U1f|5d$ENVL=Vj;qoPwvK3|9t zo}b!p5f==iH{iEKUqWJuKF_qVBAiBm8ZB4F9oQuEAsR_8ScynTSW@vFyTYx2>^1t^&;A3LrXwWn zk7>$NttN0T=S;8S{9YY_1MG?3H5NqfII!KhC$_#2Iu#B31@-##I@6G5_YU93J;?&8kuy$aZm+EZAtl2ahmeQE`Wm^ zN0YTHhZvW;0_G@4P%lSp`+FPRf{guKd@~Z0SF4dMGP5;t3Jv@ZsqI@|A=$YUNVkNM zIs;e-^ohwDE&M0)gs@1AaA6K6Z?|X|42cq&Y_*-2#rkU37VJfPZtswVpkv%Hx=USp zXqe0aK5r0lZ8{?{eR!Gn-SuDlOP^2qzNt{VkpA5DQV5XhGpf3j#{G{o95Nl^hMRo@ zXO!j^VTqjpmp*4QmeeW)AkYkaY3$O-Q0b=%S`@Kv`hkIIq8l=WRo{6RWc%%@K?N4y6rSA!^*TTN^=X^tco*JI9pC2h*%@Vj_)UqF(UYq*UsTjXCc|TqCML9sa zz{hb#ed|S2C9cTGXG>R4tJPU9AJP;g1dIFw_~i@Kwx_-Y1J-V+HZw`?g50R&W|{KU zCbtkzRy({J6oOh()cyfJ1lw1%*vy5T-2PCEcifx3$J=G7ZFeF;Ic8jL0ni<0cYX6F zy~pC%{2u0;x?nbW!Zt?x{?7bv>;U*fEvrET2ekP009U_l30{L{XDpOg`Bhcp$X;NZ ztN41ozw>T*+k03~=_8=koYH@TxcGDix+{$WB}HlT}Sd@(5IHI zF?65k)NemZwr4!#fa^zY-cH?|@lMdm8JqQuN%OhO_dg-7tV3f7Nm?7V*3*H8LG5p} zuxtQT!D5WK_%mcRTcPyCl2*n&N-{f6VWwFTzTeCq)NTlny^YJn^Mfg~B>BU~Bbd6< zkoUuLwE7Qn_D7~BaFZxt{sdd;2_<8M?o03It;)y=NetfRB={AbiD{Diov_#Gu_@`U>xl z1VLIz^6Rrt)J(OYowv=OpMONaVg=8cq3*hcUL9{Wq$qik;h*-O73$f(c{XsGepvfXjq(6gK5--pa(AbYYDY- zVXL!jhZICM>*cIjzw9+~;^uj&Dvi?zesJ5N-l^p-3-SO|0>bnjFTDYKa`L-*yQEp* zb1D^42;BL^{+q-A>gBl?i0(TJC)Z3F`GSSTJJ5MmF2LyVp<9sAT!pC3qBY-_v{@4Z9}p%8YBx zC?jl%*bfQxnAbTjPmd;xJ%E{}0@bbnu3;kxFt42R;HdRH>lTxnc-z@h2?sRL@;dPO zLeFepyah|P`W8OI0Lgs##d`Sw|`B<;dAd`2>$5;DSL zm%J0MSa5K*p$?t#uTR%r$H@k@(u2;vD{f4VMS&wX+$GJTuz_06K2?2`|3&gFJ zZuz>>Dj@17n>BvuTikvHlNK#(-Gn<9KOzk?x_2Vj!S(4QEw6)>>*PN`C%Oj=$lnco z)o)?SWP|hv;F=1><~W~^lA|lP2Nk~_rC}DN1GIs1r?~Fr?&o|vrCb=^wQTNrlTYgc z$>3NxSHKD~jJ3403LjAbq$#O$$q(RfuH_>mJo&pmOJbX=f%&X5KK2j<2?5W(<*tjJ zJA1{JB_yo3VqPk_O|8wWzQPWuO$uRsW9e`fpQt0=U_s*tRutLOgcn z&y(Q0TXQ+xKgVOXUxcW-BjFm!*o}9)WV5GH0>AxzRLt^_!f$U;H?(x zwtx{pX$<3g2DHwdH8qJa&1VOPeb(~c;0COhx0rG_Kac+ze`x|vuob8d)fPkSdPr(D zn5T>h>=`<8P4afrm16IQOI7euB(6SP(^+4a>4jIUpJlPmam$3ymSguZuFgVKt@<7b zHE9^_qM?y8MJ(Nx3b!~*kb$&y3vRb&+!F#{YGOBCkG=NqQH}@kR7@SLyLoK`EKNqg z`F9Y5ro4_KYL$7rV$}S^4h4g9PDlS#Pn3_wHtbqlz9{q#Y3?)|*34+J5Y(f0V#$U8 zP%oM0N30eIT>kFx!}z0ug$lylf(d|tZ4aTkrq>eEd>R~C?>lCH^J?T|B9BacdzugB z0`d&0?j{9VwsDpC3Epi|T)WXT;wKb|4i(yVNaUwOVv$@(>5b`D4`VI69X9z23S|gYggP5X*CnU2 zDH2ghp?Dn^Sxv#zdE#p{r0Y?U+@KpgY=#Om$O&V=5x=AoSD^O;#-MkvT*UO z{3Zs3cyXZMikRv1nkeTgs}K&1^>}l}LKKa&w{f@QvBQxS(eY$0+;!no$UCF}3+Owz zAcRC+28XJKnDZx!fOQ>y+d>W-ZsOt{xyo=@}3U~I539qhWT=TeAUCANBq z)MB9=|I97#RT1vfaOdH|JF7Mj`z9UY#0;DTrEj2%OSc%1e-U9a;64I(J^_;RY5N)a zQM19PWsm8yg3vRWZ*EdfSMuM<$#DN%inz{^;=>+Rzz9{Yo5k6mo5L6L6uv)q%m4e$ z7deN(G3x@qfwA7B7Q2kgJbmASr6j(!0M<5F%E$F9RgV2Ov(p6t!XJ5EH?>m4?)>+p zB!+IwRQU)*_ZGp?pPA(_Q3=rZky}1TkA-n@X}S!(J=|={h!n-qYiI$5?}Kiv$N$`! zh+X~F6tg4&vI*_B$yB=nSz>Txr)|gAc^wtbo#l@PuF9dzIC)Qk!=Q6_SQ<@Et}&+` zOSAAC%jcRsJN3Wsz)+ZC{&ue0$w%|ZPsVqR=o5>tH#|<^mDOFYbU*b|4ahjIbpTi8 z3d5&Hl-)a2feF{YH#Qb4k+C$rZ;XRJQbGI5(nQVL0xpxDS~`37{B?plEB8<8O7o0QUdeb?nkH$vB{yCgN}ebud8V)MOdA)Tyk|z?uu8I_)AZWPQL8onli` z0#2@BcvzY@MO0gVcVsJEDH9qkH3AIk?6HV|rAwxNFHq~??TD@FOOb(9!2GJ)Z=}q# zk~TX=OF^nBGDM<$9Uemtwp?`=yd|yQ^VVpy;(*Y1ZeHo4N=cpmyg%(V6I=}3+@W|GaHjh|eq1CWr%L3Qx;r_moO4bGr<~?Iha@4B7#X9; zp`1FRoO9e}o6{WTltXkUhcFZ7SPmOT%oyYMUU#4G_4{7muFIe8{W?5f&-3H)45$Z) zCh9c7Nu%oiZ(15#q9|O61(Q1szhGrySrAuq>f>LuD2J=NOWZ*)H~)1ykXO}UZVK23 zDW>fYt5g-IJJ}!cPvN?g3+y9a@jn?z=uiHH*F4jEt2ycKVQ$=58EMX-&P!{DxE_|h z)8?cn%K!cM@z+l4st7@Xzzt(aIReg`{;Pn9jJEfWdh8NWy+0gLxiWG%_Ve(X%)(~` zH}etDcaY8bM_7acYx+WV4kc@dsM`Gn8nSJ~z=)NRxt{7y`N;b`Fs8osI%RS|;5w+u zx5wEV)c^k21KFE2y7@G6%!1isH0bcIY46IYk~+5Ko8HdKg=55D<9eVdgXXthe`7ijb@o@^#9b_Ye%9P+PngHu|H;k5ZT&>d=@+%B=O z#k``6Kk$oT?ftTy=D$anN4eK=rknmhoX-Y_L4clYUGQu#xrIlVDOjnv0J87mNA29v zbH^d=6mXI8Z5IByHLb6XZTLnin6{#XKOjH+$Y0zg?qbr>m~7@(=cq)fm&8|i4AUzF;_=egd*RaP0iv2GJp|N*_>}@Jio~Zof9DqnhaE0c{Q;z(n zSZ08lUSDG%OR>28+-{6Ebm8Q@{8;-!3zOJ#QkpzgD@gs|V6m*NEhLY9DDwbWKRp4J=m-u+FY5An} z-$TJacK}pFeOOy~+p)h#f;ZwD9S#Uuni$C=cEP|52W-~}2v~pPX_pYQgiNuGIGF&# zRpclk(r-I5eKe9*QHm_QF7cY2f8e+19UytZ2aDQjmsYgM)oprALD#+>y81zc?Q478 zg@hX?SWs)&jlW;gPhX0<% za;DOeAwirW2>r^tK*uoQ`|;lAT?;6 z&ILfD{k{I380p*)AkPw1$(#0u}!VH{|a(o?xs(bBC!xOTz$0P8buJu*g*c#oppiqM+S|m?8N845U(j9f61QL%yc>N9`_^9uwTy%ZJk5VuOe#JaDw?7Br&?z&IF7k+uApMi;)OAlMm{ty4E z@3h|;y80983PdQoY$=1 zGdOU;u?16a}3OCz{wVzd9T4LiiDJyklk#dhy6!`Fkjl}sU_E{d&{^9lf# z%L4yVSsAB-ebpmcg7^D85mv z1ePK|J8MXl)A{#*v?}LC)s6@SMj#b}mP+T1*(Z7ckM7$+kj&AokG3>S=eVSE9i?G; zj_JMmdC%QB9=UmTgOlw^^N*1chX+7$w!*7B?Q_Ef4YNLuhf?kUoj-{{n2ad~kS$LT z1@X*ZEIv16%_&6O8jI}Awgp@Sd-`T&as_Hm30`mbrMa#Cz$yR!>I;}XQhs<3tBAGOd>0W;0GiF4J{)s* zU8vdyU__TDl^B`2?bOC~3#kNAQHJZUTsin8dxkbo0HA~p0PR1tops=CD|MY)s>0u* z?4F#XQm-J~;st)(DVl~f= z_NgWPUz|JI`wM_XE(gr)nB&3rUMP>Ksa8TgF; zG9PX)vkN0NhynXT;ZZ=DHPRC(*@h#Bm z0kijb#UA0~WSzXe$P(R5H1&WD3z?!(XGz2k;3DNxtY|e}%zH{jyib6D`MZ~MJmF9@ z;OFzJE)cx`IS`-?gdBNCbsX`2Er&E~^&}oT^vVD?(6F|AdFMe?dGakCTZ4C0m?iOR zB*z`;qm^v>+{eE-&@;|4Uvjy>aCq0qbA^x`B*}=_1&gPdO3*`Xvr!c{B$a#Zn9aYHHyEp6N^A>XIlYm1I9S}Af$^mb>&H4Ig~s3cqHBTCMVl{UO*+>+npLfyu4i0{fM*e z;EQ$u)7Y6HRz@)T5cm0ma{-hHYN|N8clxv)DugMM*Jnz5m_PM{Vb*#T*zu|NKoC|G zK7Zgbt5s84Wmq8V;(wYTYRAYQa7mBqF!@O3DJHJxli#vgMguSR1F+{zq}YMZ7f7pi zOv0~z{F%7NhhZM_bt@TNTFsDKI~Z~@A-2Unip<@~H12RjalIPmCS4Ad0~j2t+jJ@z z&q?@OW77XPxa#C1S6-A!U$UWBI`9Adrc$mqR9x5z888yIOc|H0vmUs~%~n)yh(2c{ zD}JE!8K?&}q3zx%xY73VyHUO3I4-iQhX5p`>$Z2`39`FQ05fCKc49)6wT$0nzfMpT zpr`azjx%y7u+}}x){tHwi3wR6#{fe=vy!rPNzHh7jXo^H+SZF9#Rcd-M~19elv?8) zXxmjx0RYiwXAYM{QFI(Z1`@jWi>Vw)L%WQ{DE03g5@K_$ZYjlsTFk|b{pny`h?Y0F zc6l@n>4RQAL6$rvA>cS>8+yd>c(32dJtMijNTH3keoG@<+-QD2-j%QFE;CLVA4$N% zEUHHD2nuy!MwfSH064V5Wp-rf4xpRaw59=Lc#>F~hsm6)w_9VZ)Y*G3k4XF4*gwTK z%NuBU#7t`yzB%-9=XQ~=1cU$A~Ot!r-+UH6UbAx)UjfE zz3@z@+3exk_T1som5g{ZG7#%dm>ih!9Atjnk|cMYVMB#BWXmvPA^t%L!VmqJNSEP9!4qxEYb6{DNAdR*=W*hb zYEj*{&7<9}NxWf1$UP5NHd)@eDyn(}Se-liLZOqcLW8q3&u0Ah@xshG-+2w)fFwp+ zF*2OQU6VZfB^yXZgu3pJvd)o<;`F;~T+#L|! zv8$u!#T_XW_(k@m!c+0^bgqIpAVtJ>C&|7)#3&a_&Rk0XIPjzKe#&6oU$6j_z@C+#tSxh{p^)bxCcix_F)2 zP446dc_)dt9A3tx$4r!eu%E<{VdmU@D5wP6XkMHz-g{-ZzSd80_w>xmA#Ybj49tF7 zF*mdQ9qfu^O_%U#`j%0|xkU{`t6eJ1c#aQi=ie|1Eh5;Q?} zbsSt=CtWI21C`#7eS-jyLUy1BnTru^L=zyS!BwBhvRmi%(_F#H0$;s?Ir=Z7=NSnR zk3&yx-ds&gU?Owm?^x0>qe9!?Bys_DuPiGSHU0AraZjXg{L_*ErXuVYIMwR2cs|~L zA`lzN_Cxxf12v1o4Ha1NZ*k|11up1fsmVFjk@)0Q>*Qvn{J<3`Nw4!`ryoevr`|(2 z9iK5YNm#uar&veXG~QQ)FO7cm@87ZLvY#Itg_LNEj7FNbtk6-0qLMd48_}2xd{`p5v~#)9>C=5=Bc)W4o$LUaXhsd1I<7=LY2xSGzWr7>Gc zQFovKU0kKSiMdE~v0o{Vzc&y|z&2`Sk;UfVl>U&dK|k#Sk4{a2v0||2`G^moOu<$F zTUi9_eh^J2tpPy=Tft9wzbB^BrA4J9m2d^in9`bwtNef*@3Y-WhpG7 z0WOFX;bS-z12mMF`qhsJ4?8}J;@k4H0sxkcKlC_MzHFN^bQRJ1V$4-83uQBy-e_?r z)maj95;R}lo8@WGE@=d|A66?u{@M@@S#*&5QYEE-(`sydPHSMtY98aOJ-(ynEeZJn zA{I7Ct2X6&TID&`>LQ58vwoG`?$Td(rV2=w6w~!rc1$S`@BvQu!)>ri{?3SX6}8~K zw%PB&eH+~Kgs?%H;GT}xd)?tsp+xJ!SS-Om^s)KQpc4hrkb`0!%;7#nFSkC=!N&GA z0Amf=>+JFcFr-a4Td|`lWol=ybvS^Oz4FOm9C|%WlaHk{HcI{GRY2R2mL0*{xN}J9 z_~CfbIn9z!L|>N&)~z=u3lAlqHPVb_AJ#&aq3(k?DpYTm8deI56gmu+h>i(jEtP3? z@p$Dt1ud!J-$p2Q?d2d}Hm{T6OQSEvGd??MJrh{GGluIi&%co{5kFjsG}AeEai>(j zSm7e|^H6y3(!4(55p-!ZCrCm2+!I0=0sh(PdYLA1aHOKQqSui$|ITP$J&PFoVmi!z zD<=jAKT%Z7>xRPDI@5)socweE+8hwD|3E@7=o$TBv}=N~z%$h8e;ItwC~p+A#t@qY z0E_h9Kw3%8sV(DwW&4Ck-`{>b7_LLi?44`7mf(+e7~S zFGH|Bq*rDYCw9@Z%)74bGHTyFDeszXD>lt;qCZfsZHVg^N3t|OEfO>-0)40@7= zqG#M?0h2Lr+v1pFB%!-iLUK{A1Y23!z?~}R5uVCWxby*Ci^u^l(iD=Rz{YCk1QllkcDj8MKcOEH1+3KeAPURRi; zS8=&H+4X(}m;vgC808ex*haCS&y3e8G}p+nGu|orOqn<@+bI-%#gK1NF;f zhn?aFDB)*Ai*DK~|M%g@Mb(3^UXwx7)AmS&9Zw670K$%KRF!TmxwoR>M48`>ZWM1g z^c#so0n#-52+$WL%Rt|zT0AkkW-zyNaZ;{~RtK*v%^b#eqWcz+>kc!z9D^ND?OW}% zRZ=sBd!4QeV3b>Y_bW#W1Op?Hl1}u4B=NmvZ<_kfMAG0Zz+9y1rMPIIEQe!DU;{UV zE3Ls=OR$B{UZ?(H@of#{@8{uXHe)h#BtXXKy%1K0qD4^d31RCzW3>VB8%?o|l!_un z`DTEp>4!(fT*(V{fGb@}H%MZ6J<*F04uA190K(}3ntdqp)AkWUrCPyv3zr5iO1UM8 zcs16aF;xzVd;G zLc!Og#22`6SsS8Ac-i=)hGzRM@HP6{-i0+sl@sKZWUUpL^p|3;tX)4dLOE#gJ{;e? z;TD@V4V`T^avf@fD?|^4kq%WHv=ej?IT6%# z?Pe>BiYaHxY-1{V!Nk_&!GKe@Wq#FxV)?-t4SFdu&l-Ej%k8J5agB;*niFNG2_=WLx$kaq}5qK=&t#Es75Z{tQyt>?UZR@b@BGc7#FrQhezQyRp*3zyuX^Z4mN za^*i1`v*bhLL`lJ4mQq$z#485?Eo9x-bl7@!|5&KEDR7Ij5hh$XQu)t_DmaR9m8Wb zzE-hL(kONr51JB>T!2n1F{gj})#o$liozAvB-*{DW_oZKo70azP$=7t0teI6J}p7Cq$*KOC6B>6`1bq&SNDW_rB;emQ+AA5t09)RU)pX3kF z1!ANl3B{+<1#7byc~!b>rdx^Hbj6y8jl{(LU1Xm+qpD@w`0|mOG;MW2I~lBxd$f?7 z3wFMbTqHck{wfu!Hs1mnTa*qRZ&Z8r$mNRvv5Kd^-qIQpQ@p-(p%E_{USzF&X;4$W zaC3PRJm}Zbj(H@!C%4)kHmv5bZldSz)5haYHgl{g|NlvWsg9kEt;dAK_j%-|PJ|Lg z%=+bmZg+e5LxO7YqH3=2X+J5F68hmF{*Z#n?UH4J+V&21pQsWzDc$zpk(4omIxPGo zZ@|0yLl(21KP0gZ1u}H~Bi9&uQcgn`cgD?*^6*D!Jjt;*Lo6vx3o@Es{;|5F!lv$n zAsKfTs?c>PTg!g*oS&vSS)=3SBa1ufKGVI)n|iO zsx3ziLF!4nT`Ox~$N4Q|`NB3ZG#kSuyRla}5vnPByn3Z+qy^fFhKb{%$83A@=o^cJ z_uMlJ(m0hv+Vs=O<36a>H$j#M)!kUW{-f|K~rdZ9ZzJyL&AP*EAe?Z z*205gFt&sRX>k|EPusX6%z4$934B_QIJ)1ywBHaO*RXD<59yz!*ZDM9H#{E>v>-{J z6hB^UC)W84V_vwDT2t}-Ex8OAdD0gSY>nsVxt=4YK26KxR+iSg0F1( z%_rykHGL19AQwa6?vYcWEn1^5iI2K(w3IJJI_=}?bD8(QX_oLvo94>Kfg-2x<9SA8&9xi8@??{zLcU^Tq?i? zKfDlQJ-db!zbhx7{eik%PquesgpEEBOYz!uRo$yaG`~CqE@CqbPd zWAfGrs+~j*<-4+Ox$LD};4f(kZs=pFTm=D&5sE@*L0Ht<9?Ah*1h5_}NhR8f48o&Hcngg!h zzEJmO0o_bISibC+-FtC&4z{<~+r7Tq#pI8L>Uh)$Pc?2dMBHn1lc>b&(q2YKlXUT( z7FKi{imvt*;R)F~TDvo6?V}f?rw;G&yGewcc?2W`ry(({|MviSh=S zId@5RVRHtE92!P9lGhP@bBJO)Y_Xk7XI#`p4;SJ)guh`tCI<6zX#JI8ZdcE%b!CG= z7&?qBfAU4KRC{r`a*4A`iQz_#Fws01&UEfBedG(!*@wsCzR8YBH4Je{n2c+)0g0T6 zVHRV_F6qeyR9s(M7)3T}aq}b*AsZsRM0S#JDyN_N~$13IS-ZcX+*}ydr&K~=7+kpEa--W}m_iG~8UZ{3bm3AlW(@D3lh7-DjE&`%++T|4Rn!wm*Cc3GgCI`@IJN z&f6ym%duX7wP>(7=9cW0@=*c7%nc5APG}M{QH88!g~MRPL6nq>BYep|-e()La}G8s zAKv)v1`bC$*@N6{DKmmYT%O=B6k8~@Z*NYd=hHF0ma+)DP@*(rE9Y_-Wmid>!R{d$ zo>hbIO7+-v%{RFU!quRc*3B3BHKE@Ii+RQs8~jheNZCJGC2y~GXpOGd-?Io zFpT_wYy!qo;O;${s5JXK4`wjfC_oDw-N;D=WQdj7AeUx)v*?He*gLd@4YQUVmv_|; zcDM-d`O1Sj_p@uYs2JXRU|vtuFxo~({%dL^Ik0W)Bp~;Gtwt5UztxKk%*XsqoxmY@F2Ekeo160q_PT zf7a^X7axnu(eh03wD5u_`EyMEKdby&8m~4AD^EsVscJjY@frym1hLt0UR7YOq?79K zo=2d<6UeR(mJ5-_QtWv7QmY+uACsb_keGUz8cWCSj-BJ(-E z%h!?Nvk`rST(^j=(WdUeGslsr20@C;)Ky!1h-WKjvmFQQMFktBxfz}pNIn4yG$}@SuA`9d!KAj=ZCivh{WS(O-HPV z7OxnMt$TQ&OM2hVmeM2sRUC)o#)sC*8=CjfUbX-=w(jsH6e}Nu$j5vD0{gOUu(XQ3 zjs%4BYyxFCnQICE?A+m%PLH;F|1dSn9_y{(>!)w0@kA=jH?(C3mXUy}KpmdFf^sgMUjV-Yx_?o4v)Vv5_ z0YrB}vR8O+p^x+~);RtrNP-)^+6%(|lj~42Jk#2El12+qC@_hhSg%NPJPRam%(!)` zZ#fHw{Q439d)b{cuvGSN2-s-nX}L5{gZtwY&qIE>II2eiYW7O?sZi1ZNK)|F)c|go z3~w|z>oxdUW3w$i$HpzX%yX!)w+~?Z!e6x?*6dhBtW0b;UJgFK`_pc-_)1-g-BDSI z&BX#B^zdHj4}EOZuiccVzUh%D*rbOC99h}L|K|)Z>f85>q?0+n@wf|?6h@nKc3`>} zlqKv=k=r~(1hI1egitm)oJB@`0m@O|hW6EA&N`#Rfn9=Aogc>LUJL?U79UTId`2K4 z(KODlc!RW!^u34FnI`F-*V_hHMNHw-5A(55-9VV`UfaKf^WPs@EqJPys=ptYY7UyW z2s#OhBdOEB`&TVo4qni1e1E6kPobgr&wB)clWJR?ZfE-kJ`MO+G20XM|E|5Fpyp$8 zjMDqbSs_ytSBp~fbSAG{nL$Sto(<%mjrr&xd$;F%4>e8w?Gv@@v2{?-sg$#ylHWlx z=K;~R{fN0t_|#0v7vT;Ge7!0Bn?X*DrFmS1(u_?!YN2MMHy5-8y85$&d=Fo+5gS(p zXw{Rnn7+monrzVj(RBx#XcTi&{L$&W+r8n1$6;86ukO6ApqO@K=zs6fG|SYl9#o9M zQvYW#p(MasK6`OMG*x8B&V%|RL_&MSpkvY5J{H9m`a%Zsh80|1?&^eSe-69Z&r21w zTXu3Q6)c(2GIT9r@1w&X)NZ$4HE!SuGdejK%HXfpo*(KAc|SUpGiqENeg2hJX8@$O z=VM=gK6Uk+YKN(Zq=z|q?G2P-zASZBtv~53O-o70!fAn7zyplAX!amdPW(US#KFpn zjq^aABH&Fu_K4L>(1-*l?Bu6XHI+KDeT5+xp-E*m)>%MK<#HEjc|h`V?=66AnfYD) zTjrhIy_sH}?(>*3fd#~f{TE93cj%-;T(ef+@OIalcE?JVjrf?CZ%l)%Kl+y~V&#MJ zSBH=O`2S-&cws@9A9xjio4)vOl4ppgp;7n+tb}C^HDm+fs4!T$(Y!U4G|*KC(W~wqVv2GU^<}5_rs5uC+l2CaO4U5~ zK+anTfPv8smD`e%6}N$+(9Ab#l=cN6JwnD?+a+knW8Ut(g=D_U3%$2sx*gQz<{YU~ z;wv&=Dys_&ieNPFe^APl9`Fo3eEW^hZVuqK->sN!Zl9w)nT6gbX_lnq%Ml0xYJ zx8b25aYK+=&y>{LlR(<*JqRESx|vHKSDBJ3zZuqdaSElasOcF<+55maNuAw1bL1^$ zX!BiT$)>r;eD96w~{p(M4L~)J?FSnZ=sq4MBUO?uzV6&*u%v?vmt21H+=7(3$i@> z3Rfm;)2^gyS(E>t#L*mzU&6+RE{vbMX8F)Vp|&?eU$)4@S@!BhgWkPr%}7MB(A|(f zZsg_K?od*YH8oeItE=R{=V3!XTi6%AB6_pw_KsaFY`9vbrv7$lg|tygH+-0K@j&I} zc~|9MK_ww)N8db5AgebEYsuVk1gm0H&tamkM~~AqpBaj~0HiX(ty7@MNKj-iMm!80`K~zix@4 z*7=|BfW5@$(X#*^O{iqU%G+$Mdv*)HHlh8vx{3(dK_gF! zuQv=N-}fkRP4fNO{n=MS-s8E+Yh5F*9zVc6$U5YlJG7oQcFs!$a(%7izWydJwD1}DlC#?*!N4pT?4OuS z7#r>5x6@T@=+?O|*@DrYM|LucJ8O?Wig_`-XMYA@C~Wh$MqQz-89I>|&vm zx|{0pF4x;yU6DBJvI?1;w16JBl8ID*&H6|nmkDS`O?u4; zbU~|vJ;mYweud}@ZDXLd5g)SP@RpB+hB2^k@C@OjCUk)49Fh5#YMXy1LvoAumIHPs+<8e zA%u8>@F(61u$BC=!zSsneWSPZZP3X zhS;tq;r{p`)YB^TSwOMcoe9nMH{?P+t?sQ!E0wqv6m%kS|UiKOtF5X z?P}gbW0_bnFSP!RDEqBf$L?--+LaBx5+4DbbVd(d%gv7=mKHCgx<^cF=i z$r_+!E>V=&H_ux-N)}CAo>(sb+bcWDA(F$5T5(!w7rV}!cTWw|19XvJ1Nv7-DaDem zxvw?U5)>U~8a)xT5!RP2hSzPM9o!s`pFdNh{!Gn*82VMmH>o2_8%2MU58gKd9;ss9 zGI!S!(Cgvq0#qLQcGGG(E_cX?9jd49XJh3jb}FjCa>st&c}HcAr1!e$g*czW%FCIh}`nD(1)W|yZ9d?dDle8N}tu^>NWK=2*?>6%UKqrDF zO$5P)P6$l~Z_pPiNynZVs z+G+Bwo;NjdPv@UF*vb&U7rf;91M6wzkn&B~O(y^-1B|0pueK5RsZD^)4z&|3l5vzq zpe1L*s--KN=MiO>x<}_au}=%gMnA5$ePUPAsYnCS3ZvB#f-69ArHtp7?#7x9wKQ*~ zJ?fzyXQ*9X{5lRPo38Rmg($GHMSkz+7qoM>*Cu-6>8HmH30_%7UnnR6s7|YJl0*K>b=JmVMs1Ij}HDJ)+=;MU0PI)>KBw{g}lB}D1 z1-|tj!deLZ#5Ruv+Jz-5cqg~e7 zD`5(;&&@ZQobHi`aYe0NP0L@lA>-~T6bQ7N%*it9_JjefBKd1M9t{K~L50nIfRZkG zg7KlaV)_Qp-O=OND8K&I=q$7&#|eXx*Dl%dub08Tb`7w(}{YH+!_0Rd$F> z?+jc(`Y=tLL`Lv=!vgo?C3@5B+THlhF8QN)6Tvr^kjdN$JMWZ5;%9cS+rQuYJz9qg z%*z=Bq}DyOzio19j{A-y?Mx^B-yRT%K{j%04R|2Z$GC$eyZ4klOh4Z~FeGqahua^V zTPL+o1F+jaN^AI4YXW?R?)#wS2-bW9e_h*}SCj7ndqpvdh4^EWtp(0htIm5IQf+qb zCJ(%IZ^BaC#_lR$tMPVs=oeKb{)+q%oO^LSM>}NW{Yg8kuOoEuSMMjo1%7z{C+V7 zIsOz)kt6Z><-+%S9q|sGDmSh8p0zw*rgF%I$hN3LCmjh5cs@u4B)b2G|s2ILz-BU=B@Ge7R)0r{i#KWdE$>>^c3BH zbwX9BVWiONBjx~gA~Z5+^0KE!sBg)~WMmYI-9=;qzw#12`91?Xs#BJCu05?Ds&5SSsW2@(Iuk>QGW{W%BDY%+6o-jCr-`s1Ap38nnq1`FO z2kKvBcbgu@q`(%)4qHu<9l*F=dmcE@3gBh;9j>7@oXY#`{)$E zTie7Xr>Es8{u*`y)FdO(2J~5b7|subf&nszLxpzIUy5{nj2!nn;zQBuTmgynI#28; zW{M5sZIff+SB4N3gHBONzGm{~z}|e@gU41oeP5z4$Bxey?>q5L*CQD5bQ-Vt4Ohb#xI`W;w!dEe&w~GfX~h}FKR-WLAg>=#J?cPI4WTHx zg#tzH{hp`>gaNvcBI?=W`!>lcIkCuUwh)Jr9lH`)5;yKIZUKd$e>urYnB|*0*bpw{ zAlbVx(iZ){aab^Cvlc(NaUVZ&&)+YT;FmCFx*&kTprjd768(z)&{!lLx&YYEUjb=R5Av=8{zaRPMXI zCqy=xe5|WH{j4E@0$gQDo*4fSIvtwqS&M9=x9sEm5@VZvuiBnj!He}1w%%Xn_q8XP zP#i8KAb7N^(Y_t>6_KhJ{2W0$SpWW-xA*T7w?U##BEgHQu?`5L;dA6w$-W_qJ|9_g zZ0rQMO6$BP(Z95}V$%80E%HpM>cd1tknTB? zTT*iS$%=Pd!mw&z(PYUez+J9r?BvNkgckb8jQv1sGm^St~ z+w_2l$hE$WNy4Py{8Bh(Zx;v$02bq#gH1w$E2sHy7`kSC5X0W$OtgMh5s3#=`+P)%%y0PGtTIF9x=c3k;qNw zN8d zQkJ2s-Zw(I<``t+_RGX~NZDQ<>vCt|IoVIlf8F-SXS$+jRf$os&z&>U@Sm3xrR#SG z6Zec74`a?UngEW%?#@b?k8um-`Q;X>*V-OlI0;~vzX|CmADxgJi)(BH zz?_~oPfDKjy0w_`@x<W8iFUpxX00T>&}{O&X8TN*mrDY}EDC4rQShhnAgqf@>$49lzCuNb;WPNW)$p zTjgHme&%<#Ju~m8kd)CA$R~k3&2&$40Z>TFXMcXKN1h)fEN9S~ zKhYZY-ycH-9HX3laLV60`HeDb@Fv@+m2g&(*n}I}=T0&oyV2-Uw`lm%0(qP}whCxa zD`Y2?SBA*XTll;9PF6NI@b{E!rDM_p!ACdMQ2O>V2nyr}C*H13>kwGIe^i9sT_Ogk zWDvjYh#Zmhe$KQc3%AwN$h9r_%U3Yu!mze_!=>qx|kXds}F?OOfnDv|@VK!4lQH|CwD*de?TvUk~t^HcDFWTW-@nyBxM0WyrEFQ_AeW&nTL?dm{Hdr4qxeN(jaISVduLt_maCQrxdecZR)QCF_oZih) zz;c1Og9FWE%_64PeFPI`o2$wlma zR%HH|1m?BQW&r@yhxW5`2z)2Q@I^wq9pS~Z#)P$jKRX>$MFMO2qy<8=w*%aaz>hw% z+_6tLdc93jq{s}KLLwe+e?rhQ4+hGns4Rg>DYC%?n)1^XhV2$ANS~&Zwki^t>g$>m zbm`CKUI8xmTRJ2=zDSIOmuRuiM+>tL->U6tXN|{VW3&EF|Mpr&34~AZW)|s zGE9e3kik(i#Dzy;W_t@txsp5St0FezzrQQVQ*R8zc~pXj{`_?HP^yWcYsV(iD(+LL z207eB03~p|Gz3#>IZo#UxOrfa!NMCCR|`x+CuDaCs(F3}1})I0sjI9{NE-K} zu3NQ%I~Gm8B#tyC&1y@qXpdM3UsQl**aH%taDq@35=1qh zQh|w+J*!v?yuXy%AK9>sH+0pJUx-RSVg$y!USI0WDo>XMFIkK1?ft~UAz^4o;;9s3 z?%1C3y6ZEC`MhXXV7XzeSD;G}?a%;z_GthQIr<0BJ{ef22f)G)tP^zMCo`&fyG@&< zWP?Z?X_0OYq0Z>o2k_r@dAD+Vcl3w8JqUjgKT?aIJHCgs&RUD?qQ>j)sjlk+pBRmC z1yur;@PE@&8dYTOL?K@#dP%pij#G-N2`Ocl%gD zU>>ml+WQzKg}wRxAUy&;fx~jT`!=)lhb%bO*LHE{Wf3_v>p!KZmtc-LyFf^{1Gcn{ zpPgt2U7-XJO4FnC4~I-W>h+Wq0Bq1IO*YHNjQ$&< zvoZ7gfIeKwmQzW`U1k%D_uc!P9ezT3i-eVr+^Y>$iriFhDSzD8Vtu%POzKmJ{COs% zJWk^-f*~0X%&f#TaW*k#7+bvO)A=%1Oyz)WC!e|YB~jyn@YbaiDvUrs3wq>G`XLB_ zXm$sNq6ICZCINhAWy3vLy{`7o&g;uz1WnNWK1~3#FRJ7#uFbNQV_jF~AfN-!VB<1B zjh80ymbE6aO?EHiG}M5vrU73S*XDz9hYEeSmr?TMmPzUISErs|1y?l)G&M@h{Q<{z z##5rV0m71kvCb>}O27jM6DA{_6weN!fs|iKDT)E2{}cuv zz@J~WmI2zLbnZ?h2nLR@l4nV?4fhBdrBnw%G}x5Qc74GuymQA1RVg&MgwWuI5sA(m zPIrpMgPJqTMZ8aubm+4{U|JcbWR!%v*^g4H61$!9P((<9J4~n~U-mb51QEsV#`-M> zJ;f2i2;P6JeIwJcY0+V_Rj6V@*N`O39Ucfdx|e^{cb)>6zI8?>B!t+7&%Yggo za9&1fW@8-2)McMkHJxHfY`+plvg}$pr90qW$780Y{jB5WNwVFok;I^3>3Q`d$|}8o z+_@deJ1=e-V0WxD$2j?btI9FCo>fD3?S)Z2^^R__4lX!G9B|+B)6-iqG;kT3CroL3 zmaB*QBO!<=0F7F4iwZnRb~2y{{yrHj3)Fi11dxgmkz7 zSj)VyL4yt-)2RkmZeYF~8{3D#W!Itxj}$0SX_Z%G6a-{UmI#$#3`s!!-2R3n*$$!H z&C?*bR;IYceC~E;i@80yR~eRi?b}*5@U#Dd(ystVJ#yX9^_p$%^1)`xn@=p&J|#in z4}r5s};^n7Q2R>yoaStp5Zz8aTTIhzaM=2+BLIx=idlbd}Ud%u+;Ju$&sdm&A>X9ydr(e z{NG0G=^CKfT`2M9m&61WfI&?iklBS-o>fY)zX=hDPJ=a*)gYyY#~Es zovkpKSrxXKL1U(2(^7<@F~ue^W?~vc$lllX58U&<&wHQy-rxJX_qnQMQBb7`Pl~B; zwefx$B2vK?NWLZu&F{y%u;y3ml=qp5+s1q(eVnK;KsD&MN9U;=%YtQCrP*0B_y95W zfg+xKycauMo}-^*O|ZLO2oLlwgpczf`0>StpTf;b%x7=%inRnu!-h|oSR25#E;ouN zZ#1ob%5OQ*xa`D_@{QyEoB*97F)Q%PtcTjgZurRUHKR1}S;Y{_-aE7d5XDJG?u#aA zszklWek;Phxa-JZ1BB4*4ybj_7C@R;1fCX!L0OT2C*5_IwnzE`A z!dUQfTY??0jlN)0W-qq#R!Gek-*v5x&mi)DkwSd-k?hhWJGdX$uUqpq@mGnI+YkpX zxRFN`O8Th8;iXwzFZbPypzKZNDbws^k*lkrYeeQo%sJJ5LF(O(ctvCu02Vf~R(~23 z+rMF!+ckg1l;|izj4g;$$n2e}Ed6y;$!3uRyC{#XTw-gqL^DW2r9hXde$QA;f0*|^ z%Q#cww9y+TG{Xz3ZbtuY9XXnukx+u@=qFa?rCt(od7jY|f?csj-QTJI+OF_1Eh13V zHMXT1i#&?C?=CA3Eang#P$rAA$HQ9@DWktIyhWk6CM|RN!lqVbajnWQB&6k9uR*S6 z(XbBfhP>8fIbv*URWgK0m;t*QdW-Rvgj$ez0cS`uB&0$`c~0GM1N!+LTb@$WM_Lh!N3K(Q z*)f|LH-+A0g`^0rgCbfw1;`fbg-(W5!|Yf0&x|?h#^?RG364oThf)^|XY_Mrf?P{e z1j3c3LN@N;U(=om$rczrf{tACw=-h$$VHCK8I_J_3&X26&){mSlZvbQ9*4p|);1m| zU6vlXZnjeU{eh2h)Od>`n6aUM7(u$)`XiLO#;DzLWC4wxU`Nd0$o6VX*!e~`S5tZ& zD>xLnHi{Vey?}Nqr+6#cQg1q56*JMaTN5#bPRKoE{UCy<6p~#@mH!)o8|rbn7exYN z;n>j0(bP$4qj9&c`~xGRm!B-YObB?%a(1KtyR|HO;l7PyFmJJ052x)+J2EEjcPPRZ zp^(ybt)f7m`~;?bdaZ0e9h#|v)Sg>X3Q^_v)0G2>6`s*l`h#Zt@B>^ummd?>SPFKj zfnaxw;WT7)^u7#io1alvxF--IqYXT!Am2!zRK8gODj_4IP3r}am4h+9*E-zM`oSS+ zu37$X@{j7O^KL>tms4HY_qf~-?CH@L@M^E4Tm|Fz&vj|@gliZFRa}eGL7;{6rw-a3BYF0Ke zQS`ij9r8Y9+L#XqT}qhpz)>YqL{QJCcv`=}IXz9-i7zb3B2?R(kt>mn9{RM6Nr$#V z(>&>^aW4O%;1fHZI`mcuRJrjGf)n%o|M&hkeuW?o_9%Yr>ce!n{483o_;M#0>;x$0 z0XG*PQ?R?svb(!78}}IZF4Lwc-R#PccaQhc_0Wjx2aqQ+Lz4s zsqVZiGlA}~b4Q_P*X|^&iEcQJj(Aji(Dc^$y<;M-HG7O<{C)?xSsJc=UYYr;usrEF o@qq40YToePMRwU7`|;Aci#;cGP6xai1P5E;?-T6J^*oXFAH8wQdH?_b diff --git a/docs/docs/Agile-use-of-Models-for-Coding-and-Testing--Usage-of-UML-Diagrams.png b/docs/img/Agile-use-of-Models-for-Coding-and-Testing--Usage-of-UML-Diagrams.png similarity index 100% rename from docs/docs/Agile-use-of-Models-for-Coding-and-Testing--Usage-of-UML-Diagrams.png rename to docs/img/Agile-use-of-Models-for-Coding-and-Testing--Usage-of-UML-Diagrams.png diff --git a/docs/docs/Bild6.png b/docs/img/Bild6.png similarity index 100% rename from docs/docs/Bild6.png rename to docs/img/Bild6.png diff --git a/docs/docs/Eclipse.png b/docs/img/Eclipse.png similarity index 100% rename from docs/docs/Eclipse.png rename to docs/img/Eclipse.png diff --git a/docs/docs/GenAutomataAST.png b/docs/img/GenAutomataAST.png similarity index 100% rename from docs/docs/GenAutomataAST.png rename to docs/img/GenAutomataAST.png diff --git a/docs/docs/GenAutomataParser.png b/docs/img/GenAutomataParser.png similarity index 100% rename from docs/docs/GenAutomataParser.png rename to docs/img/GenAutomataParser.png diff --git a/docs/docs/GenAutomataScopes.png b/docs/img/GenAutomataScopes.png similarity index 100% rename from docs/docs/GenAutomataScopes.png rename to docs/img/GenAutomataScopes.png diff --git a/docs/docs/GenAutomataSymbols.png b/docs/img/GenAutomataSymbols.png similarity index 100% rename from docs/docs/GenAutomataSymbols.png rename to docs/img/GenAutomataSymbols.png diff --git a/docs/docs/GenAutomataVisitors.png b/docs/img/GenAutomataVisitors.png similarity index 100% rename from docs/docs/GenAutomataVisitors.png rename to docs/img/GenAutomataVisitors.png diff --git a/docs/docs/IntelliJ-IDEA.png b/docs/img/IntelliJ-IDEA.png similarity index 100% rename from docs/docs/IntelliJ-IDEA.png rename to docs/img/IntelliJ-IDEA.png diff --git a/docs/img/MC_Symp_Banner.png b/docs/img/MC_Symp_Banner.png new file mode 100644 index 0000000000000000000000000000000000000000..df48edd80ef246dc23c25e998dbfbbd52c69a1f2 GIT binary patch literal 38582 zcmZ6z2UHVV)HWOtP`Uz95D?Le3P@8r(m_c2oQ)#5IJP6B^0!7PmQK-gZ9Ip8lW_jFBkL7?&%oZBv}z~9*euHA-# zKs>FC|Cl=ci|&FzDaO|gbge=i7wV}?Zp6sKx#%3F+<{aF{DAA5Gc{A?7o}~j?;2|I z$-J@qkfZd>O3qxxw9Mq%$aCKeD}qOeil!pM^XL)omeT~N-qAhU@BI5rlV@~}VIkbP zWvtB4a-Qi~W!?C<<-vEI#NNS~!P{kC#E^x0(l_t%Y@=`%cy9x?zE7*MQkza7X;=d? z{=Lplj*_z+c2Y~luD0=f_>QMr@6BtE|4tz(CK?AXJ-DYbt_PZY($1nABBK^&lOuMOQ--*XtOfJ|hpZ+ni`tT~q_5VCO4&PMeS9bPJ1HmsW zSThL=p8w2Q+BlxUdyKbKt8u9lop;`md|!i!i?>tahgD7b0Ew#$@=?;|}m z0!;x&Y0Urqx~b^&u%XWk>k#E0TU{<{7B_8VVE>$nSN*6w{x)t_4la?u-l2Yn0PLbAoKs$ z2zSDZ4|l&A7`4^b-8 z+E2v|jr+^;9vdLGUIRty{cqcH8P7e@jhsmgE#QFnHEzWSjgg9_oV?#ArWJO?AD-p> zKSIope#HkSCEmkNrbqPjSDQjM?7H;Z?hE;!*kahWd!O95P}t7kpru^HhsEBxq*ggB zk-urH{KD$qpC*2zAr$BHvz?B&`~I`-om}Ccq~|b$D-=#Fp^wYga_|G`(y{Wl&uTa$ z86Hrn?^2@Yz=~t+`TR0H$|q`Mx=7AFuGwz!v5nJs3H#sex}jh8)ON{G<%$Peb+IFU z{bk)4_R8+(aX+nz)$MJZinX@J@6q}G%IG@$8hyF$l!sH5(~svWdr_+^P9JCagW`a+ygW{Y^-E z*TUBf=b?M1OhugVNC8Ltfgg%QP1h%}Io`l#JAa*hYVoEj@=+aRQS%oK&v~z*_OIQh z=jA4sj8hUrKX>^>y@wP@C(Opzd6rSl!KJt{Nl#tk;`U(Vofuib(qgW^J0IG4bk=UZ z%bp0p;r{iqli}=*xMRP6c@4?DsOEvYjZ@^i=SVvAGRUwN$;)LwVdJ+kt?S3ym zp<)~@T<>o3l=89OWtI=v*farGo?saz<v?>4zg8VF65u`INJmrWlW1HB>|3 zC|iLHYlp(S+bnTu{cgzt+*F z6>LC|gB!NmyS#8mdLYiFq{ia#vs0d($uS^XHbg(H1QFo}f<>6O{bH80k_H+H|k z4S3SC6v>eKjI;l9rzEz1;repTx-z%Hjzkk$LzSduX<621Q51#k{doBAmR}p|G`5OZBvU8mo z__yv{e=XBio#gM{CK3MIgcn0Ft!5rQ$ME{;@U2T+TNcdq0jDNn2hHQ2M}bc2Ke+Q* zwVope>{pPJbLsfqtpYZ}Xs7(OqzRJcnc<$1dkg-MYks(dQ3@+QDS6qMCusb{4F+1| zO@1u5alf49heerBKRtDz(Ue3yx++TgtZWa%d_9V!*K8UC0fcg}g{lVVd&DJrgm`kk(1e=SlfNurWIVUTQxc2$EnJ z(yj8J=0i4<9LsLJ2a6f&t+SMje@ry4cxrCbMPT4$Bx9wz3j$Rr_)_GbS@$P3x8zaZ zEnEt%YT8L#uEa(TaT$TTsCSUAB-S@c1g8}3qwB4U&|wZ9B?uC}CDK}BqbsoB)KWeR!NT?9q2w3<8?GM8U3{yx-Cb@%JrD}i zExhXNwxfL2;Rz!o;&wi3^aNBt*TB{dIXGokvm?OjcH$)v3QGQxwc$y&EbAhVxKfVG zt*5QLG_4b*1hV1>?7Mgh*~!-*c&R?O_b-_rwtIowF_pfVWKueLG@d}JDxbuh9u^Z0 z^_<^T(XnUXiGasVs2C z7XyKwqiTx9eINy!vc3~{`RD(QcycD-U`#=CqgOet%0H7O9=zEo#b>s zPsa%I+nLikvJ8_`eT4Ts75bwa>-P7xr(^NORZ+ZWd!cdo8K=l5E;ll2%8p7S%gU81Mze>+lBqH(iRvwwJVl5B74WT1I`j7RI%PvIqmP#rbc!H zjE)lV(ZPQ_UN?Jpp;63woP)JyS234VTUNKhR08g|gNob7lfNnsLpE;XoH%Y#(g+hD zdI8uunODm`5kyT|e+7BKzaEmy&3IEm4tUtfnzvU*{?a3uKGe#t@xief+CEvRkgyu+ zC8;OKOUza>_n@3{EKwjNe`0(*eMoWm4PfQp;)$)|c7+gDWTn_>FW;js6SZ%~2q3~L z%N%;iU`1RVq6q`L@_P1~pSTW`DSz0i{_f72VMgT%%C8)uk12nE@N#KLVuT1sZ6S076#7i;?;j52`OFj(ki~|nMvwozbnnU z7-ZAM&ECo0%Z?!XS>BALge(0#rNa+cT~5e~tBEVSt&_*_O}smUzk@(AlCX`B#?wpC zHZ|0ZQ5bgEpRFSQ!>=uR51iM{tN&iy`yax*qH3tPu=h>@otPLQ2#CvzN+|Y)i8d+YKV03G9b%G zS@i*uK!`V=$;GB<7kEM6@~_;66q8msXtASqHrH&4RBv33<5P@N7s~72^)h5ZxGT%YIKa)r-KY;{dgK%? zo}FAg2#ZYu6H!dE%?y}ZHn&N_*x5|8L~;mVe#0;Umr6$A7ecLK&@mQ!+(V^Pol=1q z6m&xF^6^>qk}@TU;ng9G&h0%?g<|QhH|{A|Jz>D}c2vX${gk(VPu|Yp6^lJF(?YjR zDjaxy^eJgj5Ci|deV-#oSsAV{SWcDt!MitY+#%q9 z#+&Nuo}HXuD;%|R6*_dV$W5kLXhtOmyv8Z4P^c{h@r;PCxZZ!F_pHD>y8)CJ5v7jn z4~9=pOO;qDd5MmmG7k?1EqX+iDih3CZIHoFL4E)={RW3`|s3V^A(NL)NAl`qM-q^-6rBH@Xmg*vEze*VaL$#I}M8%`R0>K2ELyF?$q4L7wiAKuzoIbh~#hG zR;+rr$Qb7rf}&4l#Ml7wQ`hGVgka7JY_5QzE6CRAs;cR#Q7pdxFQXM?UOf9fS@hE2 z8!IYesov}qRCB$uQ7ez`_8fyAQtXw5;D_S?k+}dqd?B7$k2Q{T;#ks<++uV%jOA~D z-P%Wlaa5vf$Sm;I(6+FM1z$7221zE<1ctzY-yi2qryfmm+Ie{Zji6cKcvy?1dN4!P zh8c|v6>e6ugbFhjX#t$N&@SZ1*ZRW;@3!(>>Q%{jQKBoHD;JA`<3veo;y>=c7d(8C zfxJh8GZlHmIR1u9p;Kz`}L*MlQTflrb8om;_@zxc2_OBrQ+*=EtJLe2VUIU~as4oartjQ4ZiCtFf z-!?e9->`tW;t{wY0MxzQ(J3uS!qzeR?_zlSZaU-)5bl^D)QFvO`x8Ef4vtzY=m zqjDa^c$e=$w%8+gG9zKT`QSDXw58uv)jfprXV#06b1@y<ilOvNrcB<=c| zsHkM`K224Lxc?-drqZy`pfBf>q;*l0p(Pd~zU%isY>EC=s|d;8ye(JMwMZkui(*?Q z9rbJY>GYKp7DD0aVQ7|A1@lor1uwaQ`(9}?%3Q#eqiAII!F`v_P{bk*&v6SA0KYaP zU+o7eqpOteWvac9XkL^&f=Hd4I4kGd3$nfR-vgF`EZQ$g>);_e5rZ1Zt91Ur3!NwD zd)<5}C}*1swN=xc62qFT&5M_Ie(V;i+yh+{0>u8P_pr(mL%6xBsPy+{_ES;QX`5vJ zz#{-_@<`6bX6WOvC7g(M01F#{sLjv?-Uuy*e^DbJ|c}C`b->zS)KCg1`uRe7& zjvxXrCaDc(8so4x*%6j4H)1K4M`^M)k8i0l@W@<8JFvTkgHRuNmW>GM(vuetfidmg_SvBMj`iv^}f0Gx6)G%D1tMV+W4` z_3Rr>$oV@?j=`-D^LXGmUxHuc;Mkg^7i-0QxY|!fG7n!^&sIzoXGfUnmJxjBlEU^M z$9K|+xW(5zRU9LB@UR^2lZ%~OJ&%VIIN%t0_|4v8JDU#X5&1HK=%{Vt<>?S*ZUiHt z2(M!RTTez|f8**F@2RJ}+Ur0r=Ti`cWDuHe&-`zk#p#Za&*BrItt^DuuALD#hO1mR z$2@Jg0{#mGzNd%Vb2IdcG-|w{x4|FdUC@cF7=V|jECahvai90966FZQOxZptQ_8Gb zEA$Fy?b0Gu0gp2d>F#0_B)rsuXy9c|mQ*yp`!A$<}_GtL$$q!^-1(L@3@DaTS z?g4_wf3X2|jL7#25@0j`b@_}Zb z(w7>e;h!W@OM12FG@{10-$|DTsTv5HtuJs*@5>=5w(lst2DFy0no~%tqKIAM;qIL@ zJp4gP%T4LK+-L{OSjuq4oyjpfVy$(1z;OGYzGvQV9iO_Gh_Q{56kh=^3G99y!FLme7J?V!!POH%#JGyRhLu}KMcBGsl>9atAVg_)#Ftm6z^Uv2^cYMe94Cb>`2G&m z2jyHuk#NjoX%TC*k#2TSKlkD2AfMF<>XK9BugV(Cx8Ko=nmtZ?!$UTETa61&kq-(# zGJ%?Oc-ie66^I z%a;H!0r6*LwOef-V&3|`@p}?2?EfK9Gm5shK(@J;2~QDnS6^)?7+6VPs+-9oU-ZNu zrA_C`8xdn=tFHeR+a}nLb0Dl9s~(REr@evqzxN$b#xGzj2TDu&ecYCr9$rJvRrq`D|_2_~C zcVYQWcC*&Sv>h*J?U&Xn-HUK-k2QinPbX~^9j4EYP?%=W@CrX^`emj^&rirU`>AudILHrNW&ObMINkvAu#PERqFEr>fcIoAOd7(9fxb&n5NJu+ z_+aZ*huRk1N(X`DPaHv%O9S<7Mu|2+9T5_>nNw#5Q;>MM%3XM3D>AtvLtb9yHsI$1 zXepJF?$yo}9NyJhsq}@|#+m8R?~gBc7Q}}!5a*r_PImgUEumimg~!EqIe?#;3dK@_ zZ?I|1XTdKBSiKoN0oUd<=g?gF-ixs!s2>JbN%h02b9RyEz&?jSIvTAxmaX-L2BFN@?9b9o1ikd3Mc{f(D zQo&S_pfP7qj9NhF#EG8qH;E<;)Hx?S|M{tZ_{XtQHK022xs2|@>8F9K9{R}&H%x2 z_RKIOU@&AI4W%7+UC@(^=Rwf1U!SWD>I0Dh22^;A)mP1J$XMC;m`LPnMqvR1->S2%vKzC9sau?NXXex&W zibEOIRJyVXl8pe@9cm8mZ<8>5Xd8_4<*j>L&35nrMvBlv6+dmU5k;lh^ zEQw*1c!hX89|)ALTlUm9Q@=<$)dC|;W+9+#pU1s}cir+hiPeZNKy%)X#Q3664LIg` z)al{t?Xm@-ih?yl)0}`hN&pBou48oLDmik5P(irZ&((Z1*@vS#Ems3ebJv#;lKJPk4c7R%*UxTMhFA$S2ia=?_r1r0uoV69*$ko2? z*M!1Jx9?#Xp1NG0w!ivtz002EG!TY%d{W=X^}!vtx9yRF&X-~b>&T{ zV4l=>RzTZDglp8Af9`Z=I;pE7&21P>LzwolW8~2NcAZ_?Wk8>t31XJRZ-7Qxm0B0* zYwhn2;hvbULEhfdgf4dgs9p-wq-fp6qmbGG@aXZHEOp3(;k!;QjH|{Iu~oTT8=ACO!R$!qTLP1-^-k>FpNww z-HAETmsrR8^7HS>&LK#xwT=+#2GHrSmudD(=g@$)o`q~89<XDGTm#yT_)dEUOXQ66g3?-nHtujnASm!u^mgFow5kt3Ul}XIj?qZB zPtZ^lrRSpxB`KuFRXlSDJOcA%zPMkJ);*VWyZP3fS5wB(uII}d9nLlj?^Zp?g9RM? zt`Bg`UiC}(H(7SSO1w-&Ic@6asB0#4q8p^p-sy=YCjx^oxs{z?oQHB=NYH4sdO%x~ zvsxm+OqOqo50dUdv*~4L?CH6YvI?>lFH&mg=;&(4Leeob%R1R2n~X&@Fnt%mpLf}b zHwf-k8q8;ydrBZ;21t~f^lnAdNpWK3Rp%WeBVi<_;rDD+9Kt&>S(nuQqAlpu731q-Asqrhq?Foe=nS^>c`-%M`(&J(mx?!iCHtmxcd+>-lGdH70!4kV{66u=(#uJbq@O zjy!hHpzYPA-oASf}HrT7hKk6mc$ZnNpwS^?KeLQ;0rnlA-RdjsTgnQ9`Su z^nV0p!iuE#8QOSaqQsOVZC^@3E9#G^**JPTv@D^8I28Z{k^-@7~s#wgF zwa|1LUK@HCk|GJ71D>S@rZwbiy@>1&SsyhOt*p*{Z*QHMG)6^TRvBJc#wU+L)j)%= zefIRC_U6o~eL^`Mb@mKGTz|3$s5r&M0nwC492%pOh`L6^l!6807l+GTFAvQHgK5(& zy%HF5!x-S3DWe@GqOLXFzOB6(Wriy2pOc6dX)b_FaEP;SRYjHUoL%tAD*FL){Pw(l|dX`oo341sZed%Ic4<=_MnF ztiM&|#NPIOZWm(ECj0)Q`!_~NIHFms4+tq?_T+(?*H9D3ISAZKw@l*$r1Rc|(fG_d zCS9^@ER1v_K0T6+;Ccj}Y0^r`aIPu+C6iBgR`Jc|5uz!x&$T3+>iFEBi>)-dFqd+x zFlD@eur}x%l4w4p_GX#Kxx2_nfm(A`whQ37>U1DNg=~^sr*{EORg^yUv<`tx?H6HsS2KKv+D;htBTmCGE_6>r>}iKax}~>_xstxbQ!KYTU>|)E;Bu% zy9w&DB^kX0BFGkVJ0*=&^^9%9=S70{#@mveRn|`q$62bb zgF1R~HJYBgQEhHTWtLC@dzaaa_W)SYQ@-)f0KMoYy&Ss}2`LZg&HtYK=m!ML%Lyhn z&5PztUZSqthZ-!K5@{=w>HDZKyKgp&HU2aUd)N#j4DZ5Wl?{pU)R&>38 z#2NzLa|ogO4eNBpN2?E}M0kI;GQogIH3qbL6sb@uk|;$oAb#tvg+ zp>P?Wp7DIRc(ov`OrxM2Vf-i)|9k11S-GckI{&lV%@DC>Ec4R>NIXYH)$@sPaL}9* z4u<6D7?bxeX~ve!e~n1=noF);I5SM#oG$1qpSxEk7gQ?QpuVeq$|bZ2cD1yIeHVEp z?Z@=ODBfA6rowSSa4p<97t!lGkjxPRN^DgnbOlT1Vi~$jc;)h&!ReZq0bO>!J0%}8 z^$umqnr1C8i0ZFS0>mwkSoeboLBr?^HU1=#LaQ>gYtCtsn6M2+2Tk^V{?@z4^4{m) z^H2F)3Yq!Wqn>bZ1$|;K6Ns`~IR=;=7*~(_W1_2TJkT$#k}L(LNv+(ch>~v2GNW~RVwyUN>U&f@Vv>4ie)Z$| z^=(s4Yf!+sXO)DT`_m4wy(TF5vA}CD{<$)IWB{17ab^NIo9nB>_LQfw`qBbbEBc*+ zP&R@>(3)cRGD+?DjkruT@#_~uF=x(qKV$8L9wwMDOX3V6 ztDeusays5tn)yD2E+FyVn0IrkD2{*AzfYT$&#B)DK1Q2P3S1DmY{I;Ej`!)T?!$AF z`ZHN4{2G+!x8}7)a`(2N;zLlQAZ(ur+7oA@mOX_!eG)W3k=0&tFf|pN1eA6Y^|yXq zzH(pH21uXXd%y6PzCD3x%l-M{iQBszW!%Xs+55pqf!3GE=wc90G2qsClyyAWz zRSZ*o*R%UG{@>mVFH03OOXMSxR^3E2^2TV!a$xt2c#}Z?OHGo$QAV~gP`CzW=_13%vFxl(3O5$KpN+*7`8uBsV)lQ_p9mBY!NawmTddL_{ivfJ_4_6;bCQNby+_28~Hbi6~nJ+LX>6MPiZEcS)*MsDBcsUh-cnc&0=>J&dWjUPS$f88yLF zEvCN$wD>VC+*12|n)y_~Gaz>vL#d7^zvMH~D<0hO;ybC#4mb2W{SWM6$i%eCzs@z$ z!Mn8!H_O{vkDXZ`eKQd6m*rr*VBdS_yl?o?fS*-vulwXdA9_R+oD`!qeq3R+?4BM} z|3`Qd6C*j78K&7$L|~=H{wLSTCNI3m5d_t@a+g8~L3TY;>jeCDR5pL!L_8O%)s6~0 zN8m!h2=DyVliaTP(XZk3IqDYjLB%Glj($Z(Wg4ZS(l*O#R&0|#bo=LP33 z|44az2iaG8cIJv%{c)z49$@ZlV0$5PVEqrKlSJXOXPR}W4_*?llmYfO^< z1bDIn8mqI?Dmraun%YqJhQX1g(tP#(Lb_pq5NKJ;4%_bHYZ!aSPm$c8xFw8(%jeCn z(Nd6iyoxf&j=t!fAgM~APX7T&M^Wo2zag0CrCyj<5v{-sw{VD0OKrxec&%Hl4;^j` zicu^Y%`DuXj?kV#tqpk{HfR&SKi{6JGF~Bno?&JjM7%0OEUF+fHB;VC(He_quGVYn zKPUcAvmeg)A*o@==E+xJ1DkFSi3axmnU{(I6h*mGoH83f@-M-uxY;pv!R<@u*4PJ0 zKH8e`VngygYIq_A={3JO1IS|#@-ZnRLF-253AN6^l9@A2$^EU3&u|)Ya`*||%i9^~ zc|SW>c6;9kiK>srqBG9}JpVFK+RBLCYUWu!r^Eu;Kp#~-5liu+^B~C9M^fJfr=^fZ zVUTufKh^-K?I)#nJ%Y2g?a{P9qSYY_#_Sa^^=V)oU+C?qKUL{zxJIQM^lyd}7 z4tT%0QxaGAdkoh1b|O0;zwOHmC@1nTLH(3#PHIG;Ir z*WzYBud?aMX_NAmz|Y(~mLGjD-`;ADwfJdGuhAUW3wmL;uc7i4wV4zRYvU!krdJ~o z-)}FkpEd1dRKRKhW`O?v2(zYRAaWzJuw@%)$fpUNJW9bQo=y6)p9a;*t60^0#zp7) zw&(yVVn+X5Td(y!*w!<`R1ySWYe7ZE(|y_7_8+&nA5Yp$Oov4*D!2BjMNE8J zvOsGBI?P`%B-N{%lXn{4Ct=9vHvSpLq&TbeB>yrMM*VCHHz zAB{OVPQ0K1&1@>Ykx@x5{qP#d3PmvC&K%P~jjidKc}+E`T{y7&fC0zX{o0s(foyh~ zl}L4{c$+75kbu7B`!;3$&S$aNefit!z@+^7QNi@5DHSyhCXU^`Zkav{QtG# zJ4#txEZrS(XP<2TtB)fHGTE?Z1=JLoBw74~nE#)tYIe{DqJRIH=C8KfYg95BKNUUY zKSW-h>2y*Wm-8K`w$`lvb}ChuQ*&Ifk`t7dV_0-73NG}Jtq|4gl*U^(F(Y^-YJ0<- ziWVP!uCWe4qK13pyz)Iq^r*_!|4%|-v4&kp09?M>y6E05Q77jMjaInj^&Lk;LMCF0;j1~0E1qC1Hb}+!1#{BwJH#(r*2YSZ#>|w%Iw5asvSl@2=j(=R8IEq%C zqI52DdkEdzB?+jzOFncNsLeUE{hDN(IZaXMW5`}CexccKOoD|_M^QjOkv{)^3#h|I zRu(AYM~B9yQh3Y-`s>^Z)Adqk;tdzK6eDE;j!_8A!u|n-pB(N`fs@~Ok(XuuS=UV- zT<$Z;zVittTQkH0K+NX5KxWMNYt@XCt|Shv8J{`XG~!N0D~CULTk3nJw@tSP^)R7) z^8L7}`n~%dj&;<@#@?`zOrVuU@VuSI3Ah};5fMN1&3c+wqfHz#WGByi1Tmfh@CQ84 zQc&k!_ggKTw3U$!Jzdy&hV3i-CtE}@lj+dR)oY7e77vxg08h7MM<9bEWLIw+&%GkZ zt<(W7|4u7J;?o?nV?ovu0}``gesz*b|M3!MOG#5C0Ic`k=YtWkUAL=_+Q)uFM4 zm^BZS(;Ko;j$w>4w`DA}P#YuFV64f~AE&iT%}AwOH+#IV)*n|^&o~9E@@}4W)w-!L zTn|+KRP3F&0qp|zhvEocPEoFr9>K0b2I|5rWQ2;Q7Hz!p-4EpbAH6;qbJIXpx!C+% z)L(ok3a_0iNFN1P0XF<~#$oZH5=cIJe?-~$@lMeb;_}*s6v0Gw$tMWRQhGirw{-O1W#;qDK&sO7Y#nO&#Zo*RpI4^zN3A>99E1BAQwB#AK zt6n9tLq^?%tX4WT&#y^{Acs4nDaF2n)$v_l%Pk^qFK=|}?~%5#guA}55);>H7Q*N` zF|@I}N#4RbA%L_CfsdC=VitPe8qG&W(|5w|Z--UAND7DsY;Py53Zs60+qGc%y_duM zIp0f$bu;RW;Cn6!Z&4;YoM>sqE7i2}B@}1wzg|z)$ev`nyUS@ey#!Desc<4Em`Nvs#3?+_AyfRY$2Z5 z^ZG~si~|{9lQ$2+dv40Pw}t}eVA7jsG8hAjh6HDX)U!XgULNP z)x4V*fu4rQPapQt8ug2Q`xQ{dxHYGC%rd#P#otnFJ>8NnLY4z2)4%sQH74c8jsBxF zwwii^Ei)x*1G7qBniD~fp7$nfALhB(0#|jV%eJgNWS6o_8XjAkVjd?L4D$Q4Y$= z4Vt{FPq%GUC>I9%d1c&|26)-%_&82S{&| z?U%eyd9v1xUadb7|Hwste$sIuT-2_*+Kf8%!48XpQL3U;u`!kd*KL}Gt6u;w*W#p2 zgHgYzx4H_*4rrfh84rnmyNj@ylQZioFZfMVbjUEI+k`n2&{~KX7?C=gq!yAL z)Um!WIri%lG`pa$y$5;c(-ZSAZe`M=_j_+>dN}7UJ3Pqk-9+hBebVPJ>3wk2*J-i! zyxJrk2<;a|Y13%PAEW@^Z;d6G7$RRdyb}(U&a@FIM9c8zMDNr z-pg9~?Zn$!7T~Bo$RBmI*fVmwe}wl=oS5v5=z5Or?e+U(-n)3kQtim1Mjy0{9>Z76 z<;JcSR|m}6ZZ2(ho*fGjwKv*uycrz^r_1dq{~DTDdcFEGrt#FCh~-AH@{v9bnbwKJ z1?gC+74AOiiN+=W=-NgAlXkDzh1Bk70s11}{fyG#ng-f0O$N8t**Tg^IF)`R?;p^* z&13#N)_1)9n4q7*?q#9jAhN#fMYkD5z&d(|mdBvW`0xJw!c(^cmVdKlU7iBVN2zPeJ?cpVmTPY#!`*L)&Uqzh#(e8jZ9vq&C_B zJ?MxY-f4l+Vv{?$7_kf#MWD&*q=sCcXw4{Mu#XtJ#X4G}We4C&>oesj?;Y2v#>ERG=Uh`Kmi8H@f!eRO zx#-iUdkyif@m2*#Y5Nthdl5$v1GCZ}y10E%-Nh-(b3sl>mJ1yDqrnpB7_y8sF=KTV z?x)JYqL`rNg3%R+%31YcurGQNZi?f+5!YKeym=d*^%Eg_ksK^mf;9D0E1qWi?$;n- ze3)=%T|JljDw1NYI7f`OJF1Z`s;RN z<+mtaZAU56XQ_v`k%06MrKP)ZNIyF_O<2*evvEpjBJ?3wzy}ztZ#9 z;A(?1yB(3@|9Z!h@B38zRYtZeow2H;_c+HAs9{N&_fR^`dw|w-#Wci zv!JW|I;a$`iK7dGr_c<(EIow&FyVRmT zLs>IijtE)1Z`BT=s{2%cq3Oa9byUg%RjyRlflJzj61ci9$y#%YbzpbPb%XvR+Xg}= zL&~UPoQ3e4>D8YGA^!??1FiQM_IFypF`SA&9NufVUvo(WItH}h#c%Zyt3YbvpAz(^ za|70g=^U>InpdQyC7=qvY$_5) zZ>g(@?9;=a@o0+)LW_d->|n#bAxxHiNQzKS2cn%y<{ zvTE^)XVA0vr%qkx&cpSX=uyr!qme4@vawLy_1BSa)Kk-0w)KXjGBvigYp2u*!)Bma zHj42r-dn(M;Z4|eA|6P&U^qq>6){V;{XTWL!9@q{+}j!5=j2!-?JmY`i z`CRANvA~UPIjJ_a>ml7QTaGp_0!_^xx70Eoh9bF^ZUlFZ6?{d%i1a;q<9ZLe=~Lr_ zvjQ(Y8p*+xSL%QwAfaN&V{H@!3R~z<2s_k_cLGPtXF|lR8?9-eHOHyOo+8JdjZ+WdlaoiO-JF zGzQ_#8RI<_maes1#6r|H_|j&swP63&(qq(miTN-u$Iil^y=vZ8mAM103CAM=WFB>j z&dzTXiA!39vr;B%@w*LM^odEcrNimgvlutkmdM1oL{lSGCjj!T?Tv9Jwx2|*A2eo^ z$>ck7t`oD*bJgPRCp5~X%ObG&^_}G#8%y*~sWB(9J$Q81uluio0>7h~@9W|&fMPIm zDut-u9mwsCrV(JwkD)_se{CJ<4;dx(O^N|-mp^z5qa>X@^u_2Xu};6;@*;${1$=0x zPCRG`s3Y7`otl>Oyb5|VZ-FOM|=uKKw(>VbHPc7|?;Em-? zm$cR%>79iyd-UckF_f2Gblq3p?v|XM1NV(EnMl_s7jA;}>~ky0_i)+O#sgka+8!&1 z%m5ZP`1{w)7X%*hd)>r}wP=@WdSG>Ps_14h(Rm^@~j5V-u8VW=Ii*9!ui4-MuL z%(XbQcR+*LoxH6m5(XsaP`G;z_GkjR@~}$YV|j-A&}9JW1<%BL>^aOj48?n$uW^{0 zY?Q_IL8w4?CgvpPvCO2wvVJE=(R7l!b_U#6=oA&N9AHc5(>NcObh{)IXeYV(A#Xx~ z6nEcHf{#_p_9ntC%}fqiDFB^`&vwAON({^Bk5536D22U_tNdGIHgWxaYWgS+VnMgU zFc>O=RA3|MWxp+tBNRV#BP(6?dHp0L!QS)<^l%mwQZjP`us}0`Kl3WZ;jb&AN@YzT zWp=u=8CTX(1U6Ain>X(`&bP{&?OB6ehDEWZEiyLT#qu|r(+kYl`&U$+tVk>3F4k~G zYt8M&vjc8aYB{jAw7Kl1zNZP8`;crDuCPTHqcNr><3wIafZM$Qw*a}!bs2l=uhu}{ zht-DUyFL8g{)K19*3)+XTwH0WKJPP=W^Ip;tVqJ?nPi@@j==jqU3e;m-dPCgyt%Yl zN?+cXaSQbWA}f8_cHyXf>g5`f0@}AjeST|4r-9+6rbju#?hdblJGtP1IXp3zt!r~I z5@ttq^@oHODhN_4f~-!DrD&}~bYC)y*OZ9+@XtS~VuZcwL|RCcc_;`R}eXDL12>tuF~ zOym+;@QlH&H`@y6?5P9*H)@Ho? z*Z}o3sw!yG*N`Tp|ff_^Nd%rNr6b_B} zVVeX%VtXj-2d_K}-Kw)SWLovYn+V6`q8qZ1_H;fg$>5NIq2lHD#sUrq(PR`oICEJ7 zf z;++GA1~mJ>UU`ghs^Y_iv%R->XJe!Uu1I~b%J(P)B6wO%S&~{t?ToLAQam(*I*ZN zzFa~}bqIV<=CP~dh0{^%#*63|Ylah7iBW~990On5OEElOs^?YPVza+4O!c-8Z>`|J z$=$v+a_-{b+IzNn^)-%HIIQh(;W}QcK#Su&&P1XYXifD0!GDVi*}3pL=h3LcjHS(k zyiq;!NsZ1b-f*)8<-4=ReF4SFaIeN-?m6mxwwTQv@%RD<;{Nz`K=2dP4I5n?E;}(1 zmJ(62&jikhX#IH=cI#>eA-ssmS?WS4#{5qSo#c(f1hfpyTf6g8it986O&u-w;xItN+ z)ta!6r{UeT%5dH@*M^dEC+c!uW>EP-!McKLNp%U;3pU?8t>fb+4 z_F&!|f7*s}(FypV1miZL|8C1M@4^e7l{M`6?`Z36QrTA<;4sA@>S;LRK#i`qjZ~8+ z5CKTd6?$WtPFl4*K^Qt~VqzLF_jjMs0s*lQYJ>krqd86`Uf-ZKT6lc$QZ9TLCHpeJ z#U`v7zK$XIBc#$+;icZ{#bJs`r75{?7I6`ws}DOJ9d^2flji*$_Xxynv1mAOUSj}1 zu=`n4`}Pj-kp^X0DXFWnz<3q-PD9w}pOrncz4or@s)kV>-M5|W@#BH$h4?Bw)jH6 zP3@!D-!mYfoiD*Yjy?sU*- z!?Bdz6@3G^OvYALtnprC95TvdgR&(u@l5jIGx`@j!;a+q!eW`P$)z^D($1R?Y z{xx{a&x{x`DwhB*qA%NtLFT^l=33U6;8c)u}qZyeg2Q9DIH?R zzdiddx$W=6qgEF|9Pb=qIyxA~mEp{C*PEKdg}&$j{BCYw|Et!vNcf$6u^g^@bXOQ$ zm88-T16P4S+Y_MUej`dH+$Dsx1K(k4^MC^sB`)0IY*Tni;TY7gV8a{$+Fn@?3efka z_I~!sf6Hvf$XTm{uUIUtVSdhUEFu@wheneMd~$n>a{aOJV5Y6d)FWkt2Bns z_l_Px`>ZaXhK6C{lj`p0Jys74hnJGfpRZwvQ=z`CwpWxG$+yL zB=T*P0ysu)82uLxt7ks|#iDLQ56`BnW17F((TOupBT_y(@IL6pTUS5&m2d^RZy_Gru20BV4N30m_0hk?duK$WQDq;~Z`J@4xPG7t7NuwHRbNm+T zR5rG*w-_mJB&l3;W=QbcCGYuwG&sNhsK+5!FJu9GzS__MsJm~3u~tPgZC^k1Cb2;t*k+ED&$LTFZ3)?h@S%<6`NMF45wnrgGDc%3`tID+YA^j zheG+PnEfA){|Vn$wWyk!P5`j*=M%O1)yUp>If-C8ntRvWxF0kJS!4r*wfd!bkqw@a za-w^r%URm>>#3q+TkA((-R*!!{ zfb)+yhEDapQc^+kAjSilrl^+yLbI4E7l(QZV1s`?*^!fpa#BI$rkb@!NQHF9qe9oX z$h-~y{#|HZm~m|H9&5XCVJ#JVtQ82AW@`}9TT3MGWF_0J= zdDbZzU~UW_v8>E|F~h!R7`~8Rf`DeCsZM`zG0bpI6;sDjFM}RXk2TE5qm{1Rwba<{ zIzk`OLD<<@Xo?BpJY==bv`iJo3*|jHt}INJ&-_t;TToK554?mPEAwTP40BIp9Qb{L zgNus`TgV@DOy)<+*{*8?ZSik%BpL>Mwoki(wl43EH`x$zRW2Z|QX}+xx8-!l@x`a= z9~-YOPGp?;N!yz*KOMtzmfG$HBludZN9e<3 zvIA5YD&(mO87Kpw#(wG1cigJL`|X9e1#bRxln5r*G&t)AR?yieyjI0I3lDRyr-98* z_lpln-6R^4G+I#YrO^XOBi0|@W;l~$(nl0C{FXW{DK)tswlp!a?Z#`Q`Up5i*?(Mj z+WUKqF0N*StN}oV*1d1`m8Q1Vg`)uZi%?&db)wz?r97IYdJ;P93|&Pko9kM^RMo(` zLT-U>rOpv{T%4{onh_H;_BhL5xGD#{j@SeMLr><(9o!GrdLg9G269uNa3|OP()7qa zVWC4N&;55ntFs!YG^^%c%VM^0IMrVX4!Xef5->dXxuAe?3WcBycM8~cOKex z`b>Hv>*J2r2kRNNyn=(`1`P>ow&TAu6#+Erqu4!xaFp(*C9{nd*=Z#u50gG)v^AB4 z4ogOBP| zt^*tV`BBgxl*37uo@{OH25oOLLS3if+9$4yCSJz=TvuuW-_M7vE>EM##d+FfmX zV8cM67{=4nlD8y~Cxw4%ByC~JnSs)q6(|?Q+`+-YBk}&)@f#o!oWfZfgJP>B@Jw~p z?;lDE@>7KdvyqzwX%W~$P04jagP;=)m8&^WW(qefpd1`s22?AcZ(j>rFnIQiVm-M? zvibGHsq~*HJD}51*XGR)7}{f(SVJ3pK5a`Pcc~(i*Eg&blWnXnk9n<+e~G(73p>=V zBB>(`U17}%VO97HJ@#+zs~D>Sg?yTOy|~#wKd?DoelE>u)}10-N-IFM;cEriry%<% zbv{{ya!RnL=X?yi7c-@wuQM0h;q&e=a3!nRelk))LmY$oriq6V*f*SH%gtnK5Gj1_ zw|=L{G&6ZqP1hoWb|>4r-xsnfMqXJcMCz;;deIu}}J^gq!;e0B&@-W_E>Rg z*)tbWM)C#f)|?Y=Mx6}>&L?)rW+tnAjG1>Hs0XoE44n~X7W6@8=)@Poip?;HpEFPkD` zaCuBh==)X14^S8Y#17H88C$%hwi1P`B}}+d@#)3fATCux!<=GOC2i_FLLWU@*hq58 zzk6OlTV5$&N-tkBFjuXTzDkRJOGTfbDWEA09>gOAzE>MbBiBnjzlSRQeUZrrw2qM< zzzl1^@^=Z717vExsNRqPrhhtLOY>;*B^!fvCv$wuNJw>7Og?fb24aY|vn^uhc@We; zqySa4c6bRoOHe6}>5qOp%Kz-=!q#1c`?|D09er0y96jlgi(=?(IL!+j*$iBh zDddpWtl!GePGA<dW~^o?Wmjv$O}e_ zsyqrNMDiu?Ijd+y^@oxl|IP%g0^HEJvx_`aP^;}9*YKYyWX!Z3Bv0>H zQMj!ZyaOD4vLgwn`&g|5qQ{^n^4qPS{}Lb(_f&=*Y7aK?@Kn7s#TxxeXk8-ZEE;-V zzV0B`IgxV*B8aR^mmQ6W>5FOqRUs#|yk-s^Biy*Sf%^HVf%u%Zzh3p+qq^I&&t+61 zCI%+rh0dEpBn04RV<5gDZ_f^AnL@LQAzPt2G4SL3*>+WR4F2wi|6b-N^`?dQxNCS* zTm01uwb8JqV(P)6?!ZADVpG&=Z}S&wK=_$6(=g!|PZG&4%Hi4UHGg>_J1_twI5uvT z(?`|Q^KnBHkGJ`lc6DC%zWIDtj0wXOclW%f1}g@2Gd*O^0g|k3b>ncIqP=vU=7};_ ze40fqNukAV(ze>qeSY>cg0>5B&nVQ-T`9o7I)mfr!`Bw{WWj_l_?gp&JskJI)BHzT zi#vO^LL3SceQy%b#LqzvT%Q|5G{unGUOmqY7f#LRDsO0+wG`XHVBuCt9=GkA^yo2L z1!~U1Jo71{b%65okrdLMQi}F*i*$M?3OdMtq!R~?{8#gs9+k=hgL9Qxqow=lJB0?{ zkTj;Afn3fJZ6nQ+8~azO-s%F_A9`dVgi<3u6(jfRDr1q@$4V^r4>_T|Yo{*5YDE+I z)&He4=I}+7$Jyyk)n@B5kgr=8%!=3ooK|mHw030DtAmj9L3ID1G0 zN0Ca!O>MaDdxM&%TJ^UYt%e^Ts{0|p`GYnIXdgA_mcZ+ydPrStAA4@xt_(|E@o@QY zDQ$@@N_!L8wuN^hz5H6*`qOg#8`8K6DpFGX%fhzX+7hzDStk1oPAR=#a{^BDW_Q$w zZ?!va>)FXZ5R@Tmx_kiQcv!A!>RfqQVk#7{W+ix8GHyr)H9pYBCKf`1&~wHW3^VkG zs+N-Crp@h+yK}Hz66uHemFtF2?zSuonN@pnv{_3!e!wv$BZyx6Ra zAA&$Wur?BYzuEat_EAf!6sM?5DT_SwzKeoG!P_ipVpjRLltzPBc&1GP@qCFCN}koa zY{ig|pst?IvX$++X2CcDTeI-z=Fpn>4+h52Bw~KP(5ok5X2zwnY2T87_=k3g=2em=UoE6HfHXd%Hjtza&n^*(7i${Ytb z`r0E6mdrOQCtEMnZy?O-!Yc%y+ywR9rSh(_z*m1(Y!vPs!74>Nj_gG{GSf#i(e!+O z2ibJX+PtyXvyNtIi^hDIcN-X=BjlwJQXZ2dyR9Nw}%*k^|1q5}8FR(Tk^)o}+{fDXv1 zdaivl4DjxKW!+_STxKdKhAB%hm4bPcd-x5({UW>3S_AVC0y=Z5X75V0?5aeaz2$wh z-uF%CJfKzz!S@~k0j?>}?{j$M9v4Uq-7mTt9*shDryQ7Zc>Pf8I$Vfy|Jj-pv$l^W zCn8{onY8!BWku)qxR?J&jGx?*GLly3+3#~BL%B<-&XxX3c-*XF&cb`6KMht8jFNc1 zSjABg4&K9#-!H8*XZ3_$)qVV%@$wyZc`Gmf0_As2H2dd>mpP_9pd{5e`E8=fF}hguFf??dXz$zgWwpFh)pbG^h6uH`VR$1T z(=A@(g1|>|vu1C$1A4#uh#A0<=A2Q%$XYWbPrQ>I>M!Gg(zDs@erdT$!Fvz3Z`$7&7R>i1l8{X0eaeV3AlrJ5Zg zy9q*sPw8G_{&L4G(>18Uo)e^_WyGQ2>NA|SBQ{P)< z7&NVw#2hUhU5K8AVHYf7p1h*DCtqv?{k?Vh$gHlC{`#^I@lwTlY%|v$+u97Q?Z}rr zp-akwa}}I}yZ2m$u#~5sy|fH%hk~Hqv86tkT9k}7A&U8+FQ?5#chW>}(hIz*P7i=O z)yDF=^UQ0q-;%ckcmh1S;X#_ON?#spDD+Mdej)l+U-@<%Yg2$40ryhhGNdit#di$$ z%h3^%d_)_rGWr&|n>~P5>eo#hKHcRD!P9$5H^|0Y%LHriM&C+>n2qpPeZw28r@n8j z#=Hf#*ML)5g6aAe;dRI~5dN?h-zaeBJRanT_6(}p(7Yt21Punbp?F$Jmu+TaP0AbhNJ>>w0bSo2a)|1JZ9U#M#S~QlIu|zA8`b zj|%QuW*FxmpTOYppA$WxcO($V-Km3R1$KS@_06OJ=>-kPzM!r6kGD}xFhI`|O!rF! zUjUUa@dQq&6K~HpsS*O~BZ@PbIWtu4LINyC*_&Mh*^j*}0}ayUtI=)Rn>#KAiN{FS z!yWkQ9Z)E#RZ;nP2Y2SZGX#2fc;boy{xk{kJf+H((Sr+DC!DC39x!$ zzKnr9{j_F$#iO_ZV%7+6487}^d8zv+X!2)9a1w~F!o45PjuJCX?YEo>G(dvZl1Nfl zEz71OFo+Oyr|7N|+p=bj-1?efAw#^7%qGl22M62f7C5vK{U&y%f z^6_&;b>7$!SEp7z*vb>IIU>tu_A)!`e_?zDmE9NMyP^C2g%j*9jS|+oN0+fIzTh~} zEz?b|{&Jo{fJGC{dMpaxTri<@6b?fqZMliUZ}jR*?Gk6xVyX*gDA$&%Oe$@jm-p#VpV~#g9Msvrw%=C8 zX>&_{c2?|*L}&1o{fRq-gy!#wA-LhTyzIAP-ta^If=x<~G!J2NipB1g8EbCDOloU9 zS=)PS>}@#KeUcv#KXOad4={`W<6<%cuqZy8%IHNySxWsAz+VJzU+)^iYC2WMd1)s7 zZI!Bm4dA9_EmB$TuD=rcZu1WEh{L>>vm~R%FZ7OEv9|6Qzi@WyMJGWj1-+jqa(yx; zuMyzAc@l3pXS54WTP8iM=g!=8o{d%QJxE4)s_$FFXu02Z;zEwd(STcErB z1bOLi24Mn+)t2A7l^mxI32iT~Q4F|8wnpEEBj&bIsys#gP~$M=!&~8p=D$BQ-bCUy zwtC?oRZ5>u{2~dD;InG8R=Zdkkv}?5tY@UsjaEA;;YMWv+*RY1VOB-x2vV~`5-@%n z&FOYrfCm(OSIT_Gxb9Hca2#^e|8o-XeNT4W_Z_rePepGPXBf2b9xOCjrbLqVAQEZvXeur~_FLpv7CE zUv1B9qlFc_nR!)>=4k>pLG+}*uxwo1O|qSWdqoJE^Wxs1>r&F@_Xos-Qsy`AD~Gvn zB2UH|A8*aW1)w%C)JGU7Xi-FIA(7~*1>=SsSDg)WZ_t#L+|&RBC%0an-NmJ)aAR8_+=S& zhzMO;cR@N`YC7*Z-2p+8u9EDUJkhtQEV^tc)oO#kkWfLZa1~kdtTqw_c#e8%U{7%F zqxfRpuOmljTLDm!IsMdgthRm<##ARz1Q=ri^pXbC9!dw88?6i0HOu;{nhT^lSAvQZ zmJZ8SurmoLB&9*65M|u$(8ueSH<;5Plah@1?pl*feX&FN;q_iDBq&8U(M_ z8+1&SFcr5E;xrj`8LI- zhZMnTPmrq3SBvgf!okV$jhT!DETMhJ6I};OV=L!ebRZDGi}ZL zigiAKqgx<@zTX3BynVVUd-CdQu?L#F$v1z@@3p=Foy9D@F_SKy70icHp(PG+`j`sr zN*a3xmK#(Vu>87WaOW87qXF(F-z*7(b4IvSG1K~LgE*ogM^}*{ zXHyN*ar5%Hl#?T%U9^@oovYw|MzLBR=4v!2V|-MZN-Yc@lW~h2nOLn%5P9fpuf)9Vx&T%ucSw|u)6%I>nCL$i zj{WZ!<=8LO^R0NO%Y6v z-OBD1WKvL9a=|b(o4@As{pf9N+KI>uBUN(>__Y8LHmxZ9tr|&5)xo4)t;Kz#XzwDo z3D;01<`nJl(q*8ErS8c%sBz|9-s3OVTzmc~i9F!h+5|ur@1MU(G=Yy7pZ#l}h~^6( zf2s+~bq1)JlVg78))Zt#GqyegHQnG=}j(`kL3C9M;s$xuK50~U`caU=V3l%ZeL&XgfD^HZI3LjjFR+FYCc z`JK;PmgsL4uJ?NX(-Z1wR$M)O1y(BPfE9Kltdnm4l{{c9_B?Xp0H~v!j;!Q6*fXvB zlxT{MPCVPZJ^tov8^;;taL+CKUb{ zT;7hei#+doyYC*`_%K1IwQ^$(<8^kv?>MqcVqwU_B)ZWE8}eWFwgtnKna(qEm3rN6 zF0(GcI`{v+3~#amC*G(!S}p`HWQ`-`p0EyGJ4Y9bu13b{`$^Yp6cIPsoP`&OWdiP263gF^eixZZL zmY{DIMWgY`n*PR%{<1eV{Trf{vx~#pdi=v|vg$#Nx@UtO)!U)HzxmR#=8eJdv*L*S zWF;f<*E2m4_iGXTIWv8j7=F$;TYJWnv&ir?r_qfT^jsrUK*e%y=)3b(_Xtk%VP9}w5zISFHYSBi=2=hq!zMYqdViL znuhFXcKl2YYqPs>-8bsA<(|D)4YWC&`lZ=W5~u@MFf>gWms-Df&aDkrbDzx-uY%CL zI98_YJWLYjTqsAj7J*#k${n9qqTYwxVt3?pV^H7Avk1-s$k36(b=TFam{p11GL>m8 z1n#C?Q^vodDa{4xOBI{VclJ1P;yS%t;oD&EX3^Qw0KKfea68t5O?zi;a)qJFeWN~5 zh+oQ4&QoxbDc}5C|l4OMwp;)Z@e`QEa#|QrAD&O4#u%47^(WO^LfxQ!9Pv?}T zU7*oJ*Io|th8}(`$!7ajOc9KP`=yk zTV;TG(|&xy_$ZNAwVm?IF3!9k-0NlhYGa1k4t||&131dH_2M2n z(7$uuOQ-uQ!C!msBApm_-Wh&H_0++TVaGlz!=e2>XPX!&pcOdaM$BZ{$}fA$!v)Ax z==X29U=dV`Y9r^ONHr`^U8V$p+!?93;S5V&$L!Ej0#~+)8nLyob!=@oRflJEK0b;E z<^=}SUDzFcAZee~C23L_A+>K{bK0SFEovUk84 znKbxY-?myFU0!&1&i9=$Hbw!yG38IFiSnB7=OHn5aRIRd>BuXor)KT`5~+gXuO1 z8bpuzIFI;-J!cGg`#2g3og8pcHOo+&8SDG&hlj8t9}RicqWKnY{4e;Ot>-Ecmaqg2 zj-R&s6a@7+i7WR`JrGNnndf}~*rM?BA4JvZnPXTFCHjlaX#_TcFhle`Vi|$4HLgIn zeGC&aVIn9z+_0TO%p95v3HCktV&Kn!5SPF&xU|a}KTf+u2gXw#)kXMN%6uGyd2lvk zu#wzMn;DndImx=J<*(lLk-yOV)q`E`cNq_w9joHTF5mH>b2Nv4znp#5IF*W}<&HRG zCx1n>^&QE<;VAHO^x>Z`?6%$%q&bkE=B8cSe|KM2f7;zT1a2=uA$UKbdNkdX)oJ0K zrjUz`)vjvOiygwCsEmd(AT)1ALWl?B8tMH^&;!O>Qg9sWZTg&f9~HQvtnfN!%(y<% zN?Gg4{}xv*rnG7z@nxWK^X4QVDbaT!;MSSx3L(T6+deMi7T>Gxip{dLa*0JJD1IAF zKHzAA`NXtq(-~qqy5zdCE&d9N@0X#WM)%FgGP`|rBKw=LKzY*TPt9A&fJ~1^G7RkB1QaW+NK?9s!rnUbKWABrRM*NrDROu z#Q60<=|V_khTiw`v?AnmUZ#zHYgJO}aqW#gzlclterAbP?j-`fL*0(bOnhK8wqN~a za97p~p#t_?{l~H+XeE6c!s$Jf|7DBc-3$g@QEd;=43Wnkq`Cs%l%x#-v&!QkoN{=R=b{Nh55Axpb+>sc)uVXQsZ+FYYDcMvm(Q|H~w zszq??x^IUn4LkEZ$N8H4u8&hQ;pvs)BAA0h@WXo(VbI$wH3)k>-2vK|sQne1L~7k! zULO95wOJLe-Iie?9Kh(j%{blHNjm_6pv|lxJ%n*;VVWd*A3%!_2MW^BtGtIBz4Tof|W zJ8I-ZXOS!i7Xq`cJ?HfCTgb>fR|O?1)5trk`4)e1`hHsl%lR7j$>mT1w}hl*wW`e7 z-rD;iZ#xH*f7cXxOI_DK&PO+q8z{dPu=K?E2?`s=B&PW7X^j3v1N8d3hQle5fd z2l=f2fq{FwJWqNYFFSi$oSs!T{|9(nwZ_}(oXr_oe*rPi@2Q4SAN9A2eNxW_Z_ul9Ve)iZ= zKskO1I_kHWJ6uMhkB=-3{mR_(<{^aRxWSE`N9ifAeK33Jhv$*{LMx=J%e>t2@5&?P zkdkHv5_+vJhIN*fZ}|tI;oga#GaxA1rVi>Tc6^cXk8l@0qmR^=Y|gHjDbL&3hE4yC zP~J58d5G;ZLK6iE1U=&5zv^_~XfNncX$ivsv^dk2j4s6VYu^YxV4icY0FIL zBH7-hk{z>(_xFLvF&0kE%HwHKLvxT*U3yuNNTV-n!pX-cUY=IGklS+0S-!P5qnr%c zqfL0K{16P7UHRcGh{3ROZZg4DEH61Mb+B-hm`)z~);}ARf0wTQyEC#L#jVG(4A{jj zzZh9Vu&Hn(H2F`tgpp$rtyRx8&tGYXTv;XK?ek4vNec4q)Jsd6()Smf{tR9CoG?dk z#UbU!FmlOTg3XMJ+2IFMuoD7HS1{>jL-Wn5xISC>QQl>sm~}1O`wolaZqDecn*P(Y zXXnRgk%A2Z*fQ`m~)Ps6l7*9cWbXPO_R0aqo2yBdXdeW+W^%&J-L6af01< zfO#X$ubb4*Jjz_R$zKkex_oPTY^4IXq3w#b?%uzpftS@sRk3cUw!2LZ8mU&qhZL?F zGe?Yj;ECA=D>*(pHThgcH;9&gF*P)vbQ_fH+r%yOwH}<~|x38H_GCD7^`E zerc)u`w8=YYwy}{o6ZrLfeg{B@GW@0g64hhJ(%$g^e9furoz1{5{ytbcJ&urS9WGp z_uQMJ3KHs|QExWS<+gsBZ}u|Q#pINTJ!J0OrcpEBHVys9H#*BMne(i-;?Zszj0WNK zzTP)5BWIXUpap|8ilC(O-$blT#wMUum7Il(M6VE!t{h-J-Y95D9g`*J_DeboCd;~# z_8TNeL3r0AXcI%S);U(=uLC~LyhFA)e3>}s%lU~2Z~jbv;Oqt5A2p?l5xX3Z$O`V( z1_G0HP;Z+YTX_uKi~$VOReGcG|HHvWbb$a7dye@At>o}enynMQJ6XHl&93@9e2%cK z-zw!-;Q0p@=lu<^!A)>lCw4Jx%~CDwr(@>ua61v^%-H)K$~>HBfBDtW!_18g&6Hkf z`*PAd&1`fdLFJ!Bz4#-bJQ2i?ShQ?bi+U za4h%Ee65s&^}qThuNzL?$S|-(PexVDUV3f8$UdBayyn9GRA&DtIy92ioV@4?$<%~} zwN$Ob$o?Pd!q6e^4-=QPQ#ISfLdho&o}Xo}%;NoEObeFL`27>F|7WrvdVXHX4?2Yt z*oH~>Xg9oqP?cW|lQ;FFxzk&i?b!1NZvWG$Z&NxlsEmidP0qpep@){mzpuczchOt> zyHmL?5le-o}Ka3(yXTBJP*&rLOYTnCZFY(-rNMWfO$#XI!w3xG!-e zZ?T+QAvMf*d?uP=&0ya$*s|5^ipE=cTL^OY5?rs(>v-Nk=o1ACsjd1V7z5MDVk5w( z46uDWV0SWB=diohJly(ux<3B&y)o`tDK(_ z_FO;7$ZQikFCa+|5^|*JUoQvWoF^)3t6`4sv6|>t?;zb+USg9I%!ps}9@ce5Dm9ae z-f;9^kZn8>8nOR55`}IFS#_eh!Qa^4yTD$|zs>tVa#tI5T720XY}@-waLbFa;HNy3 zUs~QBc6u*UUgfWFxPflgr;)-bdLx_v$fgNZiz5s@$2wl=Z zjV>dFd$L0h=)ib}gex0IbO@UkHe88@nZbmrN$J{{B6e4mRrJx(BNLORLz2_WtIO|m zV)rj^4aP!Wc*5C%0JpNMCAw;@)}kd7w29S5m2K_&FjaUESNP2^x3yD#&sT~S$x+*q z=2xo+`SPl#{1s__0aOzlA#D5&1*+qyX_DSaUkE!7DFP-08DV4JzMEm%Kq~oU%;b=T z$fMiKr+%Z2LMXc;bW_MSRUZGkeiU#2+irj4NK2Oi+9Yl6mPj=LI{E4$Np-d6c&-G| z-_6hGI-H(nl)b0l!NXvp^iGda%JGAz#5ep(pFyI;&*&DF*ZK$Fh0i=PCSJUCrLi{; zk#?M?4qs3IX<6xVPD2Posdv~-jb&~6f}Xk!CjQn!$1QI@vQn~(^Dn%r#MX~(e{rQ^ zKTwZ3JL9gM9ZoVrM0=;3@XUBT3_%v_bRsbS_SzHh1dZ zli^xw)t#gGsyuDg<#?bS)M@GxE$7N>e4v)SiFKF6imczG9}}UzsA?bdJa#o@YiJqa z$6OZKW@B|g-`ZK3FlY4}`K$PxBRZ{bf?D1eVT>2ID>8J6W*ckBYBCO-7Y^;S zV-s1A(Vj;?q<>1ZC!|F~^M<10pDOs}W9V{wnL{6mw|#eXO~yp_p&DQibajNRNjt3$ zBmD!XL|$A$mvjzNb(rKd`7kzj8R-h;?rZ-*{!vB(BSq8{3C8&4qOx9PbJWF0mNrLc5`jMbg8# zhqmqSs83(7uQ^eErzf;L2Cl|lWGlYwN+{viwb!A7v!>Y!nqa=xnJp+OW)Zn7m+dv} z%s6xj0;lR#?u*5JrF8zVRV_lk_PqsX?8NWI?0DbxnW1ISzl*FVCk81c`ti53Lp`uJ zewRrMCYPHe^!%hqEc|H27Y+9%EDfP@tiXWt@QKXLHdJ+Oix_-E%nR%?V0z)QtV(CfKc%BcowHF zjv85(=sX|vo(WfJv=<2>G+}*E3AP5Y?RMezWwpb7$HbX-2KlcSwlY)n+l~;pQ>iiZ zsX893&J68#zx_FSENR=I|6CF&l0&Z{J)Zh)V6T*$!e742 zJP=Q`Ncp-8JF<2@z9X`g9k8BhE%%~&oPC<%U0 zi-wgwVV|t9%&veNT_*g&m^BMs4>WN6pPS@?3i*HwkX<3~8}$#Syk75yrER@~q)u%r z5SzIQS!HzIWL%AsGtS_YIAz9Iv^DiHjy$>yw7a%fuYWvZWg z9MaiN$v`dFIA>k1&6~5MsX!jDy0af!&2H|{|IO74opri{m>%TZ#T2sdxmXtrOZI|W z>rN(#sn*`NYApq~BnmF`$pR8MzLShcgG&>^Nasj{GQ+C-{6YcVjGZu3(RBe)(Iv@l zTvv#W@iD5nm|W31ZMTsKWx4S>ib&@kj-|Zie=uvqS)^sWI$@YmoUG9P{*G|C| zorP;ap3-v4Jmt0WYyC9_j{wi}`!RhdChP+^T}cC-zf;kW)OA96795__#ozjcS3Zf> z+fr&gD!mZ-XJzg4{e(Z5^1ZCwy`N_X9loFAi=zfv?ss)y@JL+4Og>zR<7rW>u@WmD z+;6tSVN%IDf5zf0uZLV0xeH%IX?{nY)o4+N_IgJj9B?ykfNsN|*3oY0gtqtp`u+33 zJoKxlD?dUOX+k7Ru%;O3hhoHEj@RbO5z--;jwdyal6Rx0X z;9!sk2h6eDHnB(Zyg+MhkQIW+ z`%gJ6N+a`4TV$8JtR#j@hrs-DNK0QSYN@Ly)XVR*iUG3le!Ktn>4}(6U>HXZ*2=J+ z5(5R3%wf^Dl*lO#VTa+umGXNo)IXTik*l_s4s?jR>l?F z9&5hjXySc%Cq`XyE4s0;PZWmYrZA~v|#04Avg)3>CYU8Du=QEKL z+TuYajU;gQV}8g(^V_erMZFLE<;sY2VsdQzc_-EdXjf5ALm^onvH-;+WZesB!Y(!7 zIS-{BoYoami+Cp!M!3OoD#fh&5>XcwD^DVf-5+|ZtBiqGK$NAp3@fU9vyCeBe1n}g z1MSLgeLP=EkmZK}8>i44rEq`(aCv2aKDO=n!2z_-2yxDonQlt4)&8)VhoNf6Q3O6zfZqW5_(hQi+Q3;+NSp z+R>J?!qp&ZACj|?$^ZVj+Ls!tGq4EJv3sj9@e}X>fnGJcCg@b&ke%3uA<&2xD!!oGu2v_u5Cs zNtK)5CMVLA?&H)6UyD8sk=Eq^K0VMVc|~2(@aLf4tYP=7NPM;C3&vu_#!B7&(wUAq zpN8hEZQT5#((rf=H2g>vStj=9hUz+RxA)t|Z`^}7xt^J)NLrzPUW0Fu%K!eX+SkFW zVQq|Q-BgOz0L3kX^-!{P^B;uk#dQJ+QvC;!z#vkW+K@zBJyiEXl#4Yj;{>I4AXonR z0NFuR-y4ij=zyN>Uc(0uZ#&oGg;UAGVM;ac#@S&C87JA{5g*qTwO)R2TCbiKzqE<5 zHUkgz@|~$2DKzE%%&IG09-=9`fIejscS9aEV0%lI?uS5_Dhb~Jg*9!gY%VN@wMDVq z4vz*1q$p&^neTs=K(O^(zES_ndTxE3u1w0H)%!X=n3Or*>AtbuM3pGL39bMiM6$+*hz}BV`&B2;h^wvm& zdX64oXgyw=qbVdbxx=`H5jq)NVe0xjz@K|FH}ei*L?I3pDn3dYNqBeH#B}J^1+Sx2 zFc2tD_vMuoEg30Pf2#3)a;3d?R}!+-F)Kk2pJs=Wyjf9R-qBEGLH1BSy4K4e)FT}c zhu^Gf$H^~j!_U+=HNtOjhX9>aDgerCbx_Y`Z7DGU6^8;W;paQ%H_?~ z^4<5=e&qYq)s{Z^H{BYRDU!5q77TUl{GU(1v_860{`DDN&%*HBjW>Lswc8#^^S#K! zavU=9MYFoA##ghD?F*WAYftU{V+I5E(PVl5e)52-CLF7iEc>JD0W&kaOPr4b_7L=U zzpL)6A_tO!Nv9MOeCYdzaz$mT`=e{?7kZ0|y0zJgEmO-R%X%-jN865=OHBhmf7ONS z`9kx}HZ~aA4S%E%%L5b;I*~ya70`t@qOs7=5_6Snb1H?R)K@q!(j2}y6p~WFdb6lW@PHf3D5v6cXARU8#Qi zk~S$Uvsdu0oKgv8RS3b4?xo_3$Fl^hh3c-+KK7&EQgd;kuj=^EM|6seslk+A$T%$4f}?IOs01HDfC|D$R11IeF$V8xZO{cj(q^toie(jrH;s-I_^uAkTGu z77@qKw82(G;}qs-BB4R+K4VeFYo&@*+VK{B7vbvVF(|}j?O~EjCJ%MvStNwox*}w2 zA^8s|zoALEN?sv!n%CUV{dLQ|vVBECC5W{k^{sW^(1+X$Jubt4T!8*{_{cVP$5sq? zGXZ&XO*6C9`=PvIYP7f%KZu{im)Y^dZ~FZXfc{@%|KXlUepoH36TO?p`&^{>mhF|E z0L=C0A-;GJm}L9y8MkdpVuR(yIYHJE=~k`T#bas%=*X7D5=*%=>GfbdNBy$$+@6@Y z<^t9&_MARMF>3AFVNu*t%rIyr4pD3Th>#yAK38KhlW7NQ{F;Vwjr*Rl`wu+ld7tO| zeBbxH@AG5lEat=KhI!ZSOr?Tm)Uzu_o)LzUn3Z}Rj@`!oqh9swyqSNQhFlu%!E#}h z%6=q=S7yY8!oT|X*+x>pLm)v$CfZP8`n*bjMAP8F`7;&9A) z&^*d~h*UmJ4&`9p|upG^FYMJd-)f&ARMlr>WZ z4LtYJQ$$CJD z)<-*)rQ8G4-QY@ibZjypU(bQUvAB{6vqrwz^lWX>EVLl{^-6D%ILK8$oDzvEI9<(V z-S;mMB>s3(nC!J4r{()QvAKk8n;U$=o7s!Rv@4n-&Ik!P3mq7T!e~gb>K>({Z#4hJ z`^rlv1S~k+c}x6NFf>5}p3B_frz{XDF{`+twr;^^meP0jr;2?<7E; z@RvcutfSa)&vg#?2d|3`S{)3h+0dzLgEDb|4_PYL(st}+p}v7+pmhEaFxm>w=+qwY zS2nL;Bp#M73~aJX0`+Hv?SvADaLekQC~?Y6W*-iLCK%3IXj&UP_|Dwemo3N$=Ed_x z%cV?kxclva&%|7L@k`xey_!_!bX`8s5Db#W)zIW8b#Z+2zd|OVs?bI%5Bq_{?IKmP zT7Bx-j!pEW(QojtMnL*3YlQzD!ph?b41BhHiz>gufLl1*NZ#Ao!xi@!{siSdIyeqV z>Zf_5m%#1p=GclU$FQx~R~(em#kYKou*q-_p?&B~B}lG(-6VKLgsVU+w*eVxKPIYn zOCz~XGxp*z(6=a|+}Uq!oVk^T>);_*HMzHIt7NOs1>ov7Q5djenh<6)FV)A5Vs$bk zym+xVnUl{(aNb$~gfpq}jdNg>rZ=~%d(Oev8!UxUKw4;44T^267Fb|>D^b{M zF+>#R@aFHWgF5t&kOn6sKU#7Cr!g9Q`B9{|y&{$&IhXJv>lp^LBA!2YUp5Z-R!e3` z2JbE7qO&LhG<2XV9;s}PKmv=m#6kg>mfVh_PsY^S-K-A+UnT7YzWO*03OM2@yzqR!1&jInp8*b5N&p)sCs4x})7GLTT#a^?y25#-4clK#Ue-Z4oC z6Zg8j%cbpRP!lESu*1_(j8%VihiBrxzB_Y$h;tp5g1)3YsxA36{ zI`R2Zkl2W2VGfop0dgd-|Ax*LXa~kYZad4mz9h8|7S-ueQS>2?Dqbj$t;z^?ec&EV z0A5W%BgywJO#OCHNtwGr5!S=?9hyl~`1XaWXHBa#%WcMy!DT^+_K?9*jzR-pd| zMX!x(bV!Hn0dg6%-${?4E()X0PGp~D*xU{zbNG{%JSx>1)2B6b`SgPSa1K;p>v@yn z5nagu!`lo!gf%HMaN6UUV`Ip}9_@|*y2Z05&EUOOsXz`p z{FgX9^{ocn8NBL?v6MeH0;S&W& ztOPFnev{>Bk3AXTHYmnY??&tfe3kzF34Hfppj1AfjBi0=a?9J>u${yaQYKH^4Sj~v zc1h>K3lUKmE%(*MeW)<`ca4C4Z5|vFwM<}WnNZ_=73CY0#Ha=;zlMmICQCl18Y$}9 zvNR?8kgy*$Yl~g&r}Zej3ZDX9@+<(tA>#U7M$;F)>lQOKL4xi!t1GW-P*q+UIV=_3 zRC+TQw(18m&j6Vh;Ifq|vu%m)qWY$k*_UdQwqy(gFX!D2aNIuvbV4|-J_caBbxSK_ zPkGmlWWU6nYX>QUu@E=k3MSae zf$3p~p0jfR=Ls7r)_r|g!mEILZnC`tzOy1&n>~oYr?O7hvqxH5)cuz;krH(X9E(pm z-=*H(ei_>vo`9GkG*=3kfch+8>}j z0Ps287rNY8>n`%Ai>= GitHub source + JavaDoc link (if found) +# - .mc4 relative link -> GitHub source +Original source is located: +https://github.com/facelessuser/pymdown-extensions/blob/f64422f87c05031a8c8d62b1988bf76e8f65f27f/pymdownx/snippets.py +------- + +MIT license. + +Copyright (c) 2017 Isaac Muse + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +""" +class SnippetExtension(snippets.SnippetExtension): + + def extendMarkdown(self, md): + """Register the extension.""" + self.md = md + md.registerExtension(self) + config = self.getConfigs() + snippet = MCSnippetPreprocessor(config, md) + md.preprocessors.register(snippet, "snippet", 32) + +# add this snippet extension here +def on_config(config, **kwargs): + config.markdown_extensions.append(SnippetExtension()) + + +# We have to copy the parse_snippets method to add our own hook point +class MCSnippetPreprocessor(snippets.SnippetPreprocessor): + + # A processing step to modify links + def process_snippet(self, s_lines, snippet): + import re + from pathlib import Path + base_path = Path(snippet).parent # directory in which the snippet resides + cwd = Path().resolve() + + # Pattern to match anchors to relative files [anchor]: url + file_pattern = r'(?!https?:\/\/)([^)]+\.(java|mc4))' + pattern_anchor = re.compile(r'\[([a-zA-Z0-9_]+)\]: ' + file_pattern) + # collect all used link-targets + relative_anchors = {m[0]: m for line in s_lines for m in pattern_anchor.findall(line)} + + # Pattern to match relative markdown links: [text](url) + pattern_rel_link = re.compile(r'\[([^\]]+)\]\(' + file_pattern + r'(#\S+)?\)') + # Pattern to match relative markdown links: [text][anchor] + pattern_anchor_link = re.compile(r'\[([^\]]+)\]\[([a-zA-Z0-9_]+)\]') + + # Replace functions + def anchor_replacer(match): # [text][anchor] + text = match.group(1) # the text within the link + a_name = match.group(2) # the name of the anchor + if a_name not in relative_anchors: + return match.group(0) # keep original + anchor = relative_anchors[a_name] + return replace_link(text, anchor[1], anchor[2]) + + def link_replacer(match): # [text](url) links + text = match.group(1) # the text within the link + url = match.group(2) # the url including everything + file_ext = match.group(3) # the url including everything + anchor = match.group(4) or "" # an optional #anchor + return replace_link(text, url, file_ext, anchor) + + def replace_link(text, url, file_ext, anchor=""): + # which file does the url point to? + resolved_path = (base_path / url).resolve().relative_to(cwd) + # step 1: construct a GitHub link + github_link = f"https://github.com/MontiCore/monticore/blob/dev/{resolved_path} \"View file on GitHub\"" + github_icon = f"[:material-github:{{ .nonhighlight}}]({github_link})" + # step 2: construct a JavaDocs link + parts = resolved_path.parts + project = parts[0] # the project, i.e. monticore-grammar, monticore-runtime, etc + source_set = parts[2] # main or testFixtures + # we have links to non main/testFixtures java files -> no javadoc link + link = github_link + if source_set in ['main', 'testFixtures'] and project in ['monticore-grammar', + 'monticore-runtime'] and file_ext == 'java': + # find the correct file location + javadoc_task = 'javadoc' if source_set == 'main' else 'testFixturesJavadoc' + back_to_root = '../' * (len(base_path.relative_to(cwd).parts)) + file = '/'.join(parts[4:])[:-len(".java")] + javadoc_link = f"{back_to_root}{project}/{javadoc_task}/{file}.html{anchor} \"View JavaDoc\"" + javadoc_icon = f"[:material-file-document:{{ .nonhighlight }}]({javadoc_link})" + link = javadoc_link + else: + javadoc_icon = '' + return f"[{text}]({link}) {github_icon} {javadoc_icon}" + + # Apply replacement + return [pattern_anchor_link.sub(anchor_replacer, pattern_rel_link.sub(link_replacer, md_text)) for md_text in + s_lines] + + + # the following code is copied 1-to-1 (just with the addition of one hook) + """Handle snippets in Markdown content. - a copy of """ + def parse_snippets(self, lines, file_name=None, is_url=False, is_section=False): + """Parse snippets snippet.""" + + if file_name: + # Track this file. + self.seen.add(file_name) + + new_lines = [] + inline = False + block = False + for line in lines: + # Check for snippets on line + inline = False + m = self.RE_ALL_SNIPPETS.match(line) + if m: + if m.group('escape'): + # The snippet has been escaped, replace first `;` and continue. + new_lines.append(line.replace(';', '', 1)) + continue + + if block and m.group('inline_marker'): + # Don't use inline notation directly under a block. + # It's okay if inline is used again in sub file though. + continue + + elif m.group('inline_marker'): + # Inline + inline = True + + else: + # Block + block = not block + continue + + elif not block: + if not is_section: + # Check for section line, if present remove, if escaped, reformat it + m2 = self.RE_SNIPPET_SECTION.match(line) + if m2 and m2.group('escape'): + line = ( + m2.group('pre') + m2.group('escape').replace(';', '', 1) + m2.group('inline_marker') + + m2.group('section') + m2.group('post') + ) + m2 = None + + # Found a section that must be removed + if m2 is not None: + continue + + # Not in snippet, and we didn't find an inline, + # so just a normal line + new_lines.append(line) + continue + + if block and not inline: + # We are in a block and we didn't just find a nested inline + # So check if a block path + m = self.RE_SNIPPET.match(line) + + if m: + # Get spaces and snippet path. Remove quotes if inline. + space = m.group('space').expandtabs(self.tab_length) + path = m.group('snippet')[1:-1].strip() if inline else m.group('snippet').strip() + + if not inline: + # Block path handling + if not path: + # Empty path line, insert a blank line + new_lines.append('') + continue + + # Ignore commented out lines + if path.startswith(';'): + continue + + # Get line numbers (if specified) + end = [] + start = [] + section = None + m = self.RE_SNIPPET_FILE.match(path) + path = '' if m is None else m.group(1).strip() + # Looks like we have an empty file and only lines specified + if not path: + if self.check_paths: + raise snippets.SnippetMissingError(f"Snippet at path '{path}' could not be found") + else: + continue + if m.group(2): + for nums in m.group(2)[1:].split(','): + span = nums.split(':') + st = int(span[0]) if span[0] else None + start.append(st if st is None or st < 0 else max(0, st - 1)) + en = int(span[1]) if len(span) > 1 and span[1] else None + end.append(en) + elif m.group(3): + section = m.group(3)[1:] + + # Ignore path links if we are in external, downloaded content + is_link = path.lower().startswith(('https://', 'http://')) + if is_url and not is_link: + continue + + # If this is a link, and we are allowing URLs, set `url` to true. + # Make sure we don't process `path` as a local file reference. + url = self.url_download and is_link + snippet = self.get_snippet_path(path) if not url else path + + if snippet: + + # This is in the stack and we don't want an infinite loop! + if snippet in self.seen: + continue + + if not url: + # Read file content + with open(snippet, 'r', encoding=self.encoding) as f: + last = False + s_lines = [] + for l in f: + last = l.endswith(('\r', '\n')) + s_lines.append(l.strip('\r\n')) + if last: + s_lines.append('') + else: + # Read URL content + try: + s_lines = self.download(snippet) + except snippets.SnippetMissingError: + if self.check_paths: + raise + s_lines = [] + + if s_lines: + total = len(s_lines) + if start and end: + final_lines = [] + for sel in zip(start, end): + s_start = snippets.util.clamp(total + sel[0], 0, total) if sel[0] and sel[0] < 0 else sel[0] + s_end = snippets.util.clamp(total + 1 + sel[1], 0, total) if sel[1] and sel[1] < 0 else sel[1] + final_lines.extend(s_lines[slice(s_start, s_end, None)]) + s_lines = self.dedent(final_lines) if self.dedent_subsections else final_lines + elif section: + s_lines = self.extract_section(section, s_lines) + + # BEGIN MODIFICATION: Call hook point + if s_lines: + s_lines = self.process_snippet(s_lines, snippet) + # END MODIFICATION + + # Process lines looking for more snippets + new_lines.extend( + [ + space + l2 for l2 in self.parse_snippets( + s_lines, + snippet, + is_url=url, + is_section=section is not None + ) + ] + ) + + elif self.check_paths: + raise snippets.SnippetMissingError(f"Snippet at path '{path}' could not be found") + + # Pop the current file name out of the cache + if file_name: + self.seen.remove(file_name) + + return new_lines diff --git a/docs/overrides/landingpage.html b/docs/overrides/landingpage.html new file mode 100644 index 0000000000..95e6e3a581 --- /dev/null +++ b/docs/overrides/landingpage.html @@ -0,0 +1,366 @@ + + +{% extends "base.html" %} + + +{% block tabs %} +{{ super() }} + + + + + + + +
+ +
+ + + + + +
+
+
+
+{% endblock %} + +{% block content %} + + +{{ page.content }} + + +{% include "partials/source-file.html" %} + +{% endblock %} diff --git a/docs/scripts/preprocessing.sh b/docs/scripts/preprocessing.sh index 8f45a9261b..ac4be83915 100644 --- a/docs/scripts/preprocessing.sh +++ b/docs/scripts/preprocessing.sh @@ -2,8 +2,9 @@ # (c) https://github.com/MontiCore/monticore # script for all preprocessing steps of the pages job # is used to have uniform bases for both gitlab and github pages -# is used from '.gitlab-ci.yml'(gitlab) and '.travis.yml'(github) # +# +# old scripts: # execute report scripts and print output to *.md file, to use these in pages #sh docs/scripts/errorList.sh '../../' 'target/site/errorList' > docs/scripts/ErrorList.md #sh docs/scripts/detailedErrorList.sh '../../' 'target/site/detailedErrorList' > docs/scripts/DetailedErrorList.md @@ -11,25 +12,75 @@ #sh docs/scripts/ftlAnalysis.sh './' 'configure.StartAllOutput' 'target/site/ftlAnalysis' > docs/scripts/FtlAnalysis.md #echo "[INFO] Executed report scripts for pages" # +# remove all occurrences of '[[_TOC_]]' in markdown files +# because mkdocs already renders its own toc +case " $* " in + *" inplace "*) + for file in $(find ./docs/docs -type f -name "*.md") + do + sed -i 's/\[\[_TOC_\]\]//' $file + perl -pi -e 's/\[([^\[\]\(\)]*)\]\([^\[\]\(\)]*git.rwth-aachen.de[^\[\]\(\)]*?\)/$1/g' $file + done + echo "[INFO] Removed all occurrences of '[[_TOC_]]' in *.md files" + echo "[INFO] Removed all links to https://git.rwth-aachen.de in *.md files" + ;; +esac # move all directories that contain *.md files to the docs folder # because mkdocs can only find *.md files there -mkdir docs/docs -mv docs/*.md docs/docs -mv docs/further_docs docs/docs/further_docs -mv monticore-grammar docs/monticore-grammar -mv monticore-runtime docs/monticore-runtime -mv 00.org docs/00.org -mv *.md docs/ -mv *.png docs/ -mv img/ docs/ -echo "[INFO] Moved *.md files to 'docs' folder" -# -# remove all occurences of '[[_TOC_]]' in markdown files -# because mkdocs already renders its own toc -for file in $(find ./docs -type f -name "*.md") -do - sed -i 's/\[\[_TOC_\]\]//' $file - perl -pi -e 's/\[([^\[\]\(\)]*)\]\([^\[\]\(\)]*git.rwth-aachen.de[^\[\]\(\)]*?\)/$1/g' $file +rm -r docs_wd || true + +case " $* " in + *" symlink "*) + # use symlinks to track updates + mkdir docs_wd + ln -s ../docs/overrides docs_wd/ + ln -s ../docs/stylesheets docs_wd/ + ln -s ../docs/scripts docs_wd/ + ln -s ../docs/img docs_wd/ + # all images referenced in the root-Readme must be handled specially :( + mkdir -p docs_wd/docs/img + ln -s ../../../docs/img/MC_Symp_Banner.png docs_wd/docs/img/MC_Symp_Banner.png + ln -s ../docs/README.md docs_wd/ + # Link to the javadoc directories + mkdir -p docs_wd/monticore-runtime + ln -s ../../monticore-runtime/target/docs/javadoc docs_wd/monticore-runtime/ + ln -s ../../monticore-runtime/target/docs/testFixturesJavadoc docs_wd/monticore-runtime/ + mkdir -p docs_wd/monticore-grammar + ln -s ../../monticore-grammar/target/docs/javadoc docs_wd/monticore-grammar/ + ln -s ../../monticore-grammar/target/docs/testFixturesJavadoc docs_wd/monticore-grammar/ + echo "[INFO] Using symlinks for live editing" + ;; + *) + cp -r docs docs_wd + rm docs_wd/*.md + cp docs/README.md docs_wd/README.md + # all images referenced in the root-Readme must be handled specially :( + mkdir -p docs_wd/docs/img + cp docs/img/MC_Symp_Banner.png docs_wd/docs/img/MC_Symp_Banner.png + echo "[INFO] Copied site design" + # Copy the javadoc directories + mkdir -p docs_wd/monticore-runtime + cp -r monticore-runtime/target/docs/javadoc docs_wd/monticore-runtime/javadoc + cp -r monticore-runtime/target/docs/testFixturesJavadoc docs_wd/monticore-runtime/testFixturesJavadoc + mkdir -p docs_wd/monticore-grammar + cp -r monticore-grammar/target/docs/javadoc docs_wd/monticore-grammar/javadoc + cp -r monticore-grammar/target/docs/testFixturesJavadoc docs_wd/monticore-grammar/testFixturesJavadoc + echo "[INFO] Copied JavaDocs" + ;; +esac + +for SOURCE_DIR in "00.org" "docs" "monticore-grammar/src" "monticore-runtime/src"; do + # We link to java & mc4 files in our md files - which is why we have to redirect them too + find "$SOURCE_DIR" -type f \( -name "*.md" \) | while read -r filepath; do + target_file="docs_wd/$filepath" + mkdir -p "$(dirname "$target_file")" + # use snippets to include the original files content + if [ ! -f "$target_file" ]; then + echo "--8<-- \"$filepath\"" > "$target_file" + fi + done done -echo "[INFO] Removed all occurrences of '[[_TOC_]]' in *.md files" -echo "[INFO] Removed all links to https://git.rwth-aachen.de in *.md files" +echo "[INFO] Created snippet files" + +# the landing page snippet has to be removed again +rm docs_wd/docs/README.md diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css index 36b3280353..f3796f0b90 100644 --- a/docs/stylesheets/extra.css +++ b/docs/stylesheets/extra.css @@ -18,3 +18,8 @@ .bibliography { empty-cells: hide; } + +/* Reduce icon intensity*/ +.nonhighlight { + color: color-mix(in srgb, currentColor 50%, transparent); +} diff --git a/gradle.properties b/gradle.properties index 79de6dd551..3bc21f46d7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -14,17 +14,19 @@ org.gradle.caching=true # org.gradle.caching.debug=true # versions used -version=7.8.0-SNAPSHOT -previous_mc_version =7.7.0 +version=7.9.0-SNAPSHOT +previous_mc_version =7.8.0 commons_cli_version = 1.4 -se_commons_version =7.7.0 +se_commons_version =7.8.0 antlr_version =4.12.0 -junit_version =5.10.3 +junit_version = 5.14.1 +junit_platform_version = 1.14.1 emf_compare_version =1.2.0 ecore_version =2.16.0 commons_lang3_version = 3.8.1 freemarker_version = 2.3.34 guava_version =31.1-jre +shadow_plugin_version=7.1.2 -cd4a_version =7.7.0 +cd4a_version =7.8.0 diff --git a/mkdocs.yml b/mkdocs.yml index 1cc00ddcad..f24cb2d0cf 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -11,6 +11,7 @@ theme: - toc.follow - content.tabs.link - content.code.copy + - navigation.instant # search index survives navigation icon: logo: 'fontawesome/solid/desktop' @@ -24,12 +25,24 @@ extra_css: copyright: '(c) https://github.com/MontiCore/monticore' markdown_extensions: + - admonition + - attr_list - pymdownx.highlight - pymdownx.inlinehilite + - pymdownx.details - pymdownx.superfences - - pymdownx.snippets + # pymdownx.snippets is added by the docsnippet hook! - pymdownx.tabbed: alternate_style: true + - pymdownx.emoji: + emoji_index: !!python/name:material.extensions.emoji.twemoji + emoji_generator: !!python/name:material.extensions.emoji.to_svg + +hooks: + - docs/overrides/extensions/docsnippet.py + +plugins: + - search nav: - Home: 'README.md' @@ -47,3 +60,13 @@ nav: - Downloads: 'docs/Download.md' - Publications: 'docs/Publications.md' - License: '00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md' + +# run `docs/scripts/preprocessing.sh symlink` to create this directory locally +docs_dir: docs_wd + +watch: + - 00.org + - docs + - monticore-grammar/src + - monticore-runtime/src + - README.md \ No newline at end of file diff --git a/monticore-generator/build.gradle b/monticore-generator/build.gradle index aab470dd09..5a16a7ffc0 100644 --- a/monticore-generator/build.gradle +++ b/monticore-generator/build.gradle @@ -11,33 +11,31 @@ buildscript { plugins { id "java-library" id "io.github.themrmilchmann.ecj" version "0.2.0" // Eclipse compiler as it's much faster than javac - id "com.github.johnrengelman.shadow" version "6.1.0" - id 'groovy-gradle-plugin' + id "com.github.johnrengelman.shadow" version "$shadow_plugin_version" id 'maven-publish' id "jacoco" } description = 'MontiCore: Generator' -group = "de.monticore" + ext.grammarDir = 'src/main/grammars' -buildDir = file("$projectDir/target") -repositories { +allprojects { + group = "de.monticore" + buildDir = file("$projectDir/target") + repositories { if (("true").equals(getProperty('useLocalRepo'))) { - mavenLocal() + mavenLocal() } maven { - url repo + url = repo } mavenCentral() + } } dependencies { - implementation gradleApi() - - implementation "de.se_rwth.commons:se-commons-gradle:$se_commons_version" - implementation "de.monticore:monticore-grammar:$previous_mc_version" implementation "de.se_rwth.commons:se-commons-groovy:$se_commons_version" implementation "de.se_rwth.commons:se-commons-logging:$se_commons_version" @@ -49,11 +47,8 @@ dependencies { implementation group: 'org.apache.commons', name: 'commons-text', version: '1.10.0' // implementation 'org.slf4j:slf4j-api:1.7.10' - implementation 'ch.qos.logback:logback-classic:1.2.0' - implementation 'ch.qos.logback:logback-core:1.2.0' - - // Remove after 7.7.0 release - compileOnly 'org.reflections:reflections:0.9.9' + implementation 'ch.qos.logback:logback-classic:[1.2.9,1.3.0)' // we appear to be incompatible with logback >= 1.3.0 + implementation 'ch.qos.logback:logback-core:[1.2.9,1.3.0)' implementation "de.monticore.lang:cd4analysis:$cd4a_version" implementation "org.antlr:antlr4:$antlr_version" @@ -61,67 +56,116 @@ dependencies { implementation("com.google.guava:guava:$guava_version") implementation "org.apache.commons:commons-lang3:$commons_lang3_version" testImplementation 'com.github.javaparser:javaparser-symbol-solver-core:3.24.2' - testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" testImplementation 'org.mockito:mockito-core:4.5.1' - testImplementation gradleTestKit() -} - -tasks.withType(JavaCompile) { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 - options.encoding = "UTF-8" - options.deprecation false - options.warnings = false } -java { - withSourcesJar() - toolchain { - languageVersion = JavaLanguageVersion.of(11) +allprojects { + apply plugin: "java" + tasks.withType(JavaCompile).configureEach { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + options.encoding = "UTF-8" + options.deprecation = false + options.warnings = false + } + java { + withSourcesJar() + toolchain { + languageVersion = JavaLanguageVersion.of(11) + } + } + dependencies { + testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" } -} -tasks.withType(Test) { - useJUnitPlatform() - - testLogging { - // controls whether test output is shown - showStandardStreams = !("false").equals(getProperty('showTestOutput')) - showExceptions true - showCauses true - showStackTraces true - exceptionFormat TestExceptionFormat.FULL - info { - events TestLogEvent.FAILED, - TestLogEvent.PASSED, - TestLogEvent.SKIPPED, - TestLogEvent.STANDARD_OUT + tasks.withType(Test).configureEach { + useJUnitPlatform() + + testLogging { + // controls whether test output is shown + showStandardStreams = !("false").equals(getProperty('showTestOutput')) + showExceptions = true + showCauses = true + showStackTraces = true + exceptionFormat = TestExceptionFormat.FULL + info { + events TestLogEvent.FAILED, + TestLogEvent.PASSED, + TestLogEvent.SKIPPED, + TestLogEvent.STANDARD_OUT + } + } + afterTest { desc, result -> + logger.lifecycle "${desc.className} > ${desc.name} ${result.resultType}" + } + afterSuite { desc, result -> + if (!desc.parent) { // will match the outermost suite + def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} passed, ${result.failedTestCount} failed, ${result.skippedTestCount} skipped)" + def startItem = '| ', endItem = ' |' + logger.lifecycle startItem + output + endItem + } + } + reports { + html.required = false } } - afterTest { desc, result -> - logger.lifecycle "${desc.className} > ${desc.name} ${result.resultType}" - } - afterSuite { desc, result -> - if (!desc.parent) { // will match the outermost suite - def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} passed, ${result.failedTestCount} failed, ${result.skippedTestCount} skipped)" - def startItem = '| ', endItem = ' |' - logger.lifecycle startItem + output + endItem + + publishing { + // The gradle-plugin plugin deploys automatically a pluginMaven publication (from the main component) + repositories { + maven { + name = "SE-Nexus" + credentials.username = mavenUser + credentials.password = mavenPassword + def releasesRepoUrl = "https://nexus.se.rwth-aachen.de/content/repositories/monticore-releases/" + def snapshotsRepoUrl = "https://nexus.se.rwth-aachen.de/content/repositories/monticore-snapshots/" + url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl + } + // Also publish to the github repository, if run on a github action + if (System.getenv("GITHUB_REPOSITORY") != null) { + maven { + name = "GitHubPackages" + url = "https://maven.pkg.github.com/" + System.getenv("GITHUB_REPOSITORY") + credentials { + username = System.getenv("GITHUB_ACTOR") + password = System.getenv("GITHUB_TOKEN") + } + } + } } + // Add the license information to the publication + publications.configureEach { + pom { + licenses { + license { + name = 'MontiCore 3-Level License Model' + url = 'https://monticore.github.io/monticore/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL/' + } + } + } + } + } - reports { - html.required = false +} +publishing { + publications { + "maven"(MavenPublication) { + // the gradle plugin is published implicitly via the java-gradle-plugin plugin + // but the generator has to be published explicitly + from components.java } + } } -shadowJar { // all in one jar +tasks.named("shadowJar") { // all in one jar manifest { attributes "Main-Class": "de.monticore.cli.MontiCoreTool" } archiveClassifier = "mc-tool" - zip64 true + zip64 = true } tasks.register("buildInfo", de.monticore.gradle.common.MCBuildInfoTask) { @@ -131,56 +175,18 @@ tasks.register("buildInfo", de.monticore.gradle.common.MCBuildInfoTask) { processResources.dependsOn("buildInfo") -def pluginName = 'monticore' - -gradlePlugin.plugins { - monticore { - id = pluginName - implementationClass = 'de.monticore.MCPlugin' - } - // New version of our plugin (supporting incremental builds) - monticoreGenerator { - id = "de.monticore.generator" - implementationClass = 'de.monticore.gradle.MCGeneratorPlugin' - } - monticoreGeneratorWithTR { - id = "de.monticore.generator-withtr" - implementationClass = 'de.monticore.gradle.MCGeneratorWithTRPlugin' - } +// Expose the shadowJar as an artifact for composite builds +artifacts { + shadow shadowJar } - -publishing { - // The gradle-plugin plugin deploys automatically a pluginMaven publication (from the main component) - repositories { - maven { - name = "SE-Nexus" - credentials.username mavenUser - credentials.password mavenPassword - def releasesRepoUrl = "https://nexus.se.rwth-aachen.de/content/repositories/monticore-releases/" - def snapshotsRepoUrl = "https://nexus.se.rwth-aachen.de/content/repositories/monticore-snapshots/" - url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl - } - // Also publish to the github repository, if run on a github action - if (System.getenv("GITHUB_REPOSITORY") != null) { - maven { - name = "GitHubPackages" - url = "https://maven.pkg.github.com/" + System.getenv("GITHUB_REPOSITORY") - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") - } - } - } - } - // Add the license information to the publication - publications.configureEach { - pom { - licenses { - license { - name = 'MontiCore 3-Level License Model' - url = 'https://monticore.github.io/monticore/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL/' - } - } - } - } +configurations { + shadow { + outgoing.capability("de.monticore:monticore-generator-shadow:$version") + } +} +// Ensure the gradle plugin's subproject is also published +['publish', 'publishToMavenLocal', 'assemble', 'check', 'test'].forEach {taskname -> + tasks.named(taskname).configure { + dependsOn subprojects*.tasks*.named(taskname) + } } diff --git a/monticore-generator/gradle-plugin/build.gradle b/monticore-generator/gradle-plugin/build.gradle new file mode 100644 index 0000000000..000882e53b --- /dev/null +++ b/monticore-generator/gradle-plugin/build.gradle @@ -0,0 +1,92 @@ +/* (c) https://github.com/MontiCore/monticore */ +buildscript { + dependencies { + classpath "de.se_rwth.commons:se-commons-gradle:$se_commons_version" + } +} +plugins { + id 'java-library' + id 'java-gradle-plugin' + id 'maven-publish' +} + +configurations { + // The plugin's footprint is fairly small, as it loads the generator itself into a "mcTool" configuration + // to avoid polluting Gradle's classpath + mcTool +} + +dependencies { + implementation gradleApi() + implementation "de.se_rwth.commons:se-commons-gradle:$se_commons_version" + implementation "de.monticore:monticore-runtime:$previous_mc_version" // Required due to json -> substitute this to remove the runtime from the gradle projects classpath + mcTool project(":") // depend on the generator subproject + + testImplementation gradleTestKit() + + testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" +} + +sourceSets { + main.compileClasspath += configurations.mcTool + test.compileClasspath += configurations.mcTool +} + + +gradlePlugin.plugins { + // New version of our plugin (supporting incremental builds) + monticoreGenerator { + id = "de.monticore.generator" + implementationClass = 'de.monticore.gradle.MCGeneratorPlugin' + } + monticoreGeneratorWithTR { + id = "de.monticore.generator-withtr" + implementationClass = 'de.monticore.gradle.MCGeneratorWithTRPlugin' + } +} + +tasks.register("buildInfo", de.monticore.gradle.common.MCBuildInfoTask) { + // With an input property ensuring UP-TO-DATE checks consider the version property + version = project.version +} + +processResources.dependsOn("buildInfo") + +tasks.named("test") { + // The test uses the output of the generator's shadowJar task + dependsOn(project(":").tasks.shadowJar) + inputs.files(project(":").tasks.shadowJar) + + // For the MontiVerse + systemProperty "maven.repo.local", System.getProperty("maven.repo.local") + systemProperty "useLocalRepo", findProperty("useLocalRepo") +} +publishing { + // The gradle-plugin plugin adds&configures a publication automatically. + // But we have to specify the repositories explicitly (again) + // allprojects in the generator project does not appear to work for this. + repositories { + maven { + name = "SE-Nexus" + credentials.username = mavenUser + credentials.password = mavenPassword + def releasesRepoUrl = "https://nexus.se.rwth-aachen.de/content/repositories/monticore-releases/" + def snapshotsRepoUrl = "https://nexus.se.rwth-aachen.de/content/repositories/monticore-snapshots/" + url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl + } + // Also publish to the github repository, if run on a github action + if (System.getenv("GITHUB_REPOSITORY") != null) { + maven { + name = "GitHubPackages" + url = "https://maven.pkg.github.com/" + System.getenv("GITHUB_REPOSITORY") + credentials { + username = System.getenv("GITHUB_ACTOR") + password = System.getenv("GITHUB_TOKEN") + } + } + } + } +} diff --git a/monticore-generator/src/main/java/de/monticore/IncChecker.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/IncChecker.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/IncChecker.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/IncChecker.java diff --git a/monticore-generator/src/main/java/de/monticore/MCMillBuildService.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/MCMillBuildService.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/MCMillBuildService.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/MCMillBuildService.java diff --git a/monticore-generator/src/main/java/de/monticore/MCPlugin.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/MCPlugin.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/MCPlugin.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/MCPlugin.java diff --git a/monticore-generator/src/main/java/de/monticore/MCTask.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/MCTask.java similarity index 98% rename from monticore-generator/src/main/java/de/monticore/MCTask.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/MCTask.java index 7a139fdd08..f44462f729 100644 --- a/monticore-generator/src/main/java/de/monticore/MCTask.java +++ b/monticore-generator/gradle-plugin/src/main/java/de/monticore/MCTask.java @@ -5,6 +5,7 @@ import com.google.common.collect.Iterables; import de.monticore.cli.MontiCoreTool; import de.monticore.codegen.cd2java._tagging.TaggingConstants; +import de.monticore.grammar.grammar_withconcepts.Grammar_WithConceptsMill; import de.monticore.mcbasics.MCBasicsMill; import de.monticore.dstlgen.util.DSTLPathUtil; import de.monticore.symboltable.serialization.json.*; @@ -78,6 +79,8 @@ public MCTask() { // Only one task using MontiCore Mills at the same time usesService(project.getGradle().getSharedServices().getRegistrations().findByName(MCPlugin.MC_MILL_BUILD_SERVICE).getService()); + + getLogger().warn("The MCTask is deprecated - Please migrate following https://monticore.github.io/monticore/docs/Gradle/"); } public final RegularFileProperty grammar = getProject().getObjects().fileProperty(); @@ -433,7 +436,9 @@ public void rebuildGrammar() { String[] p = getParameters(); try { // execute Monticore with the given parameters - MontiCoreTool.main(p); + Grammar_WithConceptsMill.init(); + new MontiCoreTool().run(p); + StatisticsHandlerFix.shutdown(); MCBasicsMill.globalScope().getSymbolPath().close(); } catch(MCTaskError e){ // in case of failure print the error and fail diff --git a/monticore-generator/src/main/java/de/monticore/MCTaskError.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/MCTaskError.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/MCTaskError.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/MCTaskError.java diff --git a/monticore-generator/src/main/java/de/monticore/MontiTransExec.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/MontiTransExec.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/MontiTransExec.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/MontiTransExec.java diff --git a/monticore-generator/src/main/java/de/monticore/gradle/GradleTaskStatistic.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/GradleTaskStatistic.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/gradle/GradleTaskStatistic.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/GradleTaskStatistic.java diff --git a/monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorBasePlugin.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorBasePlugin.java similarity index 94% rename from monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorBasePlugin.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorBasePlugin.java index d26d9e9845..e3413a7ab1 100644 --- a/monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorBasePlugin.java +++ b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorBasePlugin.java @@ -4,6 +4,7 @@ import de.monticore.MCMillBuildService; import de.monticore.MCPlugin; import de.monticore.gradle.common.MCBuildInfoTask; +import de.monticore.gradle.dependencies.MCToolDependenciesPlugin; import de.monticore.gradle.gen.MCGenTask; import de.monticore.gradle.gen.MCToolAction; import de.monticore.gradle.internal.ProgressLoggerService; @@ -27,6 +28,8 @@ public abstract class MCGeneratorBasePlugin implements Plugin { public final static String CONCURRENT_MC_PROPERTY = "de.monticore.gradle.max-concurrent-mcgen"; public void apply(Project project) { + // Populate the "mcTool" configuration with the generator itself + project.getPluginManager().apply(MCToolDependenciesPlugin.class); // ServiceProvider to pass a ProgressLogger instance to the workers Provider serviceProvider = project.getGradle().getSharedServices() .registerIfAbsent(ProgressLoggerService.class.getSimpleName(), diff --git a/monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorExtension.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorExtension.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorExtension.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorExtension.java diff --git a/monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorPlugin.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorPlugin.java similarity index 95% rename from monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorPlugin.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorPlugin.java index e048a96ec8..d58c73d807 100644 --- a/monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorPlugin.java +++ b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorPlugin.java @@ -97,6 +97,11 @@ protected TaskProvider createMCGenTaskForSourceSet(final Project proj project.getTasks().named(sourceSet.getCompileJavaTaskName()).configure(compile -> { compile.dependsOn(mcGenTaskProvider); }); + // Generate MC must run before the sources jar task (which may or may not be present) + final String sourcesJarTaskName = sourceSet.getSourcesJarTaskName(); + project.getTasks().matching(t->t.getName().equals(sourcesJarTaskName)).configureEach(sourcesJar -> { + sourcesJar.dependsOn(mcGenTaskProvider); + }); // Generate MC must run before ProcessResources (e.g. for mc4 grammars) project.getTasks().named(sourceSet.getProcessResourcesTaskName()).configure(processResources -> { processResources.dependsOn(mcGenTaskProvider); diff --git a/monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorWithTRPlugin.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorWithTRPlugin.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/gradle/MCGeneratorWithTRPlugin.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/MCGeneratorWithTRPlugin.java diff --git a/monticore-generator/src/main/java/de/monticore/gradle/StatisticData.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/StatisticData.java similarity index 96% rename from monticore-generator/src/main/java/de/monticore/gradle/StatisticData.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/StatisticData.java index 3b3f2378fb..48cde84470 100644 --- a/monticore-generator/src/main/java/de/monticore/gradle/StatisticData.java +++ b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/StatisticData.java @@ -91,7 +91,9 @@ public String toString() { result.putMember("GradleParallel", new JsonBoolean( Boolean.parseBoolean(getGradleProperty("org.gradle.parallel", "false")))); result.putMember("GradleCache", new JsonBoolean( Boolean.parseBoolean(getGradleProperty("org.gradle.caching", "false")))); result.putMember("HasBuildCacheURL", new JsonBoolean( gradle.getRootProject().getProperties().containsKey("buildCacheURL"))); - result.putMember("IsCi", new JsonBoolean( gradle.getRootProject().getProperties().containsKey("ci"))); + // Report as CI when the CI" project property or "CI" environment variable are set + result.putMember("IsCi", new JsonBoolean(gradle.getRootProject().getProperties().containsKey("ci") + || "true".equalsIgnoreCase(System.getenv("CI")))); result.putMember("MaxConcurrentMC", new JsonNumber("" + MCToolAction.getMaxConcurrentMC())); result.putMember("Tags", new UserJsonString(getGradleProperty("de.monticore.gradle.tags", ""))); diff --git a/monticore-generator/src/main/java/de/monticore/gradle/StatisticListener.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/StatisticListener.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/gradle/StatisticListener.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/StatisticListener.java diff --git a/monticore-generator/src/main/java/de/monticore/gradle/dependencies/MCDependenciesPlugin.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCDependenciesPlugin.java similarity index 98% rename from monticore-generator/src/main/java/de/monticore/gradle/dependencies/MCDependenciesPlugin.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCDependenciesPlugin.java index e4cfbc1541..477f5f2574 100644 --- a/monticore-generator/src/main/java/de/monticore/gradle/dependencies/MCDependenciesPlugin.java +++ b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCDependenciesPlugin.java @@ -1,7 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.gradle.dependencies; -import de.monticore.gradle.sources.MCGrammarsSourceDirectorySet; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; diff --git a/monticore-generator/src/main/java/de/monticore/gradle/dependencies/MCPublishingPlugin.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCPublishingPlugin.java similarity index 79% rename from monticore-generator/src/main/java/de/monticore/gradle/dependencies/MCPublishingPlugin.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCPublishingPlugin.java index 765397d664..df01716675 100644 --- a/monticore-generator/src/main/java/de/monticore/gradle/dependencies/MCPublishingPlugin.java +++ b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCPublishingPlugin.java @@ -24,7 +24,6 @@ import org.gradle.api.plugins.BasePlugin; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.plugins.internal.JavaConfigurationVariantMapping; -import org.gradle.api.provider.Provider; import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.maven.MavenPublication; import org.gradle.api.publish.maven.internal.publication.DefaultMavenPublication; @@ -51,7 +50,7 @@ public class MCPublishingPlugin implements Plugin { /** * Attribute to differentiate between outgoing configuratons of multiple source sets */ - protected static final Attribute GRAMMAR_SOURCE_SET_ATTRIBUTE = Attribute.of("monticore.generator.sourceset", String.class); + protected static final Attribute GRAMMAR_SOURCE_SET_ATTRIBUTE = Attribute.of("monticore.generator.sourceset", String.class); final SoftwareComponentFactory softwareComponentFactory; final TaskDependencyFactory taskDependencyFactory; @@ -187,10 +186,6 @@ protected void setUpPublicationOf(PublishArtifact grammarsJarArtifact, Configura * Create the Jar tasks for non-main source sets and configure them for publication */ protected void setupNonMainPublish(PublishArtifact grammarsJarArtifact, Project project, SourceSet sourceSet, AdhocComponentWithVariants component) { - if (Objects.toString(project.getGroup()).isEmpty()) { - doError(project, "Unable to publish MC-source set " + sourceSet.getName() + " due to no group being set"); - } - // Similar to the java feature, we a source set specific Jar and sourcesJar task TaskProvider jarTask = createJarTask(sourceSet, project); TaskProvider sourcesJarTask = createSourcesJarTask(sourceSet, project); @@ -216,53 +211,79 @@ protected void setupNonMainPublish(PublishArtifact grammarsJarArtifact, Project component.addVariantsFromConfiguration(compileClasspathConfig, new JavaConfigurationVariantMapping("compile", false)); compileClasspathConfig.getOutgoing().getArtifacts().add(jarArtifact); - // Ensure maven-publish is applied - @Nullable PublishingExtension publExt = project.getExtensions().findByType(PublishingExtension.class); - if (publExt == null) { - doError(project, "Publishing using the MontiCore Generator plugin requires the maven-publish plugin to be applied first!"); - return; + // We have to use afterEvaluate due to accessing the Project#getGroup() value + project.afterEvaluate(evalProj -> { + // Only register the publication when the maven-publish plugin is loaded + evalProj.getPluginManager().withPlugin("maven-publish", mavenPublishPlugin -> { + evalProj.getExtensions().configure(PublishingExtension.class, publExt -> { + // Set up a Maven publication for non-main source sets + // First, check if the publication already exists + var pubOpt = publExt.getPublications() + .matching(publication -> publication.getName().equals(sourceSet.getName()) + && publication instanceof MavenPublication).stream().findAny(); + if (pubOpt.isPresent()) { + // If present, properly configure it + configureNonMainPublication(grammarsJarArtifact, sourceSet, component, evalProj, (MavenPublication) pubOpt.get(), jarArtifact, sourcesJarArtifact); + } else { + // Otherwise create it & configure it then + publExt.getPublications().create(sourceSet.getName(), MavenPublication.class, mavenPublication -> { + configureNonMainPublication(grammarsJarArtifact, sourceSet, component, evalProj, mavenPublication, jarArtifact, sourcesJarArtifact); + }); + } + }); + }); + }); + } + + protected void configureNonMainPublication(PublishArtifact grammarsJarArtifact, SourceSet sourceSet, AdhocComponentWithVariants component, Project evalProj, MavenPublication mavenPublication, PublishArtifact jarArtifact, PublishArtifact sourcesJarArtifact) { + // And append the source set name as an appendix to the artifact id + mavenPublication.setArtifactId(evalProj.getName() + "-" + sourceSet.getName()); + // Use the same groupId as the evalProj + if (Objects.toString(evalProj.getGroup()).isEmpty()) { + doError(evalProj, "Unable to publish MC-source set " + sourceSet.getName() + " due to no group being known for the project " + evalProj.getName() + ". \nTry `group='example'` in your build.gradle"); } + mavenPublication.setGroupId(evalProj.getGroup().toString()); + // version is set implicitly - // Set up a Maven publication for non-main source sets - publExt - .getPublications().create(sourceSet.getName(), MavenPublication.class, mavenPublication -> { - // And append the source set name as an appendix to the artifact id - mavenPublication.setArtifactId(project.getName() + "-" + sourceSet.getName()); - mavenPublication.setGroupId(project.getGroup().toString()); - // version is set implicitly - - // and add all three jars as an artifact - mavenPublication.getArtifacts().artifact(grammarsJarArtifact); - mavenPublication.getArtifacts().artifact(jarArtifact); - mavenPublication.getArtifacts().artifact(sourcesJarArtifact); - - // Next, provide the source set specific component (for the Gradle module system) - mavenPublication.from(component); - - // The publication should not be considered when converting project dependencies to published metadata - // avoids: - // Publishing is not able to resolve a dependency on a project with multiple publications that have different coordinates - ((DefaultMavenPublication) mavenPublication).setAlias(true); - }); + // and add all three jars as an artifact + mavenPublication.getArtifacts().artifact(grammarsJarArtifact); + mavenPublication.getArtifacts().artifact(jarArtifact); + mavenPublication.getArtifacts().artifact(sourcesJarArtifact); + + // Next, provide the source set specific component (for the Gradle module system) + mavenPublication.from(component); + + // The publication should not be considered when converting project dependencies to published metadata + // avoids: + // Publishing is not able to resolve a dependency on a project with multiple publications that have different coordinates + ((DefaultMavenPublication) mavenPublication).setAlias(true); } /** * Create a lazy {@link org.gradle.api.internal.artifacts.publish.ArchivePublishArtifact} from a given * {@link Jar} task. * Provides compatibility between gradle 7 and 8 + * -- + * This is important for Gradle's dependency substitution to work, + * otherwise relocations have to be defined by hand. */ - protected PublishArtifact createPublishedArtifact(TaskProvider grammarsJarTask, Project project) { - // the LazyPublishArtifact constructor has changed between gradle versions: + // TODO: After 7.8.0 release: Remove this method & extends APublishingPlugin + protected PublishArtifact createPublishedArtifact(TaskProvider jarTaskProvider, Project project) { + // The LazyPublishArtifact is a part of Gradle's internals, + // but only accessible via the buildScript/groovy/kotlin API try { - // Gradle 7.4.2 - return new LazyPublishArtifact(grammarsJarTask, null, ((ProjectInternal) project).getFileResolver()); - } catch (NoSuchMethodError incompatibleVersion) { + // Attempt to use the Gradle 7.4.2 constructor via reflection + return LazyPublishArtifact.class + .getConstructor(org.gradle.api.provider.Provider.class, String.class, FileResolver.class) + .newInstance(jarTaskProvider, null, ((ProjectInternal) project).getFileResolver()); + } catch (ReflectiveOperationException e7) { + // If the 7.4.2 constructor is not found, try the Gradle 8 constructor try { // Gradle 8 - the TaskDependencyFactory parameter was added - return LazyPublishArtifact.class.getConstructor(Provider.class, String.class, FileResolver.class, TaskDependencyFactory.class) - .newInstance(grammarsJarTask, null, ((ProjectInternal) project).getFileResolver(), taskDependencyFactory); - } catch (ReflectiveOperationException e) { - throw new IllegalStateException("Incompatible LazyPublishArtifact constructor in gradle " + project.getGradle().getGradleVersion(), e); + return LazyPublishArtifact.class.getConstructor(org.gradle.api.provider.Provider.class, String.class, FileResolver.class, TaskDependencyFactory.class) + .newInstance(jarTaskProvider, null, ((ProjectInternal) project).getFileResolver(), taskDependencyFactory); + } catch (ReflectiveOperationException e8) { + throw new IllegalStateException("Incompatible LazyPublishArtifact constructor in gradle " + project.getGradle().getGradleVersion(), e8); } } } @@ -352,6 +373,7 @@ protected Configuration createDocumentationConfig(Project project, SourceSet sou sourcesElementsConfig.getAttributes().attribute(Category.CATEGORY_ATTRIBUTE, project.getObjects().named(Category.class, Category.DOCUMENTATION)); sourcesElementsConfig.getAttributes().attribute(Bundling.BUNDLING_ATTRIBUTE, project.getObjects().named(Bundling.class, Bundling.EXTERNAL)); sourcesElementsConfig.getAttributes().attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.getObjects().named(DocsType.class, docsType)); + sourcesElementsConfig.getAttributes().attribute(GRAMMAR_SOURCE_SET_ATTRIBUTE, sourceSet.getName()); return sourcesElementsConfig; } diff --git a/monticore-generator/src/main/java/de/monticore/gradle/dependencies/MCSourceSets.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCSourceSets.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/gradle/dependencies/MCSourceSets.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCSourceSets.java diff --git a/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCToolDependenciesPlugin.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCToolDependenciesPlugin.java new file mode 100644 index 0000000000..d7c51ed118 --- /dev/null +++ b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/dependencies/MCToolDependenciesPlugin.java @@ -0,0 +1,57 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.gradle.dependencies; + +import de.monticore.gradle.gen.MCGenTask; +import de.se_rwth.commons.logging.Log; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.attributes.Bundling; + +import javax.annotation.Nonnull; +import java.io.InputStream; +import java.util.Objects; +import java.util.Properties; + + +/** + * Creates "mcTool" configurations for the monticore generator tool. + * The MCGenTasks run the tool from this configuration + */ +public class MCToolDependenciesPlugin implements Plugin { + + public static final String MC_CONFIG_TOOL = "mcTool"; + + @Override + public void apply(@Nonnull Project project) { + project.getPluginManager().apply("java-library"); + + + // add a new configuration in which the monticore-generator (.jar) is loaded + // (this avoids loading the tool+all its dependencies into the shared plugin-classpath) + var toolConfig = project.getConfigurations().maybeCreate(MC_CONFIG_TOOL); + // Load the buildInfo.properties file (containing the current version) + Properties buildInfo = new Properties(); + try(InputStream is = MCToolDependenciesPlugin.class.getResourceAsStream("/buildInfo.properties")) { + buildInfo.load(is); + } catch (Exception e){ + Log.error("Can not load /buildInfo.properties from classpath", e); + } + String version = Objects.requireNonNull( + buildInfo.getProperty("version"), + "Can not find version in buildInfo.properties" + ); + // Add the (default) dependencies to the toolConfig + toolConfig.setCanBeResolved(true); + toolConfig.defaultDependencies(dependencies -> { + dependencies.add(project.getDependencies().create("de.monticore:monticore-generator:" + version)); + }); + toolConfig.attributes(it -> { + // Do not use the shadowed bundling variant (by default) + it.attribute(Bundling.BUNDLING_ATTRIBUTE, project.getObjects().named(Bundling.class, Bundling.EXTERNAL)); + }); + + // And add the config to the classpath of various tasks + project.getTasks().withType(MCGenTask.class).configureEach(t -> t.getExtraClasspathElements().from(toolConfig)); + + } +} diff --git a/monticore-generator/src/main/java/de/monticore/gradle/gen/MCGenTask.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/gen/MCGenTask.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/gradle/gen/MCGenTask.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/gen/MCGenTask.java diff --git a/monticore-generator/src/main/java/de/monticore/gradle/gen/MCToolAction.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/gen/MCToolAction.java similarity index 97% rename from monticore-generator/src/main/java/de/monticore/gradle/gen/MCToolAction.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/gen/MCToolAction.java index 270586ebab..53caa09d2a 100644 --- a/monticore-generator/src/main/java/de/monticore/gradle/gen/MCToolAction.java +++ b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/gen/MCToolAction.java @@ -65,7 +65,7 @@ protected void doRun(final String[] args) { } try { String logPrefix = "[" + getParameters().getProgressName().get() + "] "; - isolator.executeInClassloader(MCToolInvoker.class.getName(), "run", + isolator.executeInClassloader("de.monticore.gradle.gen.MCToolInvoker", "run", args, logPrefix, getParameters().getExtraClasspathElements()); } finally { semaphore.release(); diff --git a/monticore-generator/src/main/java/de/monticore/gradle/sources/MCGrammarsSourceDirectorySet.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/sources/MCGrammarsSourceDirectorySet.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/gradle/sources/MCGrammarsSourceDirectorySet.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/sources/MCGrammarsSourceDirectorySet.java diff --git a/monticore-generator/src/main/java/de/monticore/gradle/sources/MCSourcesPlugin.java b/monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/sources/MCSourcesPlugin.java similarity index 100% rename from monticore-generator/src/main/java/de/monticore/gradle/sources/MCSourcesPlugin.java rename to monticore-generator/gradle-plugin/src/main/java/de/monticore/gradle/sources/MCSourcesPlugin.java diff --git a/monticore-generator/src/test/java/de/monticore/IncCheckerTest.java b/monticore-generator/gradle-plugin/src/test/java/de/monticore/IncCheckerTest.java similarity index 61% rename from monticore-generator/src/test/java/de/monticore/IncCheckerTest.java rename to monticore-generator/gradle-plugin/src/test/java/de/monticore/IncCheckerTest.java index 2e4c4b347a..94f7111bb1 100644 --- a/monticore-generator/src/test/java/de/monticore/IncCheckerTest.java +++ b/monticore-generator/gradle-plugin/src/test/java/de/monticore/IncCheckerTest.java @@ -7,57 +7,43 @@ import de.se_rwth.commons.Files; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.*; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * This class tests the {@link IncChecker} testing against the expected incCheck result after changing the files. */ -@RunWith(Parameterized.class) public class IncCheckerTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - // Test for the default mc4, a short sc, and a longer file ending - @Parameterized.Parameters(name = "{0}") - public static Collection fileEndings() { - return Arrays.asList(new Object[][]{ - {"mc4"}, {"sc"}, {"longerEnding"} - }); - } + @TempDir + public File temporaryFolder; + - @Before + @BeforeEach public void initLog() { LogStub.init(); Log.enableFailQuick(false); } - - protected final String fileEnding; - - public IncCheckerTest(String fileEnding) { - this.fileEnding = fileEnding; - } - @Test - public void testIncCheck() throws IOException { - File tempDir = temporaryFolder.newFolder(); + @ParameterizedTest + @ValueSource(strings = {"mc4", "sc", "longerEnding"}) + public void testIncCheck(String fileEnding) throws IOException { + File tempDir = new File(temporaryFolder, "tempDir"); File outDir = new File(tempDir, "out"); File repDir = new File(tempDir, "reports"); - outDir.mkdirs(); - repDir.mkdirs(); + assertTrue(outDir.mkdirs()); + assertTrue(repDir.mkdirs()); String modelName = "IncCheckExample"; Logger logger = LoggerFactory.getLogger("nop"); @@ -75,8 +61,8 @@ public void testIncCheck() throws IOException { MCPath mcPath = new MCPath(tempDir.toPath()); // Test that the MCPath is behaving correctly for both HW Files - Assert.assertTrue("Existing file not found in MCPath", mcPath.find(existingHWFile.getName()).isPresent()); - Assert.assertFalse("Missing file found in MCPath", mcPath.find(missingHWFile.getName()).isPresent()); + assertTrue(mcPath.find(existingHWFile.getName()).isPresent(), "Existing file not found in MCPath"); + assertFalse(mcPath.find(missingHWFile.getName()).isPresent(), "Missing file found in MCPath"); // Create the IncGenGradleCheck file and fill its content File modelRepDir = new File(repDir, modelName.replaceAll("\\.", "/").toLowerCase()); @@ -85,42 +71,49 @@ public void testIncCheck() throws IOException { modelRepDir.mkdirs(); incGenGradleCheckFile.createNewFile(); Files.writeToFile(CharSource.wrap( - calcChacheEntry(inputFile) + "\n" + + calcChacheEntry(inputFile, fileEnding) + "\n" + calcHwcEntry(existingHWFile) + "\n" + calcGenEntry(missingHWFile) + "\n" ).asByteSource(StandardCharsets.UTF_8).openStream(), incGenGradleCheckFile); // Has the IncGenGradleCheck file been created? - Assert.assertTrue("IncGenGradleCheck.txt does not exists: " + incGenGradleCheckFile.getAbsolutePath(), incGenGradleCheckFile.exists()); + assertTrue(incGenGradleCheckFile.exists(), + "IncGenGradleCheck.txt does not exists: " + incGenGradleCheckFile.getAbsolutePath()); // Next, actually test the IncCheck // First without any changes - Assert.assertTrue("IncCheck without changes failed", IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, "")); + assertTrue(IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, ""), + "IncCheck without changes failed"); // Check when a HW file has been added missingHWFile.createNewFile(); - Assert.assertFalse("IncCheck with added HW file did not fire", IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, "")); + assertFalse(IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, ""), + "IncCheck with added HW file did not fire"); missingHWFile.delete(); // Test with no changes again (after deleting the added HW file) - Assert.assertTrue("IncCheck without changes (after deleting) failed", IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, "")); + assertTrue(IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, ""), + "IncCheck without changes (after deleting) failed"); // Delete the existing HW file and test existingHWFile.delete(); - Assert.assertFalse("IncCheck with deleted HW file did not fire", IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, "")); + assertFalse(IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, ""), + "IncCheck with deleted HW file did not fire"); existingHWFile.createNewFile(); // Test with no changes again (after re-adding the deleted HW file) - Assert.assertTrue("IncCheck without changes (after re-adding) failed", IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, "")); + assertTrue(IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, ""), + "IncCheck without changes (after re-adding) failed"); // Change input model/content Files.writeToFile(CharSource.wrap("new file content").asByteSource(StandardCharsets.UTF_8).openStream(), inputFile); - Assert.assertFalse("IncCheck with changed input model did not fire", IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, "")); + assertFalse(IncChecker.incCheck(incGenGradleCheckFile, modelName, logger, fileEnding, ""), + "IncCheck with changed input model did not fire"); assertTrue(Log.getFindings().isEmpty()); } - private String calcChacheEntry(File file) throws IOException { + private String calcChacheEntry(File file, String fileEnding) throws IOException { StringBuilder cacheEntry = new StringBuilder(); cacheEntry.append(fileEnding + ":"); cacheEntry.append(file.getAbsolutePath()); diff --git a/monticore-generator/src/test/java/de/monticore/gradle/MCGenPluginTest.java b/monticore-generator/gradle-plugin/src/test/java/de/monticore/gradle/MCGenPluginTest.java similarity index 51% rename from monticore-generator/src/test/java/de/monticore/gradle/MCGenPluginTest.java rename to monticore-generator/gradle-plugin/src/test/java/de/monticore/gradle/MCGenPluginTest.java index af488ec948..4fec85cf01 100644 --- a/monticore-generator/src/test/java/de/monticore/gradle/MCGenPluginTest.java +++ b/monticore-generator/gradle-plugin/src/test/java/de/monticore/gradle/MCGenPluginTest.java @@ -3,23 +3,26 @@ import de.monticore.symboltable.serialization.JsonParser; import de.monticore.symboltable.serialization.json.JsonObject; +import org.apache.commons.io.FileUtils; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.gradle.tooling.internal.consumer.ConnectorServices; +import org.gradle.tooling.internal.consumer.DefaultGradleConnector; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.rules.TemporaryFolder; +import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.util.Collections; +import java.nio.file.Path; +import java.util.*; import static org.gradle.testkit.runner.TaskOutcome.*; +import static org.junit.jupiter.api.Assertions.*; /** * Test if the plugin correctly configures a gradle project @@ -32,22 +35,54 @@ @Execution(ExecutionMode.SAME_THREAD) // Do not run in parallel, too memory hungry @NotThreadSafe // Technically thread safe, just memory hungry public class MCGenPluginTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + // TODO: Use @TempDir instead of manual creation and deletion of the temporary folder + // see: https://github.com/gradle/gradle/issues/12535 + // @TempDir + public Path temporaryFolder; File testProjectDir; File settingsFile; File propertiesFile; File buildFile; File grammarDir; + + // TODO: Remove when using TempDir + private static List workingDirs = new ArrayList<>(); - @Before + @BeforeEach public void setup() throws IOException { - testProjectDir = temporaryFolder.newFolder(); + testProjectDir = createDirectory(temporaryFolder.resolve("projectDir")); settingsFile = new File(testProjectDir, "settings.gradle"); buildFile = new File(testProjectDir, "build.gradle"); propertiesFile = new File(testProjectDir, "gradle.properties"); grammarDir = new File(testProjectDir, "src/main/grammars"); } + + // TODO: Remove when using TempDir + @BeforeEach + void createWorkspace() throws IOException{ + this.temporaryFolder = Files.createTempDirectory(getClass().getSimpleName()); + workingDirs.add(this.temporaryFolder); + } + + // TODO: Remove when using TempDir + @AfterEach + void resetGradleConnector() { + ConnectorServices.reset(); + } + + // TODO: Remove when using TempDir + @AfterAll + static void deleteWorkspace() throws IOException, InterruptedException { + DefaultGradleConnector.close(); + Thread.sleep(100); + for (Path workingDir : workingDirs) { + FileUtils.forceDelete(workingDir.toFile()); + } + } + + File createDirectory(Path path) throws IOException{ + return Files.createDirectory(path).toFile(); + } @Test public void testCanApplyPlugin_v7_4_2() throws IOException { @@ -86,8 +121,8 @@ void testCanApplyPlugin(String version) throws IOException { .build(); // A generateMCGrammars task was added - Assert.assertTrue(result.getOutput().contains("generateMCGrammars")); - Assert.assertEquals(SUCCESS, result.task(":tasks").getOutcome()); + assertTrue(result.getOutput().contains("generateMCGrammars")); + assertEquals(SUCCESS, result.task(":tasks").getOutcome()); } @@ -119,9 +154,10 @@ public void testGenerateGrammar_v8_7() throws IOException { void testGenerateGrammar(String version) throws IOException { writeFile(settingsFile, "rootProject.name = 'hello-world'"); writeFile(propertiesFile, "de.monticore.gradle.show_performance_statistic=true\norg.gradle.jvmargs=-XX:MaxMetaspaceSize=1g\n"); - String buildFileContent = "plugins {" + - " id 'de.monticore.generator' " + - "}"; + String buildFileContent = "plugins {\n" + + " id 'de.monticore.generator' \n" + + "}\n" + + createMCToolDependency(); writeFile(buildFile, buildFileContent); // Note: We are unable to load MCBasics or compile, // as the monticore-grammar dependency might not be available yet @@ -130,28 +166,30 @@ void testGenerateGrammar(String version) throws IOException { writeFile(new File(grammarDir, "MyTestGrammarS.mc4"), "grammar MyTestGrammarS extends MyTestGrammar { Monti = \"Core\"; }"); + // use a custom gradle home directory to ensure fresh caches + File gradleHome = createDirectory(temporaryFolder.resolve("gradleHome")); BuildResult result = GradleRunner.create() .withPluginClasspath() .withGradleVersion(version) .withProjectDir(testProjectDir) - .withArguments("generateMCGrammars", "--build-cache", "--info") + .withArguments(withProperties("generateMCGrammars", "--build-cache", "--info", "--stacktrace", "-g", gradleHome.getAbsolutePath())) .build(); // file MyTestGrammar is worked on -// Assert.assertTrue(result.getOutput(), result.getOutput().contains("[MyTestGrammar.mc4]")); // The Log-Prefix is unreliable - Assert.assertTrue(result.getOutput(), result.getOutput().contains("/src/main/grammars/MyTestGrammar.mc4")); +// assertTrue(result.getOutput(), result.getOutput().contains("[MyTestGrammar.mc4]")); // The Log-Prefix is unreliable + assertTrue(result.getOutput().contains("/src/main/grammars/MyTestGrammar.mc4"), result.getOutput()); // file MyTestGrammarS is worked on -// Assert.assertTrue(result.getOutput(), result.getOutput().contains("[MyTestGrammarS.mc4]")); // The Log-Prefix is unreliable - Assert.assertTrue(result.getOutput(), result.getOutput().contains("/src/main/grammars/MyTestGrammarS.mc4")); +// assertTrue(result.getOutput(), result.getOutput().contains("[MyTestGrammarS.mc4]")); // The Log-Prefix is unreliable + assertTrue(result.getOutput().contains("/src/main/grammars/MyTestGrammarS.mc4"), result.getOutput()); // and the task was successful - Assert.assertEquals(SUCCESS, result.task(":generateMCGrammars").getOutcome()); + assertEquals(SUCCESS, result.task(":generateMCGrammars").getOutcome()); JsonObject taskStats = checkAndGetStats(result.getOutput(), ":generateMCGrammars"); - Assert.assertFalse(taskStats.getBooleanMember("UpToDate")); - Assert.assertFalse(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertFalse(taskStats.getBooleanMember("UpToDate")); + assertFalse(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); // Test build-cache, by first deleting the build dir de.se_rwth.commons.Files.deleteFiles(new File(testProjectDir, "build")); @@ -160,17 +198,17 @@ void testGenerateGrammar(String version) throws IOException { .withPluginClasspath() .withGradleVersion(version) .withProjectDir(testProjectDir) - .withArguments("generateMCGrammars", "--build-cache", "--info") + .withArguments(withProperties("generateMCGrammars", "--build-cache", "--info", "-g", gradleHome.getAbsolutePath())) .build(); // and then check, that the build cache was used - Assert.assertEquals("generateMCGrammars was not cached", - FROM_CACHE, result.task(":generateMCGrammars").getOutcome()); + assertEquals(FROM_CACHE, result.task(":generateMCGrammars").getOutcome(), + "generateMCGrammars was not cached"); taskStats = checkAndGetStats(result.getOutput(), ":generateMCGrammars"); - Assert.assertTrue(taskStats.getBooleanMember("UpToDate")); - Assert.assertTrue(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertTrue(taskStats.getBooleanMember("UpToDate")); + assertTrue(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); // Next, test up-to-date checks: @@ -182,19 +220,21 @@ void testGenerateGrammar(String version) throws IOException { .withPluginClasspath() .withGradleVersion(version) .withProjectDir(testProjectDir) - .withArguments("generateMCGrammars", "--build-cache", "--info") + .withArguments(withProperties("generateMCGrammars", "--build-cache", "--info", "-g", gradleHome.getAbsolutePath())) .build(); // and the task was successful - Assert.assertEquals(SUCCESS, result.task(":generateMCGrammars").getOutcome()); + assertEquals(SUCCESS, result.task(":generateMCGrammars").getOutcome()); // Only MyTestGrammarS SHOULD not be up-to-date - Assert.assertTrue(result.getOutput(), result.getOutput().contains("MyTestGrammar.mc4 is UP-TO-DATE, no action required")); - Assert.assertFalse(result.getOutput(), result.getOutput().contains("MyTestGrammarS.mc4 is UP-TO-DATE, no action required")); + assertTrue(result.getOutput().contains("MyTestGrammar.mc4 is UP-TO-DATE, no action required"), + result.getOutput()); + assertFalse(result.getOutput().contains("MyTestGrammarS.mc4 is UP-TO-DATE, no action required"), + result.getOutput()); taskStats = checkAndGetStats(result.getOutput(), ":generateMCGrammars"); - Assert.assertFalse(taskStats.getBooleanMember("UpToDate")); // Note: The task is not up-to-date, as one of its inputs has changed - Assert.assertFalse(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertFalse(taskStats.getBooleanMember("UpToDate")); // Note: The task is not up-to-date, as one of its inputs has changed + assertFalse(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); // and change MyTestGrammar @@ -205,17 +245,17 @@ void testGenerateGrammar(String version) throws IOException { .withPluginClasspath() .withGradleVersion(version) .withProjectDir(testProjectDir) - .withArguments("generateMCGrammars", "--build-cache", "--info") + .withArguments(withProperties("generateMCGrammars", "--build-cache", "--info", "-g", gradleHome.getAbsolutePath())) .build(); // Nothing SHOULD not be up-to-date - Assert.assertFalse(result.getOutput(), result.getOutput().contains("MyTestGrammar.mc4 is UP-TO-DATE, no action required")); - Assert.assertFalse(result.getOutput(), result.getOutput().contains("MyTestGrammarS.mc4 is UP-TO-DATE, no action required")); + assertFalse(result.getOutput().contains("MyTestGrammar.mc4 is UP-TO-DATE, no action required"), result.getOutput()); + assertFalse(result.getOutput().contains("MyTestGrammarS.mc4 is UP-TO-DATE, no action required"), result.getOutput()); taskStats = checkAndGetStats(result.getOutput(), ":generateMCGrammars"); - Assert.assertFalse(taskStats.getBooleanMember("UpToDate")); - Assert.assertFalse(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertFalse(taskStats.getBooleanMember("UpToDate")); + assertFalse(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); } @@ -260,7 +300,7 @@ void testMultiProject(String version) throws IOException { " from components.java\n" + " }" + " }" + - "}"; + "}\n" + createMCToolDependency(); var aDir = new File(testProjectDir, "A"); writeFile(new File(aDir, "build.gradle"), buildFileContentA); // Note: We are unable to load MCBasics or compile, @@ -273,7 +313,8 @@ void testMultiProject(String version) throws IOException { "}\n" + "dependencies { " + " grammar(project(':A')) " + - "}"; + "}\n" + + createMCToolDependency(); var bDir = new File(testProjectDir, "B"); writeFile(new File(bDir, "build.gradle"), buildFileContentB); @@ -281,29 +322,31 @@ void testMultiProject(String version) throws IOException { writeFile(new File(new File(bDir, "src/main/grammars"), "MyTestGrammarS.mc4"), "grammar MyTestGrammarS extends MyTestGrammar { Monti = \"Core\"; }"); + // use a custom gradle home directory to ensure fresh cashes + File gradleHome = createDirectory(temporaryFolder.resolve("gradleHome")); BuildResult result = GradleRunner.create() .withPluginClasspath() .withGradleVersion(version) .withProjectDir(testProjectDir) - .withArguments("generateMCGrammars", "--build-cache", "--info") + .withArguments(withProperties("generateMCGrammars", "--build-cache", "--info", "-g", gradleHome.getAbsolutePath())) .build(); // file MyTestGrammar is worked on - // Assert.assertTrue(result.getOutput(), result.getOutput().contains("[MyTestGrammar.mc4]")); // The Log-Prefix is unreliable - Assert.assertTrue(result.getOutput(), result.getOutput().contains("/src/main/grammars/MyTestGrammar.mc4")); + // assertTrue(result.getOutput(), result.getOutput().contains("[MyTestGrammar.mc4]")); // The Log-Prefix is unreliable + assertTrue(result.getOutput().contains("/src/main/grammars/MyTestGrammar.mc4"), result.getOutput()); // file MyTestGrammarS is worked on - // Assert.assertTrue(result.getOutput(), result.getOutput().contains("[MyTestGrammarS.mc4]")); // The Log-Prefix is unreliable - Assert.assertTrue(result.getOutput(), result.getOutput().contains("/src/main/grammars/MyTestGrammarS.mc4")); + // assertTrue(result.getOutput(), result.getOutput().contains("[MyTestGrammarS.mc4]")); // The Log-Prefix is unreliable + assertTrue(result.getOutput().contains("/src/main/grammars/MyTestGrammarS.mc4"), result.getOutput()); // and the task was successful - Assert.assertEquals(SUCCESS, result.task(":A:generateMCGrammars").getOutcome()); - Assert.assertEquals(SUCCESS, result.task(":B:generateMCGrammars").getOutcome()); + assertEquals(SUCCESS, result.task(":A:generateMCGrammars").getOutcome()); + assertEquals(SUCCESS, result.task(":B:generateMCGrammars").getOutcome()); JsonObject taskStats = checkAndGetStats(result.getOutput(), ":A:generateMCGrammars"); - Assert.assertFalse(taskStats.getBooleanMember("UpToDate")); - Assert.assertFalse(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertFalse(taskStats.getBooleanMember("UpToDate")); + assertFalse(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); // Test build-cache, by first deleting the build dir de.se_rwth.commons.Files.deleteFiles(new File(testProjectDir, "build")); @@ -315,21 +358,21 @@ void testMultiProject(String version) throws IOException { .withPluginClasspath() .withGradleVersion(version) .withProjectDir(testProjectDir) - .withArguments("generateMCGrammars", "--build-cache", "--info") + .withArguments(withProperties("generateMCGrammars", "--build-cache", "--info", "-g", gradleHome.getAbsolutePath())) .build(); // and then check, that the build cache was used - Assert.assertEquals("A:generateMCGrammars was not cached", - FROM_CACHE, result.task(":A:generateMCGrammars").getOutcome()); - Assert.assertEquals("B:generateMCGrammars was not cached", - FROM_CACHE, result.task(":B:generateMCGrammars").getOutcome()); + assertEquals(FROM_CACHE, result.task(":A:generateMCGrammars").getOutcome(), + "A:generateMCGrammars was not cached"); + assertEquals(FROM_CACHE, result.task(":B:generateMCGrammars").getOutcome(), + "B:generateMCGrammars was not cached"); taskStats = checkAndGetStats(result.getOutput(), ":B:generateMCGrammars"); - Assert.assertTrue(taskStats.getBooleanMember("UpToDate")); - Assert.assertTrue(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertTrue(taskStats.getBooleanMember("UpToDate")); + assertTrue(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); // Next, test up-to-date checks: @@ -341,24 +384,24 @@ void testMultiProject(String version) throws IOException { .withPluginClasspath() .withGradleVersion(version) .withProjectDir(testProjectDir) - .withArguments("generateMCGrammars", "--build-cache", "--info") + .withArguments(withProperties("generateMCGrammars", "--build-cache", "--info", "-g", gradleHome.getAbsolutePath())) .build(); // and the B-task was successful - Assert.assertEquals(SUCCESS, result.task(":B:generateMCGrammars").getOutcome()); + assertEquals(SUCCESS, result.task(":B:generateMCGrammars").getOutcome()); // the A-task should be up to date (i.e., not even pulled from the cache) - Assert.assertEquals(UP_TO_DATE, result.task(":A:generateMCGrammars").getOutcome()); + assertEquals(UP_TO_DATE, result.task(":A:generateMCGrammars").getOutcome()); // and thus, MyTestGrammar should not be printed to the log - Assert.assertFalse(result.getOutput(), result.getOutput().contains("MyTestGrammar.mc4 is UP-TO-DATE, no action required")); - Assert.assertFalse(result.getOutput(), result.getOutput().contains("MyTestGrammar.mc4 is *NOT* UP-TO-DATE")); + assertFalse(result.getOutput().contains("MyTestGrammar.mc4 is UP-TO-DATE, no action required"), result.getOutput()); + assertFalse(result.getOutput().contains("MyTestGrammar.mc4 is *NOT* UP-TO-DATE"), result.getOutput()); // Only MyTestGrammarS SHOULD not be up-to-date - Assert.assertFalse(result.getOutput(), result.getOutput().contains("MyTestGrammarS.mc4 is UP-TO-DATE, no action required")); - Assert.assertTrue(result.getOutput(), result.getOutput().contains("MyTestGrammarS.mc4 is *NOT* UP-TO-DATE")); + assertFalse(result.getOutput().contains("MyTestGrammarS.mc4 is UP-TO-DATE, no action required"), result.getOutput()); + assertTrue(result.getOutput().contains("MyTestGrammarS.mc4 is *NOT* UP-TO-DATE"), result.getOutput()); taskStats = checkAndGetStats(result.getOutput(), ":B:generateMCGrammars"); - Assert.assertFalse(taskStats.getBooleanMember("UpToDate")); // Note: The task is not up-to-date, as one of its inputs has changed - Assert.assertFalse(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertFalse(taskStats.getBooleanMember("UpToDate")); // Note: The task is not up-to-date, as one of its inputs has changed + assertFalse(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); // and change MyTestGrammar @@ -369,23 +412,23 @@ void testMultiProject(String version) throws IOException { .withPluginClasspath() .withGradleVersion(version) .withProjectDir(testProjectDir) - .withArguments("generateMCGrammars", "--build-cache", "--info") + .withArguments(withProperties("generateMCGrammars", "--build-cache", "--info", "-g", gradleHome.getAbsolutePath())) .build(); // Nothing SHOULD not be up-to-date - Assert.assertFalse(result.getOutput(), result.getOutput().contains("MyTestGrammar.mc4 is UP-TO-DATE, no action required")); - Assert.assertFalse(result.getOutput(), result.getOutput().contains("MyTestGrammarS.mc4 is UP-TO-DATE, no action required")); + assertFalse(result.getOutput().contains("MyTestGrammar.mc4 is UP-TO-DATE, no action required"), result.getOutput()); + assertFalse(result.getOutput().contains("MyTestGrammarS.mc4 is UP-TO-DATE, no action required"), result.getOutput()); taskStats = checkAndGetStats(result.getOutput(), ":A:generateMCGrammars"); - Assert.assertFalse(taskStats.getBooleanMember("UpToDate")); - Assert.assertFalse(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertFalse(taskStats.getBooleanMember("UpToDate")); + assertFalse(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); taskStats = checkAndGetStats(result.getOutput(), ":B:generateMCGrammars"); - Assert.assertFalse(taskStats.getBooleanMember("UpToDate")); - Assert.assertFalse(taskStats.getBooleanMember("Cached")); - Assert.assertFalse(taskStats.getBooleanMember("hasError")); - Assert.assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); + assertFalse(taskStats.getBooleanMember("UpToDate")); + assertFalse(taskStats.getBooleanMember("Cached")); + assertFalse(taskStats.getBooleanMember("hasError")); + assertEquals("de.monticore.gradle.gen.MCGenTask_Decorated", taskStats.getStringMember("Type")); } @@ -407,7 +450,51 @@ JsonObject checkAndGetStats(String output, String taskPath) { } } System.err.println(output); - Assert.fail("Task " + taskPath + " was not found within the stats"); + fail("Task " + taskPath + " was not found within the stats"); return null; } + + + Properties loadProperties() { + Properties properties = new Properties(); + try { + properties.load(this.getClass().getClassLoader().getResourceAsStream("buildInfo.properties")); + } + catch (IOException e) { + throw new RuntimeException(e); + } + return properties; + } + + List withProperties(String... args) { + return withProperties(Arrays.asList(args)); + } + + List withProperties(List runnerArgs) { + List ret = new ArrayList<>(runnerArgs); + @Nullable + String mavenRepo = System.getProperty("maven.repo.local"); + if (mavenRepo != null && !mavenRepo.isEmpty()) { + ret.add("-Dmaven.repo.local=" + mavenRepo + ""); + } + @Nullable + String useLocalRepo = System.getProperty("useLocalRepo"); + if (useLocalRepo != null && !useLocalRepo.isEmpty()) { + ret.add("-PuseLocalRepo=" + useLocalRepo); + } + return ret; + } + + String createMCToolDependency() { + String projVersion = loadProperties().getProperty("version"); + File mcGenToolJar = new File(new File("../target/libs/"), "monticore-generator-" + projVersion + "-mc-tool.jar"); + return "repositories {\n" + " if ((\"true\").equals(getProperty('useLocalRepo'))) {\n " + + " mavenLocal()\n" + " }\n" + + " maven{ url 'https://nexus.se.rwth-aachen.de/content/groups/public' }\n" + + " mavenCentral()\n" + "}\n" + + // We have to inject the cdlang jar for this project (as it is not yet published) + "dependencies {\n" + " mcTool files('" + mcGenToolJar.getAbsolutePath().replace("\\", "\\\\") + + "')\n" + + "}\n"; + } } diff --git a/monticore-generator/gradle.properties b/monticore-generator/gradle.properties index 0cee32c55a..a4171758b0 100644 --- a/monticore-generator/gradle.properties +++ b/monticore-generator/gradle.properties @@ -4,19 +4,21 @@ repo=https://nexus.se.rwth-aachen.de/content/groups/public org.gradle.parallel=true -useLocalRepo=true +useLocalRepo=false # set true or use –PshowTestOutput=true to print test output showTestOutput=false # versions used -version=7.8.0-SNAPSHOT -previous_mc_version =7.7.0 +version=7.9.0-SNAPSHOT +previous_mc_version =7.8.0 -se_commons_version =7.7.0 +se_commons_version =7.8.0 antlr_version =4.12.0 -junit_version =5.10.3 -cd4a_version =7.7.0 +junit_version = 5.14.1 +junit_platform_version = 1.14.1 +cd4a_version =7.8.0 commons_lang3_version = 3.8.1 commons_cli_version = 1.4 freemarker_version = 2.3.28 guava_version =31.1-jre +shadow_plugin_version=7.1.2 diff --git a/monticore-generator/settings.gradle b/monticore-generator/settings.gradle index 908daa3a98..6b0a665a85 100644 --- a/monticore-generator/settings.gradle +++ b/monticore-generator/settings.gradle @@ -6,11 +6,15 @@ pluginManagement { mavenLocal() } maven { - url repo + url = repo } gradlePluginPortal() } } +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.9.0' +} rootProject.name = 'monticore-generator' +include "gradle-plugin" diff --git a/monticore-generator/src/main/java/de/monticore/DelegatingClassLoader.java b/monticore-generator/src/main/java/de/monticore/DelegatingClassLoader.java index 317292dc2a..562da06832 100644 --- a/monticore-generator/src/main/java/de/monticore/DelegatingClassLoader.java +++ b/monticore-generator/src/main/java/de/monticore/DelegatingClassLoader.java @@ -1,6 +1,8 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore; +import com.google.common.base.Preconditions; + import java.io.Closeable; import java.io.IOException; import java.io.InputStream; @@ -48,7 +50,7 @@ public DelegatingClassLoader(ClassLoader delegate) { @Override public Class loadClass(String name) throws ClassNotFoundException { - return Objects.requireNonNull(delegate.get()).loadClass(name); + return Preconditions.checkNotNull(delegate.get()).loadClass(name); } @Override @@ -68,22 +70,22 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE @Override public URL getResource(String name) { - return Objects.requireNonNull(delegate.get()).getResource(name); + return Preconditions.checkNotNull(delegate.get()).getResource(name); } @Override public Enumeration getResources(String name) throws IOException { - return Objects.requireNonNull(delegate.get()).getResources(name); + return Preconditions.checkNotNull(delegate.get()).getResources(name); } @Override public Stream resources(String name) { - return Objects.requireNonNull(delegate.get()).resources(name); + return Preconditions.checkNotNull(delegate.get()).resources(name); } @Override public InputStream getResourceAsStream(String name) { - return Objects.requireNonNull(delegate.get()).getResourceAsStream(name); + return Preconditions.checkNotNull(delegate.get()).getResourceAsStream(name); } @Override diff --git a/monticore-generator/src/main/java/de/monticore/MontiCoreScript.java b/monticore-generator/src/main/java/de/monticore/MontiCoreScript.java index dee43bd83e..0681c3a8bb 100644 --- a/monticore-generator/src/main/java/de/monticore/MontiCoreScript.java +++ b/monticore-generator/src/main/java/de/monticore/MontiCoreScript.java @@ -2,6 +2,7 @@ package de.monticore; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.io.Files; @@ -94,6 +95,7 @@ import de.monticore.codegen.parser.ParserGenerator; import de.monticore.codegen.prettyprint.CDPrettyPrinterDecorator; import de.monticore.codegen.prettyprint.PrettyPrinterGenerator; +import de.monticore.de.monticore.grammar.grammar_withconcepts._symboltable.Grammar_WithConceptsPhasedSTCFix; import de.monticore.dstlgen.DSTLGenScript; import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; @@ -320,7 +322,7 @@ public void generateParser(GlobalExtensionManagement glex, List getAllCDTypes(DiagramSymbol cdSymbol) { /** * methods for super CDTypes (CDClass and CDInterface) + * @param astcdType a ASTCDType which supertypes should be found + * @return a list of all super types including CDClass and CDInterface */ + public List getAllSuperClassesTransitive(ASTCDType astcdType) { + return new ArrayList<>(getAllSuperClassesTransitive(astcdType.getSymbol())); + } + public List getAllSuperClassesTransitive(ASTCDClass astcdClass) { return getAllSuperClassesTransitive(astcdClass.getSymbol()) .stream() - .map(s -> createASTFullName(s)) + .map(this::createASTFullName) .collect(Collectors.toList()); } - protected List getAllSuperClassesTransitive(CDTypeSymbol cdTypeSymbol) { - List superSymbolList = new ArrayList<>(); + protected List getAllSuperClassesTransitive(TypeSymbol cdTypeSymbol) { + List superSymbolList = new ArrayList<>(); if (cdTypeSymbol.isPresentSuperClass()) { TypeSymbol superSymbol = cdTypeSymbol.getSuperClass().getTypeInfo(); if (superSymbol instanceof TypeSymbolSurrogate) { @@ -169,13 +174,13 @@ protected List getAllSuperClassesTransitive(CDTypeSymbol cdTypeSym superSymbol = ((TypeSymbolSurrogate) superSymbol).lazyLoadDelegate(); } - superSymbolList.add((CDTypeSymbol) superSymbol); - superSymbolList.addAll(getAllSuperClassesTransitive((CDTypeSymbol) superSymbol)); + superSymbolList.add(superSymbol); + superSymbolList.addAll(getAllSuperClassesTransitive(superSymbol)); } return superSymbolList; } - public List getAllSuperInterfacesTransitive(CDTypeSymbol cdTypeSymbol) { + public List getAllSuperInterfacesTransitive(TypeSymbol cdTypeSymbol) { List superSymbolList = new ArrayList<>(); List localSuperInterfaces = Lists.newArrayList(); cdTypeSymbol.getSuperTypesList().stream() @@ -269,12 +274,26 @@ protected List getStereotypeValues(ASTModifier modifier, MC2CDStereotype modifier.getStereotype().getValuesList().stream() .filter(value -> value.getName().equals(stereotype.toString())) .filter(ASTStereoValue::isPresentText) - .forEach(value -> values.add(value.getValue())); + .forEach(value -> values.add(getStereoValueValueFix(value))); // TODO: Replace with value.getValue() after 7.8.0-RELEASE } return values; } - /** + // TODO: Remove me after 7.8.0-RELEASE + protected String getStereoValueValueFix(ASTStereoValue stereoValue) { + // The ASTStereoValue#getValue() fails with strings + if (stereoValue.getContent() == null) { + if (stereoValue.isPresentText()) { + stereoValue.setContent(StringEscapeUtils.unescapeJava(stereoValue.getText().getValue())); + } else { + stereoValue.setContent(""); + } + } + + return stereoValue.getContent(); + } + + /* * methods for determination and access to special stereotypes */ @@ -314,6 +333,11 @@ public String getInheritedGrammarName(ASTCDAttribute attribute) { return getStereotypeValues(attribute.getModifier(), MC2CDStereotypes.INHERITED).get(0); } + public List getTerminalDefaultValues(ASTCDAttribute attribute) { + return getStereotypeValues(attribute.getModifier(), MC2CDStereotypes.TERMINAL_DEFAULT_VALUE); + } + + public boolean hasDeprecatedStereotype(ASTModifier modifier) { return hasStereotype(modifier, MC2CDStereotypes.DEPRECATED); } @@ -424,8 +448,7 @@ public void addDeprecatedStereotype(ASTModifier modifier, Optional depre ASTStereoValue stereoValue = CD4AnalysisMill.stereoValueBuilder() .setName(MC2CDStereotypes.DEPRECATED.toString()).uncheckedBuild(); if (deprecatedValue.isPresent()) { - stereoValue.setText( - CD4AnalysisMill.stringLiteralBuilder().setSource(deprecatedValue.get()).build()); + stereoValue.setContent(deprecatedValue.get()); } stereoValueList.add(stereoValue); } @@ -540,9 +563,10 @@ public String getASTPackage(DiagramSymbol cdSymbol) { /** * adds the '_ast' package to a fullName to create an valid AST-package */ - public String createASTFullName(CDTypeSymbol typeSymbol) { - ICDBasisScope scope = typeSymbol.getEnclosingScope(); + public String createASTFullName(TypeSymbol typeSymbol) { + IBasicSymbolsScope scope = typeSymbol.getEnclosingScope(); List diagramSymbols = scope.getLocalDiagramSymbols(); + Objects.nonNull(diagramSymbols); while (diagramSymbols.isEmpty()) { scope = scope.getEnclosingScope(); diagramSymbols = scope.getLocalDiagramSymbols(); diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/JavaDoc.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/JavaDoc.java index a767386884..a7f8397370 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/JavaDoc.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/JavaDoc.java @@ -4,8 +4,6 @@ import de.monticore.generating.templateengine.HookPoint; import de.monticore.generating.templateengine.StringHookPoint; -import de.monticore.generating.templateengine.TemplateHookPoint; -import org.apache.tools.ant.taskdefs.Java; import java.util.*; diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/ast_class/reference/symbol/ASTReferencedSymbolDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/ast_class/reference/symbol/ASTReferencedSymbolDecorator.java index 8596f6200e..f924d0b049 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/ast_class/reference/symbol/ASTReferencedSymbolDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/ast_class/reference/symbol/ASTReferencedSymbolDecorator.java @@ -93,7 +93,7 @@ protected ASTCDAttribute getRefSymbolAttribute(ASTCDAttribute attribute, String //if the attribute is a list ASTMCType attributeType = getMCTypeFacade().createMapTypeOf(getMCTypeFacade().createStringType(), symbolLoaderType); ASTCDAttribute symbolAttribute = this.getCDAttributeFacade().createAttribute(modifier, attributeType, attributeName + SYMBOL); - replaceTemplate(VALUE, symbolAttribute, new StringHookPoint("= new HashMap<>()")); + replaceTemplate(VALUE, symbolAttribute, new StringHookPoint("= new LinkedHashMap<>()")); return symbolAttribute; } else { //if the attribute is mandatory or optional diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/builder/BuilderDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/builder/BuilderDecorator.java index b63fa8c083..7961ad159d 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/builder/BuilderDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/builder/BuilderDecorator.java @@ -13,12 +13,14 @@ import de.monticore.codegen.cd2java._ast.builder.inheritedmethods.InheritedBuilderMutatorMethodDecorator; import de.monticore.codegen.cd2java.exception.DecorateException; import de.monticore.codegen.cd2java.methods.AccessorDecorator; +import de.monticore.codegen.mc2cd.MC2CDStereotypes; import de.monticore.generating.templateengine.GlobalExtensionManagement; import de.monticore.generating.templateengine.StringHookPoint; import de.monticore.generating.templateengine.TemplateHookPoint; import de.monticore.types.mcbasictypes._ast.ASTMCPrimitiveType; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.umlmodifier._ast.ASTModifier; +import org.apache.commons.text.StringEscapeUtils; import java.util.List; import java.util.stream.Collectors; @@ -136,6 +138,12 @@ protected void addAttributeDefaultValues(ASTCDAttribute attribute) { } else if (getDecorationHelper().isOptional(CD4CodeMill.prettyPrint(attribute.getMCType(), false))) { this.replaceTemplate(VALUE, attribute, new StringHookPoint("= Optional.empty()")); + } else if (service.hasStereotype(attribute.getModifier(), MC2CDStereotypes.TERMINAL_DEFAULT_VALUE)) { + // This terminal has a default value -> use it for the builder + List terminalValues = service.getTerminalDefaultValues(attribute); + if (terminalValues.size() == 1) { + this.replaceTemplate(VALUE, attribute, new StringHookPoint("= \"" + StringEscapeUtils.escapeJava(terminalValues.get(0)) + "\"")); + } } } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_parser/ParserForSuperDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_parser/ParserForSuperDecorator.java index acf40fe956..7e593c4e2e 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_parser/ParserForSuperDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_parser/ParserForSuperDecorator.java @@ -21,6 +21,7 @@ import de.monticore.generating.templateengine.StringHookPoint; import de.monticore.generating.templateengine.TemplateHookPoint; import de.monticore.symbols.basicsymbols._symboltable.DiagramSymbol; +import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.mcbasictypes.MCBasicTypesMill; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedName; @@ -191,7 +192,7 @@ protected Map> calculateNonOverriddenCds */ protected void calculateOverriddenCds(DiagramSymbol cd, Collection nativeClasses, Map> overridden, Collection firstClasses) { - HashMap l = Maps.newLinkedHashMap(); + LinkedHashMap l = Maps.newLinkedHashMap(); //get all super cds / imports of the original cd Collection importedClasses = ((ICDBasisArtifactScope) cd.getEnclosingScope()).getImportsList().stream() .map(i -> i.getStatement()) @@ -222,8 +223,12 @@ protected void calculateOverriddenCds(DiagramSymbol cd, Collection nativ firstClasses.addAll(l.values()); } - protected boolean overrides(CDTypeSymbol first, CDTypeSymbol second){ - return getSuperTypesTransitive(first).stream().map(CDTypeSymbol::getFullName).collect(Collectors.toList()).contains(second.getFullName()); + protected boolean overrides(CDTypeSymbol first, CDTypeSymbol second) { + if (first.equals(second)) { + // Speed up check for default case + return false; + } + return getSuperTypesTransitive(first).contains(second.getFullName()); } protected List getOverriddenMethods(CDTypeSymbol type, DiagramSymbol grammar, Collection firstClasses){ @@ -300,26 +305,43 @@ protected List getParseMethodsForOtherProds(CDTypeSymbol type, Diag return methods; } - protected List getSuperTypesTransitive(CDTypeSymbol startType) { - List superTypes = new ArrayList(); - if (startType.isPresentSuperClass()) { - SymTypeExpression ste = startType.getSuperClass(); - CDTypeSymbolSurrogate s = new CDTypeSymbolSurrogate(ste.getTypeInfo().getFullName()); - s.setEnclosingScope(ste.getTypeInfo().getEnclosingScope()); - superTypes.add(s.lazyLoadDelegate()); - superTypes.addAll(getSuperTypesTransitive(s.lazyLoadDelegate())); - } + protected Set getSuperTypesTransitive(CDTypeSymbol startType) { + Set superTypeNames = new LinkedHashSet<>(); + getSuperTypesTransitive(startType, superTypeNames); + return superTypeNames; + } - for (SymTypeExpression ste : startType.getSuperTypesList()) { - CDTypeSymbolSurrogate tss = new CDTypeSymbolSurrogate(ste.getTypeInfo().getFullName()); - tss.setEnclosingScope(ste.getTypeInfo().getEnclosingScope()); - CDTypeSymbol i = tss.lazyLoadDelegate(); - superTypes.add(i); - superTypes.addAll(getSuperTypesTransitive(i)); - } - return superTypes; + protected void getSuperTypesTransitive(CDTypeSymbol cdTypeSymbol, Set superTypes) { + if (superTypes.contains(cdTypeSymbol.getFullName())) return; // typeSymbol already visited + // Add the name of the type symbol to the set + superTypes.add(cdTypeSymbol.getFullName()); + // and delve into its super types + List types = cdTypeSymbol.getEnclosingScope().resolveCDTypeMany(cdTypeSymbol.getFullName()); + getSuperTypesTransitive(types, superTypes); } + protected void getSuperTypesTransitive(TypeSymbol typeSymbol, Set superTypes) { + if (superTypes.contains(typeSymbol.getFullName())) return; // typeSymbol already visited + // Add the name of the type symbol to the set + superTypes.add(typeSymbol.getFullName()); + // and delve into its super types + List types = ((ICDBasisScope) typeSymbol.getEnclosingScope()).resolveCDTypeMany(typeSymbol.getFullName()); + getSuperTypesTransitive(types, superTypes); + } + protected void getSuperTypesTransitive(List resolvedTypes, Set superTypes) { + // if types is empty: CD Symbol not loaded (e.g., external type?) => unable to continue to load supertypes + if (!resolvedTypes.isEmpty()) { + CDTypeSymbol startTypeSymbol = resolvedTypes.get(0); // we expect to only find 1 symbol + if (startTypeSymbol.isPresentSuperClass()) { + // if a superclass is present: delve into it + getSuperTypesTransitive(startTypeSymbol.getSuperClass().getTypeInfo(), superTypes); + } + // Delve into all supertypes + for (SymTypeExpression ste : startTypeSymbol.getSuperTypesList()) { + getSuperTypesTransitive(ste.getTypeInfo(), superTypes); + } + } + } } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeClassDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeClassDecorator.java index e113654a1a..d0ceef9ee6 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeClassDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeClassDecorator.java @@ -90,6 +90,8 @@ public ASTCDClass decorate(ASTCDCompilationUnit input) { .build(); clazz.addAllCDMembers(createAcceptTraverserSuperMethods(clazz)); CD4C.getInstance().addImport(clazz, "de.monticore.symboltable.*"); + // necessary import for Preconditions.checkNotNull in constructors + CD4C.getInstance().addImport(clazz, "com.google.common.base.Preconditions"); return clazz; } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeClassDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeClassDecorator.java index 1e6e1c799e..5012de3992 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeClassDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeClassDecorator.java @@ -3,6 +3,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import de.monticore.cd.methodtemplates.CD4C; import de.monticore.cd4analysis.CD4AnalysisMill; import de.monticore.cd4code.CD4CodeMill; import de.monticore.cd4codebasis._ast.ASTCDConstructor; @@ -156,6 +157,9 @@ public ASTCDClass decorate(ASTCDCompilationUnit input) { cdClass.addCDMember(createAcceptTraverserMethod(cdClass)); cdClass.addAllCDMembers(createAcceptTraverserSuperMethods(cdClass)); + // necessary import for Preconditions.checkNotNull in constructors + CD4C.getInstance().addImport(cdClass, "com.google.common.base.Preconditions"); + return cdClass; } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecorator.java index 7c02ff57bb..e601e44e16 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecorator.java @@ -1,33 +1,38 @@ /* (c) https://github.com/MontiCore/monticore */ - package de.monticore.codegen.cd2java._symboltable.scopesgenitor; import com.google.common.collect.Lists; +import de.monticore.cd.methodtemplates.CD4C; import de.monticore.cd4code.CD4CodeMill; import de.monticore.cd4codebasis._ast.ASTCDConstructor; import de.monticore.cd4codebasis._ast.ASTCDMethod; import de.monticore.cd4codebasis._ast.ASTCDParameter; -import de.monticore.cdbasis._ast.ASTCDAttribute; -import de.monticore.cdbasis._ast.ASTCDClass; -import de.monticore.cdbasis._ast.ASTCDCompilationUnit; -import de.monticore.cdbasis._ast.ASTCDType; +import de.monticore.cdbasis._symboltable.CDTypeSymbol; +import de.monticore.cdbasis._ast.*; import de.monticore.codegen.cd2java.AbstractCreator; import de.monticore.codegen.cd2java.DecorationHelper; +import de.monticore.codegen.cd2java._symboltable.SymbolKindHierarchies; import de.monticore.codegen.cd2java._symboltable.SymbolTableService; import de.monticore.codegen.cd2java._visitor.VisitorService; import de.monticore.codegen.cd2java.methods.MethodDecorator; import de.monticore.generating.templateengine.GlobalExtensionManagement; import de.monticore.generating.templateengine.StringHookPoint; import de.monticore.generating.templateengine.TemplateHookPoint; +import de.monticore.grammar.grammar._symboltable.MCGrammarSymbol; +import de.monticore.symbols.basicsymbols._symboltable.DiagramSymbol; +import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; +import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; +import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedTypeTOP; +import de.monticore.types.mcbasictypes._ast.ASTMCImportStatement; +import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedName; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mcfullgenerictypes._ast.ASTMCWildcardTypeArgument; import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericType; import de.monticore.umlmodifier._ast.ASTModifier; import de.se_rwth.commons.Names; - +import java.lang.reflect.Type; import java.util.*; import java.util.stream.Collectors; - import static de.monticore.cd.codegen.CD2JavaTemplates.EMPTY_BODY; import static de.monticore.cd.codegen.CD2JavaTemplates.VALUE; import static de.monticore.cd.facade.CDModifier.*; @@ -104,6 +109,9 @@ public Optional decorate(ASTCDCompilationUnit input) { .addAllCDMembers(createScopeClassMethods(onlyScopeProds, scopeInterface)) .addCDMember(createAddToScopeStackMethod()) .build(); + + // monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecorator.java + CD4C.getInstance().addImport(scopesGenitor, "com.google.common.base.Preconditions"); return Optional.ofNullable(scopesGenitor); } return Optional.empty(); @@ -168,7 +176,7 @@ protected ASTCDMethod createSetScopeStackMethod(ASTMCType wildCardDequeType, AST ASTCDMethod createFromAST = getCDMethodFacade().createMethod(PUBLIC.build(), "setScopeStack", dequeParam); this.replaceTemplate(EMPTY_BODY, createFromAST, new StringHookPoint( - "this." + SCOPE_STACK_VAR + " = Log.errorIfNull((" + "this." + SCOPE_STACK_VAR + " = Preconditions.checkNotNull((" + CD4CodeMill.prettyPrint(dequeType, false) + ")" + SCOPE_STACK_VAR + ");")); return createFromAST; } @@ -208,7 +216,7 @@ protected List createSymbolClassMethods(ASTCDType symbolClass, Stri Optional attr = symbolClass.getCDAttributeList().stream().filter(a -> NAME_VAR.equals(a.getName())).findFirst(); boolean hasOptionalName = attr.isPresent() && DecorationHelper.getInstance().isOptional(attr.get().getMCType()); // visit method - methodList.add(createSymbolVisitMethod(astFullName, symbolFullName, simpleName, hasOptionalName, symbolClass.getModifier())); + methodList.add(createSymbolVisitMethod(astFullName, symbolFullName, simpleName, hasOptionalName, symbolClass)); // endVisit method methodList.add(createSymbolEndVisitMethod(astFullName, symbolClass, simpleName, symbolFullName, hasOptionalName)); @@ -218,11 +226,14 @@ protected List createSymbolClassMethods(ASTCDType symbolClass, Stri protected ASTCDMethod createSymbolVisitMethod(String astFullName, String symbolFullName, String simpleName, - boolean hasOptionalName, ASTModifier symbolModifier) { + boolean hasOptionalName, ASTCDType symbolClass ) { + ASTModifier symbolModifier = symbolClass.getModifier(); + ResolveUpperArtifactAttributes upperAttributes = resolveUpperArtifactAttributes(symbolClass); + boolean isSpanningSymbol = symbolTableService.hasScopeStereotype(symbolModifier) || symbolTableService.hasInheritedScopeStereotype(symbolModifier); - boolean isOrdered = symbolTableService.hasOrderedStereotype(symbolModifier); - boolean isShadowing = symbolTableService.hasShadowingStereotype(symbolModifier); - boolean isNonExporting = symbolTableService.hasNonExportingStereotype(symbolModifier); + boolean isOrdered = symbolTableService.hasOrderedStereotype(symbolModifier) || upperAttributes.ordered; + boolean isShadowing = symbolTableService.hasShadowingStereotype(symbolModifier) || upperAttributes.shadowing; + boolean isNonExporting = symbolTableService.hasNonExportingStereotype(symbolModifier) || upperAttributes.nonExporting; String scopeInterface = symbolTableService.getScopeInterfaceFullName(); String errorCode = symbolTableService.getGeneratedErrorCode(symbolFullName + VISIT); String millFullName = symbolTableService.getMillFullName(); @@ -234,6 +245,22 @@ protected ASTCDMethod createSymbolVisitMethod(String astFullName, String symbolF return visitMethod; } + protected ResolveUpperArtifactAttributes resolveUpperArtifactAttributes(ASTCDType symbolClass) { + boolean shadowing = false; + boolean nonExporting = false; + boolean ordered = false; + List superCDsTransitive = symbolTableService.getAllSuperClassesTransitive(symbolClass); + for (TypeSymbol typeSymbol : superCDsTransitive) { + if (typeSymbol != null && typeSymbol.isPresentAstNode()) { + ASTCDType astcdType = (ASTCDType) typeSymbol.getAstNode(); + shadowing = shadowing || symbolTableService.hasShadowingStereotype(astcdType.getModifier()); + nonExporting = nonExporting || symbolTableService.hasNonExportingStereotype(astcdType.getModifier()); + ordered = ordered || symbolTableService.hasOrderedStereotype(astcdType.getModifier()); + } + } + return new ResolveUpperArtifactAttributes(shadowing, nonExporting, ordered); + } + protected ASTCDMethod createSymbolEndVisitMethod(String astFullName, ASTCDType symbolClass, String simpleName, String symbolFullName, boolean hasOptionalName) { ASTCDMethod endVisitMethod = visitorService.getVisitorMethod(END_VISIT, getMCTypeFacade().createQualifiedType(astFullName)); boolean removeScope = (symbolTableService.hasScopeStereotype(symbolClass.getModifier()) @@ -329,4 +356,16 @@ protected List createInitSymbolMethods(List symbolClasse } return methods; } + + protected static class ResolveUpperArtifactAttributes { + boolean shadowing = false; + boolean nonExporting = false; + boolean ordered = false; + + public ResolveUpperArtifactAttributes(boolean shadowing, boolean nonExporting, boolean ordered) { + this.shadowing = shadowing; + this.nonExporting = nonExporting; + this.ordered = ordered; + } + } } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecorator.java index 29f2959d4e..3db0ee80ff 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecorator.java @@ -31,6 +31,7 @@ import static de.monticore.cd.codegen.CD2JavaTemplates.EMPTY_BODY; import static de.monticore.cd.codegen.CD2JavaTemplates.VALUE; +import static de.monticore.cd.codegen.CD2JavaTemplates.ANNOTATIONS; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java._ast.ast_class.ASTConstants.ACCEPT_METHOD; @@ -123,6 +124,8 @@ public ASTCDClass decorate(ASTCDClass symbolInput) { .flatMap(List::stream) .collect(Collectors.toList()); } + symbolMethods.add(createEqualsMethod(symbolName)); + symbolMethods.add(createGetThis(symbolName)); ASTCDParameter constructorParam = getCDParameterFacade().createParameter(getMCTypeFacade().createStringType(), NAME_VAR); ASTCDConstructor constructor = getCDConstructorFacade().createConstructor(PUBLIC.build(), symbolName, constructorParam); @@ -181,6 +184,20 @@ public ASTCDClass decorate(ASTCDClass symbolInput) { return symbolClass; } + protected ASTCDMethod createEqualsMethod(String symbolClass) { + ASTCDParameter parameter = getCDParameterFacade().createParameter(getMCTypeFacade().createQualifiedType("Object"), "obj"); + ASTCDMethod method = getCDMethodFacade().createMethod(PUBLIC.build(), getMCTypeFacade().createBooleanType(), "equals", parameter); + this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "Equals", symbolClass)); + this.replaceTemplate(ANNOTATIONS, method, new StringHookPoint("@Override")); + return method; + } + + protected ASTCDMethod createGetThis(String symbolClass) { + ASTCDMethod method = getCDMethodFacade().createMethod(PROTECTED.build(), symbolClass, "getThis"); + this.replaceTemplate(EMPTY_BODY, method, new StringHookPoint("return (" + symbolClass + ") this;")); + return method; + } + protected List createOverridingSymbolMethods(String astClassName, String scopeInterface) { List methods = Lists.newArrayList(); // getEnclosingScope diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecorator.java index 873a8891ba..f9a31a2f10 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecorator.java @@ -32,6 +32,7 @@ import java.util.List; import java.util.stream.Collectors; +import static de.monticore.cd.codegen.CD2JavaTemplates.ANNOTATIONS; import static de.monticore.cd.codegen.CD2JavaTemplates.EMPTY_BODY; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PUBLIC; @@ -110,6 +111,11 @@ public ASTCDClass decorate(ASTCDClass symbolInput) { List enclosingScopeMethods = Lists.newArrayList(createSetEnclosingScopeMethod(enclosingScopeAttribute, symbolTableService.getScopeInterfaceSimpleName())); enclosingScopeMethods.add(createGetEnclosingScopeMethod(enclosingScopeAttribute)); + List spanningScopeMethods = Lists.newArrayList(); + if (symbolTableService.hasScopeStereotype(symbolInput.getModifier()) || symbolTableService.hasInheritedScopeStereotype(symbolInput.getModifier())) { + spanningScopeMethods.addAll(createSpannedScopeMethods(symbolTableService.getScopeInterfaceFullName())); + } + List delegateStereoinfoMethods = createOverriddenStereotypeMethods(); ASTCDClassBuilder builder = CD4AnalysisMill.cDClassBuilder() @@ -120,11 +126,14 @@ public ASTCDClass decorate(ASTCDClass symbolInput) { .addAllCDMembers(nameMethods) .addAllCDMembers(delegateSymbolRuleAttributeMethods) .addAllCDMembers(delegateAccecptMethods) + .addCDMember(createEqualsMethod(this.symbolTableService.getSymbolSimpleName(symbolInput))) + .addCDMember(createGetThis(this.symbolTableService.getSymbolSimpleName(symbolInput))) .addCDMember(createGetFullNameMethod()) .addCDMember(createOverridenDeterminePackageName()) .addCDMember(createOverridenDetermineFullName()) .addAllCDMembers(delegateSymbolRuleMethods) - .addAllCDMembers(delegateStereoinfoMethods); + .addAllCDMembers(delegateStereoinfoMethods) + .addAllCDMembers(spanningScopeMethods); return builder .addCDMember(delegateAttribute) .addAllCDMembers(enclosingScopeMethods) @@ -139,6 +148,21 @@ protected ASTCDMethod createSetEnclosingScopeMethod(ASTCDAttribute enclosingScop this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "SetEnclosingScope4SymbolSurrogate", enclosingScopeAttribute, scopeName)); return method; } + + protected ASTCDMethod createEqualsMethod(String symbolClass) { + ASTCDParameter parameter = getCDParameterFacade().createParameter(getMCTypeFacade().createQualifiedType("Object"), "obj"); + ASTCDMethod method = getCDMethodFacade().createMethod(PUBLIC.build(), getMCTypeFacade().createBooleanType(), "equals", parameter); + this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "Equals", symbolClass)); + this.replaceTemplate(ANNOTATIONS, method, new StringHookPoint("@Override")); + return method; + } + + protected ASTCDMethod createGetThis(String symbolClass) { + ASTCDMethod method = getCDMethodFacade().createMethod(PROTECTED.build(), symbolClass, "getThis"); + this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "GetThis", symbolClass)); + this.replaceTemplate(ANNOTATIONS, method, new StringHookPoint("@Override")); + return method; + } protected ASTCDConstructor createConstructor(String symbolSurrogateClass) { ASTCDParameter nameParameter = getCDParameterFacade().createParameter(String.class, NAME_VAR); @@ -146,7 +170,7 @@ protected ASTCDConstructor createConstructor(String symbolSurrogateClass) { this.replaceTemplate(EMPTY_BODY, constructor, new TemplateHookPoint(TEMPLATE_PATH + "ConstructorSymbolSurrogate")); return constructor; } - + protected ASTCDAttribute createNameAttribute() { return getCDAttributeFacade().createAttribute(PROTECTED.build(), "String", "name"); } @@ -193,7 +217,7 @@ protected ASTCDMethod createCheckLazyLoadDelegateMethod(String symbolSurrogateNa symbolName, simpleName, scopeName, generatedError)); return method; } - + protected ASTCDMethod createGetFullNameMethod() { ASTCDMethod method = getCDMethodFacade().createMethod(PUBLIC.build(), getMCTypeFacade().createStringType(), "getFullName"); this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "GetFullName")); @@ -303,4 +327,21 @@ protected List createAcceptTraverserMethods(ASTCDClass symbolInput) } return result; } + + protected List createSpannedScopeMethods(String scopeInterface) { + List methods = Lists.newArrayList(); + // getSpannedScope + ASTCDMethod method = getCDMethodFacade().createMethod(PUBLIC.build(), getMCTypeFacade().createQualifiedType(scopeInterface), "getSpannedScope"); + this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "GetSpannedScopeSymbolSurrogate", + scopeInterface)); + methods.add(method); + + // setSpannedScope + ASTCDParameter parameter = getCDParameterFacade().createParameter(getMCTypeFacade().createQualifiedType(scopeInterface), "scope"); + method = getCDMethodFacade().createMethod(PUBLIC.build(), "setSpannedScope", parameter); + this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "SetSpannedScopeSymbolSurrogate", scopeInterface)); + methods.add(method); + + return methods; + } } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_tagging/TaggerDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_tagging/TaggerDecorator.java index 8f4ad0fd3b..fef9438823 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_tagging/TaggerDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_tagging/TaggerDecorator.java @@ -26,7 +26,7 @@ import de.se_rwth.commons.StringTransformations; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -304,7 +304,7 @@ protected String getPackageName(MCGrammarSymbol symbol) { protected boolean isIndirectSymbol(ProdSymbol symbol){ if (symbol.isIsSymbolDefinition()) return true; LinkedList toCheck = new LinkedList<>(); - Set checked = new HashSet<>(); + Set checked = new LinkedHashSet<>(); toCheck.add(symbol); while (!toCheck.isEmpty()) { ProdSymbol symbolToCheck = toCheck.removeFirst(); diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_visitor/TraverserClassDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_visitor/TraverserClassDecorator.java index 3ffe069c45..14da3769b1 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_visitor/TraverserClassDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_visitor/TraverserClassDecorator.java @@ -125,7 +125,7 @@ protected List addDefaultMethods() { } /** - * Adds a hashset as well as implementations for getting and setting it + * Adds a LinkedHashSet as well as implementations for getting and setting it * * @return The attribute and two methods */ diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/cli/CLIDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/cli/CLIDecorator.java index 5625702bf5..85e3d0f558 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/cli/CLIDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/cli/CLIDecorator.java @@ -10,6 +10,7 @@ import de.monticore.cdbasis._ast.ASTCDDefinition; import de.monticore.cli.updateChecker.UpdateCheckerRunnable; import de.monticore.codegen.cd2java.AbstractCreator; +import de.monticore.codegen.cd2java.JavaDoc; import de.monticore.codegen.cd2java._parser.ParserService; import de.monticore.codegen.cd2java._symboltable.SymbolTableService; import de.monticore.generating.templateengine.GlobalExtensionManagement; @@ -21,6 +22,7 @@ import java.time.LocalDate; import java.util.Optional; +import static de.monticore.cd.codegen.CD2JavaTemplates.JAVADOC; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.cd.facade.CDModifier.PUBLIC_STATIC; import static de.monticore.cd.codegen.CD2JavaTemplates.EMPTY_BODY; @@ -89,6 +91,12 @@ protected ASTCDMethod createMainMethod(DiagramSymbol cdSymbol) { ASTMCType stringArrayType = getMCTypeFacade().createArrayType("String", 1); ASTCDParameter parameter = getCDParameterFacade().createParameter(stringArrayType, "args"); ASTCDMethod method = getCDMethodFacade().createMethod(PUBLIC_STATIC.build(), "main", parameter); + this.replaceTemplate(JAVADOC, method, + JavaDoc.of("Entry point for the tool from CLI ONLY.", + "This WILL exit the Java VM.", + "From Java code itself, call {@link #run(String[])} instead.") + .param("args", "the arguments given to the tool") + .asHP()); this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "Main", grammarname)); return method; } @@ -105,6 +113,12 @@ protected ASTCDMethod createRunMethod(boolean startProdPresent, DiagramSymbol cd ASTMCType stringArrayType = getMCTypeFacade().createArrayType("String", 1); ASTCDParameter parameter = getCDParameterFacade().createParameter(stringArrayType, "args"); ASTCDMethod method = getCDMethodFacade().createMethod(PUBLIC.build(), "run", parameter); + this.replaceTemplate(JAVADOC, method, + JavaDoc.of("Entry point for the tool from Java code.", + "Except from not exiting the Java VM and catching exceptions,", + "this is identical to calling {@link #main(String[])} directly.") + .param("args", "the arguments given to the tool") + .asHP()); this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint(TEMPLATE_PATH + "Run", startProdPresent, cliName, generatedError)); return method; } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/typecd2java/TypeCD2JavaDecorator.java b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/typecd2java/TypeCD2JavaDecorator.java index 464e8da506..aaf4164d42 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/cd2java/typecd2java/TypeCD2JavaDecorator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/cd2java/typecd2java/TypeCD2JavaDecorator.java @@ -17,7 +17,7 @@ public TypeCD2JavaDecorator(ICD4AnalysisScope scope) { @Override public ASTCDCompilationUnit decorate(final ASTCDCompilationUnit compilationUnit) { - CD4CodeTraverser traverser = CD4CodeMill.traverser(); + CD4CodeTraverser traverser = CD4CodeMill.inheritanceTraverser(); traverser.add4MCBasicTypes(new TypeCD2JavaVisitor(scope)); compilationUnit.accept(traverser); return compilationUnit; diff --git a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CD4CodeSymbolTableCompleter.java b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CD4CodeSymbolTableCompleter.java index aba6292013..7042670493 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CD4CodeSymbolTableCompleter.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CD4CodeSymbolTableCompleter.java @@ -14,7 +14,7 @@ public class MC2CD4CodeSymbolTableCompleter { public MC2CD4CodeSymbolTableCompleter() { - this.traverser = CD4CodeMill.traverser(); + this.traverser = CD4CodeMill.inheritanceTraverser(); //New! FullSynthesizeFromMCSGT4Grammar synthesize = new FullSynthesizeFromMCSGT4Grammar(); diff --git a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CDStereotypes.java b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CDStereotypes.java index d0bd7527f2..4771941f15 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CDStereotypes.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/MC2CDStereotypes.java @@ -83,7 +83,12 @@ public enum MC2CDStereotypes { /** * To mark an interface generated from an external prod */ - EXTERNAL_INTERFACE("externalInterface"); + EXTERNAL_INTERFACE("externalInterface"), + + /** + * To store the value of a terminal, i.e. operator:"&&" + */ + TERMINAL_DEFAULT_VALUE("defaultTerminalValue"); protected final String stereotype; diff --git a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/TransformationHelper.java b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/TransformationHelper.java index 417a56a3b7..d1d930fdb8 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/TransformationHelper.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/TransformationHelper.java @@ -447,7 +447,7 @@ public static String getSimpleTypeFromCollection(ASTCDAttribute attribute) { } public static String getJavaAndCdConformName(String name) { - Log.errorIfNull(name); + Preconditions.checkNotNull(name); return getCdLanguageConformName(getJavaConformName(name)); } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/manipul/JavaAndCdConformNameManipulation.java b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/manipul/JavaAndCdConformNameManipulation.java index ef6ff639a0..93b64ccf9e 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/manipul/JavaAndCdConformNameManipulation.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/manipul/JavaAndCdConformNameManipulation.java @@ -23,7 +23,7 @@ public class JavaAndCdConformNameManipulation implements UnaryOperator removeRedundantAttributes(List cdAttributes) { - Iterator iterator = cdAttributes.iterator(); - while (iterator.hasNext()) { - ASTCDAttribute inspectedAttribute = iterator.next(); - List remainingAttributes = cdAttributes - .stream() - .filter(attribute -> !attribute.equals(inspectedAttribute)) - .collect(Collectors.toList()); - boolean isRedundant = remainingAttributes - .stream() - .anyMatch(a -> isRedundant(inspectedAttribute, a)); - if (isRedundant) { - iterator.remove(); + List uniqueAttributes = new ArrayList<>(); + // In case multiple attributes (with the same name & type) are present: + // The first attribute, which is created from the classprod/interface + // itself, should be kept. + // The 2nd attribute is, e.g., created by the InheritedAttributesTranslation, + // and should be removed as redundant, + // but only IFF the second attribute does not have more stereotypes + // (in particular, the inherited one) + // [a1=Attr[name], a2=Attr[name <]] => a2 + // [a1=Attr[name], a2=Attr[name]] => a1 + // in addition, the attribute with the highest category is kept + outer: + for (ASTCDAttribute cdAttributeCand : cdAttributes) { + for (int i = 0; i < uniqueAttributes.size(); i++) { + ASTCDAttribute existingAttribute = uniqueAttributes.get(i); + if (isColliding(cdAttributeCand, existingAttribute)) { + if (isAttrPreferred(cdAttributeCand, existingAttribute)) { + uniqueAttributes.set(i, cdAttributeCand); + } + continue outer; + } } + uniqueAttributes.add(cdAttributeCand); } - return cdAttributes; + return uniqueAttributes; } /** - * Checks if the remaining attributes contain an attribute that makes the inspected attribute - * redundant. + * Checks if the two attributes collide, i.e. share the same name & (original) type * - * @return true if another attribute with the same variable name, the same original type and an - * equal or higher category exists + * @return true if another attribute with the same variable name, the same original type exists */ - protected static boolean isRedundant(ASTCDAttribute inspectedAttribute, - ASTCDAttribute remainingAttribute) { + protected static boolean isColliding(ASTCDAttribute inspectedAttribute, + ASTCDAttribute remainingAttribute) { String inspectedName = inspectedAttribute.getName(); String inspectedType = getOriginalTypeName(inspectedAttribute); - AttributeCategory inspectedCategory = determineCategory(inspectedAttribute); boolean sameName = inspectedName.equalsIgnoreCase(remainingAttribute.getName()); boolean sameType = inspectedType.equals(getOriginalTypeName(remainingAttribute)); - boolean sameOrHigherCategory = inspectedCategory - .compareTo(AttributeCategory.determineCategory(remainingAttribute)) < 1; + return sameName && sameType; + } - return sameName && sameType && sameOrHigherCategory; + /** + * Checks if the candidate should replace the existing attribute: + * - if it has a higher category, in case the same category is used: + * - if the candidate has more stereotypes (in particular inherited) + * @return true if the candAttr should be preferred over the existing one + */ + protected static boolean isAttrPreferred(ASTCDAttribute candAttr, + ASTCDAttribute existingAttr) { + // The reason behind this heuristic is documented in removeRedundantAttributes + + // First: check category + AttributeCategory candCategory = determineCategory(candAttr); + int categoryRelation = candCategory + .compareTo(AttributeCategory.determineCategory(existingAttr)); + if (categoryRelation < 0) { + return false; + } else if (categoryRelation > 0) { + return true; + } + // The same category: check stereo counts to keep inherited + int candStereoCount = candAttr.getModifier().isPresentStereotype() + ? candAttr.getModifier().getStereotype().getValuesList().size() : 0; + int existingStereoCount = existingAttr.getModifier().isPresentStereotype() + ? existingAttr.getModifier().getStereotype().getValuesList().size() : 0; + return candStereoCount > existingStereoCount; + // The fallback heuristic is to keep the first attribute } protected static String getOriginalTypeName(ASTCDAttribute cdAttribute) { diff --git a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/transl/NameTranslation.java b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/transl/NameTranslation.java index 522ec53f1f..c2eeecf15c 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/transl/NameTranslation.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/mc2cd/transl/NameTranslation.java @@ -8,6 +8,8 @@ import de.monticore.cdbasis._ast.ASTCDDefinition; import de.monticore.cdinterfaceandenum._ast.ASTCDEnum; import de.monticore.cdinterfaceandenum._ast.ASTCDInterface; +import de.monticore.codegen.mc2cd.MC2CDStereotypes; +import de.monticore.codegen.mc2cd.TransformationHelper; import de.monticore.grammar.LexNamer; import de.monticore.grammar.grammar._ast.*; import de.monticore.grammar.grammar._symboltable.RuleComponentSymbol; @@ -77,6 +79,7 @@ public Link apply( Optional usageName = getUsageName(rootLink.source(), link.source()); String nameToUse = usageName.isPresent() ? usageName.get() : link.source().getName(); link.target().setName(nameToUse); + TransformationHelper.addStereotypeValue(link.target().getModifier(), MC2CDStereotypes.TERMINAL_DEFAULT_VALUE.toString(), link.source().getName()); } for (Link link : rootLink.getLinks(ASTConstantGroup.class, diff --git a/monticore-generator/src/main/java/de/monticore/codegen/parser/MCGrammarInfo.java b/monticore-generator/src/main/java/de/monticore/codegen/parser/MCGrammarInfo.java index 4973580d41..3e946d4b1b 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/parser/MCGrammarInfo.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/parser/MCGrammarInfo.java @@ -104,7 +104,7 @@ protected void addSubRules() { .newLinkedHashSet(Arrays.asList(grammarSymbol)); grammarsToHandle.addAll(MCGrammarSymbolTableHelper.getAllSuperGrammars(grammarSymbol)); for (MCGrammarSymbol grammar : grammarsToHandle) { - HashMap> ruleMap = Maps.newLinkedHashMap(); + LinkedHashMap> ruleMap = Maps.newLinkedHashMap(); // Collect superclasses and superinterfaces for classes for (ASTClassProd classProd : (grammar.getAstNode()) .getClassProdList()) { diff --git a/monticore-generator/src/main/java/de/monticore/codegen/parser/ParserGenerator.java b/monticore-generator/src/main/java/de/monticore/codegen/parser/ParserGenerator.java index 37acf4c1d9..0b5391ecfd 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/parser/ParserGenerator.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/parser/ParserGenerator.java @@ -3,6 +3,7 @@ package de.monticore.codegen.parser; import com.google.common.base.Joiner; +import com.google.common.base.Preconditions; import de.monticore.cd.codegen.CDGenerator; import de.monticore.cd.codegen.CdUtilsPrinter; import de.monticore.cd.codegen.TopDecorator; @@ -38,7 +39,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; @@ -122,7 +123,7 @@ public static ASTCDClass generateParser( astGrammar.getName()); MCGrammarSymbol grammarSymbol = symbolTable. resolveMCGrammar( qualifiedGrammarName).orElse(null); - Log.errorIfNull(grammarSymbol, "0xA4034 Grammar " + qualifiedGrammarName + Preconditions.checkNotNull(grammarSymbol, "0xA4034 Grammar " + qualifiedGrammarName + " can't be resolved in the scope " + symbolTable); MCGrammarInfo grammarInfo = new MCGrammarInfo(grammarSymbol); @@ -133,7 +134,7 @@ public static ASTCDClass generateParser( setup.setGlex(glex); if (astGrammar.isComponent()) { - ParserInfoGenerator.generateParserInfoForComponent(astGrammar, setup, genHelper.getParserPackage(), lang, new HashMap<>()); + ParserInfoGenerator.generateParserInfoForComponent(astGrammar, setup, genHelper.getParserPackage(), lang, new LinkedHashMap<>()); Log.info("No parser generation for the grammar " + astGrammar.getName(), LOG); return null; } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/parser/ParserGeneratorHelper.java b/monticore-generator/src/main/java/de/monticore/codegen/parser/ParserGeneratorHelper.java index 78548f04cb..0226931685 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/parser/ParserGeneratorHelper.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/parser/ParserGeneratorHelper.java @@ -3,6 +3,7 @@ package de.monticore.codegen.parser; import com.google.common.base.Joiner; +import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; @@ -69,7 +70,7 @@ public class ParserGeneratorHelper { * Constructor for de.monticore.codegen.parser.ParserGeneratorHelper */ public ParserGeneratorHelper(ASTMCGrammar ast, MCGrammarInfo grammarInfo) { - Log.errorIfNull(ast); + Preconditions.checkNotNull(ast); this.astGrammar = ast; this.qualifiedGrammarName = astGrammar.getPackageList().isEmpty() ? astGrammar.getName() @@ -83,7 +84,7 @@ public ParserGeneratorHelper(ASTMCGrammar ast, MCGrammarInfo grammarInfo) { } public ParserGeneratorHelper(ASTMCGrammar ast, MCGrammarInfo grammarInfo, boolean embeddedJavaCode, Languages lang) { - Log.errorIfNull(ast); + Preconditions.checkNotNull(ast); this.astGrammar = ast; this.qualifiedGrammarName = astGrammar.getPackageList().isEmpty() ? astGrammar.getName() @@ -151,7 +152,7 @@ public String getParserPackage() { * @return the name for a lexsymbol that should be used in an Antlr-File */ public String getOrComputeLexSymbolName(String constName) { - Log.errorIfNull(constName); + Preconditions.checkNotNull(constName); if (grammarInfo.getSplitRules().containsKey(constName)) { return grammarInfo.getSplitRules().get(constName); } else { @@ -159,15 +160,22 @@ public String getOrComputeLexSymbolName(String constName) { } } + /** + * @param str - A String whose contents were taken directly from a StringLiteral. + * @return The original string, but each occurrence of ' is replaced with \'. + */ + @SuppressWarnings("unused") // Used in parser/Lexer.ftl public String escapeSingleQuote(String str) { - String retStr = ""; - String del = ""; - for (String s: str.split("'")) { - retStr += del; - retStr += s; - del = "\\'"; - } - return retStr; + return str.replace("'", "\\'"); + } + + /** + * @param str - A String whose contents were taken directly from a StringLiteral. + * @return The original string, but each occurrence of \" is replaced by ". + */ + @SuppressWarnings("unused") // Used in parser/Lexer.ftl + public String unescapeDoubleQuote(String str) { + return str.replace("\\\"", "\""); } /** @@ -175,7 +183,7 @@ public String escapeSingleQuote(String str) { * @return the name for a lexsymbol that was used in an Antlr-File */ public Optional getCachedLexSymbolName(String constName) { - Log.errorIfNull(constName); + Preconditions.checkNotNull(constName); if (grammarInfo.getSplitRules().containsKey(constName)) { return Optional.of(grammarInfo.getSplitRules().get(constName)); } else { @@ -572,7 +580,7 @@ public static String getASTClassName(ProdSymbol rule) { * @return */ public static String getText(ASTNode node) { - Log.errorIfNull(node); + Preconditions.checkNotNull(node); if (node instanceof ASTAction) { StringBuilder buffer = new StringBuilder(); diff --git a/monticore-generator/src/main/java/de/monticore/codegen/parser/antlr/Grammar2ParseVisitor.java b/monticore-generator/src/main/java/de/monticore/codegen/parser/antlr/Grammar2ParseVisitor.java index 8023151a6a..9eb8d62d37 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/parser/antlr/Grammar2ParseVisitor.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/parser/antlr/Grammar2ParseVisitor.java @@ -403,7 +403,7 @@ public String getBuilderNodeName() { } } - protected Set convertMethods = new HashSet<>(); + protected Set convertMethods = new LinkedHashSet<>(); @Override public void handle(ASTLexProd node) { @@ -656,7 +656,7 @@ protected void handleTerminal(ASTITerminal node, Supplier s throw new IllegalStateException("Missing tmpname " + node.getEnclosingScope().getName()); } else if (replacedKeywords.containsKey(node.getName())) { int nokeywordindex = 0; - Map entries = new HashMap<>(); + Map entries = new LinkedHashMap<>(); for (String ignored : replacedKeywords.get(node.getName())) { // Make a new alternative out of each possible keyword diff --git a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/MC2PPTranslation.java b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/MC2PPTranslation.java index 5f98a230bf..bdbc5223ba 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/MC2PPTranslation.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/MC2PPTranslation.java @@ -78,16 +78,16 @@ public ASTCDCompilationUnit decorate(ASTMCGrammar grammar) { GrammarTraverser traverser = Grammar_WithConceptsMill.traverser(); // Collect information about the NonTerminals first - NonTermAccessorVisitor nonTermAccessorVisitor = new NonTermAccessorVisitor(); - traverser.add4Grammar(nonTermAccessorVisitor); - traverser.setGrammarHandler(new PrettyPrinterReducedTraverseHandler()); + NonTermAccessorVisitorHandler nonTermAccessorCollector = new NonTermAccessorVisitorHandler(); + traverser.add4Grammar(nonTermAccessorCollector); + traverser.setGrammarHandler(nonTermAccessorCollector); grammar.accept(traverser); // Traverse the Grammar ast and decorate the PP-handle methods PrettyPrinterGenerationVisitor transformer = new PrettyPrinterGenerationVisitor(glex, prettyPrinterCDClass, - nonTermAccessorVisitor.getClassProds()); + nonTermAccessorCollector.getClassProds()); traverser = Grammar_WithConceptsMill.traverser(); traverser.setGrammarHandler(new PrettyPrinterReducedTraverseHandler()); traverser.add4Grammar(transformer); @@ -209,7 +209,7 @@ protected ASTCDAttribute addAttribute(ASTCDClass astcdClass, boolean getter, boo protected Map>>> findReplacedKeywords(MCGrammarSymbol grammarSymbol) { PrettyPrinterReplaceKeywordFinder finder = new PrettyPrinterReplaceKeywordFinder(grammarSymbol.getReplacedKeywordsWithInherited()); - Map>>> ret = new HashMap<>(); + Map>>> ret = new LinkedHashMap<>(); Map>> finds = finder.check(grammarSymbol.getAstNode()); if (!finds.isEmpty()) diff --git a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/NonTermAccessorVisitor.java b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/NonTermAccessorVisitorHandler.java similarity index 67% rename from monticore-generator/src/main/java/de/monticore/codegen/prettyprint/NonTermAccessorVisitor.java rename to monticore-generator/src/main/java/de/monticore/codegen/prettyprint/NonTermAccessorVisitorHandler.java index a9972092b0..07d0299b1c 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/NonTermAccessorVisitor.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/NonTermAccessorVisitorHandler.java @@ -14,9 +14,10 @@ import java.util.*; -public class NonTermAccessorVisitor implements GrammarVisitor2 { +public class NonTermAccessorVisitorHandler extends PrettyPrinterReducedTraverseHandler + implements GrammarVisitor2 { - protected final Map classProds = new HashMap<>(); + protected final Map classProds = new LinkedHashMap<>(); protected ClassProdNonTermPrettyPrintData currentData; protected Collection astAttributes; @@ -25,6 +26,72 @@ public Map getClassProds() { return this.classProds; } + @Override + public void traverse(ASTBlock node) { + int effIt = getEffectiveIteration(currentData.effectiveIterationStack.peek(), node.getIteration()); + boolean doResetExhausted = effIt == ASTConstantsGrammar.DEFAULT || effIt == ASTConstantsGrammar.QUESTION; + traverseAltList(node.getAltList(), doResetExhausted); + } + + @Override + public void traverse(ASTClassProd node) { + traverseAltList(node.getAltList(), true); + } + + /** + * Support blocks which contain a NonTermRef once in each of its alts, + * such as "P | P". + * This is only supported in non-repeated ("trivial") blocks + * @param altList the list of alts of the block or class prod + * @param doResetExhausted whether the exhausted references should per-alt + */ + protected void traverseAltList(List altList, boolean doResetExhausted) { + Set exhaustedBefore = new LinkedHashSet<>(currentData.exhaustedNonTerminals); + Set exhaustedAll = new LinkedHashSet<>(); + + Map nonTerminalIterationBefore = new LinkedHashMap<>(currentData.nonTerminalIteration); + Map nonTerminalIterationAll = new LinkedHashMap<>(); + + for (ASTAlt alt : altList) { + // Before each alt: reset the exhaustedNonTerminals and nonTerminalIterations to the before-state + if (doResetExhausted) { + currentData.exhaustedNonTerminals.clear(); + currentData.exhaustedNonTerminals.addAll(exhaustedBefore); + + currentData.nonTerminalIteration.clear(); + currentData.nonTerminalIteration.putAll(nonTerminalIterationBefore); + } + // actually traverse + alt.accept(getTraverser()); + + if (doResetExhausted) { + // keep track of the alt's exhaustedNonTerminals + exhaustedAll.addAll(currentData.exhaustedNonTerminals); + // and their iteration + for (Map.Entry e : currentData.nonTerminalIteration.entrySet()) { + nonTerminalIterationAll.compute(e.getKey(), (k, prevV) -> { + if (prevV == null || e.getValue().equals(prevV)) { + return e.getValue(); + } else { + boolean isERepeated = e.getValue() == ASTConstantsGrammar.STAR || e.getValue() == ASTConstantsGrammar.PLUS; + boolean isOrigRepeated = prevV == ASTConstantsGrammar.STAR || prevV == ASTConstantsGrammar.PLUS; + // in case the iteration level changes between the alts -> non-trivial distinguishing + if (isERepeated != isOrigRepeated) { + currentData.erroringNonTerminals.add(e.getKey()); // indistinguishable alts (with our trivial approach) + } + } + return Math.max(prevV, e.getValue()); + }); + } + } + } + + // After the block/prod: Add the exhausted non-terminals from all blocks + currentData.exhaustedNonTerminals.addAll(exhaustedAll); + for (var e : nonTerminalIterationAll.entrySet()) + currentData.nonTerminalIteration.compute(e.getKey(), (k, v) -> Math.max(e.getValue(), v == null ? 0 : v)); + } + @Override public void visit(ASTClassProd node) { this.currentData = this.classProds.computeIfAbsent(node.getName(), x -> new ClassProdNonTermPrettyPrintData(node.getSpannedScope())); @@ -126,15 +193,15 @@ public void endVisit(ASTBlock node) { */ public static class ClassProdNonTermPrettyPrintData { // Count NonTerminal (references) - protected final Map nonTerminals = new HashMap<>(); - protected final Map nonTerminalIteration = new HashMap<>(); + protected final Map nonTerminals = new LinkedHashMap<>(); + protected final Map nonTerminalIteration = new LinkedHashMap<>(); // As soon as a NT* was used, we won't be able to automatically generate in case of further NT references - protected final Set exhaustedNonTerminals = new HashSet<>(); + protected final Set exhaustedNonTerminals = new LinkedHashSet<>(); // Referenced NTs after being exhausted - e.g. NT* NT - protected final Set erroringNonTerminals = new HashSet<>(); - protected final Map nonTerminalNodes = new HashMap<>(); - protected final Map nonTerminalMultiplicities = new HashMap<>(); - protected final Set effectiveIterationIteratorNonTerminals = new HashSet<>(); + protected final Set erroringNonTerminals = new LinkedHashSet<>(); + protected final Map nonTerminalNodes = new LinkedHashMap<>(); + protected final Map nonTerminalMultiplicities = new LinkedHashMap<>(); + protected final Set effectiveIterationIteratorNonTerminals = new LinkedHashSet<>(); protected final Stack effectiveIterationStack = new Stack<>(); // Note: As of now the scope is somewhat useless, due to GrammarTransformer#removeNonTerminalSeparators, etc. changing the AST but not the symbol table diff --git a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/PrettyPrinterGenerationVisitor.java b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/PrettyPrinterGenerationVisitor.java index 39b4964b3f..b58b852441 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/PrettyPrinterGenerationVisitor.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/PrettyPrinterGenerationVisitor.java @@ -43,7 +43,7 @@ public class PrettyPrinterGenerationVisitor implements GrammarVisitor2 { protected static final String ITERATOR_PREFIX = "iter_"; // data from the first phase - protected final Map classProds; + protected final Map classProds; protected final ASTCDClass ppClass; @@ -60,7 +60,7 @@ public class PrettyPrinterGenerationVisitor implements GrammarVisitor2 { // Changing attributes protected ASTClassProd currentClassProd; - protected NonTermAccessorVisitor.ClassProdNonTermPrettyPrintData currentClassProdData; + protected NonTermAccessorVisitorHandler.ClassProdNonTermPrettyPrintData currentClassProdData; protected String grammarName; protected Map> replacedKeywords; @@ -70,7 +70,7 @@ public class PrettyPrinterGenerationVisitor implements GrammarVisitor2 { protected NoSpacePredicateVisitor noSpacePredicateVisitor = new NoSpacePredicateVisitor(); protected Grammar_WithConceptsTraverser noSpacePredicateTraverser; - public PrettyPrinterGenerationVisitor(GlobalExtensionManagement glex, ASTCDClass ppClass, Map classProds) { + public PrettyPrinterGenerationVisitor(GlobalExtensionManagement glex, ASTCDClass ppClass, Map classProds) { this.glex = glex; this.ppClass = ppClass; this.classProds = classProds; @@ -107,7 +107,7 @@ public void endVisit(ASTClassProd node) { blockData.getAltDataList().sort(Collections.reverseOrder()); // Prepare iterators (used instead of direct lists access) - Map iterators = new HashMap<>(); + Map iterators = new LinkedHashMap<>(); for (String refName : currentClassProdData.getNonTerminals().keySet()) { if (!currentClassProdData.isIteratorNeeded(refName)) continue; ASTRuleComponent itNode = currentClassProdData.getNonTerminalNodes().get(refName); @@ -157,6 +157,8 @@ public void endVisit(ASTClassProd node) { iterators.put(refName, new IteratorData(getter, type)); } + this.addNegatedOptsFromOtherAlts(blockData); + if (!currentClassProdData.getErroringNonTerminals().isEmpty()) this.failureMessage = "The NonTerminal(s) " + currentClassProdData.getErroringNonTerminals() + " caused the automatic generation to fail"; @@ -191,11 +193,44 @@ public void endVisit(ASTClassProd node) { this.currentClassProdData = null; } + /** + * The ordering of alts may be more complex: + * A | (A|B) + * the first alternative has to be added with the !isPresentB() guard + * @param blockData the block to work on + */ + protected void addNegatedOptsFromOtherAlts (BlockData blockData) { + // For each alt + for (var alt : blockData.getAltDataList()) { + // collect all opts from the other alts + var optsFromOtherAlts = new LinkedHashSet(); + for (var otherAlt : blockData.getAltDataList()) { + if (otherAlt == alt) continue; + optsFromOtherAlts.addAll(otherAlt.getOptionalSet()); + } + // and remove the optionals & required ones from this alt + optsFromOtherAlts.removeAll(alt.getOptionalSet()); + optsFromOtherAlts.removeAll(alt.getRequiredSet()); + + if (optsFromOtherAlts.isEmpty()) continue; + + // optsFromOtherAlts now contains all used elements, that are not used in this alt + // Construct the expression from the given refname + List optsFromOtherAltsExpr = new ArrayList<>(); + for (var refName : optsFromOtherAlts) { + Multiplicity multiplicityOfNT = currentClassProdData.getMultiplicity(StringTransformations.uncapitalize(refName)); + optsFromOtherAltsExpr.add(getExp(refName, refName, multiplicityOfNT)); + } + // and finally, add a !(usedInAlt1 || .. || usedInAltN) to this alt's constraint + var andExr = AltData.reduceToOr(optsFromOtherAltsExpr); + alt.getExpressionList().add(CommonExpressionsMill.logicalNotExpressionBuilder().setExpression(andExr).build()); + } + } @Override public void visit(ASTAlt node) { if (blockDataStack.isEmpty()) return; // Only visit in CPs - AltData altData = new AltData(); + AltData altData = new AltData(node); blockDataStack.peek().getAltDataList().add(altData); altDataStack.push(altData); } @@ -209,6 +244,8 @@ public void endVisit(ASTAlt node) { for (int i : altData.getNoSpaceTokens()) markNoSpaceToken(altData, i); } + blockDataStack.peek().getOptionalSet().addAll(altData.getOptionalSet()); + blockDataStack.peek().getOptionalSet().addAll(altData.getRequiredSet()); } /** @@ -261,7 +298,7 @@ public void visit(ASTNonTerminal node) { AltData altData = altDataStack.peek(); if (node.getSymbol().getReferencedProd().get().isIsEnum()) { - this.failureMessage = "EnumProd references are not yet implemented"; + this.failureMessage = "EnumProd references are not yet supported by the generated pretty printer"; return; } String refName = node.isPresentUsageName() ? node.getUsageName() : node.getName(); @@ -283,6 +320,12 @@ public void visit(ASTNonTerminal node) { int iteration = node.getIteration(); + if (iteration == ASTConstantsGrammar.PLUS || iteration == ASTConstantsGrammar.DEFAULT) { + altData.getRequiredSet().add(refName); + } else { + altData.getOptionalSet().add(refName); + } + if (multiplicity == Multiplicity.STANDARD && (iteration == ASTConstantsGrammar.PLUS || iteration == ASTConstantsGrammar.STAR)) iteration = ASTConstantsGrammar.DEFAULT; // Force overwrite in case of ASTRule shenanigans if (multiplicity == Multiplicity.OPTIONAL && (iteration == ASTConstantsGrammar.PLUS || iteration == ASTConstantsGrammar.STAR)) @@ -292,7 +335,8 @@ public void visit(ASTNonTerminal node) { PPGuardComponent component = PPGuardComponent.forNTSingle(isLexType(node) ? substituteLexProdType(node.getName()) : node.getName(), refName, iteration, - isMCCommonLiteralsSuper + isMCCommonLiteralsSuper, + node ); altData.getComponentList().add(component); @@ -327,7 +371,8 @@ public void visit(ASTNonTerminal node) { refName, iteration, isIteratorUsed, - isMCCommonLiteralsSuper + isMCCommonLiteralsSuper, + node ); altData.getComponentList().add(component); @@ -373,11 +418,11 @@ protected void visitTerminals(ASTITerminal node, int nodeIteration){ if (currentClassProdData.isIteratorNeeded(usageName)) { // In case an iterator is required and the terminal is named, we can handle it like a lexed NonTerminal // replacekeyword directive can be ignored here (as the parser handles it with an action) - altData.getComponentList().add(PPGuardComponent.forNT("Name", usageName, nodeIteration, true, isMCCommonLiteralsSuper)); + altData.getComponentList().add(PPGuardComponent.forNT("Name", usageName, nodeIteration, true, isMCCommonLiteralsSuper, node)); blockDataStack.peek().markListReady(); // Mark that an iterator was used => while can be used altData.markListReady(); } else { - altData.getComponentList().add(PPGuardComponent.forT(node.getName(), usageName, nodeIteration)); + altData.getComponentList().add(PPGuardComponent.forT(node.getName(), usageName, nodeIteration, node)); } @@ -385,6 +430,12 @@ protected void visitTerminals(ASTITerminal node, int nodeIteration){ Multiplicity multiplicity = currentClassProdData.getMultiplicity(StringTransformations.uncapitalize(usageName)); + if (iteration == ASTConstantsGrammar.PLUS || iteration == ASTConstantsGrammar.DEFAULT) { + altData.getRequiredSet().add(usageName); + } else { + altData.getOptionalSet().add(usageName); + } + if (nodeIteration == ASTConstantsGrammar.DEFAULT || iteration == ASTConstantsGrammar.PLUS) { if (nodeIteration == ASTConstantsGrammar.PLUS) altData.setOptional(altData.getOptional() + 1); @@ -402,7 +453,7 @@ protected void visitTerminals(ASTITerminal node, int nodeIteration){ } }else { // Always use default iteration 0, as we have no control otherwise - PPGuardComponent component = PPGuardComponent.forT(string); + PPGuardComponent component = PPGuardComponent.forT(string, node); altData.getComponentList().add(component); altData.getExpressionList().add(AltData.TRUE_EXPRESSION); // Push a true condition @@ -416,7 +467,7 @@ public void visit(ASTBlock node) { AltData altData = altDataStack.peek(); BlockData blockData = new BlockData(false, node.getIteration(), getEffectiveIteration(outerBlock.getInheritedIteration(), node.getIteration()), node); blockDataStack.push(blockData); - altData.getComponentList().add(PPGuardComponent.forBlock(blockData, node.getIteration())); + altData.getComponentList().add(PPGuardComponent.forBlock(blockData, node.getIteration(), node)); } @Override @@ -428,6 +479,8 @@ public void endVisit(ASTBlock node) { } List allAltExpressions = new ArrayList<>(); + this.addNegatedOptsFromOtherAlts(blockData); + if (!altDataStack.isEmpty()) { AltData altData = altDataStack.peek(); @@ -436,6 +489,13 @@ public void endVisit(ASTBlock node) { boolean isOpt = node.getIteration() == ASTConstantsGrammar.STAR || node.getIteration() == ASTConstantsGrammar.QUESTION; + altData.getOptionalSet().addAll(blockData.getOptionalSet()); + if (isOpt) { + altData.getOptionalSet().addAll(blockData.getRequiredSet()); + } else { + altData.getRequiredSet().addAll(blockData.getRequiredSet()); + } + boolean isAnyListReady = false; boolean areAllListReady = true; @@ -457,7 +517,7 @@ public void endVisit(ASTBlock node) { altData.setOptional(maxOpt); altData.setRequired(maxReq); - if (!allAltExpressions.isEmpty()) + if (!allAltExpressions.isEmpty()) // might contain true || true altData.getExpressionList().add(AltData.reduceToOr(allAltExpressions)); // Prevent e.g. (Decimal | ",")* => while (hasDecimal() || true) { ... } endless loops @@ -497,7 +557,7 @@ public void visit(ASTConstantGroup node) { this.failureMessage = "Unable to handle ConstantGroup with size of 1, but multiple elements named " + humanName + " present"; } - Set> constants = new HashSet<>(); + Set> constants = new LinkedHashSet<>(); for (ASTConstant constant : node.getConstantList()) { constants.add(new AbstractMap.SimpleEntry<>(constant.getHumanName(), constant.getName())); if (!onlyOneConstant && LexNamer.createGoodName(constant.getHumanName()).isEmpty()) // The constant will be named CONSTANT{num} instead @@ -509,7 +569,7 @@ public void visit(ASTConstantGroup node) { constants = constants.stream().limit(1).collect(Collectors.toSet()); } - PPGuardComponent component = PPGuardComponent.forCG(getter, constants); + PPGuardComponent component = PPGuardComponent.forCG(getter, constants, node); AltData altData; Optional blockDataOpt = Optional.empty(); @@ -517,9 +577,9 @@ public void visit(ASTConstantGroup node) { // Add a new block with alt for this ConstantGroup BlockData outerBlock = blockDataStack.peek(); blockDataOpt = Optional.of(new BlockData(false, node.getIteration(), getEffectiveIteration(outerBlock.getInheritedIteration(), node.getIteration()), null)); - altDataStack.peek().getComponentList().add(PPGuardComponent.forBlock(blockDataOpt.get(), node.getIteration())); + altDataStack.peek().getComponentList().add(PPGuardComponent.forBlock(blockDataOpt.get(), node.getIteration(), node)); // And add one alt (without using the stack, as we will only use it in this method) - altData = new AltData(); + altData = new AltData(node); blockDataOpt.get().getAltDataList().add(altData); }else { // If this is not an optional CG, skip the extra block diff --git a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/PrettyPrinterReplaceKeywordFinder.java b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/PrettyPrinterReplaceKeywordFinder.java index f36714588b..26abe3b273 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/PrettyPrinterReplaceKeywordFinder.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/PrettyPrinterReplaceKeywordFinder.java @@ -74,7 +74,7 @@ void mark(String keyword) { // skip replacekeywords which are already present during the PP-generation of a grammar and do NOT require overwriting of a handle method if (localReplacedKeywords == null || !localReplacedKeywords.equals(replacingKeywords)) { // get keyword -> [replacing keywords] for symbol - Map> replacedKeywords = replacedKeywordsInProductions.computeIfAbsent(prodSymbol.get(), x -> new HashMap<>()); + Map> replacedKeywords = replacedKeywordsInProductions.computeIfAbsent(prodSymbol.get(), x -> new LinkedHashMap<>()); // get [replacing keywords] and add replacedKeywords.computeIfAbsent(keyword, x -> new ArrayList<>()).addAll(replacingKeywords); } @@ -96,7 +96,7 @@ public void visit(ASTTokenTerminal node) { } public Map>> check(ASTMCGrammar astmcGrammar) { - replacedKeywordsInProductions = new HashMap<>(); + replacedKeywordsInProductions = new LinkedHashMap<>(); replacedKeywordsLocalGrammar = astmcGrammar.getSymbol().getReplacedKeywordsWithInherited(); traverser.clearTraversedElements(); astmcGrammar.accept(traverser); diff --git a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/AltData.java b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/AltData.java index ff790a75f3..727e1432e1 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/AltData.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/AltData.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.codegen.prettyprint.data; +import de.monticore.ast.ASTNode; import de.monticore.cd4code.CD4CodeMill; import de.monticore.expressions.commonexpressions.CommonExpressionsMill; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; @@ -9,7 +10,9 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; public class AltData implements Comparable { @@ -43,6 +46,15 @@ public class AltData implements Comparable { */ protected List noSpaceTokens = new ArrayList<>(); + /** + * For tracing: The AST node causing this alt + */ + protected ASTNode node; + + public AltData(ASTNode node) { + this.node = node; + } + public List getComponentList() { return componentList; } @@ -71,6 +83,22 @@ public void setOptional(int optional) { this.optional = optional; } + // To add negations + protected final Set optionalSet = new LinkedHashSet<>(), requiredSet = new LinkedHashSet<>(); + + /** + * @return set of optionally used AST-elements + */ + public Set getOptionalSet() { + return optionalSet; + } + + /** + * @return set of required AST-elements to print this alt + */ + public Set getRequiredSet() { + return requiredSet; + } /** * Returns the expressions for this Alt in conjunction @@ -106,6 +134,7 @@ public String toString() { ", optional=" + optional + ", isListReady=" + isListReady + ", #expressionList=" + expressionList.size() + + ", node=[" + node.get_SourcePositionStart() + "-" + node.get_SourcePositionEnd() + "]" + '}'; } @@ -127,21 +156,25 @@ public boolean isListReady() { ASTConstantsMCCommonLiterals.FALSE).build()).build(); + // The AND(A, OR(B, C)) expression is printed as OR( AND(A, B), C) which is + // why we add extra brackets public static ASTExpression reduceToAnd(Collection expressions) { return expressions.stream().reduce(TRUE_EXPRESSION, (expression, expression2) -> expression == TRUE_EXPRESSION ? expression2 : (expression2 == TRUE_EXPRESSION ? expression : - CommonExpressionsMill.booleanAndOpExpressionBuilder().setLeft(expression).setRight(expression2) - .setOperator("&&") - .build())); + CommonExpressionsMill.bracketExpressionBuilder().setExpression( + CommonExpressionsMill.booleanAndOpExpressionBuilder().setLeft(expression).setRight(expression2) + .setOperator("&&") + .build()).build())); } public static ASTExpression reduceToOr(Collection expressions) { return expressions.stream().reduce(FALSE_EXPRESSION, (expression, expression2) -> expression == FALSE_EXPRESSION ? expression2 : (expression2 == FALSE_EXPRESSION ? expression : - CommonExpressionsMill.booleanOrOpExpressionBuilder().setLeft(expression).setRight(expression2) - .setOperator("||") - .build())); + CommonExpressionsMill.bracketExpressionBuilder().setExpression( + CommonExpressionsMill.booleanOrOpExpressionBuilder().setLeft(expression).setRight(expression2) + .setOperator("||") + .build()).build())); } } diff --git a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/BlockData.java b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/BlockData.java index e12e9563c6..ecc74784c7 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/BlockData.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/BlockData.java @@ -5,7 +5,9 @@ import de.monticore.grammar.grammar._ast.ASTConstantsGrammar; import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; public class BlockData { protected final List altDataList = new ArrayList<>(); @@ -64,6 +66,22 @@ public boolean isListReady() { return isListReady; } + protected final Set optionalSet = new LinkedHashSet<>(), requiredSet = new LinkedHashSet<>(); + + /** + * @return set of optionally used AST-elements + */ + public Set getOptionalSet() { + return optionalSet; + } + + /** + * @return set of required AST-elements to print this block + */ + public Set getRequiredSet() { + return requiredSet; + } + @Override public String toString() { return "BlockData{" + diff --git a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/PPGuardComponent.java b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/PPGuardComponent.java index 0286ff84fc..89fbe5e392 100644 --- a/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/PPGuardComponent.java +++ b/monticore-generator/src/main/java/de/monticore/codegen/prettyprint/data/PPGuardComponent.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.codegen.prettyprint.data; +import de.monticore.ast.ASTNode; import de.monticore.grammar.grammar._ast.ASTConstantsGrammar; import java.util.Map; @@ -28,8 +29,12 @@ public class PPGuardComponent { protected boolean hasNoSpace = false; + // For tracing + protected ASTNode node; + public PPGuardComponent(PPGuardType type, BlockData blockData, String name, String nameToUse, - String separator, Set> constants, int iteration, boolean isMCCommonLiteralsSuper) { + String separator, Set> constants, int iteration, boolean isMCCommonLiteralsSuper, + ASTNode node) { this.type = type; this.blockData = blockData; this.name = name; @@ -38,6 +43,7 @@ public PPGuardComponent(PPGuardType type, BlockData blockData, String name, Stri this.constants = constants; this.iteration = iteration; this.isMCCommonLiteralsSuper = isMCCommonLiteralsSuper; + this.node = node; } public PPGuardType getType() { @@ -149,30 +155,30 @@ public enum PPGuardType { } public static PPGuardComponent forBlock(BlockData blockData, - int iteration) { - return new PPGuardComponent(PPGuardType.BLOCK, blockData, null, null, null, null, iteration, false); + int iteration, ASTNode node) { + return new PPGuardComponent(PPGuardType.BLOCK, blockData, null, null, null, null, iteration, false, node); } public static PPGuardComponent forNT(String name, String nameToUse, - int iteration, boolean iterated, boolean isMCCommonLiteralsSuper) { - return new PPGuardComponent(iterated ? PPGuardType.NT_ITERATED : PPGuardType.NT, null, name, nameToUse, null, null, iteration, isMCCommonLiteralsSuper); + int iteration, boolean iterated, boolean isMCCommonLiteralsSuper, ASTNode node) { + return new PPGuardComponent(iterated ? PPGuardType.NT_ITERATED : PPGuardType.NT, null, name, nameToUse, null, null, iteration, isMCCommonLiteralsSuper, node); } public static PPGuardComponent forNTSingle(String name, String nameToUse, - int iteration, boolean isMCCommonLiteralsSuper) { - return new PPGuardComponent(PPGuardType.NT_AST_DEF, null, name, nameToUse, null, null, iteration, isMCCommonLiteralsSuper); + int iteration, boolean isMCCommonLiteralsSuper, ASTNode node) { + return new PPGuardComponent(PPGuardType.NT_AST_DEF, null, name, nameToUse, null, null, iteration, isMCCommonLiteralsSuper, node); } - public static PPGuardComponent forT(String name) { - return new PPGuardComponent(PPGuardType.T, null, name, name, null, null, ASTConstantsGrammar.DEFAULT, false); + public static PPGuardComponent forT(String name, ASTNode node) { + return new PPGuardComponent(PPGuardType.T, null, name, name, null, null, ASTConstantsGrammar.DEFAULT, false, node); } - public static PPGuardComponent forT(String name, String usageName, int iteration) { - return new PPGuardComponent(PPGuardType.T, null, name, usageName, null, null, iteration, false); + public static PPGuardComponent forT(String name, String usageName, int iteration, ASTNode node) { + return new PPGuardComponent(PPGuardType.T, null, name, usageName, null, null, iteration, false, node); } - public static PPGuardComponent forCG(String usageName, Set> constants) { - return new PPGuardComponent(PPGuardType.CG, null, usageName, usageName, null, constants, 0, false); + public static PPGuardComponent forCG(String usageName, Set> constants, ASTNode node) { + return new PPGuardComponent(PPGuardType.CG, null, usageName, usageName, null, constants, 0, false, node); } } diff --git a/monticore-generator/src/main/java/de/monticore/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsPhasedSTCFix.java b/monticore-generator/src/main/java/de/monticore/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsPhasedSTCFix.java new file mode 100644 index 0000000000..9a31654226 --- /dev/null +++ b/monticore-generator/src/main/java/de/monticore/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsPhasedSTCFix.java @@ -0,0 +1,41 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.de.monticore.grammar.grammar_withconcepts._symboltable; + +import de.monticore.grammar.concepts.antlr.antlr._ast.ASTConceptAntlr; +import de.monticore.grammar.concepts.antlr.antlr._visitor.AntlrHandler; +import de.monticore.grammar.concepts.antlr.antlr._visitor.AntlrTraverser; +import de.monticore.grammar.grammar_withconcepts._symboltable.Grammar_WithConceptsPhasedSTC; + +/** + * Backport of Grammar_WithConceptsPhasedSTC fix + * ... + * Remove after 7.9.0 release + */ +public class Grammar_WithConceptsPhasedSTCFix extends Grammar_WithConceptsPhasedSTC { + public Grammar_WithConceptsPhasedSTCFix() { + super(); + this.priorityList.get(0).setAntlrHandler(new DoNotTCJavaCode()); + } + + + // Explicitly do not check the JavaCode of ConceptAntlr (as we can't TC it without knowing the java classpath) + // required since the 7.7.0 -> 7.8.0 update + protected static class DoNotTCJavaCode implements AntlrHandler { + protected AntlrTraverser realThis; + + @Override + public AntlrTraverser getTraverser() { + return realThis; + } + + @Override + public void setTraverser(AntlrTraverser traverser) { + this.realThis = traverser; + } + + @Override + public void traverse(ASTConceptAntlr node) { + // do nothing! + } + } +} diff --git a/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/DSL2TransformationLanguageVisitor.java b/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/DSL2TransformationLanguageVisitor.java index 78c7baa78f..ef1c6aa0fa 100644 --- a/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/DSL2TransformationLanguageVisitor.java +++ b/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/DSL2TransformationLanguageVisitor.java @@ -10,7 +10,6 @@ import de.monticore.grammar.grammar._symboltable.MCGrammarSymbol; import de.monticore.grammar.grammar._symboltable.ProdSymbol; import de.monticore.grammar.grammar._visitor.GrammarVisitor2; -import de.monticore.symboltable.modifiers.AccessModifier; import de.se_rwth.commons.Splitters; import de.se_rwth.commons.logging.Log; @@ -237,50 +236,36 @@ public void visit(ASTClassProd srcNode) { tfLang.getInterfaceProdList().add(productionFactory.createInterfaceProd(srcNode, grammar_depth, isLeftRecursive)); } - ASTClassProd p = productionFactory.createProd(srcNode, LIST,superExternal, isLeftRecursive); - if (!isEmpty){ - productionFactory - .addInterfaces(srcNode.getSuperRuleList(), p); - productionFactory.addInterfaces( - srcNode.getSuperInterfaceRuleList(), p); - } else { + ASTClassProd p = productionFactory.createProd(srcNode, LIST, superExternal, isLeftRecursive); + if (!addASTClassProdInterfaces(srcNode, p, LIST, isLeftRecursive, isEmpty)) { p.add_PreComment(new Comment(" /*Skipping supers due to empty prod*/ ")); } + addASTClassProdAnnotations(p, overridden); targetClassProdList.add(0, p); p = productionFactory.createProd(srcNode, OPTIONAL, superExternal, isLeftRecursive); - if (!isLeftRecursive && !isEmpty) { - productionFactory - .addInterfaces(srcNode.getSuperRuleList(), p); - productionFactory.addInterfaces( - srcNode.getSuperInterfaceRuleList(), p); - } else { + if (!addASTClassProdInterfaces(srcNode, p, OPTIONAL, isLeftRecursive, isEmpty)) { p.add_PreComment(new Comment(" /*Skipping supers due to " + (isEmpty ? "empty prod " : "") + (isLeftRecursive ? "left recursiveness " : "") + " */ ")); } + addASTClassProdAnnotations(p, overridden); targetClassProdList.add(0, p); p = productionFactory.createProd(srcNode, NEGATION, superExternal, isLeftRecursive); - if (!isLeftRecursive && !isEmpty) { - productionFactory - .addInterfaces(srcNode.getSuperRuleList(), p); - productionFactory.addInterfaces( - srcNode.getSuperInterfaceRuleList(), p); - }else{ + if (!addASTClassProdInterfaces(srcNode, p, NEGATION, isLeftRecursive, isEmpty)) { p.add_PreComment(new Comment(" /*Skipping supers due to " + (isEmpty ? "empty prod " : "") + (isLeftRecursive ? "left recursiveness " : "") + " */ ")); } + addASTClassProdAnnotations(p, overridden); targetClassProdList.add(0, p); p = productionFactory.createPatternProd(srcNode,grammarSymbol, superExternal, isLeftRecursive, isEmpty); - + addASTClassProdAnnotations(p, overridden); targetClassProdList.add(0, p); p = productionFactory.createReplacementProd(srcNode, superExternal); - if (!isLeftRecursive && !isEmpty) { - productionFactory.addInterfaces(srcNode.getSuperRuleList(),p); - productionFactory.addInterfaces(srcNode.getSuperInterfaceRuleList(),p); - }else{ + if (!addASTClassProdInterfaces(srcNode, p, REPLACEMENT, isLeftRecursive, isEmpty)) { p.add_PreComment(new Comment(" /*Skipping supers due to " + (isEmpty ? "empty prod " : "") + (isLeftRecursive ? "left recursiveness " : "") + " */ ")); } + addASTClassProdAnnotations(p, overridden); targetClassProdList.add(0, p); targetAstRuleList.add(astRuleFactory.createAstProd(srcNode, LIST, overridden, grammarSymbol)); @@ -323,7 +308,17 @@ public void visit(ASTASTRule srcNode) { Log.debug("Visiting ast rule " + srcNode.getType(), LOG); List targetAstRuleList = tfLang.getASTRuleList(); if (!("MCCompilationUnit").equals(srcNode.getType())) { - targetAstRuleList.add(astRuleFactory.createASTRule(srcNode, grammarSymbol)); + ASTASTRule targetNode = astRuleFactory.createASTRule(srcNode, grammarSymbol); + + boolean hasSuperClass = !targetNode.isEmptyASTSuperClass(); + boolean hasSuperInterface = !targetNode.isEmptyASTSuperInterface(); + boolean hasGrammarMethods = !targetNode.isEmptyGrammarMethods(); + boolean hasAdditionalAttributes = !targetNode.isEmptyAdditionalAttributes(); + + // only create ASTRule if it has any influence + if (hasSuperClass || hasSuperInterface || hasGrammarMethods || hasAdditionalAttributes) { + targetAstRuleList.add(targetNode); + } } } @@ -340,5 +335,32 @@ public void visit(ASTConcept srcNode) { public ASTMCGrammar getTfLang() { return tfLang; } + + protected boolean addASTClassProdInterfaces(ASTClassProd srcNode, ASTClassProd prod, + ProductionType productionType, boolean isLeftRecursive, boolean isEmpty) { + if (productionType == LIST) { + if (isEmpty) { + return false; + } + productionFactory.addInterfaces(srcNode.getSuperRuleList(), prod); + productionFactory.addInterfaces(srcNode.getSuperInterfaceRuleList(), prod); + } + else if (productionType == OPTIONAL || productionType == NEGATION + || productionType == REPLACEMENT) { + if (isLeftRecursive || isEmpty) { + return false; + } + productionFactory.addInterfaces(srcNode.getSuperRuleList(), prod); + productionFactory.addInterfaces(srcNode.getSuperInterfaceRuleList(), prod); + } + return true; + } + + protected void addASTClassProdAnnotations(ASTClassProd prod, boolean override) { + // Add @Override annotation to the production if needed + if (override) { + prod.addGrammarAnnotation(productionFactory.createOverrideAnnotation()); + } + } } diff --git a/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/PostprocessPatternAttributesVisitor.java b/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/PostprocessPatternAttributesVisitor.java index d2c2668601..49707ee059 100644 --- a/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/PostprocessPatternAttributesVisitor.java +++ b/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/PostprocessPatternAttributesVisitor.java @@ -21,7 +21,7 @@ public class PostprocessPatternAttributesVisitor implements GrammarVisitor2 { protected final MCGrammarSymbol grammarSymbol; - protected final Collection additionallySupportedITFProductions = new HashSet<>(); + protected final Collection additionallySupportedITFProductions = new LinkedHashSet<>(); public PostprocessPatternAttributesVisitor(MCGrammarSymbol grammarSymbol) { this.grammarSymbol = grammarSymbol; diff --git a/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/ProductionFactory.java b/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/ProductionFactory.java index 006d164c29..20cfec5727 100644 --- a/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/ProductionFactory.java +++ b/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/ProductionFactory.java @@ -37,6 +37,10 @@ public class ProductionFactory { public static final String PSYM_TFTFSchema = "TFSchema"; public static final String PSYM_TFOBJECTS = "TFRule"; public static final String PSYM_SCHEMAVAR = "schemaVar"; + /** + * Usage name of the production's name in a pattern + */ + public static final String PSYM_PRODUNAME = "__tfpname"; public static final String PSYM_PATTERN = "de.monticore.tf.ast.IPattern"; public static final String NONTERM_PREFIX = "ITF"; @@ -262,6 +266,7 @@ protected static List createPatternAlternates(ASTClassProd srcNode, Gram // NTName as keyword ASTTerminal terminal = GrammarMill.terminalBuilder().uncheckedBuild(); terminal.setName(srcNode.getName()); + terminal.setUsageName(PSYM_PRODUNAME); terminal.setIteration(DEFAULT); abstractAlt.getComponentList().add(terminal); // schema variable @@ -303,6 +308,7 @@ protected static List createPatternAlternates(ASTClassProd srcNode, Gram ASTAlt ntOptionalAlt = GrammarMill.altBuilder().uncheckedBuild(); terminal = GrammarMill.terminalBuilder().uncheckedBuild(); terminal.setName(srcNode.getName()); + terminal.setUsageName(PSYM_PRODUNAME); terminal.setIteration(ASTConstantsGrammar.QUESTION); ntOptionalAlt.getComponentList().add(terminal); ntOptionalAlt.getComponentList() @@ -312,6 +318,7 @@ protected static List createPatternAlternates(ASTClassProd srcNode, Gram // nonterminal is mandatory but variable is optional terminal = GrammarMill.terminalBuilder().uncheckedBuild(); terminal.setName(srcNode.getName()); + terminal.setUsageName(PSYM_PRODUNAME); terminal.setIteration(DEFAULT); varOptionalAlt.getComponentList().add(terminal); ASTNonTerminal schemaVarNameOptional = schemaVarName.deepClone(); @@ -382,6 +389,7 @@ protected ASTClassProd doCreatePatternProd(ASTProd srcNode, MCGrammarSymbol gram // NTName as keyword ASTTerminal terminal = GrammarMill.terminalBuilder().uncheckedBuild(); terminal.setName(srcNode.getName()); + terminal.setUsageName(PSYM_PRODUNAME); terminal.setIteration(DEFAULT); abstractAlt.getComponentList().add(terminal); // schema variable @@ -396,6 +404,7 @@ protected ASTClassProd doCreatePatternProd(ASTProd srcNode, MCGrammarSymbol gram // syntax in parentheses terminal = GrammarMill.terminalBuilder().uncheckedBuild(); terminal.setName(srcNode.getName()); + terminal.setUsageName(PSYM_PRODUNAME); terminal.setIteration(DEFAULT); mixedAlt.getComponentList().add(terminal); ASTNonTerminal schemaVarNameOptional = schemaVarName.deepClone(); @@ -788,7 +797,7 @@ protected Optional createLexIdentifier(ASTLexProd srcNode, MCGramm .build(); // "X" identifier:TFSchema ";" ASTAlt fourth = GrammarMill.altBuilder() - .addComponent(GrammarMill.terminalBuilder().setName(srcNode.getName()).build()) + .addComponent(GrammarMill.terminalBuilder().setName(srcNode.getName()).setUsageName(PSYM_PRODUNAME).build()) .addComponent(GrammarMill.nonTerminalBuilder().setUsageName("identifierSchema").setName(PSYM_TFTFSchema).build()) .addComponent(GrammarMill.terminalBuilder().setName(";").build()) .build(); @@ -797,5 +806,13 @@ protected Optional createLexIdentifier(ASTLexProd srcNode, MCGramm .build()); } } + + /** + * Create a new @Override annotation + * @return ASTGrammarAnnotation with override property + */ + protected ASTGrammarAnnotation createOverrideAnnotation() { + return GrammarMill.grammarAnnotationBuilder().setOverride(true).build(); + } } diff --git a/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/TFLanguageOverrideVisitor.java b/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/TFLanguageOverrideVisitor.java index 4a20b2e8c1..3606050649 100644 --- a/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/TFLanguageOverrideVisitor.java +++ b/monticore-generator/src/main/java/de/monticore/dstlgen/grammartransformation/TFLanguageOverrideVisitor.java @@ -5,7 +5,7 @@ import de.monticore.grammar.grammar._visitor.GrammarVisitor2; import de.se_rwth.commons.Joiners; -import java.util.HashMap; +import java.util.LinkedHashMap; public class TFLanguageOverrideVisitor implements GrammarVisitor2 { @@ -13,13 +13,13 @@ public class TFLanguageOverrideVisitor implements private final ASTMCGrammar overideGrammar; private final ASTMCGrammar tFGrammar; - private HashMap tFClassProds = new HashMap<>(); - private HashMap tFEnumProds = new HashMap<>(); - private HashMap tFInterfaceProds = new HashMap<>(); - private HashMap tFAbstractProds = new HashMap<>(); - private HashMap tFExternalProds = new HashMap<>(); - private HashMap tFLexProds = new HashMap<>(); - private HashMap tFASTRules = new HashMap<>(); + private LinkedHashMap tFClassProds = new LinkedHashMap<>(); + private LinkedHashMap tFEnumProds = new LinkedHashMap<>(); + private LinkedHashMap tFInterfaceProds = new LinkedHashMap<>(); + private LinkedHashMap tFAbstractProds = new LinkedHashMap<>(); + private LinkedHashMap tFExternalProds = new LinkedHashMap<>(); + private LinkedHashMap tFLexProds = new LinkedHashMap<>(); + private LinkedHashMap tFASTRules = new LinkedHashMap<>(); public TFLanguageOverrideVisitor(ASTMCGrammar tFGrammar, ASTMCGrammar overrideGrammar) { diff --git a/monticore-generator/src/main/java/de/monticore/dstlgen/ruletranslation/CollectGrammarInformationVisitor.java b/monticore-generator/src/main/java/de/monticore/dstlgen/ruletranslation/CollectGrammarInformationVisitor.java index 1a5068eeb1..be3bb5667c 100644 --- a/monticore-generator/src/main/java/de/monticore/dstlgen/ruletranslation/CollectGrammarInformationVisitor.java +++ b/monticore-generator/src/main/java/de/monticore/dstlgen/ruletranslation/CollectGrammarInformationVisitor.java @@ -27,23 +27,23 @@ public class CollectGrammarInformationVisitor implements private final MCGrammarSymbol grammarSymbol; - private Map> stringAttrs = new HashMap<>(); + private Map> stringAttrs = new LinkedHashMap<>(); - private Map> stringListAttrs = new HashMap<>(); + private Map> stringListAttrs = new LinkedHashMap<>(); - private Map> booleanAltAttrs = new HashMap<>(); + private Map> booleanAltAttrs = new LinkedHashMap<>(); - private Map> booleanAttrs = new HashMap<>(); + private Map> booleanAttrs = new LinkedHashMap<>(); - private Map> booleanListAttrs = new HashMap<>(); + private Map> booleanListAttrs = new LinkedHashMap<>(); - private Map> booleanAttrNames = new HashMap<>(); + private Map> booleanAttrNames = new LinkedHashMap<>(); - private Map> booleanListAttrNames = new HashMap<>(); + private Map> booleanListAttrNames = new LinkedHashMap<>(); - private Map> componentLists = new HashMap<>(); + private Map> componentLists = new LinkedHashMap<>(); - private Map> componentNodes = new HashMap<>(); + private Map> componentNodes = new LinkedHashMap<>(); private List knownAttributes = Lists.newArrayList(); diff --git a/monticore-generator/src/main/java/de/monticore/dstlgen/ruletranslation/DSTLGenInheritanceHelper.java b/monticore-generator/src/main/java/de/monticore/dstlgen/ruletranslation/DSTLGenInheritanceHelper.java index 4793fe57cf..99b1495a34 100644 --- a/monticore-generator/src/main/java/de/monticore/dstlgen/ruletranslation/DSTLGenInheritanceHelper.java +++ b/monticore-generator/src/main/java/de/monticore/dstlgen/ruletranslation/DSTLGenInheritanceHelper.java @@ -13,7 +13,7 @@ import java.util.Set; import java.util.Optional; import java.util.Collection; -import java.util.HashSet; +import java.util.LinkedHashSet; public class DSTLGenInheritanceHelper { @@ -36,11 +36,11 @@ public static synchronized DSTLGenInheritanceHelper getInstance() { * The names of all lexical productions known to TFCommons. * Required, as the transformation languages are all extending TFCommons */ - protected final Collection tfCommonLexProds = new HashSet<>(); + protected final Collection tfCommonLexProds = new LinkedHashSet<>(); /** * FQN of TFCommons and all its super grammars */ - protected final Collection tfCommonSuperFQNs = new HashSet<>(); + protected final Collection tfCommonSuperFQNs = new LinkedHashSet<>(); /** * Constructor for de.monticore.tf.ruletranslation.InheritanceHelper diff --git a/monticore-generator/src/main/java/de/monticore/dstlgen/util/DSTLPrettyPrinter.java b/monticore-generator/src/main/java/de/monticore/dstlgen/util/DSTLPrettyPrinter.java index 608a064a7f..9d7fe35209 100644 --- a/monticore-generator/src/main/java/de/monticore/dstlgen/util/DSTLPrettyPrinter.java +++ b/monticore-generator/src/main/java/de/monticore/dstlgen/util/DSTLPrettyPrinter.java @@ -29,52 +29,50 @@ public DSTLPrettyPrinter(IndentPrinter out) { */ @Override public void handle(ASTClassProd a) { + CommentPrettyPrinter.printPreComments(a, getPrinter()); - - CommentPrettyPrinter.printPreComments(a, getPrinter()); - - getPrinter().print(a.getName()); - - if (!a.getSuperRuleList().isEmpty()) { - getPrinter().print(" extends "); - printList(a.getSuperRuleList().iterator(), ", "); - } - - if (!a.getSuperInterfaceRuleList().isEmpty()) { - getPrinter().print(" implements "); - printList(a.getSuperInterfaceRuleList().iterator(), ", "); - } - - if (!a.getASTSuperClassList().isEmpty()) { - getPrinter().print(" astextends "); - printList(a.getASTSuperClassList().iterator(), ""); - } - - if (!a.getASTSuperInterfaceList().isEmpty()) { - getPrinter().print(" astimplements "); - printList(a.getASTSuperInterfaceList().iterator(), ", "); - } - - if (a.isPresentAction()) { - print(" {"); - getPrinter().println(); - getPrinter().indent(); - a.getAction().accept(getTraverser()); - getPrinter().unindent(); - print("}"); - } - - if (!a.getAltList().isEmpty()) { - println(" ="); - - getPrinter().indent(); - printList(a.getAltList().iterator(), " | "); - } - println(";"); - - CommentPrettyPrinter.printPostComments(a, getPrinter()); + printList(a.iteratorGrammarAnnotations(), " "); + getPrinter().println(); + getPrinter().print(a.getName()); + getPrinter().print(" "); + + if (!a.isEmptySuperRule()) { + getPrinter().print("extends "); + printList(a.iteratorSuperRule(), ", "); + } + if (!a.isEmptySuperInterfaceRule()) { + getPrinter().print("implements "); + printList(a.iteratorSuperInterfaceRule(), ", "); + } + if (!a.isEmptyASTSuperClass()) { + getPrinter().print("astextends "); + printList(a.iteratorASTSuperClass(), ", "); + } + if (!a.isEmptyASTSuperInterface()) { + getPrinter().print("astimplements "); + printList(a.iteratorASTSuperInterface(), ", "); + } + + if (a.isPresentAction()) { + getPrinter().print("{"); + getPrinter().println(); + getPrinter().indent(); + a.getAction().accept(getTraverser()); getPrinter().unindent(); + getPrinter().print("} "); + } + + if (!a.isEmptyAlts()) { + getPrinter().print("="); getPrinter().println(); + getPrinter().indent(); + printList(a.iteratorAlts(), "| "); + } + getPrinter().println(";"); + + CommentPrettyPrinter.printPostComments(a, getPrinter()); + getPrinter().unindent(); + getPrinter().println(); } @Override @@ -92,60 +90,60 @@ public void handle(ASTAdditionalAttribute a) { // print("*"); // } if (a.isPresentCard() && a.getCard().isPresentMin()) { - print(" min = " + a.getCard().getMin()); + getPrinter().print(" min = " + a.getCard().getMin()); } if (a.isPresentCard() && a.getCard().isPresentMax()) { - print(" max = " + a.getCard().getMax()); + getPrinter().print(" max = " + a.getCard().getMax()); } - println(); + getPrinter().println(); } @Override public void handle(ASTLexProd a) { if (a.isFragment()) { - this.print("fragment "); + getPrinter().print("fragment "); } - CommentPrettyPrinter.printPreComments(a, this.getPrinter()); - this.print("token "); - this.println(a.getName()); - this.getPrinter().indent(); + CommentPrettyPrinter.printPreComments(a, getPrinter()); + getPrinter().print("token "); + getPrinter().println(a.getName()); + getPrinter().indent(); if (a.isPresentLexOption()) { a.getLexOption().accept(this.getTraverser()); } if (a.isPresentInitAction()) { - this.print(" {"); - this.getPrinter().println(); - this.getPrinter().indent(); + getPrinter().print(" {"); + getPrinter().println(); + getPrinter().indent(); a.getInitAction().accept(this.getTraverser()); - this.getPrinter().unindent(); - this.print("}"); + getPrinter().unindent(); + getPrinter().print("}"); } - this.getPrinter().print("="); - this.printList(a.getAltList().iterator(), "|"); + getPrinter().print("="); + printList(a.getAltList().iterator(), "|"); if (a.isPresentVariable() || a.isPresentEndAction()) { - this.getPrinter().print(" : "); + getPrinter().print(" : "); if (a.isPresentEndAction()) { - this.getPrinter().print(" { "); + getPrinter().print(" { "); a.getEndAction().accept(getTraverser()); - this.getPrinter().print(" } "); + getPrinter().print(" } "); } if (a.isPresentVariable()) { - this.getPrinter().print(a.getVariable()); + getPrinter().print(a.getVariable()); if (!a.getTypeList().isEmpty()) { - this.getPrinter().print("->"); - this.getPrinter().print(Names.getQualifiedName(a.getTypeList())); + getPrinter().print("->"); + getPrinter().print(Names.getQualifiedName(a.getTypeList())); if (a.isPresentBlock() || a.isPresentEndAction()) { - this.getPrinter().print(":"); + getPrinter().print(":"); if (a.isPresentEndAction()) { - this.print(" {"); - this.getPrinter().println(); - this.getPrinter().indent(); + getPrinter().print(" {"); + getPrinter().println(); + getPrinter().indent(); a.getEndAction().accept(this.getTraverser()); - this.getPrinter().unindent(); - this.print("}"); + getPrinter().unindent(); + getPrinter().print("}"); } if (a.isPresentBlock()) { @@ -156,23 +154,10 @@ public void handle(ASTLexProd a) { } } - this.print(";"); - CommentPrettyPrinter.printPostComments(a, this.getPrinter()); - this.println(); - this.getPrinter().unindent(); - this.println(); + getPrinter().print(";"); + CommentPrettyPrinter.printPostComments(a, getPrinter()); + getPrinter().println(); + getPrinter().unindent(); + getPrinter().println(); } - - protected void print(String o) { - getPrinter().print(o); - } - - protected void println(String o) { - this.getPrinter().println(o); - } - - protected void println() { - this.getPrinter().println(); - } - } diff --git a/monticore-generator/src/main/java/de/monticore/gradle/gen/MCToolInvoker.java b/monticore-generator/src/main/java/de/monticore/gradle/gen/MCToolInvoker.java index 26bb02b7ed..59ec8c083f 100644 --- a/monticore-generator/src/main/java/de/monticore/gradle/gen/MCToolInvoker.java +++ b/monticore-generator/src/main/java/de/monticore/gradle/gen/MCToolInvoker.java @@ -5,6 +5,7 @@ import de.monticore.cd.methodtemplates.CD4C; import de.monticore.generating.templateengine.freemarker.MontiCoreFreeMarkerException; import de.monticore.generating.templateengine.reporting.Reporting; +import de.monticore.gradle.common.GradleLog; import de.monticore.grammar.MCGrammarSymbolTableHelper; import de.monticore.grammar.grammar_withconcepts.Grammar_WithConceptsMill; import de.monticore.mcbasics.MCBasicsMill; @@ -38,7 +39,9 @@ public static void run(String[] args) { MCGradleTool.preLoad(); }); try { - MCGradleTool.main(args); + GradleLog.init(); + Grammar_WithConceptsMill.init(); + new MCGradleTool().run(args); }catch (final AmbiguityException | MontiCoreFreeMarkerException e) { RuntimeException newThrow = e; if (e.getCause() instanceof AmbiguityException) { // Freemarker adds special Freemarker Exceptions diff --git a/monticore-generator/src/main/java/de/monticore/tagging/TagLanguageOverrideVisitor.java b/monticore-generator/src/main/java/de/monticore/tagging/TagLanguageOverrideVisitor.java index 00bf7b079c..d600c43e2b 100644 --- a/monticore-generator/src/main/java/de/monticore/tagging/TagLanguageOverrideVisitor.java +++ b/monticore-generator/src/main/java/de/monticore/tagging/TagLanguageOverrideVisitor.java @@ -5,7 +5,7 @@ import de.monticore.grammar.grammar._visitor.GrammarVisitor2; import de.se_rwth.commons.Joiners; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -15,13 +15,13 @@ public class TagLanguageOverrideVisitor implements GrammarVisitor2 { protected final ASTMCGrammar grammar; - protected final Map classProdMap = new HashMap<>(); - protected final Map enumProdMap = new HashMap<>(); - protected final Map interfaceProdMap = new HashMap<>(); - protected final Map abstractProdMap = new HashMap<>(); - protected final Map externalProdMap = new HashMap<>(); - protected final Map lexProdMap = new HashMap<>(); - protected final Map astRuleMap = new HashMap<>(); + protected final Map classProdMap = new LinkedHashMap<>(); + protected final Map enumProdMap = new LinkedHashMap<>(); + protected final Map interfaceProdMap = new LinkedHashMap<>(); + protected final Map abstractProdMap = new LinkedHashMap<>(); + protected final Map externalProdMap = new LinkedHashMap<>(); + protected final Map lexProdMap = new LinkedHashMap<>(); + protected final Map astRuleMap = new LinkedHashMap<>(); /** * diff --git a/monticore-generator/src/main/resources/_cli/Init.ftl b/monticore-generator/src/main/resources/_cli/Init.ftl index 6dfe3c387c..77458678b7 100644 --- a/monticore-generator/src/main/resources/_cli/Init.ftl +++ b/monticore-generator/src/main/resources/_cli/Init.ftl @@ -1,6 +1,8 @@ <#-- (c) https://github.com/MontiCore/monticore --> ${tc.signature("millFullName")} +// reset any previous initializations of the mill +// This should not be necessary iff all tools reset their mills +${millFullName}.reset(); // initialize logging with standard logging iff not initialized already Log.ensureInitialization(); ${millFullName}.init(); -${millFullName}.globalScope().clear(); diff --git a/monticore-generator/src/main/resources/_cli/Main.ftl b/monticore-generator/src/main/resources/_cli/Main.ftl index 73ced7da38..135715f409 100644 --- a/monticore-generator/src/main/resources/_cli/Main.ftl +++ b/monticore-generator/src/main/resources/_cli/Main.ftl @@ -1,5 +1,20 @@ <#-- (c) https://github.com/MontiCore/monticore --> ${tc.signature("grammarname")} - ${grammarname}Tool tool = new ${grammarname}Tool(); - tool.run(args); + try { + ${grammarname}Tool tool = new ${grammarname}Tool(); + tool.run(args); + } + catch (Exception exception) { + // ensure a sane exit + Log.ensureInitialization(); + Log.error("0xEEEEE an internal error occurred" + + " during the execution of the ${grammarname}Tool." + + System.lineSeparator() + "This error is unexpected" + + " and does not indicate an issue with any provided models.", + exception + ); + } + // properly exit with a code + Log.ensureInitialization(); + System.exit(Log.getErrorCount() == 0 ? 0 : 1); diff --git a/monticore-generator/src/main/resources/_prettyprinter/pp/Block.ftl b/monticore-generator/src/main/resources/_prettyprinter/pp/Block.ftl index 9bfa4843d4..0267749d7d 100644 --- a/monticore-generator/src/main/resources/_prettyprinter/pp/Block.ftl +++ b/monticore-generator/src/main/resources/_prettyprinter/pp/Block.ftl @@ -31,7 +31,7 @@ ${tc.signature("glex", "blockData", "grammarName", "astPackage")} <#if !alt?is_last || alt.getExpressionList()?has_content> <#--> // Simplify else if (true) if ( ${alt.getExpressionConj()} ) - { // opt: ${alt.getOptional()} req: ${alt.getRequired()} + { // opt: ${alt.getOptional()} req: ${alt.getRequired()} #list o:${alt.getOptionalSet()?join(",")} / r:${alt.getRequiredSet()?join(",")} ${includeArgs("Alt", ast, alt, grammarName, astPackage)} } <#sep> <#if !blockData.isNotListButNoElse()>else<#else> /* noelse 1 */ @@ -43,7 +43,7 @@ ${tc.signature("glex", "blockData", "grammarName", "astPackage")} <#if !alt?is_last || alt.getExpressionList()?has_content> <#--> // Simplify else if (true) if ( ${alt.getExpressionConj()} ) - { // opt: ${alt.getOptional()} req: ${alt.getRequired()} + { // opt: ${alt.getOptional()} req: ${alt.getRequired()} #if o:${alt.getOptionalSet()?join(",")} / r:${alt.getRequiredSet()?join(",")} ${includeArgs("Alt", ast, alt, grammarName, astPackage)} } <#sep> <#if !blockData.isNotListButNoElse()>else<#else> /* noelse 2 */ diff --git a/monticore-generator/src/main/resources/_symboltable/artifactscope/ConstructorArtifactScope.ftl b/monticore-generator/src/main/resources/_symboltable/artifactscope/ConstructorArtifactScope.ftl index f4a8262b40..e66c7dd3f8 100644 --- a/monticore-generator/src/main/resources/_symboltable/artifactscope/ConstructorArtifactScope.ftl +++ b/monticore-generator/src/main/resources/_symboltable/artifactscope/ConstructorArtifactScope.ftl @@ -4,8 +4,8 @@ setEnclosingScope(enclosingScope.get()); } setExportingSymbols(true); - Log.errorIfNull(packageName); - Log.errorIfNull(imports); + Preconditions.checkNotNull(packageName); + Preconditions.checkNotNull(imports); if (!packageName.isEmpty()) { this.packageName = packageName.endsWith(".") ? packageName.substring(0, packageName.length() - 1) : packageName; diff --git a/monticore-generator/src/main/resources/_symboltable/globalscope/ConstructorGlobalScope.ftl b/monticore-generator/src/main/resources/_symboltable/globalscope/ConstructorGlobalScope.ftl index 305d4be539..5a800e8335 100644 --- a/monticore-generator/src/main/resources/_symboltable/globalscope/ConstructorGlobalScope.ftl +++ b/monticore-generator/src/main/resources/_symboltable/globalscope/ConstructorGlobalScope.ftl @@ -1,5 +1,5 @@ <#-- (c) https://github.com/MontiCore/monticore */ --> ${tc.signature()} - this.symbolPath = Log.errorIfNull(symbolPath); - this.fileExt = Log.errorIfNull(fileExt); + this.symbolPath = Preconditions.checkNotNull(symbolPath); + this.fileExt = Preconditions.checkNotNull(fileExt); init(); diff --git a/monticore-generator/src/main/resources/_symboltable/iglobalscope/CalculateModelNamesFor.ftl b/monticore-generator/src/main/resources/_symboltable/iglobalscope/CalculateModelNamesFor.ftl index f5bec7533b..d8312d7a57 100644 --- a/monticore-generator/src/main/resources/_symboltable/iglobalscope/CalculateModelNamesFor.ftl +++ b/monticore-generator/src/main/resources/_symboltable/iglobalscope/CalculateModelNamesFor.ftl @@ -1,5 +1,5 @@ <#-- (c) https://github.com/MontiCore/monticore --> - HashSet names = new HashSet<>(); + LinkedHashSet names = new LinkedHashSet<>(); names.add(name); // calculate all prefixes diff --git a/monticore-generator/src/main/resources/_symboltable/iscope/GetSymbolSize.ftl b/monticore-generator/src/main/resources/_symboltable/iscope/GetSymbolSize.ftl index be75e52824..ff7869288b 100644 --- a/monticore-generator/src/main/resources/_symboltable/iscope/GetSymbolSize.ftl +++ b/monticore-generator/src/main/resources/_symboltable/iscope/GetSymbolSize.ftl @@ -1,7 +1,7 @@ <#-- (c) https://github.com/MontiCore/monticore --> ${tc.signature("symbolAttributeNameList")} -Set allSymbols = new HashSet<>(); +Set allSymbols = new LinkedHashSet<>(); <#list symbolAttributeNameList as attrName> allSymbols.addAll(get${attrName?cap_first}().values()); diff --git a/monticore-generator/src/main/resources/_symboltable/scopesgenitor/CreateFromAST.ftl b/monticore-generator/src/main/resources/_symboltable/scopesgenitor/CreateFromAST.ftl index 9fdffbb885..1981f081cc 100644 --- a/monticore-generator/src/main/resources/_symboltable/scopesgenitor/CreateFromAST.ftl +++ b/monticore-generator/src/main/resources/_symboltable/scopesgenitor/CreateFromAST.ftl @@ -1,6 +1,6 @@ <#-- (c) https://github.com/MontiCore/monticore --> ${tc.signature("symtabMill", "artifactScope", "symboltableCreator", "generatedErrorCode")} - Log.errorIfNull(rootNode, "0xA7004${generatedErrorCode} Error by creating of the ${symboltableCreator} symbol table: top ast node is null"); + Preconditions.checkNotNull(rootNode, "0xA7004${generatedErrorCode} Error by creating of the ${symboltableCreator} symbol table: top ast node is null"); I${artifactScope} artifactScope = ${symtabMill}.artifactScope(); artifactScope.setPackageName(""); artifactScope.setImportsList(new ArrayList<>()); diff --git a/monticore-generator/src/main/resources/_symboltable/scopesgenitor/PutOnStack.ftl b/monticore-generator/src/main/resources/_symboltable/scopesgenitor/PutOnStack.ftl index 6e1015908b..91b044fb47 100644 --- a/monticore-generator/src/main/resources/_symboltable/scopesgenitor/PutOnStack.ftl +++ b/monticore-generator/src/main/resources/_symboltable/scopesgenitor/PutOnStack.ftl @@ -1,5 +1,5 @@ <#-- (c) https://github.com/MontiCore/monticore --> - Log.errorIfNull(scope); + Preconditions.checkNotNull(scope); if (scope.getEnclosingScope() == null && getCurrentScope().isPresent()) { scope.setEnclosingScope(getCurrentScope().get()); diff --git a/monticore-generator/src/main/resources/_symboltable/serialization/scopeDeSer/DeserializeSymbols.ftl b/monticore-generator/src/main/resources/_symboltable/serialization/scopeDeSer/DeserializeSymbols.ftl index 0c99573eb3..1e628e408d 100644 --- a/monticore-generator/src/main/resources/_symboltable/serialization/scopeDeSer/DeserializeSymbols.ftl +++ b/monticore-generator/src/main/resources/_symboltable/serialization/scopeDeSer/DeserializeSymbols.ftl @@ -26,7 +26,7 @@ ${tc.signature("symbolMap", "mill", "errorCode", "scopeDeserName", "scopeInterfa } <#assign count=0> <#list symbolMap?keys as kind> - else if ("${kind}".equals(kind) + else if ("${kind}".equals(kind.get()) || "${kind}".equals(deSer.getSerializedKind())) { ${kind} s${count} = (${kind}) deSer.deserialize(scope, symbol); scope.add(s${count}); diff --git a/monticore-generator/src/main/resources/_symboltable/symbol/Equals.ftl b/monticore-generator/src/main/resources/_symboltable/symbol/Equals.ftl new file mode 100644 index 0000000000..662e65a586 --- /dev/null +++ b/monticore-generator/src/main/resources/_symboltable/symbol/Equals.ftl @@ -0,0 +1,10 @@ +<#-- (c) https://github.com/MontiCore/monticore --> +${tc.signature("symbolName")} + + if(!(obj instanceof ${symbolName})) { + return false; + } + ${symbolName} s1 = getThis(); + ${symbolName} s2 = ((${symbolName}) obj).getThis(); + + return s1 == s2; diff --git a/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/Equals.ftl b/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/Equals.ftl new file mode 100644 index 0000000000..f41faac75a --- /dev/null +++ b/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/Equals.ftl @@ -0,0 +1,12 @@ +<#-- (c) https://github.com/MontiCore/monticore --> +${tc.signature("symbolName")} + + if(checkLazyLoadDelegate()) { + if(!(obj instanceof ${symbolName})) { + return false; + } + + return lazyLoadDelegate().equals(((${symbolName}) obj).getThis()); + } + + return super.equals(obj); \ No newline at end of file diff --git a/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/GetSpannedScopeSymbolSurrogate.ftl b/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/GetSpannedScopeSymbolSurrogate.ftl new file mode 100644 index 0000000000..2646f8f9e3 --- /dev/null +++ b/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/GetSpannedScopeSymbolSurrogate.ftl @@ -0,0 +1,6 @@ +<#-- (c) https://github.com/MontiCore/monticore --> +${tc.signature("scopeName")} + if (!checkLazyLoadDelegate()) { + return (${scopeName}) spannedScope; + } + return lazyLoadDelegate().getSpannedScope(); diff --git a/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/GetThis.ftl b/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/GetThis.ftl new file mode 100644 index 0000000000..e5eb8c760a --- /dev/null +++ b/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/GetThis.ftl @@ -0,0 +1,7 @@ +<#-- (c) https://github.com/MontiCore/monticore --> +${tc.signature("symbolName")} + + if(checkLazyLoadDelegate()) { + return lazyLoadDelegate(); + } + return (${symbolName}) this; diff --git a/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/SetSpannedScopeSymbolSurrogate.ftl b/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/SetSpannedScopeSymbolSurrogate.ftl new file mode 100644 index 0000000000..5bb21a6b58 --- /dev/null +++ b/monticore-generator/src/main/resources/_symboltable/symbolsurrogate/SetSpannedScopeSymbolSurrogate.ftl @@ -0,0 +1,5 @@ +<#-- (c) https://github.com/MontiCore/monticore --> +${tc.signature("scopeName")} +if(checkLazyLoadDelegate()) { + lazyLoadDelegate().setSpannedScope((${scopeName}) scope); +} diff --git a/monticore-generator/src/main/resources/dstlgen/MainClass.ftl b/monticore-generator/src/main/resources/dstlgen/MainClass.ftl index e21eaf66a3..ff25939170 100644 --- a/monticore-generator/src/main/resources/dstlgen/MainClass.ftl +++ b/monticore-generator/src/main/resources/dstlgen/MainClass.ftl @@ -60,9 +60,10 @@ public class ${className} { // do not continue, when this error is logged return; } - + + ${dstlName}Mill.reset(); ${dstlName}Mill.init(); - + Log.debug("----- Starting Transformation Generation -----", LOG_ID); Log.debug("Input file : " + cmd.getOptionValue("i"), LOG_ID); Log.debug("Output dir : " + cmd.getOptionValue("o", "out"), LOG_ID); @@ -84,11 +85,13 @@ public class ${className} { } catch ( ParseException e) { // an unexpected error from the Apache CLI parser: Log.error("0xA6153${service.getGeneratedErrorCode(classname)} Could not process CLI parameters: " + e.getMessage()); - } + } finally { + ${dstlName}Mill.reset(); + ODRulesMill.reset(); + } } public Optional parseRule(Path model) { - ${dstlName}Mill.init(); Log.debug("Start parsing of the model " + model, LOG_ID); try { ${dstlName}Parser parser = new ${dstlName}Parser(); @@ -119,6 +122,12 @@ public class ${className} { Log.debug("Starting odrule generation ", LOG_ID); ModelTraversal<${dstlName}Traverser> mt = ModelTraversalFactory.getInstance().create((java.util.function.Supplier)${dstlName}Mill::inheritanceTraverser); ast.accept(mt.getTraverser()); + + Log.debug("Switching to OD ", LOG_ID); + // Switch language to OD + ODRulesMill.reset(); + ODRulesMill.init(); + Log.debug("Starting rule2odstate ", LOG_ID); Rule2ODState state = new Rule2ODState(new Variable2AttributeMap(), mt.getParents()); state.getGenRule().setGrammarPackageList(Arrays.asList("${grammarPackage}".split("\\."))); @@ -126,10 +135,6 @@ public class ${className} { ${grammarName}RuleCollectVariables variables = new ${grammarName}RuleCollectVariables(state); ${grammarName}Rule2OD rule2OD = new ${grammarName}Rule2OD(state); - Log.debug("Switching to OD ", LOG_ID); - // Switch language to OD - ODRulesMill.init(); - ast.accept(variables.getTraverser()); ast.accept(rule2OD.getTraverser()); diff --git a/monticore-generator/src/main/resources/dstlgen/cocos/CoCoVisitorBuilder.ftl b/monticore-generator/src/main/resources/dstlgen/cocos/CoCoVisitorBuilder.ftl index 6a87686e34..f5a5f5fbc7 100644 --- a/monticore-generator/src/main/resources/dstlgen/cocos/CoCoVisitorBuilder.ftl +++ b/monticore-generator/src/main/resources/dstlgen/cocos/CoCoVisitorBuilder.ftl @@ -6,7 +6,7 @@ import ${package}.${grammarNameLower}tr._visitor.*; import ${package}.${grammarNameLower}tr._ast.*; import ${package}.${grammarNameLower}tr.${ast.getName()}TRMill; import de.monticore.tf.tfcommons._ast.ASTTfIdentifier; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Set; import de.monticore.tf.grammartransformation.CollectCoCoInformationState; import de.monticore.tf.tfcommons._ast.ASTITFPart; diff --git a/monticore-generator/src/main/resources/dstlgen/cocos/CollectRHSVariablesVisitor.ftl b/monticore-generator/src/main/resources/dstlgen/cocos/CollectRHSVariablesVisitor.ftl index 88b71c958d..2d62821144 100644 --- a/monticore-generator/src/main/resources/dstlgen/cocos/CollectRHSVariablesVisitor.ftl +++ b/monticore-generator/src/main/resources/dstlgen/cocos/CollectRHSVariablesVisitor.ftl @@ -6,7 +6,6 @@ import ${package}.${grammarNameLower}tr._visitor.*; import ${package}.${grammarNameLower}tr._ast.*; import ${package}.${grammarNameLower}tr.${ast.getName()}TRMill; import de.monticore.tf.tfcommons._ast.ASTTfIdentifier; -import java.util.HashSet; import java.util.Set; import de.monticore.tf.grammartransformation.CollectCoCoInformationState; import de.monticore.tf.tfcommons._ast.ASTITFPart; diff --git a/monticore-generator/src/main/resources/dstlgen/cocos/DiffSchemaVarTypeVisitor.ftl b/monticore-generator/src/main/resources/dstlgen/cocos/DiffSchemaVarTypeVisitor.ftl index 2746bb41d1..8f8acb0479 100644 --- a/monticore-generator/src/main/resources/dstlgen/cocos/DiffSchemaVarTypeVisitor.ftl +++ b/monticore-generator/src/main/resources/dstlgen/cocos/DiffSchemaVarTypeVisitor.ftl @@ -7,7 +7,7 @@ import ${package}.${grammarNameLower}tr._ast.*; import ${package}.${grammarNameLower}tr._visitor.*; import ${package}.${grammarNameLower}tr.${ast.getName()}TRMill; import java.util.ArrayList; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import de.monticore.tf.tfcommons._ast.ASTITFPart; @@ -21,7 +21,7 @@ public class ${className} implements ${ast.getName()}TRVisitor2, ${ast.getName() List variables = new ArrayList<>(); <#list productions as prod> - Map vars${prod.getName()}_Pat = new HashMap<>(); + Map vars${prod.getName()}_Pat = new LinkedHashMap<>(); public final ${ast.getName()}TRTraverser traverser; diff --git a/monticore-generator/src/main/resources/mill/GetMillMethod.ftl b/monticore-generator/src/main/resources/mill/GetMillMethod.ftl index 453ecc7089..3b2fbc74fc 100644 --- a/monticore-generator/src/main/resources/mill/GetMillMethod.ftl +++ b/monticore-generator/src/main/resources/mill/GetMillMethod.ftl @@ -1,6 +1,9 @@ <#-- (c) https://github.com/MontiCore/monticore --> ${tc.signature("millName")} if (mill == null) { + // Soon: throw new IllegalStateException("0x70001: A mill was used before initialization"); + // For now: Only log a deprecation-warning to std err (to avoid creating findings) + System.err.println("0x70001: Warning: The ${millName} was used before initialization. This access is deprecated!"); mill = new ${millName}(); } - return mill; \ No newline at end of file + return mill; diff --git a/monticore-generator/src/main/resources/mill/InitMeMethod.ftl b/monticore-generator/src/main/resources/mill/InitMeMethod.ftl index 3728ba2ba4..37d3fdc682 100644 --- a/monticore-generator/src/main/resources/mill/InitMeMethod.ftl +++ b/monticore-generator/src/main/resources/mill/InitMeMethod.ftl @@ -1,3 +1,11 @@ <#-- (c) https://github.com/MontiCore/monticore --> ${tc.signature()} + if (mill != null) { + // Soon: Log.error("0x70002: Warning: This mill is being initialized multiple times - Ensure to reset Mills after tests/tools/etc"); + // Soon: throw new IllegalStateException("0x70002: Warning: This mill is being initialized multiple times - Ensure to reset Mills after tests/tools/etc."); + // For now: Only log a warning to log#debug + Log.debug("0x70002: Warning: This mill is being initialized multiple times - Ensure to reset Mills after tests/tools/etc.", "Mill0x70002"); + // Do not print this warning until "https://git.rwth-aachen.de/monticore/monticore/-/issues/4687" has been decided + // and a solution to this problem (of multi-mill-initialization) can be proposed + } mill = a; \ No newline at end of file diff --git a/monticore-generator/src/main/resources/parser/Lexer.ftl b/monticore-generator/src/main/resources/parser/Lexer.ftl index 6ddf50ea02..bfa45c19cd 100644 --- a/monticore-generator/src/main/resources/parser/Lexer.ftl +++ b/monticore-generator/src/main/resources/parser/Lexer.ftl @@ -13,7 +13,7 @@ ${tc.includeArgs("parser.LexerMember", [antlrGenerator, parserHelper.getGrammarS // Implicit token <#list genHelper.getLexSymbolsWithInherited() as lexSymbol> - ${genHelper.getOrComputeLexSymbolName(lexSymbol)} : '${genHelper.escapeSingleQuote(lexSymbol)}'; + ${genHelper.getOrComputeLexSymbolName(lexSymbol)} : '${genHelper.unescapeDoubleQuote(genHelper.escapeSingleQuote(lexSymbol))}'; // Explicit token diff --git a/monticore-generator/src/main/resources/parser/ParserInfo.ftl b/monticore-generator/src/main/resources/parser/ParserInfo.ftl index c4683e9976..d802de8a49 100644 --- a/monticore-generator/src/main/resources/parser/ParserInfo.ftl +++ b/monticore-generator/src/main/resources/parser/ParserInfo.ftl @@ -20,7 +20,7 @@ public class ${ast.getName()}ParserInfo { <#if states?size == 0> = Collections.emptySet(); <#else> - = new HashSet<>(Arrays.asList( + = new LinkedHashSet<>(Arrays.asList( <#list states as state> ${state?c}<#if state?has_next>, @@ -36,7 +36,7 @@ public class ${ast.getName()}ParserInfo { <#if states?size == 0> = Collections.emptySet(); <#else> - = new HashSet<>(Arrays.asList( + = new LinkedHashSet<>(Arrays.asList( <#list states as state> ${state?c}<#if state?has_next>, @@ -51,7 +51,7 @@ public class ${ast.getName()}ParserInfo { <#if nameDefiningStates?size == 0> = Collections.emptySet(); <#else> - = new HashSet<>(Arrays.asList( + = new LinkedHashSet<>(Arrays.asList( <#list nameDefiningStates as state> ${state?c}<#if state?has_next>, diff --git a/monticore-generator/src/test/java/de/monticore/MCGrammarLanguageFamilySymbolTableTest.java b/monticore-generator/src/test/java/de/monticore/MCGrammarLanguageFamilySymbolTableTest.java index 99bb72ae25..6dd3c81667 100644 --- a/monticore-generator/src/test/java/de/monticore/MCGrammarLanguageFamilySymbolTableTest.java +++ b/monticore-generator/src/test/java/de/monticore/MCGrammarLanguageFamilySymbolTableTest.java @@ -8,15 +8,14 @@ import de.monticore.io.paths.MCPath; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCGrammarLanguageFamilySymbolTableTest { @@ -37,17 +36,17 @@ public void testSymbolTableOfGrammarStatechartDSL() { final Optional oldGrammar = globalScope.resolveMCGrammar("de.monticore.statechart.Statechart"); - Assertions.assertTrue(oldGrammar.isPresent()); + assertTrue(oldGrammar.isPresent()); final Optional newGrammar = globalScope.resolveMCGrammar("de.monticore.statechart.Statechart"); - Assertions.assertTrue(newGrammar.isPresent()); + assertTrue(newGrammar.isPresent()); // 2 = Statechart grammar symbol and TestLexicals grammar symbol (super grammar of Statechart) - Assertions.assertEquals(1, globalScope.getSubScopes().size()); + assertEquals(1, globalScope.getSubScopes().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-generator/src/test/java/de/monticore/MontiCoreScriptTest.java b/monticore-generator/src/test/java/de/monticore/MontiCoreScriptTest.java index 0a9b0ca050..1991ef3002 100644 --- a/monticore-generator/src/test/java/de/monticore/MontiCoreScriptTest.java +++ b/monticore-generator/src/test/java/de/monticore/MontiCoreScriptTest.java @@ -23,10 +23,10 @@ import de.monticore.grammar.grammar_withconcepts._symboltable.Grammar_WithConceptsGlobalScope; import de.monticore.grammar.grammar_withconcepts._symboltable.IGrammar_WithConceptsGlobalScope; import de.monticore.io.paths.MCPath; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.apache.commons.cli.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,6 +40,7 @@ import static de.monticore.MontiCoreConfiguration.*; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; +import static org.junit.jupiter.api.Assertions.*; /** * Test for the {@link MontiCoreScript} class. @@ -95,7 +96,7 @@ public void init() { Optional ast = new MontiCoreScript() .parseGrammar(Paths.get(new File( "src/test/resources/de/monticore/statechart/Statechart.mc4").getAbsolutePath())); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); grammar = ast.get(); } @@ -104,18 +105,18 @@ public void init() { */ @Test public void testParseGrammar() { - Assertions.assertNotNull(grammar); - Assertions.assertEquals("Statechart", grammar.getName()); + assertNotNull(grammar); + assertEquals("Statechart", grammar.getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } /** - * {@link MontiCoreScript#generateParser(GlobalExtensionManagement, ASTCDCompilationUnit, ASTMCGrammar, Grammar_WithConceptsGlobalScope, MCPath, MCPath, File)} + * {@link MontiCoreScript#generateParser(GlobalExtensionManagement, ASTCDCompilationUnit, ASTMCGrammar, IGrammar_WithConceptsGlobalScope, MCPath, MCPath, File)} */ @Test public void testGenerateParser() { - Assertions.assertNotNull(grammar); + assertNotNull(grammar); MontiCoreScript mc = new MontiCoreScript(); IGrammar_WithConceptsGlobalScope symbolTable = TestHelper.createGlobalScope(modelPath); mc.createSymbolsFromAST(symbolTable, grammar); @@ -126,7 +127,7 @@ public void testGenerateParser() { new MCPath(), f); f.delete(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -136,11 +137,11 @@ public void testGetOrCreateCD() { mc.createSymbolsFromAST(symbolTable, grammar); ICD4AnalysisGlobalScope cd4AGlobalScope = mc.createCD4AGlobalScope(modelPath); cdCompilationUnit = mc.getOrCreateCD(grammar, new GlobalExtensionManagement(), cd4AGlobalScope); - Assertions.assertNotNull(cdCompilationUnit); - Assertions.assertNotNull(cdCompilationUnit.getCDDefinition()); - Assertions.assertEquals("Statechart", cdCompilationUnit.getCDDefinition().getName()); + assertNotNull(cdCompilationUnit); + assertNotNull(cdCompilationUnit.getCDDefinition()); + assertEquals("Statechart", cdCompilationUnit.getCDDefinition().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -150,11 +151,11 @@ public void testDeriveASTCD() { mc.createSymbolsFromAST(symbolTable, grammar); ICD4AnalysisGlobalScope cd4AGlobalScope = mc.createCD4AGlobalScope(modelPath); cdCompilationUnit = mc.deriveASTCD(grammar, new GlobalExtensionManagement(), cd4AGlobalScope); - Assertions.assertNotNull(cdCompilationUnit); - Assertions.assertNotNull(cdCompilationUnit.getCDDefinition()); - Assertions.assertEquals("Statechart", cdCompilationUnit.getCDDefinition().getName()); + assertNotNull(cdCompilationUnit); + assertNotNull(cdCompilationUnit.getCDDefinition()); + assertEquals("Statechart", cdCompilationUnit.getCDDefinition().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -164,16 +165,16 @@ public void testDecorateCd() { mc.createSymbolsFromAST(symbolTable, grammar); ICD4AnalysisGlobalScope cd4AGlobalScope = mc.createCD4AGlobalScope(modelPath); cdCompilationUnit = mc.deriveASTCD(grammar, new GlobalExtensionManagement(), cd4AGlobalScope); - Assertions.assertNotNull(cdCompilationUnit); - Assertions.assertEquals("de.monticore.statechart", String.join(".", cdCompilationUnit.getCDPackageList())); - Assertions.assertNotNull(cdCompilationUnit.getCDDefinition()); + assertNotNull(cdCompilationUnit); + assertEquals("de.monticore.statechart", String.join(".", cdCompilationUnit.getCDPackageList())); + assertNotNull(cdCompilationUnit.getCDDefinition()); ASTCDDefinition cdDefinition = cdCompilationUnit.getCDDefinition(); - Assertions.assertEquals(8, cdDefinition.getCDClassesList().size()); - Assertions.assertEquals(5, cdDefinition.getCDInterfacesList().size()); + assertEquals(8, cdDefinition.getCDClassesList().size()); + assertEquals(5, cdDefinition.getCDInterfacesList().size()); ASTCDCompilationUnit astcdCompilationUnit = mc.decorateForASTPackage(glex, cd4AGlobalScope, cdCompilationUnit, hwPath); // Added Builder classes to the each not list class - Assertions.assertEquals(17, astcdCompilationUnit.getCDDefinition().getCDClassesList().size()); + assertEquals(17, astcdCompilationUnit.getCDDefinition().getCDClassesList().size()); // Check if there are all additional methods defined in the given CD class List methods = Lists.newArrayList(); @@ -185,31 +186,31 @@ public void testDecorateCd() { String withOrder = "WithOrder"; for (String additionalMethod : additionalMethods) { if (additionalMethod.endsWith(withOrder)) { - Assertions.assertTrue(methods.contains(additionalMethod.substring(0, + assertTrue(methods.contains(additionalMethod.substring(0, additionalMethod.indexOf(withOrder)))); } else { - Assertions.assertTrue(methods.contains(additionalMethod)); + assertTrue(methods.contains(additionalMethod)); } } } - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void testDefaultScriptSimpleArgs() { Log.getFindings().clear(); testDefaultScript(simpleArgs); - Assertions.assertEquals(0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount()); // test whether the original template is used try { List lines = Files.readAllLines(Paths.get(outputPath.getAbsolutePath() + "/de/monticore/statechart/statechart/_ast/ASTState.java")); - Assertions.assertFalse(lines.stream().filter(l -> "// Test:Replace Template".equals(l)).findAny().isPresent()); + assertFalse(lines.stream().filter(l -> "// Test:Replace Template".equals(l)).findAny().isPresent()); } catch (Exception e) { - Assertions.fail(); + fail(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } static String[] templateArgs = {"-" + GRAMMAR, @@ -223,16 +224,16 @@ public void testDefaultScriptSimpleArgs() { public void testDefaultScriptTemplateArgs() { Log.getFindings().clear(); testDefaultScript(templateArgs); - Assertions.assertEquals(0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount()); // test whether the changed template is used try { List lines = Files.readAllLines(Paths.get(outputPath.getAbsolutePath() + "/de/monticore/statechart/statechart/_ast/ASTState.java")); - Assertions.assertTrue(lines.stream().filter(l -> "// Test:Replace Template".equals(l)).findAny().isPresent()); + assertTrue(lines.stream().filter(l -> "// Test:Replace Template".equals(l)).findAny().isPresent()); } catch (Exception e) { - Assertions.fail(); + fail(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } static String[] subsubgrammarArgs = {"-" + GRAMMAR, @@ -244,18 +245,14 @@ public void testDefaultScriptTemplateArgs() { public void testDefaultScriptSubsubgrammarArgs() { Log.getFindings().clear(); testDefaultScript(subsubgrammarArgs); - Assertions.assertEquals(0, Log.getErrorCount()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void testDefaultScriptSubsubgrammarArgs_EMF() { Log.getFindings().clear(); testDefaultScriptWithEmf(subsubgrammarArgs); - Assertions.assertEquals(0, Log.getErrorCount()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } static String[] inheritedgrammarArgs = {"-" + GRAMMAR, @@ -269,14 +266,14 @@ public void testDefaultScriptSubsubgrammarArgs_EMF() { public void testDefaultScriptSupergrammarArgs() { Log.getFindings().clear(); testDefaultScript(inheritedgrammarArgs); - Assertions.assertEquals(0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount()); } @Test public void testDefaultScriptSupergrammarArgs_EMF() { Log.getFindings().clear(); testDefaultScriptWithEmf(inheritedgrammarArgs); - Assertions.assertEquals(0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount()); } static String[] supersubgrammarArgs = {"-" + GRAMMAR, @@ -289,18 +286,14 @@ public void testDefaultScriptSupergrammarArgs_EMF() { public void testDefaultScriptSupersubgrammarArgs() { Log.getFindings().clear(); testDefaultScript(supersubgrammarArgs); - Assertions.assertEquals(0, Log.getErrorCount()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void testDefaultScriptSupersubgrammarArgs_EMF() { Log.getFindings().clear(); testDefaultScriptWithEmf(supersubgrammarArgs); - Assertions.assertEquals(0, Log.getErrorCount()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } private void testDefaultScript(String[] args) { @@ -318,7 +311,6 @@ private void testDefaultScript(String[] args) { // Reporting is enabled in the monticore_standard.groovy script but needs to be disabled for other tests // because Reporting is static directly disable it again here Reporting.off(); - Assertions.assertTrue(!false); } private void testDefaultScriptWithEmf(String[] args) { @@ -336,7 +328,7 @@ private void testDefaultScriptWithEmf(String[] args) { // Reporting is enabled in the monticore_standard.groovy script but needs to be disabled for other tests // because Reporting is static directly disable it again here Reporting.off(); - Assertions.assertTrue(!false); + assertTrue(!false); } @Test @@ -347,21 +339,21 @@ public void testDeriveSymbolCD() { ICD4AnalysisGlobalScope cd4AGlobalScope = mc.createCD4AGlobalScope(modelPath); ASTCDCompilationUnit cdCompilationUnit = mc.deriveSymbolCD(grammar, cd4AGlobalScope); // check directly created scope - Assertions.assertNotNull(cdCompilationUnit); - Assertions.assertNotNull(cdCompilationUnit.getCDDefinition()); - Assertions.assertEquals("StatechartSymbols", cdCompilationUnit.getCDDefinition().getName()); + assertNotNull(cdCompilationUnit); + assertNotNull(cdCompilationUnit.getCDDefinition()); + assertEquals("StatechartSymbols", cdCompilationUnit.getCDDefinition().getName()); // no symbol defined - Assertions.assertEquals(0, cdCompilationUnit.getCDDefinition().getCDClassesList().size()); + assertEquals(0, cdCompilationUnit.getCDDefinition().getCDClassesList().size()); // check saved cd for grammar ASTCDCompilationUnit symbolCDOfParsedGrammar = mc.getSymbolCDOfParsedGrammar(grammar); - Assertions.assertNotNull(symbolCDOfParsedGrammar); - Assertions.assertNotNull(symbolCDOfParsedGrammar.getCDDefinition()); - Assertions.assertEquals("StatechartSymbols", symbolCDOfParsedGrammar.getCDDefinition().getName()); + assertNotNull(symbolCDOfParsedGrammar); + assertNotNull(symbolCDOfParsedGrammar.getCDDefinition()); + assertEquals("StatechartSymbols", symbolCDOfParsedGrammar.getCDDefinition().getName()); // no symbol defined - Assertions.assertEquals(0, symbolCDOfParsedGrammar.getCDDefinition().getCDClassesList().size()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(0, symbolCDOfParsedGrammar.getCDDefinition().getCDClassesList().size()); + + MCAssertions.assertNoFindings(); } @Test @@ -372,21 +364,21 @@ public void testDeriveScopeCD() { ICD4AnalysisGlobalScope cd4AGlobalScope = mc.createCD4AGlobalScope(modelPath); ASTCDCompilationUnit cdCompilationUnit = mc.deriveScopeCD(grammar, cd4AGlobalScope); // test normal created scope cd - Assertions.assertNotNull(cdCompilationUnit); - Assertions.assertNotNull(cdCompilationUnit.getCDDefinition()); - Assertions.assertEquals("StatechartScope", cdCompilationUnit.getCDDefinition().getName()); - Assertions.assertEquals(1, cdCompilationUnit.getCDDefinition().getCDClassesList().size()); - Assertions.assertEquals("Statechart", cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getName()); + assertNotNull(cdCompilationUnit); + assertNotNull(cdCompilationUnit.getCDDefinition()); + assertEquals("StatechartScope", cdCompilationUnit.getCDDefinition().getName()); + assertEquals(1, cdCompilationUnit.getCDDefinition().getCDClassesList().size()); + assertEquals("Statechart", cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getName()); // test correct saved scope cd ASTCDCompilationUnit scopeCDOfParsedGrammar = mc.getScopeCDOfParsedGrammar(grammar); - Assertions.assertNotNull(scopeCDOfParsedGrammar); - Assertions.assertNotNull(scopeCDOfParsedGrammar.getCDDefinition()); - Assertions.assertEquals("StatechartScope", scopeCDOfParsedGrammar.getCDDefinition().getName()); - Assertions.assertEquals(1, scopeCDOfParsedGrammar.getCDDefinition().getCDClassesList().size()); - Assertions.assertEquals("Statechart", scopeCDOfParsedGrammar.getCDDefinition().getCDClassesList().get(0).getName()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertNotNull(scopeCDOfParsedGrammar); + assertNotNull(scopeCDOfParsedGrammar.getCDDefinition()); + assertEquals("StatechartScope", scopeCDOfParsedGrammar.getCDDefinition().getName()); + assertEquals(1, scopeCDOfParsedGrammar.getCDDefinition().getCDClassesList().size()); + assertEquals("Statechart", scopeCDOfParsedGrammar.getCDDefinition().getCDClassesList().get(0).getName()); + + MCAssertions.assertNoFindings(); } @Test @@ -397,26 +389,26 @@ public void testAddListSuffixToAttributeName() { ICD4AnalysisGlobalScope cd4AGlobalScope = mc.createCD4AGlobalScope(modelPath); ASTCDCompilationUnit cdCompilationUnit = mc.deriveASTCD(grammar, new GlobalExtensionManagement(), cd4AGlobalScope); - Assertions.assertNotNull(cdCompilationUnit); - Assertions.assertNotNull(cdCompilationUnit.getCDDefinition()); - Assertions.assertEquals("Statechart", cdCompilationUnit.getCDDefinition().getName()); + assertNotNull(cdCompilationUnit); + assertNotNull(cdCompilationUnit.getCDDefinition()); + assertEquals("Statechart", cdCompilationUnit.getCDDefinition().getName()); ASTCDClass stateChartClass = cdCompilationUnit.getCDDefinition().getCDClassesList().get(0); - Assertions.assertEquals("ASTStatechart", stateChartClass.getName()); - Assertions.assertEquals("state", stateChartClass.getCDAttributeList().get(1).getName()); + assertEquals("ASTStatechart", stateChartClass.getName()); + assertEquals("state", stateChartClass.getCDAttributeList().get(1).getName()); // add list suffix ASTCDCompilationUnit listSuffixCD = mc.addListSuffixToAttributeName(cdCompilationUnit); - Assertions.assertNotNull(listSuffixCD); - Assertions.assertNotNull(listSuffixCD.getCDDefinition()); - Assertions.assertEquals("Statechart", listSuffixCD.getCDDefinition().getName()); + assertNotNull(listSuffixCD); + assertNotNull(listSuffixCD.getCDDefinition()); + assertEquals("Statechart", listSuffixCD.getCDDefinition().getName()); ASTCDClass listSuffixStateChartClass = listSuffixCD.getCDDefinition().getCDClassesList().get(0); - Assertions.assertEquals("ASTStatechart", listSuffixStateChartClass.getName()); + assertEquals("ASTStatechart", listSuffixStateChartClass.getName()); assertDeepEquals("java.util.List", listSuffixStateChartClass.getCDAttributeList().get(1).getMCType()); // attribute with 's' at the end now - Assertions.assertEquals("states", listSuffixStateChartClass.getCDAttributeList().get(1).getName()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("states", listSuffixStateChartClass.getCDAttributeList().get(1).getName()); + + MCAssertions.assertNoFindings(); } @Test @@ -436,28 +428,28 @@ public void testDecorateForSymbolTablePackage() { MCPath handcodedPath = new MCPath("src/test/resources"); mc.decorateForSymbolTablePackage(glex, cd4AGlobalScope, cd, symbolCD, scopeCD, symbolPackageCD, handcodedPath); - Assertions.assertNotNull(symbolPackageCD); - Assertions.assertNotNull(symbolPackageCD.getCDDefinition()); - Assertions.assertEquals("Statechart", symbolPackageCD.getCDDefinition().getName()); + assertNotNull(symbolPackageCD); + assertNotNull(symbolPackageCD.getCDDefinition()); + assertEquals("Statechart", symbolPackageCD.getCDDefinition().getName()); int index = 0; - Assertions.assertEquals(7, symbolPackageCD.getCDDefinition().getCDClassesList().size()); - Assertions.assertEquals("StatechartScope", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); - Assertions.assertEquals("StatechartSymbols2Json", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); - Assertions.assertEquals("StatechartScopesGenitorDelegator", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); - Assertions.assertEquals("StatechartArtifactScope", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); - Assertions.assertEquals("StatechartDeSer", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); - Assertions.assertEquals("StatechartGlobalScope", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); - Assertions.assertEquals("StatechartScopesGenitor", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); + assertEquals(7, symbolPackageCD.getCDDefinition().getCDClassesList().size()); + assertEquals("StatechartScope", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); + assertEquals("StatechartSymbols2Json", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); + assertEquals("StatechartScopesGenitorDelegator", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); + assertEquals("StatechartArtifactScope", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); + assertEquals("StatechartDeSer", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); + assertEquals("StatechartGlobalScope", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); + assertEquals("StatechartScopesGenitor", symbolPackageCD.getCDDefinition().getCDClassesList().get(index++).getName()); index = 0; - Assertions.assertEquals(4, symbolPackageCD.getCDDefinition().getCDInterfacesList().size()); - Assertions.assertEquals("IStatechartScope", symbolPackageCD.getCDDefinition().getCDInterfacesList().get(index++).getName()); - Assertions.assertEquals("ICommonStatechartSymbol", symbolPackageCD.getCDDefinition().getCDInterfacesList().get(index++).getName()); - Assertions.assertEquals("IStatechartGlobalScope", symbolPackageCD.getCDDefinition().getCDInterfacesList().get(index++).getName()); - Assertions.assertEquals("IStatechartArtifactScope", symbolPackageCD.getCDDefinition().getCDInterfacesList().get(index++).getName()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(4, symbolPackageCD.getCDDefinition().getCDInterfacesList().size()); + assertEquals("IStatechartScope", symbolPackageCD.getCDDefinition().getCDInterfacesList().get(index++).getName()); + assertEquals("ICommonStatechartSymbol", symbolPackageCD.getCDDefinition().getCDInterfacesList().get(index++).getName()); + assertEquals("IStatechartGlobalScope", symbolPackageCD.getCDDefinition().getCDInterfacesList().get(index++).getName()); + assertEquals("IStatechartArtifactScope", symbolPackageCD.getCDDefinition().getCDInterfacesList().get(index++).getName()); + + MCAssertions.assertNoFindings(); } @Test @@ -474,18 +466,18 @@ public void testDecorateForVisitorPackage() { mc.configureGenerator(glex,visitorPackageCD, templatePath); mc.decorateTraverserForVisitorPackage(glex, cd4AGlobalScope, cd, visitorPackageCD, handcodedPath); - Assertions.assertNotNull(visitorPackageCD); - Assertions.assertNotNull(visitorPackageCD.getCDDefinition()); - Assertions.assertEquals("Statechart", visitorPackageCD.getCDDefinition().getName()); - Assertions.assertEquals(2, visitorPackageCD.getCDDefinition().getCDClassesList().size()); - Assertions.assertEquals("StatechartTraverserImplementation", visitorPackageCD.getCDDefinition().getCDClassesList().get(0).getName()); - Assertions.assertEquals("StatechartInheritanceHandler", visitorPackageCD.getCDDefinition().getCDClassesList().get(1).getName()); - Assertions.assertEquals(3, visitorPackageCD.getCDDefinition().getCDInterfacesList().size()); - Assertions.assertEquals("StatechartTraverser", visitorPackageCD.getCDDefinition().getCDInterfacesList().get(0).getName()); - Assertions.assertEquals("StatechartVisitor2", visitorPackageCD.getCDDefinition().getCDInterfacesList().get(1).getName()); - Assertions.assertEquals("StatechartHandler", visitorPackageCD.getCDDefinition().getCDInterfacesList().get(2).getName()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertNotNull(visitorPackageCD); + assertNotNull(visitorPackageCD.getCDDefinition()); + assertEquals("Statechart", visitorPackageCD.getCDDefinition().getName()); + assertEquals(2, visitorPackageCD.getCDDefinition().getCDClassesList().size()); + assertEquals("StatechartTraverserImplementation", visitorPackageCD.getCDDefinition().getCDClassesList().get(0).getName()); + assertEquals("StatechartInheritanceHandler", visitorPackageCD.getCDDefinition().getCDClassesList().get(1).getName()); + assertEquals(3, visitorPackageCD.getCDDefinition().getCDInterfacesList().size()); + assertEquals("StatechartTraverser", visitorPackageCD.getCDDefinition().getCDInterfacesList().get(0).getName()); + assertEquals("StatechartVisitor2", visitorPackageCD.getCDDefinition().getCDInterfacesList().get(1).getName()); + assertEquals("StatechartHandler", visitorPackageCD.getCDDefinition().getCDInterfacesList().get(2).getName()); + + MCAssertions.assertNoFindings(); } @Test @@ -501,27 +493,27 @@ public void testDecorateForCoCoPackage() { ASTCDCompilationUnit cocoPackageCD = createEmptyCompilationUnit(cd); mc.decorateForCoCoPackage(glex, cd4AGlobalScope, cd, cocoPackageCD, handcodedPath); - Assertions.assertNotNull(cocoPackageCD); - Assertions.assertNotNull(cocoPackageCD.getCDDefinition()); - Assertions.assertEquals("Statechart", cocoPackageCD.getCDDefinition().getName()); - Assertions.assertEquals(1, cocoPackageCD.getCDDefinition().getCDClassesList().size()); - Assertions.assertEquals("StatechartCoCoChecker", cocoPackageCD.getCDDefinition().getCDClassesList().get(0).getName()); - Assertions.assertEquals(13, cocoPackageCD.getCDDefinition().getCDInterfacesList().size()); - Assertions.assertEquals("StatechartASTStatechartCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(0).getName()); - Assertions.assertEquals("StatechartASTEntryActionCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(1).getName()); - Assertions.assertEquals("StatechartASTExitActionCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(2).getName()); - Assertions.assertEquals("StatechartASTStateCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(3).getName()); - Assertions.assertEquals("StatechartASTTransitionCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(4).getName()); - Assertions.assertEquals("StatechartASTArgumentCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(5).getName()); - Assertions.assertEquals("StatechartASTCodeCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(6).getName()); - Assertions.assertEquals("StatechartASTAbstractAnythingCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(7).getName()); - Assertions.assertEquals("StatechartASTSCStructureCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(8).getName()); - Assertions.assertEquals("StatechartASTBlockStatementExtCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(9).getName()); - Assertions.assertEquals("StatechartASTExpressionExtCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(10).getName()); - Assertions.assertEquals("StatechartASTClassbodyExtCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(11).getName()); - Assertions.assertEquals("StatechartASTStatechartNodeCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(12).getName()); + assertNotNull(cocoPackageCD); + assertNotNull(cocoPackageCD.getCDDefinition()); + assertEquals("Statechart", cocoPackageCD.getCDDefinition().getName()); + assertEquals(1, cocoPackageCD.getCDDefinition().getCDClassesList().size()); + assertEquals("StatechartCoCoChecker", cocoPackageCD.getCDDefinition().getCDClassesList().get(0).getName()); + assertEquals(13, cocoPackageCD.getCDDefinition().getCDInterfacesList().size()); + assertEquals("StatechartASTStatechartCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(0).getName()); + assertEquals("StatechartASTEntryActionCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(1).getName()); + assertEquals("StatechartASTExitActionCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(2).getName()); + assertEquals("StatechartASTStateCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(3).getName()); + assertEquals("StatechartASTTransitionCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(4).getName()); + assertEquals("StatechartASTArgumentCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(5).getName()); + assertEquals("StatechartASTCodeCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(6).getName()); + assertEquals("StatechartASTAbstractAnythingCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(7).getName()); + assertEquals("StatechartASTSCStructureCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(8).getName()); + assertEquals("StatechartASTBlockStatementExtCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(9).getName()); + assertEquals("StatechartASTExpressionExtCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(10).getName()); + assertEquals("StatechartASTClassbodyExtCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(11).getName()); + assertEquals("StatechartASTStatechartNodeCoCo", cocoPackageCD.getCDDefinition().getCDInterfacesList().get(12).getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -537,38 +529,38 @@ public void testDecorateForASTPackage() { ASTCDCompilationUnit astPackageCD = mc.decorateForASTPackage(glex, cd4AGlobalScope, cd, handcodedPath); mc.configureGenerator(glex,astPackageCD, templatePath); - Assertions.assertNotNull(astPackageCD); - Assertions.assertNotNull(astPackageCD.getCDDefinition()); - Assertions.assertEquals("Statechart", astPackageCD.getCDDefinition().getName()); - Assertions.assertEquals(17, astPackageCD.getCDDefinition().getCDClassesList().size()); - Assertions.assertEquals("ASTStatechart", astPackageCD.getCDDefinition().getCDClassesList().get(0).getName()); - Assertions.assertEquals("ASTEntryAction", astPackageCD.getCDDefinition().getCDClassesList().get(1).getName()); - Assertions.assertEquals("ASTExitAction", astPackageCD.getCDDefinition().getCDClassesList().get(2).getName()); - Assertions.assertEquals("ASTState", astPackageCD.getCDDefinition().getCDClassesList().get(3).getName()); - Assertions.assertEquals("ASTTransition", astPackageCD.getCDDefinition().getCDClassesList().get(4).getName()); - Assertions.assertEquals("ASTArgument", astPackageCD.getCDDefinition().getCDClassesList().get(5).getName()); - Assertions.assertEquals("ASTCode", astPackageCD.getCDDefinition().getCDClassesList().get(6).getName()); - Assertions.assertEquals("ASTAbstractAnything", astPackageCD.getCDDefinition().getCDClassesList().get(7).getName()); - Assertions.assertEquals("ASTStatechartBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(8).getName()); - Assertions.assertEquals("ASTEntryActionBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(9).getName()); - Assertions.assertEquals("ASTExitActionBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(10).getName()); - Assertions.assertEquals("ASTStateBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(11).getName()); - Assertions.assertEquals("ASTTransitionBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(12).getName()); - Assertions.assertEquals("ASTArgumentBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(13).getName()); - Assertions.assertEquals("ASTCodeBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(14).getName()); - Assertions.assertEquals("ASTAbstractAnythingBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(15).getName()); - Assertions.assertEquals("ASTConstantsStatechart", astPackageCD.getCDDefinition().getCDClassesList().get(16).getName()); - - Assertions.assertEquals(5, astPackageCD.getCDDefinition().getCDInterfacesList().size()); - Assertions.assertEquals("ASTSCStructure", astPackageCD.getCDDefinition().getCDInterfacesList().get(0).getName()); - Assertions.assertEquals("ASTBlockStatementExt", astPackageCD.getCDDefinition().getCDInterfacesList().get(1).getName()); - Assertions.assertEquals("ASTExpressionExt", astPackageCD.getCDDefinition().getCDInterfacesList().get(2).getName()); - Assertions.assertEquals("ASTClassbodyExt", astPackageCD.getCDDefinition().getCDInterfacesList().get(3).getName()); - Assertions.assertEquals("ASTStatechartNode", astPackageCD.getCDDefinition().getCDInterfacesList().get(4).getName()); - Assertions.assertEquals(1, astPackageCD.getCDDefinition().getCDEnumsList().size()); - Assertions.assertEquals("StatechartLiterals", astPackageCD.getCDDefinition().getCDEnumsList().get(0).getName()); + assertNotNull(astPackageCD); + assertNotNull(astPackageCD.getCDDefinition()); + assertEquals("Statechart", astPackageCD.getCDDefinition().getName()); + assertEquals(17, astPackageCD.getCDDefinition().getCDClassesList().size()); + assertEquals("ASTStatechart", astPackageCD.getCDDefinition().getCDClassesList().get(0).getName()); + assertEquals("ASTEntryAction", astPackageCD.getCDDefinition().getCDClassesList().get(1).getName()); + assertEquals("ASTExitAction", astPackageCD.getCDDefinition().getCDClassesList().get(2).getName()); + assertEquals("ASTState", astPackageCD.getCDDefinition().getCDClassesList().get(3).getName()); + assertEquals("ASTTransition", astPackageCD.getCDDefinition().getCDClassesList().get(4).getName()); + assertEquals("ASTArgument", astPackageCD.getCDDefinition().getCDClassesList().get(5).getName()); + assertEquals("ASTCode", astPackageCD.getCDDefinition().getCDClassesList().get(6).getName()); + assertEquals("ASTAbstractAnything", astPackageCD.getCDDefinition().getCDClassesList().get(7).getName()); + assertEquals("ASTStatechartBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(8).getName()); + assertEquals("ASTEntryActionBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(9).getName()); + assertEquals("ASTExitActionBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(10).getName()); + assertEquals("ASTStateBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(11).getName()); + assertEquals("ASTTransitionBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(12).getName()); + assertEquals("ASTArgumentBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(13).getName()); + assertEquals("ASTCodeBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(14).getName()); + assertEquals("ASTAbstractAnythingBuilder", astPackageCD.getCDDefinition().getCDClassesList().get(15).getName()); + assertEquals("ASTConstantsStatechart", astPackageCD.getCDDefinition().getCDClassesList().get(16).getName()); + + assertEquals(5, astPackageCD.getCDDefinition().getCDInterfacesList().size()); + assertEquals("ASTSCStructure", astPackageCD.getCDDefinition().getCDInterfacesList().get(0).getName()); + assertEquals("ASTBlockStatementExt", astPackageCD.getCDDefinition().getCDInterfacesList().get(1).getName()); + assertEquals("ASTExpressionExt", astPackageCD.getCDDefinition().getCDInterfacesList().get(2).getName()); + assertEquals("ASTClassbodyExt", astPackageCD.getCDDefinition().getCDInterfacesList().get(3).getName()); + assertEquals("ASTStatechartNode", astPackageCD.getCDDefinition().getCDInterfacesList().get(4).getName()); + assertEquals(1, astPackageCD.getCDDefinition().getCDEnumsList().size()); + assertEquals("StatechartLiterals", astPackageCD.getCDDefinition().getCDEnumsList().get(0).getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -583,41 +575,41 @@ public void testDecorateForEmfASTPackage() { ASTCDCompilationUnit astEmfPackageCD = mc.decorateEmfForASTPackage(glex, cd4AGlobalScope, cd, handcodedPath); - Assertions.assertNotNull(astEmfPackageCD); - Assertions.assertNotNull(astEmfPackageCD.getCDDefinition()); - Assertions.assertEquals("Statechart", astEmfPackageCD.getCDDefinition().getName()); - Assertions.assertEquals(18, astEmfPackageCD.getCDDefinition().getCDClassesList().size()); - Assertions.assertEquals("ASTStatechart", astEmfPackageCD.getCDDefinition().getCDClassesList().get(0).getName()); - Assertions.assertEquals("ASTEntryAction", astEmfPackageCD.getCDDefinition().getCDClassesList().get(1).getName()); - Assertions.assertEquals("ASTExitAction", astEmfPackageCD.getCDDefinition().getCDClassesList().get(2).getName()); - Assertions.assertEquals("ASTState", astEmfPackageCD.getCDDefinition().getCDClassesList().get(3).getName()); - Assertions.assertEquals("ASTTransition", astEmfPackageCD.getCDDefinition().getCDClassesList().get(4).getName()); - Assertions.assertEquals("ASTArgument", astEmfPackageCD.getCDDefinition().getCDClassesList().get(5).getName()); - Assertions.assertEquals("ASTCode", astEmfPackageCD.getCDDefinition().getCDClassesList().get(6).getName()); - Assertions.assertEquals("ASTAbstractAnything", astEmfPackageCD.getCDDefinition().getCDClassesList().get(7).getName()); - Assertions.assertEquals("ASTStatechartBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(8).getName()); - Assertions.assertEquals("ASTEntryActionBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(9).getName()); - Assertions.assertEquals("ASTExitActionBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(10).getName()); - Assertions.assertEquals("ASTStateBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(11).getName()); - Assertions.assertEquals("ASTTransitionBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(12).getName()); - Assertions.assertEquals("ASTArgumentBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(13).getName()); - Assertions.assertEquals("ASTCodeBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(14).getName()); - Assertions.assertEquals("ASTAbstractAnythingBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(15).getName()); - Assertions.assertEquals("ASTConstantsStatechart", astEmfPackageCD.getCDDefinition().getCDClassesList().get(16).getName()); - Assertions.assertEquals("StatechartPackageImpl", astEmfPackageCD.getCDDefinition().getCDClassesList().get(17).getName()); - - Assertions.assertEquals(6, astEmfPackageCD.getCDDefinition().getCDInterfacesList().size()); - Assertions.assertEquals("ASTSCStructure", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(0).getName()); - Assertions.assertEquals("ASTBlockStatementExt", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(1).getName()); - Assertions.assertEquals("ASTExpressionExt", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(2).getName()); - Assertions.assertEquals("ASTClassbodyExt", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(3).getName()); - Assertions.assertEquals("ASTStatechartNode", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(4).getName()); - Assertions.assertEquals("StatechartPackage", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(5).getName()); - - Assertions.assertEquals(1, astEmfPackageCD.getCDDefinition().getCDEnumsList().size()); - Assertions.assertEquals("StatechartLiterals", astEmfPackageCD.getCDDefinition().getCDEnumsList().get(0).getName()); + assertNotNull(astEmfPackageCD); + assertNotNull(astEmfPackageCD.getCDDefinition()); + assertEquals("Statechart", astEmfPackageCD.getCDDefinition().getName()); + assertEquals(18, astEmfPackageCD.getCDDefinition().getCDClassesList().size()); + assertEquals("ASTStatechart", astEmfPackageCD.getCDDefinition().getCDClassesList().get(0).getName()); + assertEquals("ASTEntryAction", astEmfPackageCD.getCDDefinition().getCDClassesList().get(1).getName()); + assertEquals("ASTExitAction", astEmfPackageCD.getCDDefinition().getCDClassesList().get(2).getName()); + assertEquals("ASTState", astEmfPackageCD.getCDDefinition().getCDClassesList().get(3).getName()); + assertEquals("ASTTransition", astEmfPackageCD.getCDDefinition().getCDClassesList().get(4).getName()); + assertEquals("ASTArgument", astEmfPackageCD.getCDDefinition().getCDClassesList().get(5).getName()); + assertEquals("ASTCode", astEmfPackageCD.getCDDefinition().getCDClassesList().get(6).getName()); + assertEquals("ASTAbstractAnything", astEmfPackageCD.getCDDefinition().getCDClassesList().get(7).getName()); + assertEquals("ASTStatechartBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(8).getName()); + assertEquals("ASTEntryActionBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(9).getName()); + assertEquals("ASTExitActionBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(10).getName()); + assertEquals("ASTStateBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(11).getName()); + assertEquals("ASTTransitionBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(12).getName()); + assertEquals("ASTArgumentBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(13).getName()); + assertEquals("ASTCodeBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(14).getName()); + assertEquals("ASTAbstractAnythingBuilder", astEmfPackageCD.getCDDefinition().getCDClassesList().get(15).getName()); + assertEquals("ASTConstantsStatechart", astEmfPackageCD.getCDDefinition().getCDClassesList().get(16).getName()); + assertEquals("StatechartPackageImpl", astEmfPackageCD.getCDDefinition().getCDClassesList().get(17).getName()); + + assertEquals(6, astEmfPackageCD.getCDDefinition().getCDInterfacesList().size()); + assertEquals("ASTSCStructure", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(0).getName()); + assertEquals("ASTBlockStatementExt", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(1).getName()); + assertEquals("ASTExpressionExt", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(2).getName()); + assertEquals("ASTClassbodyExt", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(3).getName()); + assertEquals("ASTStatechartNode", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(4).getName()); + assertEquals("StatechartPackage", astEmfPackageCD.getCDDefinition().getCDInterfacesList().get(5).getName()); + + assertEquals(1, astEmfPackageCD.getCDDefinition().getCDEnumsList().size()); + assertEquals("StatechartLiterals", astEmfPackageCD.getCDDefinition().getCDEnumsList().get(0).getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -634,15 +626,15 @@ public void testDecorateForODPackage() { ASTCDCompilationUnit odPackage = createEmptyCompilationUnit(cd); mc.decorateForODPackage(glex, cd4AGlobalScope, cd, odPackage, handcodedPath); - Assertions.assertNotNull(odPackage); - Assertions.assertNotNull(odPackage.getCDDefinition()); - Assertions.assertEquals("Statechart", odPackage.getCDDefinition().getName()); - Assertions.assertEquals(1, odPackage.getCDDefinition().getCDClassesList().size()); - Assertions.assertEquals("Statechart2OD", odPackage.getCDDefinition().getCDClassesList().get(0).getName()); - Assertions.assertTrue(odPackage.getCDDefinition().getCDInterfacesList().isEmpty()); - Assertions.assertTrue(odPackage.getCDDefinition().getCDEnumsList().isEmpty()); + assertNotNull(odPackage); + assertNotNull(odPackage.getCDDefinition()); + assertEquals("Statechart", odPackage.getCDDefinition().getName()); + assertEquals(1, odPackage.getCDDefinition().getCDClassesList().size()); + assertEquals("Statechart2OD", odPackage.getCDDefinition().getCDClassesList().get(0).getName()); + assertTrue(odPackage.getCDDefinition().getCDInterfacesList().isEmpty()); + assertTrue(odPackage.getCDDefinition().getCDEnumsList().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -663,14 +655,14 @@ public void testDecorateForMill() { mc.decorateMill(glex, cd4AGlobalScope, cd, decoratedCompilationUnit, handcodedPath); - Assertions.assertNotNull(decoratedCompilationUnit); - Assertions.assertNotNull(decoratedCompilationUnit.getCDDefinition()); + assertNotNull(decoratedCompilationUnit); + assertNotNull(decoratedCompilationUnit.getCDDefinition()); Optional millPackage = decoratedCompilationUnit.getCDDefinition().getPackageWithName("de.monticore.statechart.statechart"); - Assertions.assertTrue(millPackage.isPresent()); - Assertions.assertEquals("Statechart", decoratedCompilationUnit.getCDDefinition().getName()); - Assertions.assertEquals(1, millPackage.get().getCDElementList().size()); + assertTrue(millPackage.isPresent()); + assertEquals("Statechart", decoratedCompilationUnit.getCDDefinition().getName()); + assertEquals(1, millPackage.get().getCDElementList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -687,15 +679,15 @@ public void testDecorateForAuxiliaryPackage(){ mc.decorateAuxiliary(glex, cd4AGlobalScope, cd, decoratedCd, handcodedPath); - Assertions.assertNotNull(decoratedCd); - Assertions.assertNotNull(decoratedCd.getCDDefinition()); + assertNotNull(decoratedCd); + assertNotNull(decoratedCd.getCDDefinition()); Optional pp = decoratedCd.getCDDefinition().getPackageWithName("de.monticore.statechart.statechart._auxiliary"); - Assertions.assertEquals("Statechart", decoratedCd.getCDDefinition().getName()); - Assertions.assertEquals(1, pp.get().getCDElementList().size()); - Assertions.assertTrue(decoratedCd.getCDDefinition().getCDInterfacesList().isEmpty()); - Assertions.assertTrue(decoratedCd.getCDDefinition().getCDEnumsList().isEmpty()); + assertEquals("Statechart", decoratedCd.getCDDefinition().getName()); + assertEquals(1, pp.get().getCDElementList().size()); + assertTrue(decoratedCd.getCDDefinition().getCDInterfacesList().isEmpty()); + assertTrue(decoratedCd.getCDDefinition().getCDEnumsList().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } /** diff --git a/monticore-generator/src/test/java/de/monticore/cli/MontiCoreToolTest.java b/monticore-generator/src/test/java/de/monticore/cli/MontiCoreToolTest.java index 676cfc022d..5291b15522 100644 --- a/monticore-generator/src/test/java/de/monticore/cli/MontiCoreToolTest.java +++ b/monticore-generator/src/test/java/de/monticore/cli/MontiCoreToolTest.java @@ -9,7 +9,6 @@ import de.se_rwth.commons.logging.LogStub; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -19,12 +18,13 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static de.monticore.MontiCoreConfiguration.*; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * A collection of exemplary use cases for the CLI arguments. These unit tests @@ -122,63 +122,63 @@ public void setup() { public void testMontiCoreCLI() { new MontiCoreTool().run(simpleArgs); - Assertions.assertTrue(!false); + assertFalse(false); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMontiCoreDevLogCLI() { new MontiCoreTool().run(devLogArgs); - Assertions.assertTrue(!false); + assertFalse(false); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMontiCoreCustomLogCLI() { new MontiCoreTool().run(customLogArgs); - Assertions.assertTrue(!false); + assertFalse(false); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMontiCoreCustomScriptCLI() { new MontiCoreTool().run(customScriptArgs); - Assertions.assertTrue(!false); + assertFalse(false); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMontiCoreCustomEmfScriptCLI() { new MontiCoreTool().run(customEmfScriptArgs); - Assertions.assertTrue(!false); + assertFalse(false); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testHelp() { new MontiCoreTool().run(help); - - Assertions.assertTrue(!false); + + assertFalse(false); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Disabled // It's not possible to switch off fail quick (Logger in CLI) @Test public void testArgsWithNoGrammars() { new MontiCoreTool().run(argsWithNoGrammars); - Assertions.assertTrue(!false); + assertFalse(false); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -203,7 +203,7 @@ public void generateGrammarAndCheckFiles(Path path, String grammar) throws IOExc File reproOutDir1 = Paths.get("target/test-run-repo/repo1/").toFile(); File reproOutDir2 = Paths.get("target/test-run-repo/repo2/").toFile(); - Set allowedDirtyFiles = new HashSet<>(); + Set allowedDirtyFiles = new LinkedHashSet<>(); allowedDirtyFiles.add(path); // "20_Statistics" contains the execution duration, which varies between runs @@ -234,7 +234,7 @@ public void generateGrammarAndCheckFiles(Path path, String grammar) throws IOExc diff.add(relPath1.toString()); } - Assertions.assertTrue(f2.isFile(), "File does not exist \n\t" + f2.getAbsolutePath()); + assertTrue(f2.isFile(), "File does not exist \n\t" + f2.getAbsolutePath()); /*assertTrue("Different output generating twice! \n" + "\t" + f1.getAbsolutePath() + "\n" + "\t" + f2.getAbsolutePath() + "\n", @@ -243,9 +243,9 @@ public void generateGrammarAndCheckFiles(Path path, String grammar) throws IOExc } } diff.forEach(s -> System.err.println("\t " + s)); - Assertions.assertTrue(diff.isEmpty()); + assertTrue(diff.isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @AfterEach diff --git a/monticore-generator/src/test/java/de/monticore/cli/UpdateCheckerRunnableTest.java b/monticore-generator/src/test/java/de/monticore/cli/UpdateCheckerRunnableTest.java index c94607db3e..32ea3c66ce 100644 --- a/monticore-generator/src/test/java/de/monticore/cli/UpdateCheckerRunnableTest.java +++ b/monticore-generator/src/test/java/de/monticore/cli/UpdateCheckerRunnableTest.java @@ -5,11 +5,10 @@ import de.monticore.cli.updateChecker.UpdateCheckerRunnable; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -43,9 +42,9 @@ public void init() { @Test public void testFindLocalPropertiesFile() { - Assertions.assertNotNull(updateCheckerRunnable.getLocalVersion()); + assertNotNull(updateCheckerRunnable.getLocalVersion()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -53,28 +52,28 @@ public void testFindLocalPropertiesFile() { public void testNewVersionAvailable() { when(httpGetter.getResponse()).thenReturn(NEW_VERSION_AVAILABLE); - Assertions.assertTrue(updateCheckerRunnable.newVersionAvailable()); - Assertions.assertEquals(NEW_VERSION, updateCheckerRunnable.getNewVersion()); + assertTrue(updateCheckerRunnable.newVersionAvailable()); + assertEquals(NEW_VERSION, updateCheckerRunnable.getNewVersion()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNoNewVersionAvailable() { when(httpGetter.getResponse()).thenReturn(NO_NEW_VERSION_AVAILABLE); - Assertions.assertFalse(updateCheckerRunnable.newVersionAvailable()); + assertFalse(updateCheckerRunnable.newVersionAvailable()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNoResponse() { when(httpGetter.getResponse()).thenReturn(NO_RESPONSE); - Assertions.assertFalse(updateCheckerRunnable.newVersionAvailable()); + assertFalse(updateCheckerRunnable.newVersionAvailable()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -83,8 +82,8 @@ public void testRun() { updateCheckerRunnable.run(); - Assertions.assertEquals(NEW_VERSION, updateCheckerRunnable.getNewVersion()); + assertEquals(NEW_VERSION, updateCheckerRunnable.getNewVersion()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorAssert.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorAssert.java index 0f4303285e..693883ccf6 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorAssert.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorAssert.java @@ -9,8 +9,7 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.umlmodifier._ast.ASTModifier; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public final class DecoratorAssert { @@ -22,7 +21,8 @@ private DecoratorAssert() { } public static void assertDeepEquals(ASTNode expected, ASTNode actual) { - assertTrue(String.format("Expected: [%s], Actual: [%s]", getAsString(expected), getAsString(actual)), expected.deepEquals(actual)); + assertTrue(expected.deepEquals(actual), + String.format("Expected: [%s], Actual: [%s]", getAsString(expected), getAsString(actual))); } public static void assertDeepEquals(ASTMCType expected, ASTMCType actual) { @@ -34,7 +34,7 @@ private static String getAsString(ASTNode node) { } public static void assertDeepEquals(CDModifier expected, ASTNode actual) { - assertTrue(actual instanceof ASTModifier); + assertInstanceOf(ASTModifier.class, actual); ASTModifier actualMod = (ASTModifier) actual; ASTModifier expectedMod = expected.build(); assertEquals(expectedMod.isAbstract(), actualMod.isAbstract()); @@ -48,27 +48,27 @@ public static void assertDeepEquals(CDModifier expected, ASTNode actual) { } public static void assertDeepEquals(Class expected, ASTNode actual) { - assertTrue(actual instanceof ASTMCType); + assertInstanceOf(ASTMCType.class, actual); assertEquals(expected.getSimpleName(), CD4CodeMill.prettyPrint(actual, false)); } public static void assertDeepEquals(String name, ASTNode actual) { - assertTrue(actual instanceof ASTMCType); + assertInstanceOf(ASTMCType.class, actual); assertEquals(name, CD4CodeMill.prettyPrint(actual, false)); } public static void assertBoolean(ASTNode actual) { - assertTrue(actual instanceof ASTMCPrimitiveType); + assertInstanceOf(ASTMCPrimitiveType.class, actual); assertTrue(((ASTMCPrimitiveType) actual).isBoolean()); } public static void assertInt(ASTNode actual) { - assertTrue(actual instanceof ASTMCPrimitiveType); + assertInstanceOf(ASTMCPrimitiveType.class, actual); assertTrue(((ASTMCPrimitiveType) actual).isInt()); } public static void assertFloat(ASTNode actual){ - assertTrue(actual instanceof ASTMCPrimitiveType); + assertInstanceOf(ASTMCPrimitiveType.class, actual); assertTrue(((ASTMCPrimitiveType) actual).isFloat()); } @@ -78,19 +78,19 @@ public static void assertVoid(ASTNode acutal) { public static void assertOptionalOf(Class clazz, ASTNode actual) { String type = "Optional<" + clazz.getSimpleName() + ">"; - assertTrue(actual instanceof ASTMCType); + assertInstanceOf(ASTMCType.class, actual); assertEquals(type,CD4CodeMill.prettyPrint(actual, false)); } public static void assertOptionalOf(String name, ASTNode actual) { String type = "Optional<" + name + ">"; - assertTrue(actual instanceof ASTMCType); + assertInstanceOf(ASTMCType.class, actual); assertEquals(type,CD4CodeMill.prettyPrint(actual, false)); } public static void assertListOf(Class clazz, ASTNode actual) { String type = "List<" + clazz.getSimpleName() + ">"; - assertTrue(actual instanceof ASTMCType); + assertInstanceOf(ASTMCType.class, actual); assertEquals(type,CD4CodeMill.prettyPrint(actual, false)); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorTestCase.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorTestCase.java index 9ee6ea8db4..9ef88ae7e8 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorTestCase.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorTestCase.java @@ -20,13 +20,13 @@ import de.se_rwth.commons.Joiners; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; public abstract class DecoratorTestCase { @@ -35,13 +35,13 @@ public abstract class DecoratorTestCase { protected GlobalExtensionManagement glex; - @Before + @BeforeEach public void initLog() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUpDecoratorTestCase() { CD4CodeMill.reset(); CD4CodeMill.init(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorTestUtil.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorTestUtil.java index 61e0d2373f..eeece230fd 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorTestUtil.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DecoratorTestUtil.java @@ -14,7 +14,7 @@ import java.util.function.Predicate; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public final class DecoratorTestUtil { @@ -24,7 +24,8 @@ public static ASTCDClass getClassBy(String name, ASTCDCompilationUnit ast) { List filtered = ast.getCDDefinition().getCDClassesList().stream() .filter(c -> name.equals(c.getName())) .collect(Collectors.toList()); - assertEquals(String.format("Expected to find 1 class, but found '%s'", filtered.size()), 1, filtered.size()); + assertEquals(1, filtered.size(), + String.format("Expected to find 1 class, but found '%s'", filtered.size())); return filtered.get(0); } @@ -32,7 +33,8 @@ public static ASTCDInterface getInterfaceBy(String name, ASTCDCompilationUnit as List filtered = ast.getCDDefinition().getCDInterfacesList().stream() .filter(c -> name.equals(c.getName())) .collect(Collectors.toList()); - assertEquals(String.format("Expected to find 1 interface, but found '%s'", filtered.size()), 1, filtered.size()); + assertEquals(1, filtered.size(), + String.format("Expected to find 1 interface, but found '%s'", filtered.size())); return filtered.get(0); } @@ -40,7 +42,8 @@ public static ASTCDEnum getEnumBy(String name, ASTCDCompilationUnit ast) { List filtered = ast.getCDDefinition().getCDEnumsList().stream() .filter(c -> name.equals(c.getName())) .collect(Collectors.toList()); - assertEquals(String.format("Expected to find 1 enum, but found '%s'", filtered.size()), 1, filtered.size()); + assertEquals(1, filtered.size(), + String.format("Expected to find 1 enum, but found '%s'", filtered.size())); return filtered.get(0); } @@ -100,7 +103,8 @@ public static ASTCDMethod getMethodBy(String name, int parameterSize, List methods, List> predicates) { List filtered = filterMethods(methods, predicates); - assertEquals(String.format("Expected find 1 method, but found '%s'", filtered.size()), 1, filtered.size()); + assertEquals(1, filtered.size(), + String.format("Expected find 1 method, but found '%s'", filtered.size())); return filtered.get(0); } @@ -116,7 +120,8 @@ public static ASTCDAttribute getAttributeBy(String name, ASTCDClass clazz) { List filtered = clazz.getCDAttributeList().stream() .filter(attribute -> name.equals(attribute.getName())) .collect(Collectors.toList()); - assertEquals(String.format("Expected find 1 attribute, but found '%s'", filtered.size()), 1, filtered.size()); + assertEquals(1, filtered.size(), + String.format("Expected find 1 attribute, but found '%s'", filtered.size())); return filtered.get(0); } @@ -125,7 +130,8 @@ public static ASTCDAttribute getAttributeBy(String name, ASTCDInterface clazz) { List filtered = clazz.getCDAttributeList().stream() .filter(attribute -> name.equals(attribute.getName())) .collect(Collectors.toList()); - assertEquals(String.format("Expected find 1 attribute, but found '%s'", filtered.size()), 1, filtered.size()); + assertEquals(1, filtered.size(), + String.format("Expected find 1 attribute, but found '%s'", filtered.size())); return filtered.get(0); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DeprecatedTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DeprecatedTest.java index abea234589..dd0a8c5eb4 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DeprecatedTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/DeprecatedTest.java @@ -28,8 +28,8 @@ import de.monticore.codegen.cd2java.methods.MethodDecorator; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; @@ -37,9 +37,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getEnumBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class DeprecatedTest extends DecoratorTestCase { @@ -63,7 +61,7 @@ private ASTCDCompilationUnit compilationUnit; - @Before + @BeforeEach public void setup() { compilationUnit = this.parse("de", "monticore", "codegen", "deprecated", "DeprecatedProds"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/GeneratedErrorCodeTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/GeneratedErrorCodeTest.java index 5ac85eb9a8..448edafa8f 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/GeneratedErrorCodeTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/GeneratedErrorCodeTest.java @@ -4,10 +4,10 @@ import de.monticore.cdbasis._ast.ASTCDCompilationUnit; import de.monticore.codegen.cd2java._ast.ast_class.ASTService; import de.se_rwth.commons.logging.Log; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * test that error codes are generated deterministic diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_constants/ASTConstantsDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_constants/ASTConstantsDecoratorTest.java index b614b11ceb..8697d22971 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_constants/ASTConstantsDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_constants/ASTConstantsDecoratorTest.java @@ -17,16 +17,14 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorAssert.assertInt; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTConstantsDecoratorTest extends DecoratorTestCase { @@ -35,7 +33,7 @@ public class ASTConstantsDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit originalCompilationUnit; - @Before + @BeforeEach public void setUp() { decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); originalCompilationUnit = decoratedCompilationUnit.deepClone(); @@ -139,7 +137,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/ASTInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/ASTInterfaceDecoratorTest.java index 28a569ae25..7449908f9e 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/ASTInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/ASTInterfaceDecoratorTest.java @@ -26,8 +26,8 @@ import de.monticore.generating.templateengine.GlobalExtensionManagement; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static de.monticore.cd.facade.CDModifier.PUBLIC_ABSTRACT; @@ -35,14 +35,14 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ASTInterfaceDecoratorTest extends DecoratorTestCase { private ASTCDInterface dataInterface; - @Before + @BeforeEach public void setUp() { ASTCDCompilationUnit astcdCompilationUnit = this.parse("de", "monticore", "codegen", "data", "DataInterface"); this.glex.setGlobalValue("service", new AbstractService(astcdCompilationUnit)); @@ -178,7 +178,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/ASTLanguageInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/ASTLanguageInterfaceDecoratorTest.java index ec1c0ae071..b7076b78b6 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/ASTLanguageInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/ASTLanguageInterfaceDecoratorTest.java @@ -17,13 +17,13 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ASTLanguageInterfaceDecoratorTest extends DecoratorTestCase { @@ -35,11 +35,11 @@ public class ASTLanguageInterfaceDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { this.MCTypeFacade = MCTypeFacade.getInstance(); originalCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); - this.glex.setGlobalValue("service", new AbstractService(originalCompilationUnit)); + this.glex.setGlobalValue("service", new AbstractService<>(originalCompilationUnit)); ASTService astService = new ASTService(originalCompilationUnit); VisitorService visitorService = new VisitorService(originalCompilationUnit); @@ -102,7 +102,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/FullASTInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/FullASTInterfaceDecoratorTest.java index 3637db4586..3e12b0bac8 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/FullASTInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_interface/FullASTInterfaceDecoratorTest.java @@ -26,17 +26,15 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PUBLIC_ABSTRACT; import static de.monticore.codegen.cd2java.DecoratorAssert.assertBoolean; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class FullASTInterfaceDecoratorTest extends DecoratorTestCase { @@ -46,7 +44,7 @@ public class FullASTInterfaceDecoratorTest extends DecoratorTestCase { private static final String NAME_SYMBOL = "de.monticore.codegen.ast.referencedsymbol._symboltable.FooSymbol"; - @Before + @BeforeEach public void setUp() { ASTCDCompilationUnit astcdCompilationUnit = this.parse("de", "monticore", "codegen", "data", "DataInterface"); this.glex.setGlobalValue("service", new AbstractService(astcdCompilationUnit)); @@ -368,7 +366,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTCDDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTCDDecoratorTest.java index 7813dd8587..717c00726d 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTCDDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTCDDecoratorTest.java @@ -35,13 +35,12 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ASTCDDecoratorTest extends DecoratorTestCase { @@ -49,7 +48,7 @@ public class ASTCDDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit originalCompilationUnit; - @Before + @BeforeEach public void setup() { this.originalCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "AST"); this.glex.setGlobalValue("service", new AbstractService(originalCompilationUnit)); @@ -123,7 +122,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTDecoratorTest.java index 7b63400bdc..dff8cc57b0 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTDecoratorTest.java @@ -25,8 +25,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; @@ -39,9 +39,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTDecoratorTest extends DecoratorTestCase { @@ -53,7 +51,7 @@ public class ASTDecoratorTest extends DecoratorTestCase { private static final String AST_SYMBOL = "de.monticore.codegen.ast.ast._symboltable.ASymbol"; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "AST"); @@ -204,7 +202,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTFullDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTFullDecoratorTest.java index 1913fb1f2a..38fdede07a 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTFullDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTFullDecoratorTest.java @@ -17,14 +17,11 @@ import de.monticore.codegen.cd2java.data.DataDecoratorUtil; import de.monticore.codegen.cd2java.methods.MethodDecorator; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTFullDecoratorTest extends DecoratorTestCase { @@ -35,7 +32,7 @@ public class ASTFullDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit originalCompilationUnit; - @Before + @BeforeEach public void setup() { decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "AST"); originalCompilationUnit = decoratedCompilationUnit.deepClone(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTScopeDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTScopeDecoratorTest.java index a1f5c8b3d2..97c5458432 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTScopeDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTScopeDecoratorTest.java @@ -12,8 +12,8 @@ import de.monticore.codegen.mc2cd.TransformationHelper; import de.monticore.umlmodifier._ast.ASTModifier; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; @@ -22,9 +22,7 @@ import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTScopeDecoratorTest extends DecoratorTestCase { @@ -34,7 +32,7 @@ public class ASTScopeDecoratorTest extends DecoratorTestCase { private static final String SUPER_I_SCOPE= "de.monticore.codegen.ast.supercd._symboltable.ISuperCDScope"; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "AST"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTServiceTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTServiceTest.java index 3034032021..2697f6c3d7 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTServiceTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTServiceTest.java @@ -9,16 +9,14 @@ import de.monticore.codegen.cd2java.DecoratorTestCase; import de.monticore.codegen.cd2java._ast.ast_class.ASTService; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTServiceTest extends DecoratorTestCase { @@ -30,7 +28,7 @@ public class ASTServiceTest extends DecoratorTestCase { private ASTCDClass astAutomaton; - @Before + @BeforeEach public void setup() { astcdCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); astAutomaton = astcdCompilationUnit.getCDDefinition().getCDClassesList().get(0); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTSymbolDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTSymbolDecoratorTest.java index 4bd2b0fa1e..1c685c3b53 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTSymbolDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/ASTSymbolDecoratorTest.java @@ -9,8 +9,8 @@ import de.monticore.codegen.cd2java._ast.ast_class.ASTSymbolDecorator; import de.monticore.codegen.cd2java._symboltable.SymbolTableService; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; @@ -19,15 +19,13 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorAssert.assertOptionalOf; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTSymbolDecoratorTest extends DecoratorTestCase { private List attributes; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "AST"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/ASTReferenceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/ASTReferenceDecoratorTest.java index 0e577243db..07fb76e00b 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/ASTReferenceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/ASTReferenceDecoratorTest.java @@ -9,15 +9,13 @@ import de.monticore.codegen.cd2java._ast.ast_class.reference.ASTReferenceDecorator; import de.monticore.codegen.cd2java._symboltable.SymbolTableService; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTReferenceDecoratorTest extends DecoratorTestCase { @@ -30,7 +28,7 @@ public class ASTReferenceDecoratorTest extends DecoratorTestCase { private ASTReferenceDecorator referenceDecorator; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "ReferencedSymbol"); this.referenceDecorator = new ASTReferenceDecorator(this.glex, new SymbolTableService(ast)); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorListTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorListTest.java index 95d610b739..c2f7a59ce4 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorListTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorListTest.java @@ -17,18 +17,18 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ASTReferencedDefinitionDecoratorListTest extends DecoratorTestCase { private ASTCDClass astClass; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "ReferencedSymbol"); @@ -74,7 +74,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorMandatoryTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorMandatoryTest.java index 7aba85de30..6e9618a462 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorMandatoryTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorMandatoryTest.java @@ -18,16 +18,16 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertBoolean; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ASTReferencedDefinitionDecoratorMandatoryTest extends DecoratorTestCase { @@ -35,7 +35,7 @@ public class ASTReferencedDefinitionDecoratorMandatoryTest extends DecoratorTest private static final String NAME_DEFINITION = "de.monticore.codegen.ast.referencedsymbol._ast.ASTFoo"; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "ReferencedSymbol"); this.glex.setGlobalValue("service", new AbstractService(ast)); @@ -102,7 +102,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorOptionalTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorOptionalTest.java index 5798ab64b4..d9cc162fd9 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorOptionalTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedDefinition/ASTReferencedDefinitionDecoratorOptionalTest.java @@ -18,16 +18,16 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertBoolean; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ASTReferencedDefinitionDecoratorOptionalTest extends DecoratorTestCase { @@ -35,7 +35,7 @@ public class ASTReferencedDefinitionDecoratorOptionalTest extends DecoratorTestC private static final String NAME_DEFINITION = "de.monticore.codegen.ast.referencedsymbol._ast.ASTFoo"; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "ReferencedSymbol"); this.glex.setGlobalValue("service", new AbstractService(ast)); @@ -102,7 +102,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorListTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorListTest.java index 1f84c0897e..0ab8d75308 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorListTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorListTest.java @@ -19,17 +19,15 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.umlstereotype._ast.ASTStereotype; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTReferencedSymbolDecoratorListTest extends DecoratorTestCase { @@ -39,7 +37,7 @@ public class ASTReferencedSymbolDecoratorListTest extends DecoratorTestCase { private static final String NAME_SYMBOL_MAP = "Map"; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "ReferencedSymbol"); this.glex.setGlobalValue("service", new AbstractService(ast)); @@ -118,7 +116,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorMandatoryTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorMandatoryTest.java index 074d5f42b9..e9f9f3b874 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorMandatoryTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorMandatoryTest.java @@ -20,8 +20,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.umlstereotype._ast.ASTStereotype; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PUBLIC; @@ -30,9 +30,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTReferencedSymbolDecoratorMandatoryTest extends DecoratorTestCase { @@ -46,7 +44,7 @@ public class ASTReferencedSymbolDecoratorMandatoryTest extends DecoratorTestCase private static final String NAME_SYMBOL = "de.monticore.codegen.ast.referencedsymbol._symboltable.FooSymbol"; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "ReferencedSymbol"); this.glex.setGlobalValue("service", new AbstractService(ast)); @@ -147,7 +145,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorOptionalTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorOptionalTest.java index fcf17f51b4..5b3fa5edf5 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorOptionalTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/ast_new/reference/referencedSymbol/ASTReferencedSymbolDecoratorOptionalTest.java @@ -19,8 +19,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.umlstereotype._ast.ASTStereotype; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PUBLIC; @@ -29,9 +29,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTReferencedSymbolDecoratorOptionalTest extends DecoratorTestCase { @@ -45,7 +43,7 @@ public class ASTReferencedSymbolDecoratorOptionalTest extends DecoratorTestCase private static final String NAME_SYMBOL = "de.monticore.codegen.ast.referencedsymbol._symboltable.FooSymbol"; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "ast", "ReferencedSymbol"); this.glex.setGlobalValue("service", new AbstractService(ast)); @@ -146,7 +144,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); @@ -228,7 +226,7 @@ public void testGeneratedCodeMand() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/builder/ASTBuilderDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/builder/ASTBuilderDecoratorTest.java index fd5cf19fb4..0043a4d4c4 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/builder/ASTBuilderDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/builder/ASTBuilderDecoratorTest.java @@ -15,13 +15,13 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ASTBuilderDecoratorTest extends DecoratorTestCase { @@ -31,7 +31,7 @@ public class ASTBuilderDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit originalCompilationUnit; - @Before + @BeforeEach public void setup() { decoratedCompilationUnit = parse("de", "monticore", "codegen", "ast", "Builder"); originalCompilationUnit = decoratedCompilationUnit.deepClone(); @@ -83,7 +83,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/builder/BuilderDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/builder/BuilderDecoratorTest.java index 4b8f57ca96..f0d5bfdb28 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/builder/BuilderDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/builder/BuilderDecoratorTest.java @@ -16,8 +16,8 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -26,7 +26,7 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.*; import static de.monticore.codegen.cd2java.DecoratorTestUtil.*; import static de.monticore.codegen.cd2java._ast.builder.BuilderConstants.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class BuilderDecoratorTest extends DecoratorTestCase { @@ -34,7 +34,7 @@ public class BuilderDecoratorTest extends DecoratorTestCase { private ASTCDClass builderClass; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = parse("de", "monticore", "codegen", "builder", "Builder"); this.glex.setGlobalValue("service", new AbstractService(ast)); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/enums/LiteralsEnumDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/enums/LiteralsEnumDecoratorTest.java index 7c11f755d3..31ee58be3a 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/enums/LiteralsEnumDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast/enums/LiteralsEnumDecoratorTest.java @@ -20,14 +20,14 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorAssert.assertInt; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getEnumBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class LiteralsEnumDecoratorTest extends DecoratorTestCase { @@ -37,7 +37,7 @@ public class LiteralsEnumDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit originalCompilationUnit; - @Before + @BeforeEach public void setUp() { decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); originalCompilationUnit = decoratedCompilationUnit.deepClone(); @@ -127,7 +127,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ASTEmfCDDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ASTEmfCDDecoratorTest.java index afb4ecfe30..998adeea13 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ASTEmfCDDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ASTEmfCDDecoratorTest.java @@ -37,11 +37,11 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ASTEmfCDDecoratorTest extends DecoratorTestCase { @@ -49,7 +49,7 @@ public class ASTEmfCDDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit originalCompilationUnit; - @Before + @BeforeEach public void setup() { this.decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "AST"); this.originalCompilationUnit = decoratedCompilationUnit.deepClone(); @@ -117,7 +117,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/ASTEmfDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/ASTEmfDecoratorTest.java index e7404077b6..b2d4ab86e1 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/ASTEmfDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/ASTEmfDecoratorTest.java @@ -21,8 +21,8 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PUBLIC; @@ -32,9 +32,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTEmfDecoratorTest extends DecoratorTestCase { @@ -42,7 +40,7 @@ public class ASTEmfDecoratorTest extends DecoratorTestCase { private ASTCDClass emfTransitionClass; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "_ast_emf", "Automata"); @@ -216,9 +214,9 @@ public void testEStaticClassMethod() { * ASTTransitionWithAction already has a toString method in the classdiagramm * tests that no toString method is separately generated */ - @Test (expected = AssertionError.class) + @Test public void testToStringASTTransitionWithAction() { - getMethodBy("toString", emfTransitionClass); + assertThrows(AssertionError.class, () -> getMethodBy("toString", emfTransitionClass)); assertTrue(Log.getFindings().isEmpty()); } @@ -243,7 +241,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/ASTFullEmfDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/ASTFullEmfDecoratorTest.java index a995c93fab..7469bb9c22 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/ASTFullEmfDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/ASTFullEmfDecoratorTest.java @@ -16,14 +16,11 @@ import de.monticore.codegen.cd2java.data.DataDecoratorUtil; import de.monticore.codegen.cd2java.methods.MethodDecorator; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ASTFullEmfDecoratorTest extends DecoratorTestCase { @@ -34,7 +31,7 @@ public class ASTFullEmfDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit originalCompilationUnit; - @Before + @BeforeEach public void setup() { decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); originalCompilationUnit = decoratedCompilationUnit.deepClone(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/DataEmfDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/DataEmfDecoratorTest.java index 9ecbda9400..651c7ad616 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/DataEmfDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/ast_class/DataEmfDecoratorTest.java @@ -18,18 +18,18 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DataEmfDecoratorTest extends DecoratorTestCase { private ASTCDClass emfClass; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit compilationUnit = this.parse("de", "monticore", "codegen", "_ast_emf", "Automata"); @@ -73,7 +73,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/emf_package/PackageImplDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/emf_package/PackageImplDecoratorTest.java index 350e8ac39f..0714a40958 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/emf_package/PackageImplDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/emf_package/PackageImplDecoratorTest.java @@ -19,8 +19,8 @@ import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PRIVATE; import static de.monticore.cd.facade.CDModifier.PROTECTED; @@ -31,15 +31,13 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class PackageImplDecoratorTest extends DecoratorTestCase { private ASTCDClass packageClass; - @Before + @BeforeEach public void setup() { LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only @@ -332,7 +330,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/emf_package/PackageInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/emf_package/PackageInterfaceDecoratorTest.java index 6d471e4415..ee09f5c201 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/emf_package/PackageInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_ast_emf/emf_package/PackageInterfaceDecoratorTest.java @@ -16,8 +16,8 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PACKAGE_PRIVATE; import static de.monticore.cd.facade.CDModifier.PACKAGE_PRIVATE_ABSTRACT; @@ -25,9 +25,7 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertInt; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class PackageInterfaceDecoratorTest extends DecoratorTestCase { @@ -35,7 +33,7 @@ public class PackageInterfaceDecoratorTest extends DecoratorTestCase { private ASTCDDefinition astcdDefinition; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "_ast_emf", "Automata"); @@ -398,7 +396,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoCheckerDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoCheckerDecoratorTest.java index 89a87c27f1..ed257243e3 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoCheckerDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoCheckerDecoratorTest.java @@ -22,9 +22,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -34,9 +33,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.*; public class CoCoCheckerDecoratorTest extends DecoratorTestCase { @@ -64,7 +61,7 @@ public class CoCoCheckerDecoratorTest extends DecoratorTestCase { private static final String LEXICALS_NODE = "de.monticore.codegen.ast.lexicals._ast.ASTLexicalsNode"; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = parse("de", "monticore", "codegen", "ast", "Automaton"); ICD4CodeGlobalScope gs = CD4CodeMill.globalScope(); @@ -85,7 +82,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); @@ -203,7 +200,7 @@ public void testAddCoCoAutomatonMethod() { assertEquals("coco", method.getCDParameter(0).getName()); assertTrue(method.getMCReturnType().isPresentMCVoidType()); - Assert.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoDecoratorTest.java index 2c46b978fe..1b35fd7bde 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoDecoratorTest.java @@ -18,17 +18,17 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.io.paths.MCPath; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CoCoDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedAst; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = this.parse("de", "monticore", "codegen", "cocos", "CoCos"); decoratedAst = createEmptyCompilationUnit(ast); @@ -64,7 +64,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); } for (ASTCDInterface astcdInterface : decoratedAst.getCDDefinition().getCDInterfacesList()) { @@ -72,7 +72,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoInterfaceDecoratorTest.java index 1c10fb018d..6ea5aee32b 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoInterfaceDecoratorTest.java @@ -16,22 +16,22 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.cd.facade.CDModifier.PUBLIC_ABSTRACT; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CoCoInterfaceDecoratorTest extends DecoratorTestCase { private List interfaces; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = parse("de", "monticore", "codegen", "cocos", "CoCos"); this.glex.setGlobalValue("service", new AbstractService(ast)); @@ -154,7 +154,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoServiceTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoServiceTest.java index f60e4908a6..9f6b652704 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoServiceTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_cocos/CoCoServiceTest.java @@ -5,12 +5,12 @@ import de.monticore.cdbasis._ast.ASTCDCompilationUnit; import de.monticore.codegen.cd2java.DecoratorTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CoCoServiceTest extends DecoratorTestCase { @@ -22,7 +22,7 @@ public class CoCoServiceTest extends DecoratorTestCase { private ASTCDClass astAutomaton; - @Before + @BeforeEach public void setup() { astcdCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); astAutomaton = astcdCompilationUnit.getCDDefinition().getCDClassesList().get(0); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_od/ODDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_od/ODDecoratorTest.java index da0753a795..c85c1c1984 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_od/ODDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_od/ODDecoratorTest.java @@ -18,8 +18,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -30,9 +30,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ODDecoratorTest extends DecoratorTestCase { @@ -64,7 +62,7 @@ public class ODDecoratorTest extends DecoratorTestCase { private MCTypeFacade mcTypeFacade; - @Before + @BeforeEach public void setup() { this.mcTypeFacade = MCTypeFacade.getInstance(); @@ -88,7 +86,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserCDDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserCDDecoratorTest.java index 4fb398054a..33fd4d08db 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserCDDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserCDDecoratorTest.java @@ -8,14 +8,14 @@ import de.monticore.codegen.cd2java.DecoratorTestCase; import de.monticore.umlmodifier._ast.ASTModifier; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ParserCDDecoratorTest extends DecoratorTestCase { @@ -27,7 +27,7 @@ public class ParserCDDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit parserCDComponent; - @Before + @BeforeEach public void setUp() { decoratedASTCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); originalASTCompilationUnit = decoratedASTCompilationUnit.deepClone(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserClassDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserClassDecoratorTest.java index 057acf7a11..972e4757d2 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserClassDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserClassDecoratorTest.java @@ -19,8 +19,8 @@ import de.monticore.types.mcbasictypes.MCBasicTypesMill; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedName; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; @@ -29,8 +29,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertOptionalOf; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ParserClassDecoratorTest extends DecoratorTestCase { @@ -50,7 +50,7 @@ public class ParserClassDecoratorTest extends DecoratorTestCase { private final String AUTOMATON_ANTLR_PARSER = "AutomatonAntlrParser"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); @@ -288,7 +288,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserForSuperDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserForSuperDecoratorTest.java index 1cbb6f0d64..d2cd64671a 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserForSuperDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserForSuperDecoratorTest.java @@ -18,16 +18,16 @@ import de.monticore.types.mcbasictypes.MCBasicTypesMill; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedName; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorAssert.assertOptionalOf; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ParserForSuperDecoratorTest extends DecoratorTestCase { @@ -37,7 +37,7 @@ public class ParserForSuperDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "parser", "SubAutomaton"); originalCompilationUnit = decoratedCompilationUnit.deepClone(); @@ -167,7 +167,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserServiceTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserServiceTest.java index 0bc2c1c286..b922931bbb 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserServiceTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_parser/ParserServiceTest.java @@ -7,12 +7,12 @@ import de.monticore.codegen.cd2java.DecoratorTestCase; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ParserServiceTest extends DecoratorTestCase { @@ -24,7 +24,7 @@ public class ParserServiceTest extends DecoratorTestCase { private ASTCDClass astAutomaton; - @Before + @BeforeEach public void setup() { this.mcTypeFacade = MCTypeFacade.getInstance(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecoratorTest.java index ef0458e704..c2654553a0 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableCDDecoratorTest.java @@ -32,15 +32,15 @@ import de.monticore.io.paths.MCPath; import de.monticore.umlmodifier._ast.ASTModifier; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class SymbolTableCDDecoratorTest extends DecoratorTestCase { @@ -62,7 +62,7 @@ public class SymbolTableCDDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit symTabCDComponent; - @Before + @BeforeEach public void setUp() { MCPath targetPath = Mockito.mock(MCPath.class); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableServiceTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableServiceTest.java index 834536c43a..d14dd0837f 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableServiceTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/SymbolTableServiceTest.java @@ -14,16 +14,14 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.umlmodifier._ast.ASTModifier; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SymbolTableServiceTest extends DecoratorTestCase { @@ -35,7 +33,7 @@ public class SymbolTableServiceTest extends DecoratorTestCase { private MCTypeFacade mcTypeFacade; - @Before + @BeforeEach public void setup() { this.mcTypeFacade = MCTypeFacade.getInstance(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/Symbols2JsonTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/Symbols2JsonTest.java index 5413774563..2922943df3 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/Symbols2JsonTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/Symbols2JsonTest.java @@ -14,16 +14,16 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class Symbols2JsonTest extends DecoratorTestCase { @@ -40,7 +40,7 @@ public class Symbols2JsonTest extends DecoratorTestCase { private static final String AUTOMATON_SYMBOL = "de.monticore.codegen.symboltable.automaton._symboltable.AutomatonSymbol"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeClassDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeClassDecoratorTest.java index bd178326db..27559658e9 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeClassDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeClassDecoratorTest.java @@ -21,8 +21,8 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -33,9 +33,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ArtifactScopeClassDecoratorTest extends DecoratorTestCase { @@ -53,7 +51,7 @@ public class ArtifactScopeClassDecoratorTest extends DecoratorTestCase { private static final String IMPORT_STATEMENT = "de.monticore.symboltable.ImportStatement"; - @Before + @BeforeEach public void setUp() { this.MCTypeFacade = MCTypeFacade.getInstance(); @@ -295,7 +293,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeInterfaceDecoratorTest.java index 5636826072..be8ce9b4bb 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ArtifactScopeInterfaceDecoratorTest.java @@ -17,8 +17,8 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -31,7 +31,7 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertVoid; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class ArtifactScopeInterfaceDecoratorTest extends DecoratorTestCase { @@ -55,7 +55,7 @@ public class ArtifactScopeInterfaceDecoratorTest extends DecoratorTestCase { private static final String PREDICATE_QUALIFIED_NAME = "java.util.function.Predicate"; - @Before + @BeforeEach public void setUp() { this.MCTypeFacade = MCTypeFacade.getInstance(); @@ -81,7 +81,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeClassDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeClassDecoratorTest.java index a2d8bc48aa..f5485fb126 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeClassDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeClassDecoratorTest.java @@ -20,8 +20,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -29,7 +29,7 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorAssert.assertVoid; import static de.monticore.codegen.cd2java.DecoratorTestUtil.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class GlobalScopeClassDecoratorTest extends DecoratorTestCase { @@ -45,7 +45,7 @@ public class GlobalScopeClassDecoratorTest extends DecoratorTestCase { private static final String AUTOMATON_SCOPE = "de.monticore.codegen.ast.automaton._symboltable.AutomatonScope"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); @@ -332,7 +332,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeInterfaceDecoratorTest.java index 2978e200b7..6091b39713 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/GlobalScopeInterfaceDecoratorTest.java @@ -11,8 +11,8 @@ import de.monticore.codegen.cd2java.methods.MethodDecorator; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -24,8 +24,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertVoid; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class GlobalScopeInterfaceDecoratorTest extends DecoratorTestCase { @@ -49,7 +49,7 @@ public class GlobalScopeInterfaceDecoratorTest extends DecoratorTestCase { private static final String PREDICATE_QUALIFIED_NAME = "java.util.function.Predicate"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ScopeClassDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ScopeClassDecoratorTest.java index 274954d552..4e9b928a16 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ScopeClassDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ScopeClassDecoratorTest.java @@ -20,10 +20,10 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -38,9 +38,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ScopeClassDecoratorTest extends DecoratorTestCase { @@ -82,7 +80,7 @@ public class ScopeClassDecoratorTest extends DecoratorTestCase { private static final String I_LEXICAS_SCOPE = "de.monticore.codegen.ast.lexicals._symboltable.ILexicalsScope"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = mcTypeFacade.getInstance(); @@ -386,7 +384,7 @@ public void testMethodCount() { public void testRemoveSymbolMethod() { List methodList = getMethodsBy("remove", scopeClass); - Map methods = new HashMap<>(); + Map methods = new LinkedHashMap<>(); methodList.forEach(l -> methods.put( CD4CodeMill.prettyPrint(l.getCDParameter(0).getMCType(), false), l) ); @@ -429,7 +427,7 @@ public void testRemoveSymbolMethod() { @Test public void testAddSymbolMethod() { List methodList = getMethodsBy("add", scopeClass); - Map methods = new HashMap<>(); + Map methods = new LinkedHashMap<>(); methodList.forEach(l -> methods.put( CD4CodeMill.prettyPrint(l.getCDParameter(0).getMCType(), false), l) ); @@ -815,7 +813,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ScopeInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ScopeInterfaceDecoratorTest.java index b040cc9e06..4693d22ae8 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ScopeInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scope/ScopeInterfaceDecoratorTest.java @@ -17,8 +17,8 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -31,8 +31,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertVoid; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ScopeInterfaceDecoratorTest extends DecoratorTestCase { private ASTCDInterface scopeInterface; @@ -54,7 +54,7 @@ public class ScopeInterfaceDecoratorTest extends DecoratorTestCase { private static final String PREDICATE = "java.util.function.Predicate"; - @Before + @BeforeEach public void setUp() { this.MCTypeFacade = MCTypeFacade.getInstance(); ASTCDCompilationUnit astcdCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); @@ -809,7 +809,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecoratorTest.java index 13cee735b2..ddd0afac5f 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDecoratorTest.java @@ -26,8 +26,8 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.List; @@ -41,9 +41,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ScopesGenitorDecoratorTest extends DecoratorTestCase { @@ -83,7 +81,7 @@ public class ScopesGenitorDecoratorTest extends DecoratorTestCase { private static final String AST_SCOPE = "de.monticore.codegen.symboltable.automaton._ast.ASTScope"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); @@ -535,7 +533,7 @@ public void testGeneratedCodeState() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDelegatorDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDelegatorDecoratorTest.java index 32adf75dd0..88f0731786 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDelegatorDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/scopesgenitor/ScopesGenitorDelegatorDecoratorTest.java @@ -23,8 +23,8 @@ import de.monticore.generating.templateengine.GlobalExtensionManagement; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Optional; @@ -35,9 +35,7 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ScopesGenitorDelegatorDecoratorTest extends DecoratorTestCase { @@ -59,7 +57,7 @@ public class ScopesGenitorDelegatorDecoratorTest extends DecoratorTestCase { private static final String AST_AUTOMATON = "de.monticore.codegen.symboltable.automaton._ast.ASTAutomaton"; - @Before + @BeforeEach public void setUp() { this.MCTypeFacade = MCTypeFacade.getInstance(); @@ -219,7 +217,7 @@ public void testGeneratedCodeState() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/ScopeDeSerDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/ScopeDeSerDecoratorTest.java index 2a0ed57d30..d96af7df98 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/ScopeDeSerDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/ScopeDeSerDecoratorTest.java @@ -26,8 +26,8 @@ import de.monticore.prettyprint.IndentPrinter; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -37,10 +37,7 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertOptionalOf; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class ScopeDeSerDecoratorTest extends DecoratorTestCase { @@ -62,7 +59,7 @@ public class ScopeDeSerDecoratorTest extends DecoratorTestCase { public static final String I_SCOPE = "de.monticore.symboltable.IScope"; - @Before + @BeforeEach public void setUp() { this.glex = new GlobalExtensionManagement(); @@ -360,7 +357,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); @@ -372,6 +369,7 @@ public static void assertOneOf(ASTMCType actualType, String... expected) { for (String exp : expected) { if (actual.equals(exp)) { result = true; + break; } } if (!result) { diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/SymbolDeSerDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/SymbolDeSerDecoratorTest.java index f4ae2b932c..bf271c91d1 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/SymbolDeSerDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/SymbolDeSerDecoratorTest.java @@ -20,8 +20,8 @@ import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -32,9 +32,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SymbolDeSerDecoratorTest extends DecoratorTestCase { @@ -58,7 +56,7 @@ public class SymbolDeSerDecoratorTest extends DecoratorTestCase { private static final String IAUTOMATON_SCOPE = "de.monticore.codegen.symboltable.automatonsymbolcd._symboltable.IAutomatonSymbolCDScope"; - @Before + @BeforeEach public void setUp() { LogStub.init(); Log.enableFailQuick(false); @@ -404,7 +402,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); @@ -421,7 +419,7 @@ public void testGeneratedCodeFoo() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/Symbols2JsonDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/Symbols2JsonDecoratorTest.java index f192bb9922..eca7b34793 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/Symbols2JsonDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/serialization/Symbols2JsonDecoratorTest.java @@ -25,8 +25,8 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mcbasictypes.MCBasicTypesMill; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -34,10 +34,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class Symbols2JsonDecoratorTest extends DecoratorTestCase { @@ -67,7 +64,7 @@ public class Symbols2JsonDecoratorTest extends DecoratorTestCase { private static final String FOO_SYMBOL = "de.monticore.codegen.symboltable.automaton._symboltable.FooSymbol"; - @Before + @BeforeEach public void setUp(){ ASTCDCompilationUnit astcdCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); decoratedSymbolCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "AutomatonSymbolCD"); @@ -353,6 +350,7 @@ public static void assertOneOf(ASTMCType actualType, String... expected) { for (String exp : expected) { if (actual.equals(exp)) { result = true; + break; } } if (!result) { @@ -375,8 +373,8 @@ public void testGeneratedCode() { // Then ParseResult parseResult = new JavaParser(new ParserConfiguration()).parse(generate.toString()); - assertTrue("Parsing of the generated code failed. The generated code is: \n" - + generate, parseResult.isSuccessful()); + assertTrue(parseResult.isSuccessful(), + "Parsing of the generated code failed. The generated code is: \n" + generate); assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/CommonSymbolInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/CommonSymbolInterfaceDecoratorTest.java index 78d697f482..87ca957b81 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/CommonSymbolInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/CommonSymbolInterfaceDecoratorTest.java @@ -18,15 +18,15 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PUBLIC_ABSTRACT; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CommonSymbolInterfaceDecoratorTest extends DecoratorTestCase { @@ -42,7 +42,7 @@ public class CommonSymbolInterfaceDecoratorTest extends DecoratorTestCase { private static final String AUTOMATON_TRAVERSER = "de.monticore.codegen.ast.automaton._visitor.AutomatonTraverser"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); @@ -141,7 +141,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolBuilderDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolBuilderDecoratorTest.java index 102f430fe4..689af615d7 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolBuilderDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolBuilderDecoratorTest.java @@ -21,8 +21,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertBoolean; @@ -30,9 +30,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SymbolBuilderDecoratorTest extends DecoratorTestCase { @@ -52,7 +50,7 @@ public class SymbolBuilderDecoratorTest extends DecoratorTestCase { private static final String VALUE = "de.monticore.interpreter.MIValue"; - @Before + @BeforeEach public void setup() { this.mcTypeFacade = MCTypeFacade.getInstance(); @@ -474,7 +472,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecoratorTest.java index 90f8237bda..393e7fb1d0 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolDecoratorTest.java @@ -22,8 +22,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.List; @@ -39,9 +39,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SymbolDecoratorTest extends DecoratorTestCase { @@ -73,7 +71,7 @@ public class SymbolDecoratorTest extends DecoratorTestCase { private static final String AUTOMATON_TRAVERSER = "de.monticore.codegen.symboltable.automatonsymbolcd._visitor.AutomatonSymbolCDTraverser"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); @@ -263,7 +261,7 @@ public void testSymbolRuleAttributes() { @Test public void testMethods() { - assertEquals(23, symbolClassAutomaton.getCDMethodList().size()); + assertEquals(25, symbolClassAutomaton.getCDMethodList().size()); } @Test @@ -572,7 +570,7 @@ public void testGeneratedCodeAutomaton() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); @@ -608,30 +606,30 @@ public void testAttributeCountStateSymbol() { assertTrue(Log.getFindings().isEmpty()); } - @Test(expected = AssertionError.class) + @Test public void testSpannedScopeAttributeStateSymbol() { - getAttributeBy("spannedScope", symbolClassState); + assertThrows(AssertionError.class, () -> getAttributeBy("spannedScope", symbolClassState)); assertTrue(Log.getFindings().isEmpty()); } @Test public void testMethodsStateSymbol() { - assertEquals(21, symbolClassState.getCDMethodList().size()); + assertEquals(23, symbolClassState.getCDMethodList().size()); assertTrue(Log.getFindings().isEmpty()); } - @Test(expected = AssertionError.class) + @Test public void testGetSpannedScopeMethodStateSymbol() { - getMethodBy("getSpannedScope", symbolClassState); + assertThrows(AssertionError.class, () -> getMethodBy("getSpannedScope", symbolClassState)); assertTrue(Log.getFindings().isEmpty()); } - @Test(expected = AssertionError.class) + @Test public void testSetSpannedScopeMethodStateSymbol() { - getMethodBy("setSpannedScope", symbolClassState); + assertThrows(AssertionError.class, () -> getMethodBy("setSpannedScope", symbolClassState)); assertTrue(Log.getFindings().isEmpty()); } @@ -727,7 +725,7 @@ public void testGeneratedCodeState() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolResolverInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolResolverInterfaceDecoratorTest.java index 0bb5ffdaa9..6c36187ef1 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolResolverInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolResolverInterfaceDecoratorTest.java @@ -10,17 +10,15 @@ import de.monticore.codegen.cd2java._symboltable.SymbolTableService; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PUBLIC_ABSTRACT; import static de.monticore.codegen.cd2java.DecoratorAssert.assertBoolean; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SymbolResolverInterfaceDecoratorTest extends DecoratorTestCase { @@ -38,7 +36,7 @@ public class SymbolResolverInterfaceDecoratorTest extends DecoratorTestCase { private static final String ACCESS_MODIFIER = "de.monticore.symboltable.modifiers.AccessModifier"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateBuilderDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateBuilderDecoratorTest.java index a1231c291b..aa4afa9e8b 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateBuilderDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateBuilderDecoratorTest.java @@ -19,8 +19,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PUBLIC; @@ -28,9 +28,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SymbolSurrogateBuilderDecoratorTest extends DecoratorTestCase { @@ -48,7 +46,7 @@ public class SymbolSurrogateBuilderDecoratorTest extends DecoratorTestCase { private static final String VALUE = "de.monticore.interpreter.MIValue"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); @@ -272,7 +270,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecoratorTest.java index 786c2ed3c2..7fc585280e 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_symboltable/symbol/SymbolSurrogateDecoratorTest.java @@ -21,8 +21,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -34,9 +34,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SymbolSurrogateDecoratorTest extends DecoratorTestCase { @@ -58,7 +56,7 @@ public class SymbolSurrogateDecoratorTest extends DecoratorTestCase { private static final String AUTOMATON_SYMBOL = "de.monticore.codegen.symboltable.automatonsymbolcd._symboltable.AutomatonSymbol"; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "AutomatonSymbolCD"); @@ -141,7 +139,8 @@ public void testLoadedSymbolAttribute() { @Test public void testMethods() { - assertEquals(13, symbolClassAutomaton.getCDMethodList().size()); + + assertEquals(17, symbolClassAutomaton.getCDMethodList().size()); assertTrue(Log.getFindings().isEmpty()); } @@ -209,6 +208,32 @@ public void testSetEnclosingScopeNameMethod() { assertTrue(Log.getFindings().isEmpty()); } + @Test + public void testGetSpannedScopeNameMethod() { + ASTCDMethod method = getMethodBy("getSpannedScope", symbolClassAutomaton); + assertDeepEquals(PUBLIC, method.getModifier()); + assertDeepEquals(mcTypeFacade.createQualifiedType(I_AUTOMATON_SCOPE) + , method.getMCReturnType().getMCType()); + + assertTrue(method.isEmptyCDParameters()); + + assertTrue(Log.getFindings().isEmpty()); + } + + @Test + public void testSetSpannedScopeNameMethod() { + ASTCDMethod method = getMethodBy("setSpannedScope", symbolClassAutomaton); + assertDeepEquals(PUBLIC, method.getModifier()); + + assertTrue(method.getMCReturnType().isPresentMCVoidType()); + + assertEquals(1, method.sizeCDParameters()); + assertEquals("scope", method.getCDParameter(0).getName()); + assertDeepEquals(I_AUTOMATON_SCOPE, method.getCDParameter(0).getMCType()); + + assertTrue(Log.getFindings().isEmpty()); + } + @Test public void testGetFullNameMethod() { ASTCDMethod method = getMethodBy("getFullName", symbolClassAutomaton); @@ -269,13 +294,12 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); } - @Test public void testGeneratedCodeFoo() { GeneratorSetup generatorSetup = new GeneratorSetup(); @@ -286,7 +310,7 @@ public void testGeneratedCodeFoo() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/CDTraverserDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/CDTraverserDecoratorTest.java index 3571845f61..4df02add37 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/CDTraverserDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/CDTraverserDecoratorTest.java @@ -13,14 +13,14 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.io.paths.MCPath; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CDTraverserDecoratorTest extends DecoratorTestCase { @@ -28,7 +28,7 @@ public class CDTraverserDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { originalCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/HandlerDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/HandlerDecoratorTest.java index 3a1de28831..0360925cbc 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/HandlerDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/HandlerDecoratorTest.java @@ -17,8 +17,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; @@ -27,8 +27,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class HandlerDecoratorTest extends DecoratorTestCase { @@ -51,7 +51,7 @@ public class HandlerDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); @@ -261,7 +261,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/InheritanceHandlerDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/InheritanceHandlerDecoratorTest.java index 446f0e7cc7..8f37cbbb89 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/InheritanceHandlerDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/InheritanceHandlerDecoratorTest.java @@ -21,8 +21,8 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -31,8 +31,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class InheritanceHandlerDecoratorTest extends DecoratorTestCase { @@ -58,7 +58,7 @@ public class InheritanceHandlerDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { this.glex = new GlobalExtensionManagement(); this.mcTypeFacade = MCTypeFacade.getInstance(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/TraverserClassDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/TraverserClassDecoratorTest.java index 8dd3efefd5..55f0e71549 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/TraverserClassDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/TraverserClassDecoratorTest.java @@ -17,8 +17,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PUBLIC; @@ -27,8 +27,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertOptionalOf; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TraverserClassDecoratorTest extends DecoratorTestCase { @@ -48,7 +48,7 @@ public class TraverserClassDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); @@ -160,7 +160,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/TraverserInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/TraverserInterfaceDecoratorTest.java index b30e5e9573..24e5ff8ad0 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/TraverserInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/TraverserInterfaceDecoratorTest.java @@ -17,8 +17,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; @@ -27,8 +27,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.*; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TraverserInterfaceDecoratorTest extends DecoratorTestCase { @@ -51,7 +51,7 @@ public class TraverserInterfaceDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/Visitor2DecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/Visitor2DecoratorTest.java index f71c52730a..efd29ddd40 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/Visitor2DecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/Visitor2DecoratorTest.java @@ -16,16 +16,16 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.types.MCTypeFacade; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class Visitor2DecoratorTest extends DecoratorTestCase { @@ -55,7 +55,7 @@ public class Visitor2DecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { this.mcTypeFacade = MCTypeFacade.getInstance(); @@ -255,7 +255,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/VisitorServiceTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/VisitorServiceTest.java index 7fa18f67b3..01056ebb93 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/VisitorServiceTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/_visitor/VisitorServiceTest.java @@ -8,14 +8,14 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class VisitorServiceTest extends DecoratorTestCase { @@ -29,7 +29,7 @@ public class VisitorServiceTest extends DecoratorTestCase { private MCTypeFacade mcTypeFacade; - @Before + @BeforeEach public void setup() { this.mcTypeFacade = MCTypeFacade.getInstance(); astcdCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/cli/CDCLIDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/cli/CDCLIDecoratorTest.java index 032f6ad111..079c7a66df 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/cli/CDCLIDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/cli/CDCLIDecoratorTest.java @@ -15,13 +15,13 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CDCLIDecoratorTest extends DecoratorTestCase { @@ -32,7 +32,7 @@ public class CDCLIDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit clonedCD; - @Before + @BeforeEach public void setup() { originalCD = parse("de", "monticore", "codegen", "ast", "Automaton"); clonedCD = originalCD.deepClone(); @@ -104,7 +104,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/cli/CLIDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/cli/CLIDecoratorTest.java index b1a98efd8c..700240bd26 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/cli/CLIDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/cli/CLIDecoratorTest.java @@ -16,16 +16,14 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.cd.facade.CDModifier.PUBLIC_STATIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.*; public class CLIDecoratorTest extends DecoratorTestCase { private static final String AST_AUTOMATON = "de.monticore.codegen.ast.automaton._ast.ASTAutomaton"; @@ -33,7 +31,7 @@ public class CLIDecoratorTest extends DecoratorTestCase { private static final String CLI_OPTIONS = "org.apache.commons.cli.Options"; private ASTCDClass cliClass; - @Before + @BeforeEach public void setup() { ASTCDCompilationUnit ast = parse("de", "monticore", "codegen", "ast", "Automaton"); this.glex.setGlobalValue("service", new AbstractService(ast)); @@ -284,7 +282,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/DataDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/DataDecoratorTest.java index 5bbfb29ead..64a0cfe3c3 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/DataDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/DataDecoratorTest.java @@ -21,8 +21,8 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PUBLIC; @@ -34,15 +34,13 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.*; public class DataDecoratorTest extends DecoratorTestCase { private ASTCDClass dataClass; - @Before + @BeforeEach public void setUp() { ASTCDCompilationUnit cd = this.parse("de", "monticore", "codegen", "data", "Data"); ASTCDClass clazz = getClassBy("A", cd); @@ -288,7 +286,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); @@ -317,7 +315,7 @@ public void testGeneratedAutomatonCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/DataInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/DataInterfaceDecoratorTest.java index d1f756103e..328b9389e6 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/DataInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/DataInterfaceDecoratorTest.java @@ -18,22 +18,20 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PUBLIC_ABSTRACT; import static de.monticore.codegen.cd2java.DecoratorAssert.assertBoolean; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.*; public class DataInterfaceDecoratorTest extends DecoratorTestCase { private ASTCDInterface dataInterface; - @Before + @BeforeEach public void setUp() { ASTCDCompilationUnit cd = this.parse("de", "monticore", "codegen", "data", "DataInterface"); ASTCDInterface clazz = getInterfaceBy("ASTA", cd); @@ -199,7 +197,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/FullConstructorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/FullConstructorTest.java index 3f933e2729..a6532defcf 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/FullConstructorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/FullConstructorTest.java @@ -20,16 +20,16 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.generating.templateengine.GlobalExtensionManagement; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.codegen.cd2java.DecoratorAssert.assertBoolean; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class FullConstructorTest extends DecoratorTestCase { @@ -39,7 +39,7 @@ public class FullConstructorTest extends DecoratorTestCase { private ASTCDClass subAClass; - @Before + @BeforeEach public void setup() { this.glex.setGlobalValue("astHelper", DecorationHelper.getInstance()); this.glex.setGlobalValue("cdPrinter", new CdUtilsPrinter()); @@ -128,7 +128,7 @@ public void testGeneratedCodeSubA() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); @@ -145,7 +145,7 @@ public void testGeneratedCodeSubB() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/ListSuffixDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/ListSuffixDecoratorTest.java index 72a287272e..333af42971 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/ListSuffixDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/data/ListSuffixDecoratorTest.java @@ -7,13 +7,14 @@ import de.monticore.codegen.cd2java.AbstractService; import de.monticore.codegen.cd2java.DecoratorTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ListSuffixDecoratorTest extends DecoratorTestCase { @@ -21,7 +22,7 @@ public class ListSuffixDecoratorTest extends DecoratorTestCase { private ASTCDClass originalClass; - @Before + @BeforeEach public void setUp() { ASTCDCompilationUnit cd = this.parse("de", "monticore", "codegen", "data", "Data"); @@ -43,9 +44,9 @@ public void testNoSBefore() { assertTrue(Log.getFindings().isEmpty()); } - @Test(expected = AssertionError.class) + @Test public void testWithSSBefore() { - getAttributeBy("lists", originalClass); + assertThrows(AssertionError.class, () -> getAttributeBy("lists", originalClass)); assertTrue(Log.getFindings().isEmpty()); } @@ -59,9 +60,9 @@ public void testWithSAfter() { assertTrue(Log.getFindings().isEmpty()); } - @Test(expected = AssertionError.class) + @Test public void testNoSAfter() { - getAttributeBy("list", classWithS); + assertThrows(AssertionError.class, () -> getAttributeBy("list", classWithS)); assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index 83583393a5..b7de1d16c5 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -16,12 +16,15 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; -import static groovy.test.GroovyTestCase.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class InterpreterDecoratorTest extends DecoratorTestCase { @@ -29,7 +32,7 @@ public class InterpreterDecoratorTest extends DecoratorTestCase { protected ASTCDClass decoratedClass; - @Before + @BeforeEach public void before() { originalCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); ASTService astService = new ASTService(originalCompilationUnit); @@ -52,10 +55,15 @@ public void testConstructors() { assertEquals(2, constructors.size()); assertTrue(constructors.get(0).getCDParameterList().isEmpty()); - assertEquals(1, constructors.get(1).getCDParameterList().size()); - assertEquals("realThis", constructors.get(1).getCDParameter(0).getName()); - assertEquals(InterpreterConstants.MODELINTERPRETER_FULLNAME, - constructors.get(1).getCDParameter(0).getMCType().printType()); + assertEquals( + 1, + constructors.get(1).getCDParameterList().size()); + assertEquals( + "realThis", + constructors.get(1).getCDParameter(0).getName()); + assertEquals( + InterpreterConstants.MODELINTERPRETER_FULLNAME, + constructors.get(1).getCDParameter(0).getMCType().printType()); } @Test @@ -65,8 +73,8 @@ public void testSuperInterfaces() { assertEquals(1, interfaces.size()); assertEquals( - ((ASTMCQualifiedType) interfaces.get(0)).getMCQualifiedName().getQName(), - "IAutomatonInterpreter"); + "IAutomatonInterpreter", + ((ASTMCQualifiedType) interfaces.get(0)).getMCQualifiedName().getQName()); } @Test @@ -75,18 +83,30 @@ public void testClassAttributes() { assertEquals(3, attributes.size()); - assertEquals("lexicalsInterpreter", attributes.get(0).getName()); - assertEquals("de.monticore.codegen.ast.lexicals._visitor.ILexicalsInterpreter", - attributes.get(0).getMCType().printType()); + assertEquals( + "lexicalsInterpreter", + attributes.get(0).getName()); + assertEquals( + "de.monticore.codegen.ast.lexicals._visitor.ILexicalsInterpreter", + attributes.get(0).getMCType().printType()); - assertEquals("realThis", attributes.get(1).getName()); - assertEquals(InterpreterConstants.MODELINTERPRETER_FULLNAME, - attributes.get(1).getMCType().printType()); + assertEquals( + "realThis", + attributes.get(1).getName()); + assertEquals( + InterpreterConstants.MODELINTERPRETER_FULLNAME, + attributes.get(1).getMCType().printType()); - assertEquals("scopeCallstack", attributes.get(2).getName()); - assertEquals("java.util.Stack", ((ASTMCGenericType)attributes.get(2).getMCType()).printWithoutTypeArguments()); - assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, - ((ASTMCGenericType)attributes.get(2).getMCType()).getMCTypeArgument(0).printType()); + assertEquals( + "contextMap", + attributes.get(2).getName()); + assertInstanceOf(ASTMCMapType.class, attributes.get(2).getMCType()); + assertEquals( + InterpreterConstants.SYMBOL_FULLNAME, + ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(0).printType()); + assertEquals( + InterpreterConstants.VALUE_FULLNAME, + ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(1).printType()); } @Test @@ -100,8 +120,9 @@ public void testRealThisMethods() { ASTCDMethod getMethod = optGetMethod.get(); assertTrue(getMethod.getCDParameterList().isEmpty()); - assertEquals(InterpreterConstants.MODELINTERPRETER_FULLNAME, - getMethod.getMCReturnType().printType()); + assertEquals( + InterpreterConstants.MODELINTERPRETER_FULLNAME, + getMethod.getMCReturnType().printType()); Optional optSetMethod = decoratedClass.getCDMethodList() .stream() @@ -112,10 +133,12 @@ public void testRealThisMethods() { ASTCDMethod setMethod = optSetMethod.get(); assertEquals(1, setMethod.getCDParameterList().size()); - assertEquals(InterpreterConstants.MODELINTERPRETER_FULLNAME, - setMethod.getCDParameter(0).getMCType().printType()); - assertEquals("realThis", - setMethod.getCDParameter(0).getName()); + assertEquals( + InterpreterConstants.MODELINTERPRETER_FULLNAME, + setMethod.getCDParameter(0).getMCType().printType()); + assertEquals( + "realThis", + setMethod.getCDParameter(0).getName()); assertTrue(setMethod.getMCReturnType().isPresentMCVoidType()); } @@ -133,9 +156,74 @@ public void testScopeCallstackMethod() { assertEquals("java.util.Stack", returnTypeType.printWithoutTypeArguments()); assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, returnTypeType.getMCTypeArgument(0).printType()); + assertTrue(optStoreMethod.isPresent()); + ASTCDMethod storeMethod = optStoreMethod.get(); + + assertTrue(storeMethod.getMCReturnType().isPresentMCVoidType()); + assertEquals(2, storeMethod.getCDParameterList().size()); + assertEquals("symbol", storeMethod.getCDParameter(0).getName()); + assertEquals( + InterpreterConstants.SYMBOL_FULLNAME, + storeMethod.getCDParameter(0).getMCType().printType()); + assertEquals("value", storeMethod.getCDParameter(1).getName()); + assertEquals( + InterpreterConstants.VALUE_FULLNAME, + storeMethod.getCDParameter(1).getMCType().printType()); + + Optional optLoadMethod = decoratedClass.getCDMethodList() + .stream() + .filter(m -> m.getName().equals("load")) + .findAny(); + + assertTrue(optLoadMethod.isPresent()); + ASTCDMethod loadMethod = optLoadMethod.get(); + + assertEquals( + InterpreterConstants.VALUE_FULLNAME, + loadMethod.getMCReturnType().printType()); + assertEquals(1, loadMethod.getCDParameterList().size()); + assertEquals( + InterpreterConstants.SYMBOL_FULLNAME, + loadMethod.getCDParameter(0).getMCType().printType()); + assertEquals( + "symbol", + loadMethod.getCDParameter(0).getName()); + + Optional optGetMap = decoratedClass.getCDMethodList() + .stream() + .filter(m -> m.getName().equals("getContextMap")) + .findAny(); + + assertTrue(optGetMap.isPresent()); + ASTCDMethod getMapMethod = optGetMap.get(); + + assertTrue(getMapMethod.getCDParameterList().isEmpty()); + assertInstanceOf(ASTMCMapType.class, getMapMethod.getMCReturnType().getMCType()); + assertEquals( + InterpreterConstants.SYMBOL_FULLNAME, + ((ASTMCMapType) getMapMethod.getMCReturnType().getMCType()).getMCTypeArgument(0).printType()); + assertEquals( + InterpreterConstants.VALUE_FULLNAME, + ((ASTMCMapType) getMapMethod.getMCReturnType().getMCType()).getMCTypeArgument(1).printType()); + } + + @Test + @Disabled + public void testInterpretMethods() { + List interpretMethods = decoratedClass.getCDMethodList() + .stream() + .filter(m -> m.getName().equals("interpret")) + .collect(Collectors.toList()); + + assertEquals(0, interpretMethods.size()); + ASTCDMethod method = interpretMethods.get(0); + + assertEquals(1, method.getCDParameterList().size()); + assertEquals("node", method.getCDParameter(0).getName()); + assertEquals(InterpreterConstants.VALUE_FULLNAME, method.getMCReturnType().printType()); } - @After + @AfterEach public void after() { assertTrue(Log.getFindings().isEmpty()); Log.getFindings().clear(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterInterfaceDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterInterfaceDecoratorTest.java index 88a0c985c0..f313da9e7a 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterInterfaceDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterInterfaceDecoratorTest.java @@ -9,18 +9,16 @@ import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; import de.se_rwth.commons.logging.Log; -import org.checkerframework.checker.interning.qual.FindDistinct; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; -import static groovy.test.GroovyTestCase.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class InterpreterInterfaceDecoratorTest extends DecoratorTestCase { @@ -29,7 +27,7 @@ public class InterpreterInterfaceDecoratorTest extends DecoratorTestCase { protected ASTCDInterface decoratedInterface; - @Before + @BeforeEach public void before() { originalCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "Automaton"); VisitorService visitorService = new VisitorService(originalCompilationUnit); @@ -49,15 +47,15 @@ public void testSuperInterfaces() { List interfaces = decoratedInterface.getInterfaceList(); assertEquals(2, interfaces.size()); assertEquals( - ((ASTMCQualifiedType) interfaces.get(0)).getMCQualifiedName().getQName(), - "de.monticore.codegen.ast.lexicals._visitor.ILexicalsInterpreter"); + "de.monticore.codegen.ast.lexicals._visitor.ILexicalsInterpreter", + ((ASTMCQualifiedType) interfaces.get(0)).getMCQualifiedName().getQName()); assertEquals( - ((ASTMCQualifiedType) interfaces.get(1)).getMCQualifiedName().getQName(), - InterpreterConstants.MODELINTERPRETER_FULLNAME); + InterpreterConstants.MODELINTERPRETER_FULLNAME, + ((ASTMCQualifiedType) interfaces.get(1)).getMCQualifiedName().getQName()); } @Test - @Ignore + @Disabled public void testInterpretMethods() { List interpretMethods = decoratedInterface.getCDMethodList() .stream() @@ -74,7 +72,7 @@ public void testInterpretMethods() { assertTrue(method.getModifier().isAbstract()); } - @After + @AfterEach public void after() { assertTrue(Log.getFindings().isEmpty()); Log.getFindings().clear(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/ListAccessorDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/ListAccessorDecoratorTest.java index 7162860d4d..26fdba79f2 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/ListAccessorDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/ListAccessorDecoratorTest.java @@ -11,8 +11,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -20,15 +20,15 @@ import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.DecoratorAssert.*; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ListAccessorDecoratorTest extends DecoratorTestCase { private List methods; - @Before + @BeforeEach public void setup() { ASTMCType listType = MCTypeFacade.getInstance().createListTypeOf(String.class); ASTCDAttribute attribute = CDAttributeFacade.getInstance().createAttribute(PROTECTED.build(), listType, "a"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/MandatoryAccessorDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/MandatoryAccessorDecoratorTest.java index 3d8ce6b681..b5283986ed 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/MandatoryAccessorDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/MandatoryAccessorDecoratorTest.java @@ -7,7 +7,7 @@ import de.monticore.codegen.cd2java.DecoratorTestCase; import de.monticore.codegen.cd2java.methods.accessor.MandatoryAccessorDecorator; import de.se_rwth.commons.logging.Log; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; @@ -15,8 +15,8 @@ import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MandatoryAccessorDecoratorTest extends DecoratorTestCase { diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/OptionalAccessorDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/OptionalAccessorDecoratorTest.java index 3ff866fca3..239c899ff8 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/OptionalAccessorDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/accessor/OptionalAccessorDecoratorTest.java @@ -11,9 +11,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -22,14 +21,14 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertBoolean; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class OptionalAccessorDecoratorTest extends DecoratorTestCase { private List methods; - @Before + @BeforeEach public void setup() { // dummy cd needed for a good generated error Code ASTCDCompilationUnit cd = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); @@ -51,7 +50,7 @@ public void testMethods() { public void testGetMethod() { ASTCDMethod method = getMethodBy("getA", this.methods); assertTrue(method.getCDParameterList().isEmpty()); - Assert.assertTrue(method.getMCReturnType().isPresentMCType()); + assertTrue(method.getMCReturnType().isPresentMCType()); assertDeepEquals(String.class, method.getMCReturnType().getMCType()); assertDeepEquals(PUBLIC, method.getModifier()); @@ -61,7 +60,7 @@ public void testGetMethod() { @Test public void testIsPresentMethod() { ASTCDMethod method = getMethodBy("isPresentA", this.methods); - Assert.assertTrue(method.getMCReturnType().isPresentMCType()); + assertTrue(method.getMCReturnType().isPresentMCType()); assertBoolean(method.getMCReturnType().getMCType()); assertDeepEquals(PUBLIC, method.getModifier()); assertTrue(method.getCDParameterList().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/ListMutatorDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/ListMutatorDecoratorTest.java index 4a1f60ab63..2ca3a2192a 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/ListMutatorDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/ListMutatorDecoratorTest.java @@ -10,8 +10,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; @@ -24,15 +24,15 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertListOf; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodsBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ListMutatorDecoratorTest extends DecoratorTestCase { private List methods; - @Before + @BeforeEach public void setup() { ASTMCType listType = MCTypeFacade.getInstance().createListTypeOf(String.class); ASTCDAttribute attribute = CDAttributeFacade.getInstance().createAttribute(PROTECTED.build(), listType, "a"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/MandatoryMutatorDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/MandatoryMutatorDecoratorTest.java index 339cd967c5..af7bad7181 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/MandatoryMutatorDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/MandatoryMutatorDecoratorTest.java @@ -8,8 +8,8 @@ import de.monticore.codegen.cd2java.DecoratorTestCase; import de.monticore.codegen.cd2java.methods.mutator.MandatoryMutatorDecorator; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -17,14 +17,14 @@ import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MandatoryMutatorDecoratorTest extends DecoratorTestCase { private List methods; - @Before + @BeforeEach public void setup() { ASTCDAttribute attribute = CDAttributeFacade.getInstance().createAttribute(PROTECTED.build(), String.class, "a"); MandatoryMutatorDecorator mandatoryMutatorDecorator = new MandatoryMutatorDecorator(glex); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/OptionalMutatorDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/OptionalMutatorDecoratorTest.java index e7fa870f40..aa64f1b909 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/OptionalMutatorDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/method/mutator/OptionalMutatorDecoratorTest.java @@ -10,8 +10,8 @@ import de.monticore.types.MCTypeFacade; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; @@ -19,14 +19,14 @@ import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class OptionalMutatorDecoratorTest extends DecoratorTestCase { private List methods; - @Before + @BeforeEach public void setup() { ASTMCType optionalType = MCTypeFacade.getInstance().createOptionalTypeOf(String.class); ASTCDAttribute attribute = CDAttributeFacade.getInstance().createAttribute(PROTECTED.build(), optionalType, "a"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/CDAuxiliaryDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/CDAuxiliaryDecoratorTest.java index 08aab95ad4..814c0fe8a6 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/CDAuxiliaryDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/CDAuxiliaryDecoratorTest.java @@ -29,15 +29,14 @@ import de.monticore.codegen.cd2java.methods.AccessorDecorator; import de.monticore.codegen.cd2java.methods.MethodDecorator; import de.se_rwth.commons.logging.Log; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Optional; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CDAuxiliaryDecoratorTest extends DecoratorTestCase { @@ -45,7 +44,7 @@ public class CDAuxiliaryDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { originalCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); @@ -90,7 +89,7 @@ protected ASTCDCompilationUnit getASTCD() { @Test public void testPackageName() { - Assert.assertTrue (decoratedCompilationUnit.getCDDefinition().getPackageWithName("de.monticore.codegen.symboltable.automaton._auxiliary").isPresent()); + assertTrue (decoratedCompilationUnit.getCDDefinition().getPackageWithName("de.monticore.codegen.symboltable.automaton._auxiliary").isPresent()); assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/CDMillDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/CDMillDecoratorTest.java index ce377069d2..a614478ab4 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/CDMillDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/CDMillDecoratorTest.java @@ -49,17 +49,16 @@ import de.monticore.codegen.cd2java.methods.MethodDecorator; import de.monticore.io.paths.MCPath; import de.se_rwth.commons.logging.Log; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Optional; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CDMillDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit originalCompilationUnit; @@ -72,7 +71,7 @@ public class CDMillDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit clonedCD; - @Before + @BeforeEach public void setUp() { originalCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); scopeCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "AutomatonScopeCD"); @@ -168,7 +167,7 @@ public void testCompilationUnitNotChanged() { @Test public void testPackageName() { - Assert.assertTrue (decoratedCompilationUnit.getCDDefinition().getPackageWithName("de.monticore.codegen.symboltable.automaton").isPresent()); + assertTrue (decoratedCompilationUnit.getCDDefinition().getPackageWithName("de.monticore.codegen.symboltable.automaton").isPresent()); assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillDecoratorTest.java index f472606286..9305f5f5b9 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillDecoratorTest.java @@ -66,8 +66,8 @@ import de.monticore.io.paths.MCPath; import de.monticore.umlmodifier._ast.ASTModifier; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.ArrayList; @@ -82,8 +82,8 @@ import static de.monticore.codegen.cd2java._ast.ast_class.ASTConstants.AST_PACKAGE; import static de.monticore.codegen.cd2java._symboltable.SymbolTableConstants.SYMBOL_TABLE_PACKAGE; import static de.monticore.codegen.cd2java._visitor.VisitorConstants.VISITOR_PACKAGE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MillDecoratorTest extends DecoratorTestCase { @@ -99,7 +99,7 @@ public class MillDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit clonedCD; - @Before + @BeforeEach public void setUp() { originalCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); originalScopeCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "AutomatonScopeCD"); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillForSuperDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillForSuperDecoratorTest.java index 9a1e123a01..14e1934c8a 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillForSuperDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillForSuperDecoratorTest.java @@ -11,16 +11,16 @@ import de.monticore.codegen.cd2java._parser.ParserService; import de.monticore.codegen.cd2java._visitor.VisitorService; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MillForSuperDecoratorTest extends DecoratorTestCase { @@ -30,7 +30,7 @@ public class MillForSuperDecoratorTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "ast", "ExtAutomaton"); originalCompilationUnit = decoratedCompilationUnit.deepClone(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillWithInheritanceTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillWithInheritanceTest.java index a83dc52ecb..7d0c7fc090 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillWithInheritanceTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/mill/MillWithInheritanceTest.java @@ -40,16 +40,16 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static de.monticore.cd.facade.CDModifier.PROTECTED; import static de.monticore.cd.facade.CDModifier.PROTECTED_STATIC; import static de.monticore.cd.facade.CDModifier.PUBLIC_STATIC; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MillWithInheritanceTest extends DecoratorTestCase { @@ -59,7 +59,7 @@ public class MillWithInheritanceTest extends DecoratorTestCase { private ASTCDCompilationUnit decoratedCompilationUnit; - @Before + @BeforeEach public void setUp() { decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "factory", "CGrammar"); ICD4CodeGlobalScope gs = CD4CodeMill.globalScope(); @@ -255,7 +255,7 @@ public void testGeneratedCode() { // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); - ParseResult parseResult = parser.parse(sb.toString()); + ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/typecd2java/TypeCD2JavaTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/typecd2java/TypeCD2JavaTest.java index 3d79b467fc..7a0f28c11c 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/typecd2java/TypeCD2JavaTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/typecd2java/TypeCD2JavaTest.java @@ -8,18 +8,16 @@ import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; import de.monticore.types.mccollectiontypes._ast.ASTMCGenericType; import de.se_rwth.commons.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class TypeCD2JavaTest extends DecoratorTestCase { private ASTCDCompilationUnit cdCompilationUnit; - @Before + @BeforeEach public void setUp() { ICD4AnalysisGlobalScope globalScope = CD4AnalysisMill.globalScope(); cdCompilationUnit = parse("de", "monticore", "codegen", "ast", "Automaton"); @@ -32,7 +30,9 @@ public void setUp() { @Test public void testTypeJavaConformList() { - assertTrue(cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(1).getMCType() instanceof ASTMCGenericType); + assertInstanceOf(ASTMCGenericType.class, + cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(1) + .getMCType()); ASTMCGenericType simpleReferenceType = (ASTMCGenericType) cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(1).getMCType(); assertFalse(simpleReferenceType.getNameList().isEmpty()); assertEquals(3, simpleReferenceType.getNameList().size()); @@ -46,11 +46,14 @@ public void testTypeJavaConformList() { @Test public void testTypeJavaConformASTPackage() { //test that for AST classes the package is now java conform - assertTrue(cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(1).getMCType() instanceof ASTMCGenericType); + assertInstanceOf(ASTMCGenericType.class, + cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(1) + .getMCType()); ASTMCGenericType listType = (ASTMCGenericType) cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(1).getMCType(); assertEquals(1, listType.getMCTypeArgumentList().size()); assertTrue(listType.getMCTypeArgumentList().get(0).getMCTypeOpt().isPresent()); - assertTrue(listType.getMCTypeArgumentList().get(0).getMCTypeOpt().get() instanceof ASTMCQualifiedType); + assertInstanceOf(ASTMCQualifiedType.class, + listType.getMCTypeArgumentList().get(0).getMCTypeOpt().get()); ASTMCQualifiedType typeArgument = (ASTMCQualifiedType) listType.getMCTypeArgumentList().get(0).getMCTypeOpt().get(); assertEquals(7, typeArgument.getNameList().size()); assertEquals("de", typeArgument.getNameList().get(0)); @@ -67,7 +70,9 @@ public void testTypeJavaConformASTPackage() { @Test public void testStringType() { //test that types like String are not changed - assertTrue(cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(0).getMCType() instanceof ASTMCQualifiedType); + assertInstanceOf(ASTMCQualifiedType.class, + cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(0) + .getMCType()); ASTMCQualifiedType simpleReferenceType = (ASTMCQualifiedType) cdCompilationUnit.getCDDefinition().getCDClassesList().get(0).getCDAttributeList().get(0).getMCType(); assertFalse(simpleReferenceType.getNameList().isEmpty()); assertEquals(1, simpleReferenceType.getNameList().size()); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/manipul/RemoveRedundantReferencesManipulationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/manipul/RemoveRedundantReferencesManipulationTest.java index 27a65e1dbe..a6a4da37c3 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/manipul/RemoveRedundantReferencesManipulationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/manipul/RemoveRedundantReferencesManipulationTest.java @@ -9,11 +9,10 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class RemoveRedundantReferencesManipulationTest extends TranslationTestCase { @@ -23,14 +22,14 @@ public void testGenericList() { TransformationHelper.createType("ASTReference"), "name", TransformationHelper.createType("java.util.List", "ASTReference")); - Assertions.assertEquals(2, cdClass.getCDAttributeList().size()); + assertEquals(2, cdClass.getCDAttributeList().size()); cdClass.setCDAttributeList(new RemoveRedundantAttributesManipulation() .removeRedundantAttributes(cdClass.getCDAttributeList())); - Assertions.assertEquals(1, cdClass.getCDAttributeList().size()); + assertEquals(1, cdClass.getCDAttributeList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private ASTCDClass setupCDClass(String firstReferenceName, ASTMCType firstReferenceType, @@ -40,10 +39,12 @@ private ASTCDClass setupCDClass(String firstReferenceName, ASTMCType firstRefere ASTCDAttribute singleAttribute = CD4AnalysisMill.cDAttributeBuilder().uncheckedBuild(); singleAttribute.setName(firstReferenceName); singleAttribute.setMCType(firstReferenceType); - + singleAttribute.setModifier(CD4AnalysisMill.modifierBuilder().uncheckedBuild()); + ASTCDAttribute listAttribute = CD4AnalysisMill.cDAttributeBuilder().uncheckedBuild(); listAttribute.setName(secondReferenceName); listAttribute.setMCType(secondReferenceType); + listAttribute.setModifier(CD4AnalysisMill.modifierBuilder().uncheckedBuild()); cdClass.addCDMember(singleAttribute); cdClass.addCDMember(listAttribute); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/scopeTransl/CDScopeTranslationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/scopeTransl/CDScopeTranslationTest.java index f74e8bab38..b24d302f67 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/scopeTransl/CDScopeTranslationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/scopeTransl/CDScopeTranslationTest.java @@ -10,7 +10,6 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,8 +17,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CDScopeTranslationTest extends TranslationTestCase { @@ -33,50 +32,50 @@ public void setUp() { @Test public void testDefinitionName() { - Assertions.assertEquals("ScopeRuleScope", compilationUnit.getCDDefinition().getName()); + assertEquals("ScopeRuleScope", compilationUnit.getCDDefinition().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPackage() { - Assertions.assertEquals(2, compilationUnit.getCDPackageList().size()); - Assertions.assertEquals("mc2cdtransformation", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(0)); - Assertions.assertEquals("scopeTransl", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(1)); + assertEquals(2, compilationUnit.getCDPackageList().size()); + assertEquals("mc2cdtransformation", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(0)); + assertEquals("scopeTransl", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(1)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testClassCount() { - Assertions.assertEquals(1, compilationUnit.getCDDefinition().getCDClassesList().size()); + assertEquals(1, compilationUnit.getCDDefinition().getCDClassesList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testClassSymbol() { ASTCDClass scopeClass = getClassBy("ScopeRule", compilationUnit); - Assertions.assertEquals(1, scopeClass.getCDAttributeList().size()); - Assertions.assertEquals(1, scopeClass.getCDMethodList().size()); - Assertions.assertEquals(1, scopeClass.getInterfaceList().size()); + assertEquals(1, scopeClass.getCDAttributeList().size()); + assertEquals(1, scopeClass.getCDMethodList().size()); + assertEquals(1, scopeClass.getInterfaceList().size()); - Assertions.assertTrue(scopeClass.getCDConstructorList().isEmpty()); - Assertions.assertTrue(scopeClass.isPresentCDExtendUsage()); + assertTrue(scopeClass.getCDConstructorList().isEmpty()); + assertTrue(scopeClass.isPresentCDExtendUsage()); ASTCDAttribute cdAttribute = scopeClass.getCDAttributeList().get(0); - Assertions.assertEquals("extraAttr", cdAttribute.getName()); + assertEquals("extraAttr", cdAttribute.getName()); assertDeepEquals(String.class, cdAttribute.getMCType()); assertDeepEquals(CDModifier.PROTECTED, cdAttribute.getModifier()); ASTCDMethod cdMethod = scopeClass.getCDMethodList().get(0); - Assertions.assertEquals("toString", cdMethod.getName()); - Assertions.assertTrue(cdMethod.getMCReturnType().isPresentMCType()); + assertEquals("toString", cdMethod.getName()); + assertTrue(cdMethod.getMCReturnType().isPresentMCType()); assertDeepEquals(String.class, cdMethod.getMCReturnType().getMCType()); - Assertions.assertTrue(cdMethod.getModifier().isPublic()); - Assertions.assertTrue(cdMethod.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, cdMethod.getModifier().getStereotype().sizeValues()); - Assertions.assertEquals("methodBody", cdMethod.getModifier().getStereotype().getValues(0).getName()); + assertTrue(cdMethod.getModifier().isPublic()); + assertTrue(cdMethod.getModifier().isPresentStereotype()); + assertEquals(1, cdMethod.getModifier().getStereotype().sizeValues()); + assertEquals("methodBody", cdMethod.getModifier().getStereotype().getValues(0).getName()); ASTMCObjectType cdInterface = scopeClass.getCDInterfaceUsage().getInterface(0); assertDeepEquals("de.monticore.symboltable.IScope", cdInterface); @@ -84,7 +83,7 @@ public void testClassSymbol() { ASTMCObjectType superclass = scopeClass.getCDExtendUsage().getSuperclass(0); assertDeepEquals("de.monticore.mcbasics._symboltable.IMCBasicsScope", superclass); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/symbolTransl/CDSymbolTranslationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/symbolTransl/CDSymbolTranslationTest.java index 8a057a5b9b..e712143380 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/symbolTransl/CDSymbolTranslationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/symbolTransl/CDSymbolTranslationTest.java @@ -10,7 +10,6 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +17,7 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; +import static org.junit.jupiter.api.Assertions.*; public class CDSymbolTranslationTest extends TranslationTestCase { @@ -31,49 +31,49 @@ public void setUp() { @Test public void testDefinitionName() { - Assertions.assertEquals("SymbolRuleSymbols", compilationUnit.getCDDefinition().getName()); + assertEquals("SymbolRuleSymbols", compilationUnit.getCDDefinition().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPackage() { - Assertions.assertEquals(2, compilationUnit.getCDPackageList().size()); - Assertions.assertEquals("mc2cdtransformation", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(0)); - Assertions.assertEquals("symbolTransl", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(1)); + assertEquals(2, compilationUnit.getCDPackageList().size()); + assertEquals("mc2cdtransformation", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(0)); + assertEquals("symbolTransl", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(1)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testClassCount() { - Assertions.assertEquals(4, compilationUnit.getCDDefinition().getCDClassesList().size()); + assertEquals(4, compilationUnit.getCDDefinition().getCDClassesList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testClassSymbol() { ASTCDClass symbolClassSymbol = getClassBy("SymbolClass", compilationUnit); - Assertions.assertEquals(1, symbolClassSymbol.getCDAttributeList().size()); - Assertions.assertEquals(1, symbolClassSymbol.getInterfaceList().size()); - Assertions.assertEquals(1, symbolClassSymbol.getCDMethodList().size()); - Assertions.assertTrue(symbolClassSymbol.getCDConstructorList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.isPresentCDExtendUsage()); + assertEquals(1, symbolClassSymbol.getCDAttributeList().size()); + assertEquals(1, symbolClassSymbol.getInterfaceList().size()); + assertEquals(1, symbolClassSymbol.getCDMethodList().size()); + assertTrue(symbolClassSymbol.getCDConstructorList().isEmpty()); + assertTrue(symbolClassSymbol.isPresentCDExtendUsage()); ASTCDAttribute cdAttribute = symbolClassSymbol.getCDAttributeList().get(0); - Assertions.assertEquals("extraString", cdAttribute.getName()); + assertEquals("extraString", cdAttribute.getName()); assertDeepEquals(String.class, cdAttribute.getMCType()); assertDeepEquals(CDModifier.PROTECTED, cdAttribute.getModifier()); ASTCDMethod cdMethod = symbolClassSymbol.getCDMethodList().get(0); - Assertions.assertEquals("toString", cdMethod.getName()); - Assertions.assertTrue(cdMethod.getMCReturnType().isPresentMCType()); + assertEquals("toString", cdMethod.getName()); + assertTrue(cdMethod.getMCReturnType().isPresentMCType()); assertDeepEquals(String.class, cdMethod.getMCReturnType().getMCType()); - Assertions.assertTrue(cdMethod.getModifier().isPublic()); - Assertions.assertTrue(cdMethod.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, cdMethod.getModifier().getStereotype().sizeValues()); - Assertions.assertEquals("methodBody", cdMethod.getModifier().getStereotype().getValues(0).getName()); + assertTrue(cdMethod.getModifier().isPublic()); + assertTrue(cdMethod.getModifier().isPresentStereotype()); + assertEquals(1, cdMethod.getModifier().getStereotype().sizeValues()); + assertEquals("methodBody", cdMethod.getModifier().getStereotype().getValues(0).getName()); ASTMCObjectType cdInterface = symbolClassSymbol.getInterfaceList().get(0); assertDeepEquals("de.monticore.symboltable.ISymbol", cdInterface); @@ -81,62 +81,62 @@ public void testClassSymbol() { ASTMCObjectType superclass = symbolClassSymbol.getCDExtendUsage().getSuperclass(0); assertDeepEquals("de.monticore.symboltable.Symbol", superclass); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAbstractClassSymbol() { ASTCDClass symbolClassSymbol = getClassBy("SymbolAbstractClass", compilationUnit); - Assertions.assertEquals(1, symbolClassSymbol.getCDAttributeList().size()); - Assertions.assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getCDConstructorList().isEmpty()); - Assertions.assertFalse(symbolClassSymbol.isPresentCDExtendUsage()); + assertEquals(1, symbolClassSymbol.getCDAttributeList().size()); + assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); + assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); + assertTrue(symbolClassSymbol.getCDConstructorList().isEmpty()); + assertFalse(symbolClassSymbol.isPresentCDExtendUsage()); ASTCDAttribute cdAttribute = symbolClassSymbol.getCDAttributeList().get(0); - Assertions.assertEquals("extraString", cdAttribute.getName()); + assertEquals("extraString", cdAttribute.getName()); assertDeepEquals(String.class, cdAttribute.getMCType()); assertDeepEquals(CDModifier.PROTECTED, cdAttribute.getModifier()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInterfaceCount() { - Assertions.assertTrue(compilationUnit.getCDDefinition().getCDInterfacesList().isEmpty()); + assertTrue(compilationUnit.getCDDefinition().getCDInterfacesList().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInterfaceSymbol() { ASTCDClass symbolClassSymbol = getClassBy("SymbolInterface", compilationUnit); - Assertions.assertEquals(1, symbolClassSymbol.getCDAttributeList().size()); - Assertions.assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); + assertEquals(1, symbolClassSymbol.getCDAttributeList().size()); + assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); + assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); ASTCDAttribute cdAttribute = symbolClassSymbol.getCDAttributeList().get(0); - Assertions.assertEquals("extraString", cdAttribute.getName()); + assertEquals("extraString", cdAttribute.getName()); assertDeepEquals(String.class, cdAttribute.getMCType()); assertDeepEquals(CDModifier.PROTECTED, cdAttribute.getModifier()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExternalSymbol() { ASTCDClass symbolClassSymbol = getClassBy("SymbolExternal", compilationUnit); - Assertions.assertEquals(1, symbolClassSymbol.getCDAttributeList().size()); - Assertions.assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); + assertEquals(1, symbolClassSymbol.getCDAttributeList().size()); + assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); + assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); ASTCDAttribute cdAttribute = symbolClassSymbol.getCDAttributeList().get(0); - Assertions.assertEquals("extraString", cdAttribute.getName()); + assertEquals("extraString", cdAttribute.getName()); assertDeepEquals(String.class, cdAttribute.getMCType()); assertDeepEquals(CDModifier.PROTECTED, cdAttribute.getModifier()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/symbolTransl/SpanningScopeTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/symbolTransl/SpanningScopeTest.java index 2fe4f89a7a..da9544d8ae 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/symbolTransl/SpanningScopeTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/symbolTransl/SpanningScopeTest.java @@ -8,13 +8,13 @@ import de.monticore.umlstereotype._ast.ASTStereoValue; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; +import static org.junit.jupiter.api.Assertions.*; public class SpanningScopeTest extends TranslationTestCase { @@ -32,64 +32,64 @@ public void setUp() { @Test public void testDefinitionName() { - Assertions.assertEquals("ScopeSpanningSymbols", compilationUnit.getCDDefinition().getName()); + assertEquals("ScopeSpanningSymbols", compilationUnit.getCDDefinition().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPackage() { - Assertions.assertEquals(2, compilationUnit.getCDPackageList().size()); - Assertions.assertEquals("mc2cdtransformation", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(0)); - Assertions.assertEquals("symbolTransl", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(1)); + assertEquals(2, compilationUnit.getCDPackageList().size()); + assertEquals("mc2cdtransformation", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(0)); + assertEquals("symbolTransl", compilationUnit.getMCPackageDeclaration().getMCQualifiedName().getParts(1)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testClassCount() { - Assertions.assertEquals(2, compilationUnit.getCDDefinition().getCDClassesList().size()); + assertEquals(2, compilationUnit.getCDDefinition().getCDClassesList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testScopeSpanningSymbol() { ASTCDClass symbolClassSymbol = getClassBy("ScopeSpanning", compilationUnit); - Assertions.assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getCDConstructorList().isEmpty()); - Assertions.assertFalse(symbolClassSymbol.isPresentCDExtendUsage()); - Assertions.assertTrue(symbolClassSymbol.getCDAttributeList().isEmpty()); + assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); + assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); + assertTrue(symbolClassSymbol.getCDConstructorList().isEmpty()); + assertFalse(symbolClassSymbol.isPresentCDExtendUsage()); + assertTrue(symbolClassSymbol.getCDAttributeList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getModifier().isPresentStereotype()); - Assertions.assertFalse(symbolClassSymbol.getModifier().getStereotype().isEmptyValues()); - Assertions.assertEquals(2, symbolClassSymbol.getModifier().getStereotype().sizeValues()); + assertTrue(symbolClassSymbol.getModifier().isPresentStereotype()); + assertFalse(symbolClassSymbol.getModifier().getStereotype().isEmptyValues()); + assertEquals(2, symbolClassSymbol.getModifier().getStereotype().sizeValues()); ASTStereoValue symbolStereotype = symbolClassSymbol.getModifier().getStereotype().getValues(0); - Assertions.assertEquals("symbol", symbolStereotype.getName()); + assertEquals("symbol", symbolStereotype.getName()); ASTStereoValue scopeStereotype = symbolClassSymbol.getModifier().getStereotype().getValues(1); - Assertions.assertEquals("scope", scopeStereotype.getName()); + assertEquals("scope", scopeStereotype.getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testOnlySymbol() { ASTCDClass symbolClassSymbol = getClassBy("OnlySymbol", compilationUnit); - Assertions.assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getCDConstructorList().isEmpty()); - Assertions.assertFalse(symbolClassSymbol.isPresentCDExtendUsage()); - Assertions.assertTrue(symbolClassSymbol.getCDAttributeList().isEmpty()); + assertTrue(symbolClassSymbol.getInterfaceList().isEmpty()); + assertTrue(symbolClassSymbol.getCDMethodList().isEmpty()); + assertTrue(symbolClassSymbol.getCDConstructorList().isEmpty()); + assertFalse(symbolClassSymbol.isPresentCDExtendUsage()); + assertTrue(symbolClassSymbol.getCDAttributeList().isEmpty()); - Assertions.assertTrue(symbolClassSymbol.getModifier().isPresentStereotype()); - Assertions.assertFalse(symbolClassSymbol.getModifier().getStereotype().isEmptyValues()); - Assertions.assertEquals(2, symbolClassSymbol.getModifier().getStereotype().sizeValues()); + assertTrue(symbolClassSymbol.getModifier().isPresentStereotype()); + assertFalse(symbolClassSymbol.getModifier().getStereotype().isEmptyValues()); + assertEquals(2, symbolClassSymbol.getModifier().getStereotype().sizeValues()); ASTStereoValue symbolStereotype = symbolClassSymbol.getModifier().getStereotype().getValues(0); - Assertions.assertEquals("symbol", symbolStereotype.getName()); + assertEquals("symbol", symbolStereotype.getName()); ASTStereoValue startProdStereotype = symbolClassSymbol.getModifier().getStereotype().getValues(1); - Assertions.assertEquals("startProd", startProdStereotype.getName()); + assertEquals("startProd", startProdStereotype.getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AbstractProdTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AbstractProdTest.java index ecc24b651a..4f1e6a2be9 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AbstractProdTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AbstractProdTest.java @@ -8,7 +8,6 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import java.util.List; import static de.monticore.codegen.mc2cd.TransformationHelper.typeToString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for the proper transformation of ASTAbstractProds to corresponding @@ -53,12 +52,12 @@ public void setupAbstractProdTest() { @Test public void testAbstract() { - Assertions.assertTrue(astA.getModifier().isAbstract()); - Assertions.assertTrue(astB.getModifier().isAbstract()); - Assertions.assertTrue(astC.getModifier().isAbstract()); - Assertions.assertTrue(astD.getModifier().isAbstract()); + assertTrue(astA.getModifier().isAbstract()); + assertTrue(astB.getModifier().isAbstract()); + assertTrue(astC.getModifier().isAbstract()); + assertTrue(astD.getModifier().isAbstract()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -67,11 +66,11 @@ public void testAbstract() { */ @Test public void testExtends() { - Assertions.assertTrue(astA.isPresentCDExtendUsage()); + assertTrue(astA.isPresentCDExtendUsage()); String name = typeToString(astA.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("mc2cdtransformation.AbstractProd.ASTextendedProd", name); + assertEquals("mc2cdtransformation.AbstractProd.ASTextendedProd", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -81,11 +80,11 @@ public void testExtends() { @Test public void testImplements() { List superInterfaces = astB.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("mc2cdtransformation.AbstractProd.ASTimplementedProd", name); + assertEquals("mc2cdtransformation.AbstractProd.ASTimplementedProd", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -94,11 +93,11 @@ public void testImplements() { */ @Test public void testAstextends() { - Assertions.assertTrue(astC.isPresentCDExtendUsage()); + assertTrue(astC.isPresentCDExtendUsage()); String name = typeToString(astC.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("AstExtendedType", name); + assertEquals("AstExtendedType", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -108,11 +107,11 @@ public void testAstextends() { @Test public void testAstimplements() { List superInterfaces = astD.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("AstImplementedType", name); + assertEquals("AstImplementedType", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -121,11 +120,11 @@ public void testAstimplements() { */ @Test public void testAstextendsQualified() { - Assertions.assertTrue(astE.isPresentCDExtendUsage()); + assertTrue(astE.isPresentCDExtendUsage()); String name = typeToString(astE.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("java.util.Observable", name); + assertEquals("java.util.Observable", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -135,10 +134,10 @@ public void testAstextendsQualified() { @Test public void testAstimplementsQualified() { List superInterfaces = astF.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("java.io.Serializable", name); + assertEquals("java.io.Serializable", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AstRuleInheritanceTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AstRuleInheritanceTest.java index 811bc0520b..dc70aea89a 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AstRuleInheritanceTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AstRuleInheritanceTest.java @@ -10,7 +10,6 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -19,6 +18,7 @@ import java.util.Optional; import static de.monticore.codegen.mc2cd.TransformationHelper.typeToString; +import static org.junit.jupiter.api.Assertions.*; /** * tests astextends and astimplements functionality at astrules @@ -49,12 +49,12 @@ public void setUp() { Optional asteOpt = TestHelper.getCDInterface(cdCompilationUnit, "ASTE"); Optional astfOpt = TestHelper.getCDClass(cdCompilationUnit, "ASTF"); - Assertions.assertTrue(astaOpt.isPresent()); - Assertions.assertTrue(astbOpt.isPresent()); - Assertions.assertTrue(astcOpt.isPresent()); - Assertions.assertTrue(astdOpt.isPresent()); - Assertions.assertTrue(asteOpt.isPresent()); - Assertions.assertTrue(astfOpt.isPresent()); + assertTrue(astaOpt.isPresent()); + assertTrue(astbOpt.isPresent()); + assertTrue(astcOpt.isPresent()); + assertTrue(astdOpt.isPresent()); + assertTrue(asteOpt.isPresent()); + assertTrue(astfOpt.isPresent()); astA = astaOpt.get(); astB = astbOpt.get(); @@ -69,23 +69,23 @@ public void setUp() { */ @Test public void testAstSuperClass() { - Assertions.assertTrue(astA.isPresentCDExtendUsage()); + assertTrue(astA.isPresentCDExtendUsage()); String name = typeToString(astA.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("ASTExternalProd", name); + assertEquals("ASTExternalProd", name); - Assertions.assertTrue(astC.isPresentCDExtendUsage()); + assertTrue(astC.isPresentCDExtendUsage()); name = typeToString(astC.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("mc2cdtransformation.AstRuleInheritance.ASTA", name); + assertEquals("mc2cdtransformation.AstRuleInheritance.ASTA", name); - Assertions.assertTrue(astD.isPresentCDExtendUsage()); + assertTrue(astD.isPresentCDExtendUsage()); name = typeToString(astD.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("mc2cdtransformation.Supergrammar.ASTSuperProd", name); + assertEquals("mc2cdtransformation.Supergrammar.ASTSuperProd", name); - Assertions.assertTrue(astF.isPresentCDExtendUsage()); + assertTrue(astF.isPresentCDExtendUsage()); name = typeToString(astF.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("java.util.Observable", name); + assertEquals("java.util.Observable", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -94,26 +94,29 @@ public void testAstSuperClass() { */ @Test public void testStereotypesForAstSuperclass() { - Assertions.assertTrue(astA.getModifier().isPresentStereotype()); + assertTrue(astA.getModifier().isPresentStereotype()); // one stereotype for the startProd flag and one for the checked external type - Assertions.assertEquals(2, astA.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals(astA.getModifier().getStereotype().getValuesList().get(0).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); - Assertions.assertFalse(astA.getModifier().getStereotype().getValuesList().get(0).getValue().isEmpty()); - Assertions.assertEquals(astA.getModifier().getStereotype().getValuesList().get(0).getValue(), "ASTExternalProd"); - - Assertions.assertTrue(astF.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astF.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals(astF.getModifier().getStereotype().getValuesList().get(0).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); - Assertions.assertFalse(astF.getModifier().getStereotype().getValuesList().get(0).getValue().isEmpty()); - Assertions.assertEquals(astF.getModifier().getStereotype().getValuesList().get(0).getValue(), "java.util.Observable"); - - Assertions.assertTrue(astD.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astD.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals(astD.getModifier().getStereotype().getValuesList().get(0).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); - Assertions.assertFalse(astD.getModifier().getStereotype().getValuesList().get(0).getValue().isEmpty()); - Assertions.assertEquals(astD.getModifier().getStereotype().getValuesList().get(0).getValue(), "java.io.Serializable"); + assertEquals(2, astA.getModifier().getStereotype().getValuesList().size()); + assertEquals(astA.getModifier().getStereotype().getValuesList().get(0).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); + assertFalse(astA.getModifier().getStereotype().getValuesList().get(0).getValue().isEmpty()); + assertEquals("ASTExternalProd", + astA.getModifier().getStereotype().getValuesList().get(0).getValue()); + + assertTrue(astF.getModifier().isPresentStereotype()); + assertEquals(1, astF.getModifier().getStereotype().getValuesList().size()); + assertEquals(astF.getModifier().getStereotype().getValuesList().get(0).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); + assertFalse(astF.getModifier().getStereotype().getValuesList().get(0).getValue().isEmpty()); + assertEquals("java.util.Observable", + astF.getModifier().getStereotype().getValuesList().get(0).getValue()); + + assertTrue(astD.getModifier().isPresentStereotype()); + assertEquals(1, astD.getModifier().getStereotype().getValuesList().size()); + assertEquals(astD.getModifier().getStereotype().getValuesList().get(0).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); + assertFalse(astD.getModifier().getStereotype().getValuesList().get(0).getValue().isEmpty()); + assertEquals("java.io.Serializable", + astD.getModifier().getStereotype().getValuesList().get(0).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -122,16 +125,18 @@ public void testStereotypesForAstSuperclass() { */ @Test public void testStereotypesForAstInterfaces() { - Assertions.assertTrue(astE.getModifier().isPresentStereotype()); - Assertions.assertEquals(2, astE.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals(astE.getModifier().getStereotype().getValuesList().get(0).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); - Assertions.assertFalse(astE.getModifier().getStereotype().getValuesList().get(0).getValue().isEmpty()); - Assertions.assertEquals(astE.getModifier().getStereotype().getValuesList().get(0).getValue(), "ASTExternalInterface"); - Assertions.assertEquals(astE.getModifier().getStereotype().getValuesList().get(1).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); - Assertions.assertFalse(astE.getModifier().getStereotype().getValuesList().get(1).getValue().isEmpty()); - Assertions.assertEquals(astE.getModifier().getStereotype().getValuesList().get(1).getValue(), "java.io.Serializable"); + assertTrue(astE.getModifier().isPresentStereotype()); + assertEquals(2, astE.getModifier().getStereotype().getValuesList().size()); + assertEquals(astE.getModifier().getStereotype().getValuesList().get(0).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); + assertFalse(astE.getModifier().getStereotype().getValuesList().get(0).getValue().isEmpty()); + assertEquals("ASTExternalInterface", + astE.getModifier().getStereotype().getValuesList().get(0).getValue()); + assertEquals(astE.getModifier().getStereotype().getValuesList().get(1).getName(), MC2CDStereotypes.EXTERNAL_TYPE.toString()); + assertFalse(astE.getModifier().getStereotype().getValuesList().get(1).getValue().isEmpty()); + assertEquals("java.io.Serializable", + astE.getModifier().getStereotype().getValuesList().get(1).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -141,15 +146,15 @@ public void testStereotypesForAstInterfaces() { @Test public void testASTExtendsAndImplements() { List superInterfaces = astD.getInterfaceList(); - Assertions.assertEquals(3, superInterfaces.size()); + assertEquals(3, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("mc2cdtransformation.AstRuleInheritance.ASTB", name); + assertEquals("mc2cdtransformation.AstRuleInheritance.ASTB", name); name = typeToString(superInterfaces.get(1)); - Assertions.assertEquals("mc2cdtransformation.Supergrammar.ASTSuperInterface", name); + assertEquals("mc2cdtransformation.Supergrammar.ASTSuperInterface", name); name = typeToString(superInterfaces.get(2)); - Assertions.assertEquals("java.io.Serializable", name); + assertEquals("java.io.Serializable", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -159,17 +164,17 @@ public void testASTExtendsAndImplements() { @Test public void testAstInterfaces() { List superInterfaces = astE.getInterfaceList(); - Assertions.assertEquals(4, superInterfaces.size()); + assertEquals(4, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("mc2cdtransformation.AstRuleInheritance.ASTB", name); + assertEquals("mc2cdtransformation.AstRuleInheritance.ASTB", name); name = typeToString(superInterfaces.get(1)); - Assertions.assertEquals("mc2cdtransformation.Supergrammar.ASTSuperInterface", name); + assertEquals("mc2cdtransformation.Supergrammar.ASTSuperInterface", name); name = typeToString(superInterfaces.get(2)); - Assertions.assertEquals("ASTExternalInterface", name); + assertEquals("ASTExternalInterface", name); name = typeToString(superInterfaces.get(3)); - Assertions.assertEquals("java.io.Serializable", name); + assertEquals("java.io.Serializable", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AstRuleTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AstRuleTest.java index 9ca5a8db06..248e73a98e 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AstRuleTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AstRuleTest.java @@ -8,7 +8,6 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,8 +16,8 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorAssert.assertInt; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * this test checks the addition of attributes with astrules @@ -39,17 +38,17 @@ public void setUpASTRuleTest() { @Test public void testAstRuleAddedAttribute() { - Assertions.assertEquals(1, astC.getCDAttributeList().size()); - Assertions.assertEquals("dimensions", astC.getCDAttributeList().get(0).getName()); + assertEquals(1, astC.getCDAttributeList().size()); + assertEquals("dimensions", astC.getCDAttributeList().get(0).getName()); assertInt(astC.getCDAttributeList().get(0).getMCType()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAstRuleDoubleInheritance() { // attributes from super interfaces are inherited - Assertions.assertEquals(2, impl.getCDAttributeList().size()); + assertEquals(2, impl.getCDAttributeList().size()); ASTCDAttribute varName = getAttributeBy("varName", impl); assertDeepEquals("varType", varName.getMCType()); @@ -57,7 +56,7 @@ public void testAstRuleDoubleInheritance() { ASTCDAttribute varName2 = getAttributeBy("varName2", impl); assertDeepEquals("varType2", varName2.getMCType()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTMultiplicityTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTMultiplicityTest.java index fe9cea2189..84b64d0885 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTMultiplicityTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTMultiplicityTest.java @@ -8,7 +8,6 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import java.util.List; import static de.monticore.codegen.mc2cd.TransformationHelper.typeToString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for the proper transformation of AttributeInASTs to corresponding @@ -48,10 +47,10 @@ public void setupAttributeInASTMultiplicityTest() { @Test public void testStarMultiplicity() { List attributes = astA.getCDAttributeList(); - Assertions.assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), + assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), "mc2cdtransformation.AttributeInASTMultiplicityGrammar.ASTX")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -62,17 +61,17 @@ public void testStarMultiplicity() { public void testOptionalCardinality() { List attributes = astB.getCDAttributeList(); String name = typeToString(attributes.get(0).getMCType()); - Assertions.assertEquals("Optional", name); + assertEquals("Optional", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testOneCardinality() { List attributes = astC.getCDAttributeList(); String name = typeToString(attributes.get(0).getMCType()); - Assertions.assertEquals("mc2cdtransformation.AttributeInASTMultiplicityGrammar.ASTZ", name); + assertEquals("mc2cdtransformation.AttributeInASTMultiplicityGrammar.ASTZ", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTOverridingTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTOverridingTest.java index 6e45e4f186..53f4a457dd 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTOverridingTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTOverridingTest.java @@ -9,15 +9,14 @@ import de.monticore.codegen.mc2cd.TransformationHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests that attributes that are redefined in ASTRules correctly override their counterparts in the @@ -36,23 +35,23 @@ public void setupAttributeInASTOverridingTest() { astA = TestHelper.getCDClass(cdCompilationUnit, "ASTA").get(); astB = TestHelper.getCDClass(cdCompilationUnit, "ASTB").get(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAttributeOverridden() { List attributes = astA.getCDAttributeList(); - Assertions.assertEquals(1, attributes.size()); - Assertions.assertEquals("mc2cdtransformation.AttributeInASTOverridingGrammar.ASTY", TransformationHelper.typeToString(attributes.get(0).getMCType())); + assertEquals(1, attributes.size()); + assertEquals("mc2cdtransformation.AttributeInASTOverridingGrammar.ASTY", TransformationHelper.typeToString(attributes.get(0).getMCType())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAttributeNotOverridden() { List attributes = astB.getCDAttributeList(); - Assertions.assertEquals(2, attributes.size()); + assertEquals(2, attributes.size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTTypeTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTTypeTest.java index a6c00c94a2..ab8f566ae0 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTTypeTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/AttributeInASTTypeTest.java @@ -9,14 +9,13 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCPrimitiveType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AttributeInASTTypeTest extends TranslationTestCase { @@ -34,9 +33,9 @@ public void testType() { astA.getCDAttributeList().stream() .map(ASTCDAttribute::getMCType) .map(Object::getClass) - .forEach(type -> Assertions.assertEquals(ASTMCPrimitiveType.class, type)); + .forEach(type -> assertEquals(ASTMCPrimitiveType.class, type)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ComponetTranslationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ComponetTranslationTest.java index a2d4548df3..295bcdedab 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ComponetTranslationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ComponetTranslationTest.java @@ -5,12 +5,13 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; +import static org.junit.jupiter.api.Assertions.*; + public class ComponetTranslationTest extends TranslationTestCase { private ASTCDCompilationUnit componentCD; @@ -27,19 +28,19 @@ public void setUp() { @Test public void testIsComponent() { - Assertions.assertTrue(componentCD.getCDDefinition().getModifier().isPresentStereotype()); - Assertions.assertEquals(1, componentCD.getCDDefinition().getModifier().getStereotype().sizeValues()); - Assertions.assertEquals("component", componentCD.getCDDefinition().getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(componentCD.getCDDefinition().getModifier().getStereotype().getValues(0).isPresentText()); + assertTrue(componentCD.getCDDefinition().getModifier().isPresentStereotype()); + assertEquals(1, componentCD.getCDDefinition().getModifier().getStereotype().sizeValues()); + assertEquals("component", componentCD.getCDDefinition().getModifier().getStereotype().getValues(0).getName()); + assertFalse(componentCD.getCDDefinition().getModifier().getStereotype().getValues(0).isPresentText()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIsNotComponent() { - Assertions.assertFalse(nonComponentCD.getCDDefinition().getModifier().isPresentStereotype()); + assertFalse(nonComponentCD.getCDDefinition().getModifier().isPresentStereotype()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/DerivedAttributeNameTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/DerivedAttributeNameTest.java index 2aab1eedeb..1bc006a7b5 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/DerivedAttributeNameTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/DerivedAttributeNameTest.java @@ -8,13 +8,14 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class DerivedAttributeNameTest extends TranslationTestCase { private ASTCDCompilationUnit compilationUnit; @@ -36,58 +37,58 @@ protected boolean hasDerivedAttributeName(ASTCDAttribute astcdAttribute) { @Test public void testFoo() { Optional fooClass = TestHelper.getCDClass(compilationUnit, "ASTFoo"); - Assertions.assertTrue(fooClass.isPresent()); - Assertions.assertEquals(1, fooClass.get().getCDAttributeList().size()); - Assertions.assertEquals("foo", fooClass.get().getCDAttributeList().get(0).getName()); - Assertions.assertFalse(hasDerivedAttributeName(fooClass.get().getCDAttributeList().get(0))); + assertTrue(fooClass.isPresent()); + assertEquals(1, fooClass.get().getCDAttributeList().size()); + assertEquals("foo", fooClass.get().getCDAttributeList().get(0).getName()); + assertFalse(hasDerivedAttributeName(fooClass.get().getCDAttributeList().get(0))); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBar() { Optional bar = TestHelper.getCDClass(compilationUnit, "ASTBar"); - Assertions.assertTrue(bar.isPresent()); - Assertions.assertEquals(2, bar.get().getCDAttributeList().size()); - Assertions.assertEquals("abc", bar.get().getCDAttributeList().get(0).getName()); - Assertions.assertFalse(hasDerivedAttributeName(bar.get().getCDAttributeList().get(0))); - Assertions.assertEquals("d", bar.get().getCDAttributeList().get(1).getName()); - Assertions.assertTrue(hasDerivedAttributeName(bar.get().getCDAttributeList().get(1))); + assertTrue(bar.isPresent()); + assertEquals(2, bar.get().getCDAttributeList().size()); + assertEquals("abc", bar.get().getCDAttributeList().get(0).getName()); + assertFalse(hasDerivedAttributeName(bar.get().getCDAttributeList().get(0))); + assertEquals("d", bar.get().getCDAttributeList().get(1).getName()); + assertTrue(hasDerivedAttributeName(bar.get().getCDAttributeList().get(1))); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBlub() { Optional blub = TestHelper.getCDClass(compilationUnit, "ASTBlub"); - Assertions.assertTrue(blub.isPresent()); - Assertions.assertEquals(4, blub.get().getCDAttributeList().size()); - Assertions.assertEquals("foo", blub.get().getCDAttributeList().get(0).getName()); - Assertions.assertTrue(hasDerivedAttributeName(blub.get().getCDAttributeList().get(0))); - Assertions.assertEquals("bar2", blub.get().getCDAttributeList().get(1).getName()); - Assertions.assertFalse(hasDerivedAttributeName(blub.get().getCDAttributeList().get(1))); - Assertions.assertEquals("fooOpt", blub.get().getCDAttributeList().get(2).getName()); - Assertions.assertFalse(hasDerivedAttributeName(blub.get().getCDAttributeList().get(2))); - Assertions.assertEquals("efg", blub.get().getCDAttributeList().get(3).getName()); - Assertions.assertFalse(hasDerivedAttributeName(blub.get().getCDAttributeList().get(3))); + assertTrue(blub.isPresent()); + assertEquals(4, blub.get().getCDAttributeList().size()); + assertEquals("foo", blub.get().getCDAttributeList().get(0).getName()); + assertTrue(hasDerivedAttributeName(blub.get().getCDAttributeList().get(0))); + assertEquals("bar2", blub.get().getCDAttributeList().get(1).getName()); + assertFalse(hasDerivedAttributeName(blub.get().getCDAttributeList().get(1))); + assertEquals("fooOpt", blub.get().getCDAttributeList().get(2).getName()); + assertFalse(hasDerivedAttributeName(blub.get().getCDAttributeList().get(2))); + assertEquals("efg", blub.get().getCDAttributeList().get(3).getName()); + assertFalse(hasDerivedAttributeName(blub.get().getCDAttributeList().get(3))); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testTest() { Optional test = TestHelper.getCDClass(compilationUnit, "ASTTest"); - Assertions.assertTrue(test.isPresent()); - Assertions.assertEquals(4, test.get().getCDAttributeList().size()); - Assertions.assertEquals("blub", test.get().getCDAttributeList().get(0).getName()); - Assertions.assertTrue(hasDerivedAttributeName(test.get().getCDAttributeList().get(0))); - Assertions.assertEquals("faa", test.get().getCDAttributeList().get(1).getName()); - Assertions.assertFalse(hasDerivedAttributeName(test.get().getCDAttributeList().get(1))); - Assertions.assertEquals("bar", test.get().getCDAttributeList().get(2).getName()); - Assertions.assertTrue(hasDerivedAttributeName(test.get().getCDAttributeList().get(2))); - Assertions.assertEquals("k", test.get().getCDAttributeList().get(3).getName()); - Assertions.assertFalse(hasDerivedAttributeName(test.get().getCDAttributeList().get(3))); + assertTrue(test.isPresent()); + assertEquals(4, test.get().getCDAttributeList().size()); + assertEquals("blub", test.get().getCDAttributeList().get(0).getName()); + assertTrue(hasDerivedAttributeName(test.get().getCDAttributeList().get(0))); + assertEquals("faa", test.get().getCDAttributeList().get(1).getName()); + assertFalse(hasDerivedAttributeName(test.get().getCDAttributeList().get(1))); + assertEquals("bar", test.get().getCDAttributeList().get(2).getName()); + assertTrue(hasDerivedAttributeName(test.get().getCDAttributeList().get(2))); + assertEquals("k", test.get().getCDAttributeList().get(3).getName()); + assertFalse(hasDerivedAttributeName(test.get().getCDAttributeList().get(3))); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/DirectLeftRecursionDetectorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/DirectLeftRecursionDetectorTest.java index 5f94929a17..54000306ac 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/DirectLeftRecursionDetectorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/DirectLeftRecursionDetectorTest.java @@ -8,7 +8,6 @@ import de.monticore.grammar.grammar._ast.ASTMCGrammar; import de.monticore.grammar.grammar_withconcepts.Grammar_WithConceptsMill; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,7 +17,8 @@ import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests the helper class on a concrete grammar containing left recursive and normal rules. @@ -34,7 +34,7 @@ public class DirectLeftRecursionDetectorTest extends TranslationTestCase { public void setup() throws IOException { final Path modelPath = Paths.get("src/test/resources/mc2cdtransformation/DirectLeftRecursionDetector.mc4"); astMCGrammarOptional =Grammar_WithConceptsMill.parser().parse(modelPath.toString());; - Assertions.assertTrue(astMCGrammarOptional.isPresent()); + assertTrue(astMCGrammarOptional.isPresent()); } @Test @@ -44,17 +44,17 @@ public void testRecursiveRule() { final ASTClassProd exprProduction = productions.get(0); boolean isLeftRecursive = directLeftRecursionDetector.isAlternativeLeftRecursive(exprProduction.getAlt(0), exprProduction.getName()); - Assertions.assertTrue(isLeftRecursive); + assertTrue(isLeftRecursive); final ASTClassProd nonRecursiveProudction1 = productions.get(1); isLeftRecursive = directLeftRecursionDetector.isAlternativeLeftRecursive(nonRecursiveProudction1.getAlt(0), nonRecursiveProudction1.getName()); - Assertions.assertFalse(isLeftRecursive); + assertFalse(isLeftRecursive); final ASTClassProd nonRecursiveProudction2 = productions.get(2); isLeftRecursive = directLeftRecursionDetector.isAlternativeLeftRecursive(nonRecursiveProudction2.getAlt(0), nonRecursiveProudction2.getName()); - Assertions.assertFalse(isLeftRecursive); + assertFalse(isLeftRecursive); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/EnumProdTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/EnumProdTest.java index 3e1f6cd38f..e2667de1d8 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/EnumProdTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/EnumProdTest.java @@ -6,15 +6,14 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class EnumProdTest extends TranslationTestCase { @@ -29,8 +28,8 @@ public void setupEnumProdTest() { @Test public void testExist() { - Assertions.assertEquals(4, cdCompilationUnit.getCDDefinition().getCDEnumsList().size()); + assertEquals(4, cdCompilationUnit.getCDDefinition().getCDEnumsList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ExternalImplementationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ExternalImplementationTest.java index 3d1c9f088b..38f74cac6b 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ExternalImplementationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ExternalImplementationTest.java @@ -9,14 +9,12 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ExternalImplementationTest extends TranslationTestCase { @@ -32,10 +30,10 @@ public void setupExternalImplementationTest() { @Test public void testExternalImplementation() { ASTMCObjectType cdInterface = astZ.getInterfaceList().get(0); - Assertions.assertTrue(cdInterface != null); + assertNotNull(cdInterface); String name = TransformationHelper.typeToString(cdInterface); - Assertions.assertEquals("mc2cdtransformation.Supergrammar.ASTZExt", name); + assertEquals("mc2cdtransformation.Supergrammar.ASTZExt", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ExternalInterfaceTranslationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ExternalInterfaceTranslationTest.java index cef24665d8..c6f92a7086 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ExternalInterfaceTranslationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/ExternalInterfaceTranslationTest.java @@ -6,13 +6,13 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; +import static org.junit.jupiter.api.Assertions.*; public class ExternalInterfaceTranslationTest extends TranslationTestCase { @@ -27,11 +27,11 @@ public void setUp() { @Test public void testExternalInterface(){ ASTCDInterface a = getInterfaceBy("ASTAExt", externalInterface); - Assertions.assertTrue(a.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, a.getModifier().getStereotype().sizeValues()); - Assertions.assertEquals("externalInterface", a.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(a.getModifier().getStereotype().getValues(0).isPresentText()); + assertTrue(a.getModifier().isPresentStereotype()); + assertEquals(1, a.getModifier().getStereotype().sizeValues()); + assertEquals("externalInterface", a.getModifier().getStereotype().getValues(0).getName()); + assertFalse(a.getModifier().getStereotype().getValues(0).isPresentText()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InheritanceTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InheritanceTest.java index bdc7a05b1a..2aeb0ee0c6 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InheritanceTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InheritanceTest.java @@ -8,7 +8,6 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import java.util.List; import static de.monticore.codegen.mc2cd.TransformationHelper.typeToString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for the proper transformation of ASTClassProds to corresponding @@ -58,11 +57,11 @@ public void setupInheritanceTest() { */ @Test public void testExtends() { - Assertions.assertTrue(astA.isPresentCDExtendUsage()); + assertTrue(astA.isPresentCDExtendUsage()); String name = typeToString(astA.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("mc2cdtransformation.InheritanceGrammar.ASTextendedProd", name); + assertEquals("mc2cdtransformation.InheritanceGrammar.ASTextendedProd", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -72,11 +71,11 @@ public void testExtends() { @Test public void testImplements() { List superInterfaces = astB.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("mc2cdtransformation.InheritanceGrammar.ASTimplementedProd", name); + assertEquals("mc2cdtransformation.InheritanceGrammar.ASTimplementedProd", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -85,11 +84,11 @@ public void testImplements() { */ @Test public void testAstextends() { - Assertions.assertTrue(astC.isPresentCDExtendUsage()); + assertTrue(astC.isPresentCDExtendUsage()); String name = typeToString(astC.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("AstExtendedType", name); + assertEquals("AstExtendedType", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -99,11 +98,11 @@ public void testAstextends() { @Test public void testAstimplements() { List superInterfaces = astD.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("AstImplementedType", name); + assertEquals("AstImplementedType", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -112,11 +111,11 @@ public void testAstimplements() { */ @Test public void testAstextendsQualified() { - Assertions.assertTrue(astE.isPresentCDExtendUsage()); + assertTrue(astE.isPresentCDExtendUsage()); String name = typeToString(astE.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("java.util.Observable", name); + assertEquals("java.util.Observable", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -126,10 +125,10 @@ public void testAstextendsQualified() { @Test public void testAstimplementsQualified() { List superInterfaces = astF.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("java.io.Serializable", name); + assertEquals("java.io.Serializable", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InheritedAttributesTranslationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InheritedAttributesTranslationTest.java index 43294f378c..1d53400d93 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InheritedAttributesTranslationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InheritedAttributesTranslationTest.java @@ -9,7 +9,6 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +17,7 @@ import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; +import static org.junit.jupiter.api.Assertions.*; public class InheritedAttributesTranslationTest extends TranslationTestCase { @@ -39,7 +39,7 @@ public class InheritedAttributesTranslationTest extends TranslationTestCase { public void setupInheritedAttributesTranslationTest() { Optional cdCompilationUnitSuper = TestHelper.parseAndTransform(Paths .get("src/test/resources/mc2cdtransformation/SuperInheritedAttributesGrammar.mc4")); - Assertions.assertTrue(cdCompilationUnitSuper.isPresent()); + assertTrue(cdCompilationUnitSuper.isPresent()); //get classes from super grammar astASuper = getClassBy("ASTA", cdCompilationUnitSuper.get()); @@ -50,7 +50,7 @@ public void setupInheritedAttributesTranslationTest() { Optional cdCompilationUnitSub = TestHelper.parseAndTransform(Paths .get("src/test/resources/mc2cdtransformation/SubInheritedAttributesGrammar.mc4")); - Assertions.assertTrue(cdCompilationUnitSub.isPresent()); + assertTrue(cdCompilationUnitSub.isPresent()); //get classes from sub grammar astASub = getClassBy("ASTA", cdCompilationUnitSub.get()); @@ -59,66 +59,66 @@ public void setupInheritedAttributesTranslationTest() { @Test public void testASuper() { - Assertions.assertTrue(astASuper.getCDAttributeList().stream().noneMatch(this::hasInheritedStereotype)); + assertTrue(astASuper.getCDAttributeList().stream().noneMatch(this::hasInheritedStereotype)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testESuper() { - Assertions.assertTrue(astESuper.getCDAttributeList().stream().noneMatch(this::hasInheritedStereotype)); + assertTrue(astESuper.getCDAttributeList().stream().noneMatch(this::hasInheritedStereotype)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBSuper() { - Assertions.assertTrue(astB.getCDAttributeList().stream().allMatch(this::hasInheritedStereotype)); + assertTrue(astB.getCDAttributeList().stream().allMatch(this::hasInheritedStereotype)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCSuper() { for (ASTCDAttribute astcdAttribute : astC.getCDAttributeList()) { if (!astcdAttribute.getName().equals("name2")) { - Assertions.assertTrue(hasInheritedStereotype(astcdAttribute)); + assertTrue(hasInheritedStereotype(astcdAttribute)); } else { - Assertions.assertFalse(hasInheritedStereotype(astcdAttribute)); + assertFalse(hasInheritedStereotype(astcdAttribute)); } } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFSuper() { for (ASTCDAttribute astcdAttribute : astF.getCDAttributeList()) { if (!astcdAttribute.getName().equals("name2")) { - Assertions.assertTrue(hasInheritedStereotype(astcdAttribute)); + assertTrue(hasInheritedStereotype(astcdAttribute)); } else { - Assertions.assertFalse(hasInheritedStereotype(astcdAttribute)); + assertFalse(hasInheritedStereotype(astcdAttribute)); } } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testASub() { - Assertions.assertTrue(astASub.getCDAttributeList().stream().allMatch(this::hasInheritedStereotype)); + assertTrue(astASub.getCDAttributeList().stream().allMatch(this::hasInheritedStereotype)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testESub() { - Assertions.assertEquals(1, astESub.getCDAttributeList().size()); + assertEquals(1, astESub.getCDAttributeList().size()); ASTCDAttribute name2Attr = astESub.getCDAttributeList().get(0); - Assertions.assertEquals("name2", name2Attr.getName()); + assertEquals("name2", name2Attr.getName()); assertDeepEquals(String.class, name2Attr.getMCType()); - Assertions.assertFalse(hasInheritedStereotype(name2Attr)); + assertFalse(hasInheritedStereotype(name2Attr)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private boolean hasInheritedStereotype(ASTCDAttribute astcdAttribute) { diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InterfaceProdTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InterfaceProdTest.java index 02c9675e47..8a0ecc80db 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InterfaceProdTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/InterfaceProdTest.java @@ -8,7 +8,6 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import java.util.List; import static de.monticore.codegen.mc2cd.TransformationHelper.typeToString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for the proper transformation of ASTInterfaceProds to corresponding ASTCDInterfaces @@ -47,11 +46,11 @@ public void setupInterfaceProdTest() { @Test public void testExtends() { List superInterfaces = astA.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("mc2cdtransformation.InterfaceProd.ASTextendedProd", name); + assertEquals("mc2cdtransformation.InterfaceProd.ASTextendedProd", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -61,11 +60,11 @@ public void testExtends() { @Test public void testAstextends() { List superInterfaces = astB.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("AstExtendedType", name); + assertEquals("AstExtendedType", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -75,11 +74,11 @@ public void testAstextends() { @Test public void testAstimplementsQualified() { List superInterfaces = astC.getInterfaceList(); - Assertions.assertEquals(1, superInterfaces.size()); + assertEquals(1, superInterfaces.size()); String name = typeToString(superInterfaces.get(0)); - Assertions.assertEquals("java.io.Serializable", name); + assertEquals("java.io.Serializable", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/LeftRecursiveTranslationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/LeftRecursiveTranslationTest.java index 9151638378..3f98bf9159 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/LeftRecursiveTranslationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/LeftRecursiveTranslationTest.java @@ -6,13 +6,13 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; +import static org.junit.jupiter.api.Assertions.*; public class LeftRecursiveTranslationTest extends TranslationTestCase { @@ -27,12 +27,12 @@ public void setUpLeftRecursiveTranslationTest() { @Test public void testLeftRecursiveProd(){ ASTCDClass a = getClassBy("ASTA", leftRecursive); - Assertions.assertTrue(a.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, a.getModifier().getStereotype().sizeValues()); - Assertions.assertEquals("left_recursive", a.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(a.getModifier().getStereotype().getValues(0).isPresentText()); + assertTrue(a.getModifier().isPresentStereotype()); + assertEquals(1, a.getModifier().getStereotype().sizeValues()); + assertEquals("left_recursive", a.getModifier().getStereotype().getValues(0).getName()); + assertFalse(a.getModifier().getStereotype().getValues(0).isPresentText()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/NonTerminalMultiplicityTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/NonTerminalMultiplicityTest.java index 169b0c3b6a..5a9f0e45b4 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/NonTerminalMultiplicityTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/NonTerminalMultiplicityTest.java @@ -8,7 +8,6 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import java.util.List; import static de.monticore.codegen.mc2cd.TransformationHelper.typeToString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for the proper transformation of NonTerminals to corresponding ASTCDAttributes @@ -65,9 +64,9 @@ public void setupNonTerminalMultiplicityTest() { @Test public void testNonTerminalName() { List attributes = astA.getCDAttributeList(); - Assertions.assertEquals("x", attributes.get(0).getName()); + assertEquals("x", attributes.get(0).getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -77,10 +76,10 @@ public void testNonTerminalName() { @Test public void testStarMultiplicity() { List attributes = astA.getCDAttributeList(); - Assertions.assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), + assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), "mc2cdtransformation.NonTerminalMultiplicityGrammar.ASTX")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -90,10 +89,10 @@ public void testStarMultiplicity() { @Test public void testParenthesizedStarMultiplicity() { List attributes = astB.getCDAttributeList(); - Assertions.assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), + assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), "mc2cdtransformation.NonTerminalMultiplicityGrammar.ASTX")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -103,10 +102,10 @@ public void testParenthesizedStarMultiplicity() { @Test public void testPlusMultiplicity() { List attributes = astC.getCDAttributeList(); - Assertions.assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), + assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), "mc2cdtransformation.NonTerminalMultiplicityGrammar.ASTX")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -116,10 +115,10 @@ public void testPlusMultiplicity() { @Test public void testParenthesizedPlusMultiplicity() { List attributes = astD.getCDAttributeList(); - Assertions.assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), + assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), "mc2cdtransformation.NonTerminalMultiplicityGrammar.ASTX")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -130,9 +129,9 @@ public void testParenthesizedPlusMultiplicity() { public void testOptionalMultiplicity() { List attributes = astE.getCDAttributeList(); String name = typeToString(attributes.get(0).getMCType()); - Assertions.assertEquals("Optional", name); + assertEquals("Optional", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -143,9 +142,9 @@ public void testOptionalMultiplicity() { public void testParenthesizedOptionalMultiplicity() { List attributes = astF.getCDAttributeList(); String name = typeToString(attributes.get(0).getMCType()); - Assertions.assertEquals("Optional", name); + assertEquals("Optional", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -155,10 +154,10 @@ public void testParenthesizedOptionalMultiplicity() { @Test public void testDuplicateMultiplicity() { List attributes = astG.getCDAttributeList(); - Assertions.assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), + assertTrue(TestHelper.isListOfType(attributes.get(0).getMCType(), "mc2cdtransformation.NonTerminalMultiplicityGrammar.ASTX")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -170,12 +169,12 @@ public void testAlternative() { List attributes = astH.getCDAttributeList(); String xTypeName = typeToString(attributes.get(0).getMCType()); - Assertions.assertEquals("Optional", xTypeName); + assertEquals("Optional", xTypeName); String yTypeName = typeToString(attributes.get(1).getMCType()); - Assertions.assertEquals("Optional", yTypeName); + assertEquals("Optional", yTypeName); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -185,10 +184,10 @@ public void testAlternative() { @Test public void testTwinAlternative() { List attributes = astJ.getCDAttributeList(); - Assertions.assertEquals(1, attributes.size()); + assertEquals(1, attributes.size()); String xTypeName = typeToString(attributes.get(0).getMCType()); - Assertions.assertEquals("Optional", xTypeName); + assertEquals("Optional", xTypeName); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/OverridingClassProdTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/OverridingClassProdTest.java index 3ff24e980e..b60444d46d 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/OverridingClassProdTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/OverridingClassProdTest.java @@ -7,15 +7,14 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import static de.monticore.codegen.mc2cd.TransformationHelper.typeToString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class OverridingClassProdTest extends TranslationTestCase { @@ -34,10 +33,10 @@ public void setupOverridingClassProdTest() { */ @Test public void testOverride() { - Assertions.assertTrue(astX.isPresentCDExtendUsage()); + assertTrue(astX.isPresentCDExtendUsage()); String name = typeToString(astX.getCDExtendUsage().getSuperclass(0)); - Assertions.assertEquals("mc2cdtransformation.Supergrammar.ASTX", name); + assertEquals("mc2cdtransformation.Supergrammar.ASTX", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/StarImportSuperGrammarTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/StarImportSuperGrammarTest.java index ff762b2889..873b1df4a3 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/StarImportSuperGrammarTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/StarImportSuperGrammarTest.java @@ -7,14 +7,13 @@ import de.monticore.codegen.mc2cd.TranslationTestCase; import de.monticore.types.mcbasictypes._ast.ASTMCImportStatement; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class StarImportSuperGrammarTest extends TranslationTestCase { @@ -29,9 +28,9 @@ public void setupStarImportSuperGrammarTest() { @Test public void testStarImport() { ASTMCImportStatement importStatement = cdCompilationUnit.getMCImportStatementList().get(0); - Assertions.assertTrue(importStatement.isStar()); - Assertions.assertEquals("mc2cdtransformation.Supergrammar", importStatement.getQName()); + assertTrue(importStatement.isStar()); + assertEquals("mc2cdtransformation.Supergrammar", importStatement.getQName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/StartProdTranslationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/StartProdTranslationTest.java index 2aef15e529..a20ec60ea2 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/StartProdTranslationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/StartProdTranslationTest.java @@ -7,7 +7,6 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -15,6 +14,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; +import static org.junit.jupiter.api.Assertions.*; public class StartProdTranslationTest extends TranslationTestCase { @@ -36,34 +36,34 @@ public void setUpStartProdTranslationTest() { @Test public void testGlobalStartProd() { - Assertions.assertTrue(globalStartProd.getCDDefinition().getModifier().isPresentStereotype()); - Assertions.assertEquals(1, globalStartProd.getCDDefinition().getModifier().getStereotype().sizeValues()); - Assertions.assertEquals("startProd", globalStartProd.getCDDefinition().getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(globalStartProd.getCDDefinition().getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.Supergrammar.X", globalStartProd.getCDDefinition().getModifier().getStereotype().getValues(0).getValue()); + assertTrue(globalStartProd.getCDDefinition().getModifier().isPresentStereotype()); + assertEquals(1, globalStartProd.getCDDefinition().getModifier().getStereotype().sizeValues()); + assertEquals("startProd", globalStartProd.getCDDefinition().getModifier().getStereotype().getValues(0).getName()); + assertFalse(globalStartProd.getCDDefinition().getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.Supergrammar.X", globalStartProd.getCDDefinition().getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testClassStartProd() { ASTCDClass xClass = getClassBy("ASTX", classStartProd); - Assertions.assertTrue(xClass.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, xClass.getModifier().getStereotype().sizeValues()); - Assertions.assertEquals("startProd", xClass.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(xClass.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertTrue(xClass.getModifier().isPresentStereotype()); + assertEquals(1, xClass.getModifier().getStereotype().sizeValues()); + assertEquals("startProd", xClass.getModifier().getStereotype().getValues(0).getName()); + assertTrue(xClass.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInterfaceStartProd() { ASTCDInterface aInterface = getInterfaceBy("ASTA", interfaceStartProd); - Assertions.assertTrue(aInterface.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, aInterface.getModifier().getStereotype().sizeValues()); - Assertions.assertEquals("startProd", aInterface.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(aInterface.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertTrue(aInterface.getModifier().isPresentStereotype()); + assertEquals(1, aInterface.getModifier().getStereotype().sizeValues()); + assertEquals("startProd", aInterface.getModifier().getStereotype().getValues(0).getName()); + assertTrue(aInterface.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/SymbolAndScopeTranslationTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/SymbolAndScopeTranslationTest.java index 87df96e3a5..cfcf51303d 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/SymbolAndScopeTranslationTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/SymbolAndScopeTranslationTest.java @@ -7,7 +7,6 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -15,6 +14,7 @@ import static de.monticore.codegen.cd2java.DecoratorTestUtil.getClassBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getInterfaceBy; +import static org.junit.jupiter.api.Assertions.*; public class SymbolAndScopeTranslationTest extends TranslationTestCase { @@ -32,136 +32,136 @@ public void setUpSymbolAndScopeTranslationTest() { @Test public void testSimpleSymbolInterface() { ASTCDInterface astType = getInterfaceBy("ASTType", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); + assertTrue(astType.getModifier().isPresentStereotype()); // only 2 because other one is the start prod stereotype - Assertions.assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("symbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("startProd", astType.getModifier().getStereotype().getValues(1).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); + assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("symbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("startProd", astType.getModifier().getStereotype().getValues(1).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInheritedSymbolInterface_OneLevel() { ASTCDInterface astType = getInterfaceBy("ASTCDType", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); + assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.TypeSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.TypeSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInheritedSymbolInterface_TwoLevels() { ASTCDClass astType = getClassBy("ASTCDClass", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); + assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.TypeSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.TypeSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSimpleSymbolClass() { ASTCDClass astType = getClassBy("ASTSimpleSymbolClass", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("symbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("symbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSymbolClassOverwritten() { ASTCDClass astType = getClassBy("ASTSymbolClass", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.symboltransl.symbolrule._symboltable.SymbolClassSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.symboltransl.symbolrule._symboltable.SymbolClassSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(1).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); + assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(1).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSymbolClassExtents() { ASTCDClass astType = getClassBy("ASTExtentsSymbolClass", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.FooSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.FooSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(1).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); + assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(1).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSymbolInterfaceOverwritten() { ASTCDClass astType = getClassBy("ASTSymbolInterface", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.symboltransl.symbolrule._symboltable.SymbolInterfaceSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.symboltransl.symbolrule._symboltable.SymbolInterfaceSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSymbolInterfaceImplements() { ASTCDClass astType = getClassBy("ASTImplementsSymbolInterface", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.InterfaceFooSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.InterfaceFooSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(1).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); + assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(1).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSymbolAbstractClassOverwritten() { ASTCDClass astType = getClassBy("ASTSymbolAbstractClass", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.symboltransl.symbolrule._symboltable.SymbolAbstractClassSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.symboltransl.symbolrule._symboltable.SymbolAbstractClassSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSymbolAbstractClassExtents() { ASTCDClass astType = getClassBy("ASTExtentsSymbolAbstractClass", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.AbstractFooSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedSymbol", astType.getModifier().getStereotype().getValues(0).getName()); + assertFalse(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("mc2cdtransformation.symbolandscopetranslation._symboltable.AbstractFooSymbol", astType.getModifier().getStereotype().getValues(0).getValue()); - Assertions.assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(1).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); + assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(1).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -170,85 +170,85 @@ public void testSymbolAbstractClassExtents() { @Test public void testSimpleScopeInterface() { ASTCDInterface astType = getInterfaceBy("ASTTypeScope", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInheritedScopeInterface_OneLevel() { ASTCDInterface astType = getInterfaceBy("ASTCDTypeScope", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); + assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInheritedScopeInterface_TwoLevels() { ASTCDClass astType = getClassBy("ASTCDClassScope", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); + assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("inheritedScope", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSimpleScopeClass() { ASTCDClass astType = getClassBy("ASTSimpleScopeClass", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(1, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNoShadowingScopeClass() { ASTCDClass astType = getClassBy("ASTScopeShadowing", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("shadowing", astType.getModifier().getStereotype().getValues(1).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("shadowing", astType.getModifier().getStereotype().getValues(1).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNoExportingScopeClass() { ASTCDClass astType = getClassBy("ASTScopeNonExporting", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("non_exporting", astType.getModifier().getStereotype().getValues(1).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("non_exporting", astType.getModifier().getStereotype().getValues(1).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testOrderedScopeClass() { ASTCDClass astType = getClassBy("ASTScopeOrdered", symbolCD); - Assertions.assertTrue(astType.getModifier().isPresentStereotype()); - Assertions.assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); - Assertions.assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); - Assertions.assertEquals("ordered", astType.getModifier().getStereotype().getValues(1).getName()); - Assertions.assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(astType.getModifier().isPresentStereotype()); + assertEquals(2, astType.getModifier().getStereotype().getValuesList().size()); + assertEquals("scope", astType.getModifier().getStereotype().getValues(0).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(0).getValue().isEmpty()); + assertEquals("ordered", astType.getModifier().getStereotype().getValues(1).getName()); + assertTrue(astType.getModifier().getStereotype().getValues(1).getValue().isEmpty()); + + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TerminalWithUsageNameTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TerminalWithUsageNameTest.java index 903246a31d..cedd6f9f10 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TerminalWithUsageNameTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TerminalWithUsageNameTest.java @@ -10,14 +10,13 @@ import de.monticore.codegen.mc2cd.TransformationHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TerminalWithUsageNameTest extends TranslationTestCase { @@ -38,9 +37,9 @@ public void setupTerminalWithUsageNameTest() { public void testTerminalUsageName() { ASTCDAttribute cdAttribute = Iterables.getOnlyElement(astA.getCDAttributeList()); - Assertions.assertEquals("testname", cdAttribute.getName()); - Assertions.assertEquals("String", TransformationHelper.typeToString(cdAttribute.getMCType())); + assertEquals("testname", cdAttribute.getName()); + assertEquals("String", TransformationHelper.typeToString(cdAttribute.getMCType())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TokenMultiplicityTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TokenMultiplicityTest.java index 874326cade..d3fbe7f20f 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TokenMultiplicityTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TokenMultiplicityTest.java @@ -8,7 +8,6 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,8 +16,8 @@ import java.util.Optional; import static de.monticore.codegen.mc2cd.TransformationHelper.typeToString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TokenMultiplicityTest extends TranslationTestCase { @@ -35,8 +34,8 @@ public void setupTokenMultiplicityTest() { public void testTokenStar() { List attributes = testListClass.getCDAttributeList(); String name = typeToString(attributes.get(0).getMCType()); - Assertions.assertEquals("java.util.List", name); + assertEquals("java.util.List", name); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TokenTypeTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TokenTypeTest.java index 15b3aa4832..8d9dbc9173 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TokenTypeTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/TokenTypeTest.java @@ -9,13 +9,15 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class TokenTypeTest extends TranslationTestCase { private ASTCDClass astTest; @@ -36,88 +38,88 @@ private Optional getCDAttributeByName(String name) { @Test public void testNumber() { ASTCDAttribute cdAttribute = getCDAttributeByName("a").get(); - Assertions.assertEquals("int", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("int", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBoolean() { ASTCDAttribute cdAttribute = getCDAttributeByName("b").get(); - Assertions.assertEquals("boolean", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("boolean", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testChar() { ASTCDAttribute cdAttribute = getCDAttributeByName("c").get(); - Assertions.assertEquals("char", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("char", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInt() { ASTCDAttribute cdAttribute = getCDAttributeByName("d").get(); - Assertions.assertEquals("int", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("int", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFloat() { ASTCDAttribute cdAttribute = getCDAttributeByName("e").get(); - Assertions.assertEquals("float", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("float", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDouble() { ASTCDAttribute cdAttribute = getCDAttributeByName("f").get(); - Assertions.assertEquals("double", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("double", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLong() { ASTCDAttribute cdAttribute = getCDAttributeByName("g").get(); - Assertions.assertEquals("long", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("long", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCard() { ASTCDAttribute cdAttribute = getCDAttributeByName("h").get(); - Assertions.assertEquals("int", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("int", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testShort() { ASTCDAttribute cdAttribute = getCDAttributeByName("i").get(); - Assertions.assertEquals("short", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("short", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testByte() { ASTCDAttribute cdAttribute = getCDAttributeByName("j").get(); - Assertions.assertEquals("byte", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("byte", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testByte2() { ASTCDAttribute cdAttribute = getCDAttributeByName("k").get(); - Assertions.assertEquals("byte", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); + assertEquals("byte", CD4CodeMill.prettyPrint(cdAttribute.getMCType(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/UsageNameTest.java b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/UsageNameTest.java index b1a38951e5..b2f7153c01 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/UsageNameTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/mc2cd/transl/UsageNameTest.java @@ -9,14 +9,13 @@ import de.monticore.codegen.mc2cd.TestHelper; import de.monticore.codegen.mc2cd.TranslationTestCase; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class UsageNameTest extends TranslationTestCase { @@ -35,16 +34,16 @@ public void setupUsageNameTest() { @Test public void testNonTerminal() { ASTCDAttribute cdAttribute = Iterables.getOnlyElement(astA.getCDAttributeList()); - Assertions.assertEquals("nonTerminalUsageName", cdAttribute.getName()); + assertEquals("nonTerminalUsageName", cdAttribute.getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testConstant() { ASTCDAttribute cdAttribute = Iterables.getOnlyElement(astB.getCDAttributeList()); - Assertions.assertEquals("constantUsageName", cdAttribute.getName()); + assertEquals("constantUsageName", cdAttribute.getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/codegen/parser/MCGrammarParserTest.java b/monticore-generator/src/test/java/de/monticore/codegen/parser/MCGrammarParserTest.java index 0ebed23a33..215a79331c 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/parser/MCGrammarParserTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/parser/MCGrammarParserTest.java @@ -8,7 +8,6 @@ import de.monticore.grammar.grammar_withconcepts._parser.Grammar_WithConceptsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,6 +15,8 @@ import java.io.StringReader; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCGrammarParserTest { @BeforeEach @@ -32,16 +33,16 @@ public void testParse() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); - Assertions.assertEquals("Statechart", grammar.getName()); - Assertions.assertEquals(7, grammar.getClassProdList().size()); - Assertions.assertEquals(3, grammar.getExternalProdList().size()); - Assertions.assertEquals(1, grammar.getInterfaceProdList().size()); + assertEquals("Statechart", grammar.getName()); + assertEquals(7, grammar.getClassProdList().size()); + assertEquals(3, grammar.getExternalProdList().size()); + assertEquals(1, grammar.getInterfaceProdList().size()); GrammarTransformer.transform(grammar); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -51,15 +52,15 @@ public void testASTRule() throws IOException { str = "astrule MCGrammar = GrammarOption max=1 ;"; Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parseASTRule(new StringReader(str)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); str = " astrule State = method public String getName(){ return \"\";};"; result = parser.parseASTRule(new StringReader(str)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -69,10 +70,10 @@ public void testSematicPred() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parseSemanticpredicateOrAction(new StringReader(str)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -81,10 +82,10 @@ public void testScript() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -93,10 +94,10 @@ public void testAutomatonV1() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -105,10 +106,10 @@ public void testAutomatonV2() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -117,8 +118,8 @@ public void testAutomatonV3() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); } @Test @@ -127,10 +128,10 @@ public void testHierarchicalAutomaton() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -139,11 +140,11 @@ public void testAutomatonWithInvsComp() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertEquals(1, Log.getFindings().size()); - Assertions.assertEquals("0xA4003 The grammar name InvAutomaton must be identical to the file name" + + assertEquals(1, Log.getFindings().size()); + assertEquals("0xA4003 The grammar name InvAutomaton must be identical to the file name" + " AutomatonWithInvsComp of the grammar (without its file extension).", Log.getFindings().get(0).getMsg()); Log.getFindings().clear(); @@ -155,8 +156,8 @@ public void testAutomatonWithInvs() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); } @Test @@ -165,8 +166,8 @@ public void testAutomatonWithInvsAndStartRule() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); } @Test @@ -175,22 +176,22 @@ public void testGrammarSymbolTableInfo() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); - Assertions.assertEquals(4, grammar.getClassProdList().size()); + assertEquals(4, grammar.getClassProdList().size()); ASTClassProd transition = grammar.getClassProdList().get(2); ASTNonTerminal fromState = (ASTNonTerminal) transition.getAltList().get(0).getComponentList().get(0); - Assertions.assertTrue(fromState.isPresentReferencedSymbol()); - Assertions.assertEquals("State", fromState.getReferencedSymbol()); + assertTrue(fromState.isPresentReferencedSymbol()); + assertEquals("State", fromState.getReferencedSymbol()); ASTNonTerminal toState = (ASTNonTerminal) transition.getAltList().get(0).getComponentList().get(0); - Assertions.assertTrue(toState.isPresentReferencedSymbol()); - Assertions.assertEquals("State", toState.getReferencedSymbol()); + assertTrue(toState.isPresentReferencedSymbol()); + assertEquals("State", toState.getReferencedSymbol()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -199,8 +200,8 @@ public void testPackageNameWithPointsDefined() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); parser.parse(model); - Assertions.assertEquals(1, Log.getFindings().size()); - Assertions.assertEquals("0xA4004 The package declaration point.in.packagename of the grammar must not differ from " + + assertEquals(1, Log.getFindings().size()); + assertEquals("0xA4004 The package declaration point.in.packagename of the grammar must not differ from " + "the package of the grammar file.", Log.getFindings().get(0).getMsg()); Log.getFindings().clear(); @@ -212,8 +213,8 @@ public void testPackageWrongPackageDefined() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); parser.parse(model); - Assertions.assertEquals(1, Log.getFindings().size()); - Assertions.assertEquals("0xA4004 The package declaration de.ronticore of the grammar " + + assertEquals(1, Log.getFindings().size()); + assertEquals("0xA4004 The package declaration de.ronticore of the grammar " + "must not differ from the package of the grammar file.", Log.getFindings().get(0).getMsg()); Log.getFindings().clear(); diff --git a/monticore-generator/src/test/java/de/monticore/codegen/parser/ParserGeneratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/parser/ParserGeneratorTest.java index 7358e57faa..a1a7161e48 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/parser/ParserGeneratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/parser/ParserGeneratorTest.java @@ -18,7 +18,6 @@ import de.se_rwth.commons.Names; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,8 +28,8 @@ import java.util.Optional; import static de.monticore.codegen.mc2cd.TestHelper.createGlobalScope; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for the MontiCore parser generator. @@ -70,15 +69,15 @@ public void testAutomatonSTParserGeneration() { Optional ast = new MontiCoreScript() .parseGrammar(Paths.get(new File( "src/test/resources/de/monticore/AutomatonST.mc4").getAbsolutePath())); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); ASTMCGrammar grammar = ast.get(); createSymbolsFromAST(Grammar_WithConceptsMill.globalScope(), ast.get()); ParserGenerator.generateParser(glex, grammar, Grammar_WithConceptsMill.globalScope(), new MCPath(), new MCPath(), new File("target/generated-test-sources/parsertest")); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -86,15 +85,15 @@ public void testExpressionParserGeneration() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional ast = parser .parse("src/test/resources/de/monticore/expression/Expression.mc4"); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); ASTMCGrammar grammar = ast.get(); createSymbolsFromAST(Grammar_WithConceptsMill.globalScope(), ast.get()); ParserGenerator.generateParser(glex, grammar, Grammar_WithConceptsMill.globalScope(), new MCPath(), new MCPath(), new File("target/generated-test-sources/parsertest")); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -102,15 +101,15 @@ public void testCdAttributesParserGeneration() { Optional ast = new MontiCoreScript() .parseGrammar(Paths.get(new File( "src/test/resources/de/monticore/CdAttributes.mc4").getAbsolutePath())); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); ASTMCGrammar grammar = ast.get(); createSymbolsFromAST(Grammar_WithConceptsMill.globalScope(), ast.get()); ParserGenerator.generateParser(glex, grammar, Grammar_WithConceptsMill.globalScope(), new MCPath(), new MCPath(), new File("target/generated-test-sources/parsertest")); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -118,15 +117,15 @@ public void testSubsubgrammarParserGeneration() { Optional ast = new MontiCoreScript() .parseGrammar(Paths.get(new File( "src/test/resources/de/monticore/inherited/subsub/Subsubgrammar.mc4").getAbsolutePath())); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); ASTMCGrammar grammar = ast.get(); createSymbolsFromAST(Grammar_WithConceptsMill.globalScope(), ast.get()); ParserGenerator.generateParser(glex, grammar, Grammar_WithConceptsMill.globalScope(), new MCPath(), new MCPath(), new File("target/generated-test-sources/parsertest")); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -134,15 +133,15 @@ public void testSubgrammarParserGeneration() { Optional ast = new MontiCoreScript() .parseGrammar(Paths.get(new File( "src/test/resources/de/monticore/inherited/sub/Subgrammar.mc4").getAbsolutePath())); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); ASTMCGrammar grammar = ast.get(); createSymbolsFromAST(Grammar_WithConceptsMill.globalScope(), ast.get()); ParserGenerator.generateParser(glex, grammar, Grammar_WithConceptsMill.globalScope(), new MCPath(), new MCPath(), new File("target/generated-test-sources/parsertest")); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -151,15 +150,15 @@ public void testActionParserGeneration() { Optional ast = new MontiCoreScript() .parseGrammar(Paths.get(new File( "src/test/resources/de/monticore/Action.mc4").getAbsolutePath())); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); ASTMCGrammar grammar = ast.get(); createSymbolsFromAST(Grammar_WithConceptsMill.globalScope(), ast.get()); ParserGenerator.generateParser(glex, grammar, Grammar_WithConceptsMill.globalScope(), new MCPath(), new MCPath(), new File("target/generated-test-sources/parsertest")); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private ASTMCGrammar createSymbolsFromAST(IGrammar_WithConceptsGlobalScope globalScope, ASTMCGrammar ast) { diff --git a/monticore-generator/src/test/java/de/monticore/codegen/prettyprint/MCGrammarPrettyPrinterTest.java b/monticore-generator/src/test/java/de/monticore/codegen/prettyprint/MCGrammarPrettyPrinterTest.java index 472dbb11f4..d30fc399f1 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/prettyprint/MCGrammarPrettyPrinterTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/prettyprint/MCGrammarPrettyPrinterTest.java @@ -7,7 +7,6 @@ import de.monticore.grammar.grammar_withconcepts._parser.Grammar_WithConceptsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -15,8 +14,8 @@ import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCGrammarPrettyPrinterTest { @@ -36,8 +35,8 @@ public void testStatechart() throws IOException { // Parsing input Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -45,12 +44,12 @@ public void testStatechart() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader (output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get())); + assertTrue(grammar.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -61,8 +60,8 @@ public void testAutomaton() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -70,12 +69,12 @@ public void testAutomaton() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get())); + assertTrue(grammar.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -86,8 +85,8 @@ public void testGrammar() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -95,12 +94,12 @@ public void testGrammar() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get())); + assertTrue(grammar.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -111,8 +110,8 @@ public void testLexicals() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -120,12 +119,12 @@ public void testLexicals() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get())); + assertTrue(grammar.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -136,8 +135,8 @@ public void testAnnotations() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -145,12 +144,12 @@ public void testAnnotations() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get())); + assertTrue(grammar.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-generator/src/test/java/de/monticore/runtime/junit/MCAssertions.java b/monticore-generator/src/test/java/de/monticore/runtime/junit/MCAssertions.java new file mode 100644 index 0000000000..befbabcc5a --- /dev/null +++ b/monticore-generator/src/test/java/de/monticore/runtime/junit/MCAssertions.java @@ -0,0 +1,63 @@ +package de.monticore.runtime.junit; + +import com.google.common.collect.Streams; +import de.se_rwth.commons.logging.Finding; +import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.Assertions; + +import java.util.stream.Collectors; + +/** + * A copy of the MCAssertions class from the runtime test fixtures + */ +public class MCAssertions { + /** + * Asserts that no findings are present. + * + * @param message the message to fail with iff findings were found + */ + public static void assertNoFindings(String message) { + if (!Log.getFindings().isEmpty()) { + failAndPrintFindings(message); + } + } + + /** + * Asserts that no findings are present. + */ + public static void assertNoFindings() { + assertNoFindings("Encountered Log-Findings while expecting none"); + } + + + /** + * Fails a test with the given failure message. + * Additionally, Lists the state of Log-Findings. + * See Javadoc for {@link Assertions#fail(String, Throwable)} + * for an explanation of this method's generic return type V. + * + * @param message message to print + * @return nothing + */ + public static V failAndPrintFindings(String message) { + StringBuilder messageWithFindings = new StringBuilder(); + if (!message.isBlank()) { + messageWithFindings.append(message); + } else { + messageWithFindings.append("Failed (no reason stated)"); + } + messageWithFindings.append(System.lineSeparator()); + if (Log.getFindings().isEmpty()) { + messageWithFindings.append("Got no Log-Findings."); + } else { + messageWithFindings.append("Got Log-Findings:"); + messageWithFindings.append(System.lineSeparator()); + messageWithFindings.append(Streams.mapWithIndex( + Log.getFindings().stream().map(Finding::buildMsg), + (str, index) -> "[" + index + "]" + str) + .collect(Collectors.joining(System.lineSeparator())) + ); + } + return Assertions.fail(messageWithFindings.toString()); + } +} diff --git a/monticore-generator/src/test/resources/de/monticore/inherited/Supergrammar.mc4 b/monticore-generator/src/test/resources/de/monticore/inherited/Supergrammar.mc4 index 665aade3a8..43e9556968 100644 --- a/monticore-generator/src/test/resources/de/monticore/inherited/Supergrammar.mc4 +++ b/monticore-generator/src/test/resources/de/monticore/inherited/Supergrammar.mc4 @@ -15,4 +15,8 @@ component grammar Supergrammar { K implements G = "OO"; N; + + ODName_Rep implements ITFODName ; + + interface ITFODName astextends de.monticore.ast.ASTNode; // any class not specified by a grammar } diff --git a/monticore-generator/src/test/resources/de/monticore/inherited/sub/Subgrammar.mc4 b/monticore-generator/src/test/resources/de/monticore/inherited/sub/Subgrammar.mc4 index 928e8d5282..618465fb3e 100644 --- a/monticore-generator/src/test/resources/de/monticore/inherited/sub/Subgrammar.mc4 +++ b/monticore-generator/src/test/resources/de/monticore/inherited/sub/Subgrammar.mc4 @@ -20,5 +20,8 @@ grammar Subgrammar extends de.monticore.inherited.Supergrammar { @Override N = X?; + + @Override + ODName_Rep = "hello" ; } diff --git a/monticore-generator/src/test/resources/de/monticore/inherited/subsub/Subsubgrammar.mc4 b/monticore-generator/src/test/resources/de/monticore/inherited/subsub/Subsubgrammar.mc4 index 1e0e57f3ad..3a7d034ced 100644 --- a/monticore-generator/src/test/resources/de/monticore/inherited/subsub/Subsubgrammar.mc4 +++ b/monticore-generator/src/test/resources/de/monticore/inherited/subsub/Subsubgrammar.mc4 @@ -12,5 +12,9 @@ grammar Subsubgrammar extends de.monticore.inherited.sub.Subgrammar { S = X*; // X = Y "HH" J D; + + + @Override + ODName_Rep = "world" ; } diff --git a/monticore-grammar-emf/build.gradle b/monticore-grammar-emf/build.gradle index 6a5c246383..eb551b83bb 100644 --- a/monticore-grammar-emf/build.gradle +++ b/monticore-grammar-emf/build.gradle @@ -21,9 +21,10 @@ dependencies { implementation 'org.eclipse.emf:org.eclipse.emf.common:2.15.0' testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" testImplementation 'org.apache.groovy:groovy:4.0.2' + testImplementation testFixtures(project(':monticore-runtime')) } def srcDir = "$buildDir/main/java" @@ -80,6 +81,7 @@ generateTestMCGrammars { } test { + useJUnitPlatform() exclude '**/CommentsOnASTTest.class' exclude '**/SwitchStatementValidTest.class' exclude '**/GrammarInheritanceCycleTest.class' @@ -92,7 +94,7 @@ test { exclude '**/SynthesizeSymTypeFromMCFullGenericTypesTest.class' exclude '**/SynthesizeSymTypeFromMCArrayTypesTest.class' exclude '**/MCType2SymTypeExpressionTest.class' - exclude '**/ComponentSymbolDeSerTest.class' + exclude '**/ComponentTypeSymbolDeSerTest.class' } diff --git a/monticore-grammar/build.gradle b/monticore-grammar/build.gradle index eb98fe2193..4f70adbead 100644 --- a/monticore-grammar/build.gradle +++ b/monticore-grammar/build.gradle @@ -7,10 +7,13 @@ buildscript { plugins { id "java-library" - id "com.github.johnrengelman.shadow" version "7.1.2" + id "com.github.johnrengelman.shadow" version "$shadow_plugin_version" // in case a "genTR" property is set to "true", transformation grammars are also created id "de.monticore.generator-withtr" version "$version" id "jacoco" + // this project provides test fixtures. Test fixtures are commonly used to setup the code under test, + // or provide utilities aimed at facilitating the tests of a component + id 'java-test-fixtures' } description = 'MontiCore: Grammar' @@ -57,6 +60,12 @@ configurations { capability("de.monticore:monticore-grammar:$version") // default } } + // We have to give the trafo component a different capability + trafoGrammarSymbolOutElements { + outgoing { + capability("de.monticore:monticore-grammar-trafo:$version") // default + } + } } @@ -70,14 +79,20 @@ dependencies { testImplementation "de.monticore:class2mc:$version" testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" + // grammar test fixtures includes runtime test dependencies + testFixturesApi testFixtures(project(":monticore-runtime")) if (("true").equals(getProperty('genTagging'))) { // use compileOnly as the tagging- and trafo-artifact are only an extension to the default artifact taggingCompileOnly project(path) } } +test { + useJUnitPlatform() +} + tasks.named('generateMCGrammars') { outputDir = file grammarOutDir @@ -547,13 +562,14 @@ java { registerFeature('tests') { usingSourceSet(sourceSets.test) } + withJavadocJar() } -shadowJar { +tasks.named("shadowJar") { from sourceSets.main.grammars } -generateTestMCGrammars { +tasks.named("generateTestMCGrammars") { // Temporary - for optimizations (due to feature) genINT = true dependsOn(tasks.grammarsForVariantJar) @@ -571,7 +587,7 @@ if (findProperty('ci') == null) { } if (("true").equals(getProperty('genTR'))) { - generateTrafoMCGrammars { + tasks.named("generateTrafoMCGrammars") { // Temporary - for optimizations dependsOn(tasks.grammarsForVariantJar) } @@ -645,9 +661,79 @@ if (("true").equals(getProperty('genTR'))) { publishing { publications { - "trafo" { + "trafo" (MavenPublication) { groupId = "de.monticore" // do not use the fake "de.mc" group, which was set during the plugin init phase } } } } + +// Workaround for https://github.com/gradle/gradle/issues/20539 +import org.gradle.api.plugins.internal.JvmPluginsHelper +import org.gradle.api.internal.file.FileResolver +import org.gradle.internal.component.external.model.ProjectDerivedCapability +import org.gradle.internal.component.external.model.TestFixturesSupport + +if(GradleVersion.current() < GradleVersion.version("8.5")){ + pluginManager.withPlugin("java-test-fixtures") { + def sourceSet = sourceSets["testFixtures"] + JvmPluginsHelper.configureDocumentationVariantWithArtifact( + sourceSet.sourcesElementsConfigurationName, + TestFixturesSupport.TEST_FIXTURE_SOURCESET_NAME, + DocsType.SOURCES, + [new ProjectDerivedCapability(project, "testFixtures")], + sourceSet.sourcesJarTaskName, + sourceSet.allSource, + components["java"] as AdhocComponentWithVariants, + configurations, + tasks, + objects, + project.services.get(FileResolver) + ) + JvmPluginsHelper.configureDocumentationVariantWithArtifact( + sourceSet.javadocElementsConfigurationName, + TestFixturesSupport.TEST_FIXTURE_SOURCESET_NAME, + DocsType.JAVADOC, + [new ProjectDerivedCapability(project, "testFixtures")], + sourceSet.javadocJarTaskName, + tasks.named(sourceSet.javadocTaskName), + components["java"] as AdhocComponentWithVariants, + configurations, + tasks, + objects, + project.services.get(FileResolver) + ) + } +} else { + pluginManager.withPlugin("java-test-fixtures") { + def sourceSet = sourceSets["testFixtures"] + def caps = [new ProjectDerivedCapability(project, "testFixtures")]; + if (GradleVersion.current() != GradleVersion.version("8.5")) + caps = caps.toSet() + JvmPluginsHelper.createDocumentationVariantWithArtifact( + sourceSet.sourcesElementsConfigurationName, + TestFixturesSupport.TEST_FIXTURE_SOURCESET_NAME, + DocsType.SOURCES, + caps, + sourceSet.sourcesJarTaskName, + sourceSet.allSource, + project + ) + JvmPluginsHelper.createDocumentationVariantWithArtifact( + sourceSet.javadocElementsConfigurationName, + TestFixturesSupport.TEST_FIXTURE_SOURCESET_NAME, + DocsType.JAVADOC, + caps, + sourceSet.javadocJarTaskName, + tasks.named(sourceSet.javadocTaskName), + project + ) + } +} +//End Workaround + + +tasks.named("build") { + dependsOn javadoc, testFixturesJavadoc +} + diff --git a/monticore-grammar/src/main/grammars/de/monticore/Grammars.md b/monticore-grammar/src/main/grammars/de/monticore/Grammars.md index d9622c9e8e..ec565584fe 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/Grammars.md +++ b/monticore-grammar/src/main/grammars/de/monticore/Grammars.md @@ -550,8 +550,8 @@ grammars: * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](Grammars.md) +* [Best Practices](../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-grammar/src/main/grammars/de/monticore/JavaLight.md b/monticore-grammar/src/main/grammars/de/monticore/JavaLight.md index c91bffc423..9268607e8b 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/JavaLight.md +++ b/monticore-grammar/src/main/grammars/de/monticore/JavaLight.md @@ -57,7 +57,7 @@ It can be **extended** by domain specific constructs, such as be addded through a predefined language library component. JavaLight is fully compatible with various expression language components -that [MontiCore's library](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) provides. These extensions can +that [MontiCore's library](Grammars.md) provides. These extensions can simply be added by MontiCore's language composition mechanism (see [Handbook](https://monticore.de/handbook.pdf)). @@ -150,9 +150,9 @@ The CoCos of embedded languages, such as statements and expressions are defined * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](Grammars.md) +* [Best Practices](../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [License definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-grammar/src/main/grammars/de/monticore/MCBasics.mlc b/monticore-grammar/src/main/grammars/de/monticore/MCBasics.mlc index fed57bb04c..28f35453b6 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/MCBasics.mlc +++ b/monticore-grammar/src/main/grammars/de/monticore/MCBasics.mlc @@ -39,6 +39,7 @@ mlc MCBasics { include "$mp/de/se_rwth/commons/**"; include "$mp/org/antlr/v4/runtime/**"; include "$mp/com/google/common/collect/**"; + include "$mp/com/google/common/base/**"; } } diff --git a/monticore-grammar/src/main/grammars/de/monticore/expressions/Expressions.md b/monticore-grammar/src/main/grammars/de/monticore/expressions/Expressions.md index 359e402dab..67dc107ad5 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/expressions/Expressions.md +++ b/monticore-grammar/src/main/grammars/de/monticore/expressions/Expressions.md @@ -64,9 +64,9 @@ for an example. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../Grammars.md) +* [Best Practices](../../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-grammar/src/main/grammars/de/monticore/literals/Literals.md b/monticore-grammar/src/main/grammars/de/monticore/literals/Literals.md index 1b4e237e55..c4bf19e496 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/literals/Literals.md +++ b/monticore-grammar/src/main/grammars/de/monticore/literals/Literals.md @@ -50,9 +50,9 @@ This is documented in [`SIUnits`](../siunit/SIUnits.md). * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../Grammars.md) +* [Best Practices](../../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-grammar/src/main/grammars/de/monticore/ocl/OCLExpressions.mc4 b/monticore-grammar/src/main/grammars/de/monticore/ocl/OCLExpressions.mc4 index 780e747ce6..ef2aea5ed1 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/ocl/OCLExpressions.mc4 +++ b/monticore-grammar/src/main/grammars/de/monticore/ocl/OCLExpressions.mc4 @@ -245,7 +245,7 @@ component grammar OCLExpressions * only directly applied to a reflexive association. It * cannot be applied on chains of associations of the form (a.b.c)** * The transitive closure of an association is also calculated if the - * association’s source and target are not identical or even if they + * association's source and target are not identical or even if they * are not subclasses of each other. In that case, the transitive * closure is identical to the initial association. * Example: this.clique = this.friend** diff --git a/monticore-grammar/src/main/grammars/de/monticore/siunit/SIUnits.md b/monticore-grammar/src/main/grammars/de/monticore/siunit/SIUnits.md index def21cd52a..59c1062384 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/siunit/SIUnits.md +++ b/monticore-grammar/src/main/grammars/de/monticore/siunit/SIUnits.md @@ -192,9 +192,9 @@ It is up to the developer of a generator to decide which solution to take. [SIUnitLiteralsGrammar]: SIUnitLiterals.mc4 [SIUnitTypes4MathGrammar]: SIUnitTypes4Math.mc4 [SIUnitTypes4ComputingGrammar]: SIUnitTypes4Computing.mc4 -[MCCommonLiteralsGrammar]: https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/literals/MCCommonLiterals.mc4 -[MCBasicTypesGrammar]: https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/types/MCBasicTypes.mc4 -[OOSymbols]: https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/symbols/OOSymbols.mc4 +[MCCommonLiteralsGrammar]: ../literals/MCCommonLiterals.mc4 +[MCBasicTypesGrammar]: ../types/MCBasicTypes.mc4 +[OOSymbols]: ../symbols/OOSymbols.mc4 [SIUnitBasic]: ../../../../java/de/monticore/types/check/SIUnitBasic.java [SymTypeOfSIUnit]: ../../../../java/de/monticore/types/check/SymTypeOfSIUnit.java @@ -211,8 +211,8 @@ It is up to the developer of a generator to decide which solution to take. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](http://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../Grammars.md) +* [Best Practices](../../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-grammar/src/main/grammars/de/monticore/symbols/CompSymbols.mc4 b/monticore-grammar/src/main/grammars/de/monticore/symbols/CompSymbols.mc4 index dff77cfdae..e898c1302e 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/symbols/CompSymbols.mc4 +++ b/monticore-grammar/src/main/grammars/de/monticore/symbols/CompSymbols.mc4 @@ -4,7 +4,7 @@ package de.monticore.symbols; /** * Common symbols for component-connector ADLs. */ -component grammar CompSymbols extends de.monticore.symbols.BasicSymbols { +component grammar CompSymbols extends de.monticore.symbols.BasicSymbols, de.monticore.expressions.ExpressionsBasis { interface scope symbol ComponentType = Name; @@ -49,4 +49,5 @@ component grammar CompSymbols extends de.monticore.symbols.BasicSymbols { stronglyCausal: Boolean ; + interface SubcomponentArgument = Name? Expression; } diff --git a/monticore-grammar/src/main/grammars/de/monticore/symbols/OOSymbols.mc4 b/monticore-grammar/src/main/grammars/de/monticore/symbols/OOSymbols.mc4 index 2b3f046a6f..9ea9343cc7 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/symbols/OOSymbols.mc4 +++ b/monticore-grammar/src/main/grammars/de/monticore/symbols/OOSymbols.mc4 @@ -78,6 +78,7 @@ component grammar OOSymbols extends BasicSymbols { isPublic: boolean isStatic:boolean isFinal: boolean + isEnumConstant: boolean isDerived: boolean ; /*=================================================================*/ diff --git a/monticore-grammar/src/main/grammars/de/monticore/types/Types.md b/monticore-grammar/src/main/grammars/de/monticore/types/Types.md index cb61d13af4..2a16c39954 100644 --- a/monticore-grammar/src/main/grammars/de/monticore/types/Types.md +++ b/monticore-grammar/src/main/grammars/de/monticore/types/Types.md @@ -126,8 +126,8 @@ This is documented in [`RegEx`](../regex/RegEx.md). * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../Grammars.md) +* [Best Practices](../../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/types3/AssignmentExpressionsCTTIVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/types3/AssignmentExpressionsCTTIVisitor.java index 52f52abb70..84e3355455 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/types3/AssignmentExpressionsCTTIVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/assignmentexpressions/types3/AssignmentExpressionsCTTIVisitor.java @@ -1,12 +1,12 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.expressions.assignmentexpressions.types3; +import com.google.common.base.Preconditions; import de.monticore.expressions.assignmentexpressions._ast.ASTAssignmentExpression; import de.monticore.expressions.assignmentexpressions._visitor.AssignmentExpressionsHandler; import de.monticore.expressions.assignmentexpressions._visitor.AssignmentExpressionsTraverser; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.SymTypeRelations; -import de.se_rwth.commons.logging.Log; /** * AssignmentExpressions with additional generics support. @@ -37,7 +37,7 @@ public void handle(ASTAssignmentExpression expr) { } protected void setTargetType(ASTAssignmentExpression expr) { - Log.errorIfNull(expr); + Preconditions.checkNotNull(expr); SymTypeExpression left = getType4Ast().getPartialTypeOfExpr(expr.getLeft()); if (!SymTypeRelations.normalize(left).isObscureType()) { getInferenceContext4Ast().setTargetTypeOfExpression(expr.getRight(), left); diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsCTTIVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsCTTIVisitor.java index 0243e73464..bf406132da 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsCTTIVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsCTTIVisitor.java @@ -8,6 +8,7 @@ import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeOfFunction; +import de.monticore.types3.SymTypeRelations; import de.monticore.types3.generics.TypeParameterRelations; import de.monticore.types3.generics.context.InferenceContext; import de.monticore.types3.generics.context.InferenceVisitorMode; @@ -73,7 +74,10 @@ public void handle(ASTCallExpression expr) { CompileTimeTypeCalculator.handleCall(expr, expr.getExpression(), expr.getArguments().getExpressionList(), getTraverser(), getType4Ast(), getInferenceContext4Ast()); - if (getType4Ast().hasPartialTypeOfExpression(expr)) { + if (getType4Ast().hasPartialTypeOfExpression(expr) && + !SymTypeRelations.normalize(getType4Ast().getPartialTypeOfExpr(expr)) + .isObscureType() + ) { endVisit(expr); } } diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeIdAsConstructorCTTIVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeIdAsConstructorCTTIVisitor.java new file mode 100644 index 0000000000..1a438fb8e3 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeIdAsConstructorCTTIVisitor.java @@ -0,0 +1,83 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.expressions.commonexpressions.types3; + +import de.monticore.expressions.commonexpressions._ast.ASTFieldAccessExpression; +import de.monticore.symboltable.IScope; +import de.monticore.symboltable.modifiers.AccessModifier; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeOfFunction; +import de.monticore.types3.util.OOWithinTypeBasicSymbolsResolver; +import de.monticore.types3.util.TypeContextCalculator; + +import java.util.List; +import java.util.Optional; + +/** + * This visitor allows the use of type identifiers "as" the types constructors, + * e.g., pack.age.Foo(1) is accepted if the constructor + * pack.age.Foo::Foo(int) exists. + */ +public class CommonExpressionsTypeIdAsConstructorCTTIVisitor extends + CommonExpressionsCTTIVisitor { + + @Override + protected Optional calculateTypeIdFieldAccess( + ASTFieldAccessExpression expr, + boolean resultsAreOptional) { + Optional exprType = + super.calculateTypeIdFieldAccess(expr, resultsAreOptional); + if (exprType.isEmpty() && !resultsAreOptional) { + Optional typeIdType = + calculateInnerTypeIdFieldAccess(expr); + if (typeIdType.isPresent()) { + exprType = + constructorsOfTypeId(typeIdType.get(), expr.getEnclosingScope()); + } + } + return exprType; + } + + @Override + protected Optional calculateExprQName( + ASTFieldAccessExpression expr, + boolean resultsAreOptional) { + Optional exprType = super.calculateExprQName(expr, resultsAreOptional); + if (exprType.isEmpty() && !resultsAreOptional) { + Optional typeIdType = + calculateTypeIdQName(expr); + if (typeIdType.isPresent()) { + exprType = + constructorsOfTypeId(typeIdType.get(), expr.getEnclosingScope()); + } + } + return exprType; + } + + // Helper + + protected Optional constructorsOfTypeId( + SymTypeExpression typeIdType, + IScope enclosingScope) { + AccessModifier accessModifier = TypeContextCalculator.getAccessModifier( + typeIdType.getTypeInfo(), + enclosingScope, + true + ); + List constructors = + OOWithinTypeBasicSymbolsResolver.resolveConstructors( + typeIdType, + accessModifier, + c -> true + ); + if (constructors.isEmpty()) { + return Optional.empty(); + } + else { + return Optional.of(SymTypeExpressionFactory.createIntersectionOrDefault( + SymTypeExpressionFactory.createObscureType(), constructors + )); + } + } + +} diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeIdAsConstructorTypeVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeIdAsConstructorTypeVisitor.java index af52f73eca..f95d555211 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeIdAsConstructorTypeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeIdAsConstructorTypeVisitor.java @@ -17,7 +17,10 @@ * This visitor allows the use of type identifiers "as" the types constructors, * e.g., pack.age.Foo(1) is accepted if the constructor * pack.age.Foo::Foo(int) exists. + * + * @deprecated use {@link CommonExpressionsTypeIdAsConstructorCTTIVisitor} */ +@Deprecated public class CommonExpressionsTypeIdAsConstructorTypeVisitor extends CommonExpressionsTypeVisitor { diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeVisitor.java index cc160568eb..74148c8998 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/commonexpressions/types3/CommonExpressionsTypeVisitor.java @@ -33,7 +33,7 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; @@ -477,12 +477,12 @@ public void endVisit(ASTCallExpression expr) { getType4Ast().getPartialTypeOfExpr(expr.getExpression()) ); if (calculatedInner.isIntersectionType()) { - inner = new HashSet<>( + inner = new LinkedHashSet<>( ((SymTypeOfIntersection) calculatedInner).getIntersectedTypeSet() ); } else { - inner = new HashSet<>(); + inner = new LinkedHashSet<>(); inner.add(calculatedInner); } if (inner.stream().allMatch(SymTypeExpression::isObscureType)) { @@ -812,8 +812,9 @@ protected Optional calculateExprFieldAccess( type = Optional.empty(); } else { - SymTypeExpression innerAsExprType = - getType4Ast().getPartialTypeOfExpr(expr.getExpression()); + SymTypeExpression innerAsExprType = SymTypeRelations.normalize( + getType4Ast().getPartialTypeOfExpr(expr.getExpression()) + ); if (WithinTypeBasicSymbolsResolver.canResolveIn(innerAsExprType)) { AccessModifier modifier = innerAsExprType.hasTypeInfo() ? TypeContextCalculator.getAccessModifier( @@ -1135,7 +1136,7 @@ protected Optional resolveVariablesAndFunctionsWithinType( Predicate varPredicate, Predicate funcPredicate ) { - Set types = new HashSet<>(); + Set types = new LinkedHashSet<>(); Optional variable = WithinTypeBasicSymbolsResolver.resolveVariable(innerAsExprType, name, @@ -1170,7 +1171,7 @@ protected Optional resolveVariablesAndFunctionsWithinType( * this analyses the expression and returns a qualified name if possible, * which _may_ be of a type / value * Note: Java (Spec v.20 chapter 19: Syntax) does not allow type arguments, - * e.g., class C{T t;} C.t = 3.2; + * e.g., {@code class C{T t;} C.t = 3.2;} */ protected Optional getExprAsQName(ASTExpression expr) { if (expr instanceof ASTNameExpression) { diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/types3/ExpressionBasisTypeIdAsConstructorCTTIVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/types3/ExpressionBasisTypeIdAsConstructorCTTIVisitor.java new file mode 100644 index 0000000000..7293633b0a --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/types3/ExpressionBasisTypeIdAsConstructorCTTIVisitor.java @@ -0,0 +1,57 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.expressions.expressionsbasis.types3; + +import de.monticore.expressions.expressionsbasis._ast.ASTNameExpression; +import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; +import de.monticore.symboltable.modifiers.AccessModifier; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeOfFunction; +import de.monticore.types3.util.OOWithinTypeBasicSymbolsResolver; +import de.monticore.types3.util.TypeContextCalculator; +import de.monticore.types3.util.WithinScopeBasicSymbolsResolver; + +import java.util.List; +import java.util.Optional; + +/** + * s. {@link de.monticore.expressions.commonexpressions.types3.CommonExpressionsTypeIdAsConstructorCTTIVisitor} + */ +public class ExpressionBasisTypeIdAsConstructorCTTIVisitor + extends ExpressionBasisCTTIVisitor { + + /** + * adds support for the type id to be used as if it were the constructors of the type, + * e.g., Foo(1) based on Constructor Foo::Foo(int) + */ + @Override + protected Optional calculateNameExpression( + ASTNameExpression expr) { + Optional exprType = super.calculateNameExpression(expr); + // add constructors only if no expression has been found + if (exprType.isEmpty()) { + IBasicSymbolsScope enclosingScope = + getAsBasicSymbolsScope(expr.getEnclosingScope()); + Optional typeIdType = WithinScopeBasicSymbolsResolver + .resolveType(enclosingScope, expr.getName()); + if (typeIdType.isPresent()) { + AccessModifier accessModifier = TypeContextCalculator + .getAccessModifier(typeIdType.get().getTypeInfo(), enclosingScope); + List constructors = + OOWithinTypeBasicSymbolsResolver.resolveConstructors( + typeIdType.get(), + accessModifier, + c -> true + ); + if (constructors.size() == 1) { + exprType = Optional.of(constructors.get(0)); + } + else if (constructors.size() > 1) { + exprType = Optional.of(SymTypeExpressionFactory.createIntersection(constructors)); + } + } + } + return exprType; + } + +} \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/types3/ExpressionBasisTypeIdAsConstructorTypeVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/types3/ExpressionBasisTypeIdAsConstructorTypeVisitor.java index 34920a4c51..154ef2521e 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/types3/ExpressionBasisTypeIdAsConstructorTypeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/expressionsbasis/types3/ExpressionBasisTypeIdAsConstructorTypeVisitor.java @@ -16,7 +16,10 @@ /** * s. {@link de.monticore.expressions.commonexpressions.types3.CommonExpressionsTypeIdAsConstructorTypeVisitor} + * + * @deprecated use {@link ExpressionBasisTypeIdAsConstructorCTTIVisitor} */ +@Deprecated public class ExpressionBasisTypeIdAsConstructorTypeVisitor extends ExpressionBasisTypeVisitor { diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_symboltable/LambdaExpressionsSTCompleteTypes.java b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_symboltable/LambdaExpressionsSTCompleteTypes.java index 95fc2b40eb..79328ab912 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_symboltable/LambdaExpressionsSTCompleteTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_symboltable/LambdaExpressionsSTCompleteTypes.java @@ -9,6 +9,10 @@ import de.monticore.types.check.TypeCheckResult; import de.monticore.types.mcbasictypes._ast.ASTMCType; +/** + * @deprecated use {@link LambdaExpressionsSTCompleteTypes2} + */ +@Deprecated(forRemoval = true) public class LambdaExpressionsSTCompleteTypes implements LambdaExpressionsVisitor2 { ISynthesize synthesize; diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_symboltable/LambdaExpressionsSTCompleteTypes2.java b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_symboltable/LambdaExpressionsSTCompleteTypes2.java index 08e9f557ff..077cf6a960 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_symboltable/LambdaExpressionsSTCompleteTypes2.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/lambdaexpressions/_symboltable/LambdaExpressionsSTCompleteTypes2.java @@ -6,6 +6,7 @@ import de.monticore.types.check.SymTypeExpression; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types3.Type4Ast; +import de.monticore.types3.TypeCheck3; import de.monticore.visitor.ITraverser; public class LambdaExpressionsSTCompleteTypes2 implements LambdaExpressionsVisitor2 { @@ -16,16 +17,22 @@ public class LambdaExpressionsSTCompleteTypes2 implements LambdaExpressionsVisit // the traverser filling the type map // not required, if the map is already filled + @Deprecated protected ITraverser typeTraverser; + @Deprecated protected Type4Ast getTypeMap() { return type4Ast; } + @Deprecated protected ITraverser getTypeTraverser() { return typeTraverser; } + public LambdaExpressionsSTCompleteTypes2() { + } + // after moving the typemap, the other constructor ought to be used @Deprecated public LambdaExpressionsSTCompleteTypes2(ITraverser typeTraverser, Type4Ast type4Ast) { @@ -33,14 +40,24 @@ public LambdaExpressionsSTCompleteTypes2(ITraverser typeTraverser, Type4Ast type this.type4Ast = type4Ast; } + @Deprecated public LambdaExpressionsSTCompleteTypes2(ITraverser typeTraverser) { this.typeTraverser = typeTraverser; } @Override public void endVisit(ASTLambdaParameter ast) { - if (ast.isPresentMCType()) { - ast.getSymbol().setType(calculateType(ast.getMCType())); + // deprecated behavior: + if(type4Ast != null) { + if (ast.isPresentMCType()) { + ast.getSymbol().setType(calculateType(ast.getMCType())); + } + return; + } + // actual behavior + if(ast.isPresentMCType()) { + SymTypeExpression type = TypeCheck3.symTypeFromAST(ast.getMCType()); + ast.getSymbol().setType(type); } // else: currently, the typecheck will set the type later. // Example: @@ -50,7 +67,7 @@ public void endVisit(ASTLambdaParameter ast) { } // Helper - + @Deprecated protected SymTypeExpression calculateType(ASTMCType mcType) { if (!getTypeMap().hasTypeOfTypeIdentifier(mcType)) { mcType.accept(getTypeTraverser()); diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/tupleexpressions/types3/TupleExpressionsCTTIVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/tupleexpressions/types3/TupleExpressionsCTTIVisitor.java new file mode 100644 index 0000000000..ae8d02ba54 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/expressions/tupleexpressions/types3/TupleExpressionsCTTIVisitor.java @@ -0,0 +1,79 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.expressions.tupleexpressions.types3; + +import com.google.common.base.Preconditions; +import de.monticore.expressions.tupleexpressions._ast.ASTTupleExpression; +import de.monticore.expressions.tupleexpressions._visitor.TupleExpressionsHandler; +import de.monticore.expressions.tupleexpressions._visitor.TupleExpressionsTraverser; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeInferenceVariable; +import de.monticore.types.check.SymTypeOfFunction; +import de.monticore.types3.generics.util.CompileTimeTypeCalculator; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static de.monticore.types.check.SymTypeExpressionFactory.createFunction; +import static de.monticore.types.check.SymTypeExpressionFactory.createTuple; + +public class TupleExpressionsCTTIVisitor extends TupleExpressionsTypeVisitor + implements TupleExpressionsHandler { + + // handler + + protected TupleExpressionsTraverser traverser; + + @Override + public TupleExpressionsTraverser getTraverser() { + return traverser; + } + + @Override + public void setTraverser(TupleExpressionsTraverser traverser) { + Preconditions.checkNotNull(traverser); + this.traverser = traverser; + } + + // CTTI + + @Override + public void handle(ASTTupleExpression expr) { + SymTypeOfFunction exprFunc; + if (getInferenceContext4Ast().hasResolvedOfExpression(expr)) { + exprFunc = getInferenceContext4Ast() + .getResolvedOfExpression(expr) + .asFunctionType(); + } + else { + exprFunc = getTupleExpressionFunc(expr.sizeExpressions()); + getInferenceContext4Ast().setResolvedOfExpression(expr, exprFunc); + } + CompileTimeTypeCalculator.handleCall( + expr, + exprFunc, + expr.getExpressionList(), + getTraverser(), getType4Ast(), getInferenceContext4Ast() + ); + if (getType4Ast().hasPartialTypeOfExpression(expr) && + !getType4Ast().getPartialTypeOfExpr(expr).isObscureType() + ) { + visit(expr); + traverse(expr); + endVisit(expr); + } + } + + // Helper + + /** {@code (T1,T2) -> (T1,T2)} */ + protected SymTypeOfFunction getTupleExpressionFunc(int n) { + List typeVars = + Stream.generate(SymTypeExpressionFactory::createInferenceVariable) + .limit(n) + .collect(Collectors.toList()); + SymTypeOfFunction tupleExprFunc = + createFunction(createTuple(typeVars), typeVars); + return tupleExprFunc; + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/expressions/tupleexpressions/types3/TupleExpressionsTypeVisitor.java b/monticore-grammar/src/main/java/de/monticore/expressions/tupleexpressions/types3/TupleExpressionsTypeVisitor.java index 7f2dad6016..d1f7356c28 100644 --- a/monticore-grammar/src/main/java/de/monticore/expressions/tupleexpressions/types3/TupleExpressionsTypeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/expressions/tupleexpressions/types3/TupleExpressionsTypeVisitor.java @@ -1,12 +1,12 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.expressions.tupleexpressions.types3; +import com.google.common.base.Preconditions; import de.monticore.expressions.tupleexpressions._ast.ASTTupleExpression; import de.monticore.expressions.tupleexpressions._visitor.TupleExpressionsVisitor2; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types3.AbstractTypeVisitor; -import de.se_rwth.commons.logging.Log; import java.util.List; import java.util.stream.Collectors; @@ -16,7 +16,7 @@ public class TupleExpressionsTypeVisitor extends AbstractTypeVisitor @Override public void endVisit(ASTTupleExpression expr) { - Log.errorIfNull(expr); + Preconditions.checkNotNull(expr); SymTypeExpression result; List listedTypes = expr.streamExpressions() .map(e -> getType4Ast().getPartialTypeOfExpr(e)) diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/DirectLeftRecursionDetector.java b/monticore-grammar/src/main/java/de/monticore/grammar/DirectLeftRecursionDetector.java index e2d2fe4009..39163bf88f 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/DirectLeftRecursionDetector.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/DirectLeftRecursionDetector.java @@ -10,7 +10,7 @@ import java.util.List; /** - * Checks if a MC production is a left directly left recursive: e.g. of the form A -> A.* + * Checks if a MC production is a left directly left recursive: e.g. of the form {@code A -> A.*} * */ public class DirectLeftRecursionDetector { diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/LexNamer.java b/monticore-grammar/src/main/java/de/monticore/grammar/LexNamer.java index 60ab5d5055..ae97a86fbf 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/LexNamer.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/LexNamer.java @@ -2,7 +2,7 @@ package de.monticore.grammar; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -24,15 +24,15 @@ public class LexNamer { protected int lexCounter = 0; - protected Map usedLex = new HashMap(); + protected Map usedLex = new LinkedHashMap(); - protected Map usedConstants = new HashMap(); + protected Map usedConstants = new LinkedHashMap(); protected static Map goodNames = null; public static Map getGoodNames() { if (goodNames == null) { - goodNames = new HashMap(); + goodNames = new LinkedHashMap(); // Put all common names here, one character only, since all others are // concatanation of these goodNames.put(";", "SEMI"); diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/MCGrammarSymbolTableHelper.java b/monticore-grammar/src/main/java/de/monticore/grammar/MCGrammarSymbolTableHelper.java index 3fc4ae8152..eb520fe974 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/MCGrammarSymbolTableHelper.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/MCGrammarSymbolTableHelper.java @@ -2,6 +2,7 @@ package de.monticore.grammar; +import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -214,8 +215,8 @@ protected static boolean isSubtype(ProdSymbol subType, ProdSymbol superType, } public static boolean areSameTypes(ProdSymbol type1, ProdSymbol type2) { - Log.errorIfNull(type1); - Log.errorIfNull(type2); + Preconditions.checkNotNull(type1); + Preconditions.checkNotNull(type2); if (type1 == type2) { return true; diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ExternalNTNoASTRule.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ExternalNTNoASTRule.java index 62b2225afa..7e3da5b030 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ExternalNTNoASTRule.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ExternalNTNoASTRule.java @@ -19,7 +19,9 @@ public class ExternalNTNoASTRule implements GrammarASTASTRuleCoCo { public void check(ASTASTRule node) { Optional prod = node.getEnclosingScope().resolveProd(node.getType()); if(prod.isPresent() && prod.get().isIsExternal()){ - Log.error(ERROR_CODE+String.format(ERROR_MSG_FORMAT, prod.get().getName())); + Log.error(ERROR_CODE+String.format(ERROR_MSG_FORMAT, prod.get().getName()), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/InheritedModiOverwrite.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/InheritedModiOverwrite.java index 1af62cec7f..98af9693b4 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/InheritedModiOverwrite.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/InheritedModiOverwrite.java @@ -33,7 +33,9 @@ public void check(ASTMCGrammar node) { for (ASTLexProd lex : supLexProdList) { if (!lex.isPresentMode()) { //warn the user that he inherits a token mode - Log.warn(String.format(ERROR_CODE + ERROR_MSG_FORMAT, prodName, grammarName, modeString, prodName, superGrammarName)); + Log.warn(String.format(ERROR_CODE + ERROR_MSG_FORMAT, prodName, grammarName, modeString, prodName, superGrammarName), + lex.get_SourcePositionStart(), + lex.get_SourcePositionEnd()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/InterfaceNTWithoutImplementationOnlyInComponentGrammar.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/InterfaceNTWithoutImplementationOnlyInComponentGrammar.java index 6c11d6e980..2ed3eb0625 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/InterfaceNTWithoutImplementationOnlyInComponentGrammar.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/InterfaceNTWithoutImplementationOnlyInComponentGrammar.java @@ -47,7 +47,7 @@ public void check(ASTMCGrammar a) { // for every interface production we get all other interfaces implementing it and save it to map of all interface // productions mapping to all their subinterfaces - Map> subSymbols = new HashMap<>(); + Map> subSymbols = new LinkedHashMap<>(); for (ProdSymbol interfaceProd : interfaceProds) { for (ProdSymbol superInterface : interfaceProd.getSuperInterfaceProds()) { if (!subSymbols.containsKey(superInterface.getName())) { diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoASTExtendsForClasses.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoASTExtendsForClasses.java index 66c96016f7..e0f8db4503 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoASTExtendsForClasses.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoASTExtendsForClasses.java @@ -32,13 +32,13 @@ public void check(ASTMCGrammar a) { Map allProds = grammarSymbol.getProdsWithInherited(); for (ProdSymbol classProd : grammarSymbol.getProds()) { - for (ProdSymbolSurrogate sClass : classProd.getAstSuperClasses()) { + for (ProdSymbol sClass : classProd.getAstSuperClasses()) { if (!allProds.containsKey( sClass.getName().substring("AST".length()))) { Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, classProd.getName(), - Names.getSimpleName(sClass.getName()), - classProd.getAstNode().get_SourcePositionStart())); + Names.getSimpleName(sClass.getName())), + classProd.getAstNode().get_SourcePositionStart()); } } } @@ -51,8 +51,8 @@ public void check(ASTMCGrammar a) { String simpleName = simpleName(type); if (!allProds.containsKey(simpleName.substring("AST".length()))) { Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, - rule.getType(), simpleName, - rule.get_SourcePositionStart())); + rule.getType(), simpleName), + rule.get_SourcePositionStart()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoExtensionOfSymbolThatOnlySpansScope.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoExtensionOfSymbolThatOnlySpansScope.java index 11f74bf24a..cc0d9c82fe 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoExtensionOfSymbolThatOnlySpansScope.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoExtensionOfSymbolThatOnlySpansScope.java @@ -62,7 +62,7 @@ protected void checkProdsAndLogError(List superProds, ProdS } protected void logError(ProdSymbol original, ProdSymbol superProd){ - Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, original, superProd)); + Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, original, superProd), original.getSourcePosition()); } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenGrammarName.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenGrammarName.java index f971e17a77..ebfd354bba 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenGrammarName.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenGrammarName.java @@ -21,7 +21,9 @@ public class NoForbiddenGrammarName implements GrammarASTMCGrammarCoCo { public void check (ASTMCGrammar node){ String grammarName = node.getName(); if(forbiddenNames.contains(grammarName)){ - Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, grammarName)); + Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, grammarName), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdAndSymbolName.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdAndSymbolName.java index 61a50473db..f93e1fdfa4 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdAndSymbolName.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdAndSymbolName.java @@ -42,7 +42,7 @@ protected void handle(String grammarName, String addon, String prodName, Collect if(!forbidden.isEmpty()){ for(ProdSymbol prod: forbidden){ - Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prodName, grammarName, prod.getName())); + Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prodName, grammarName, prod.getName()), prod.getSourcePosition()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdName.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdName.java index 73747e65ee..9fb10f910b 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdName.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdName.java @@ -35,10 +35,10 @@ public void check(ASTMCGrammar node) { for(ProdSymbol prod: prods){ String prodName = prod.getName(); if(forbiddenNames.contains(prodName)){ - Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prodName, grammarName)); + Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prodName, grammarName), prod.getSourcePosition()); } if((grammarName+NODE).equals(prodName) || (CONSTANTS+grammarName).equals(prodName)){ - Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prodName, grammarName)); + Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prodName, grammarName), prod.getSourcePosition()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdNameAddon.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdNameAddon.java index 414f39c276..0cb1de1488 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdNameAddon.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenProdNameAddon.java @@ -40,7 +40,7 @@ protected void handle(String grammarName, String addon, String prodName, Collect if(!forbidden.isEmpty()){ for(ProdSymbol prod: forbidden){ - Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prodName, grammarName, prod.getName())); + Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prodName, grammarName, prod.getName()), prod.getSourcePosition()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenSymbolName.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenSymbolName.java index d8dd1790c7..9df4fcecb2 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenSymbolName.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenSymbolName.java @@ -1,12 +1,14 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.grammar.cocos; +import com.google.common.collect.Lists; import de.monticore.grammar.grammar._ast.ASTMCGrammar; import de.monticore.grammar.grammar._cocos.GrammarASTMCGrammarCoCo; import de.monticore.grammar.grammar._symboltable.MCGrammarSymbol; import de.monticore.grammar.grammar._symboltable.ProdSymbol; import de.se_rwth.commons.logging.Log; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -18,6 +20,8 @@ public class NoForbiddenSymbolName implements GrammarASTMCGrammarCoCo { protected static final String SYMBOL = "Symbol"; + protected static final List forbiddenSymbolNames = Collections.unmodifiableList(Lists.newArrayList("I", "IScopeSpanning")); + @Override public void check(ASTMCGrammar node) { String grammarName = node.getName(); @@ -33,10 +37,16 @@ public void check(ASTMCGrammar node) { .collect(Collectors.toList()); if(!forbidden.isEmpty()){ for(ProdSymbol prod: forbidden){ - Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prod.getName(), grammarName)); + Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prod.getName(), grammarName), prod.getSourcePosition()); } } } + + for(ProdSymbol prod : symbolProds){ + if(forbiddenSymbolNames.contains(prod.getName())){ + Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, prod.getName(), grammarName), prod.getSourcePosition()); + } + } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenSymbolNameAddon.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenSymbolNameAddon.java index 44bee40a69..571541790f 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenSymbolNameAddon.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/NoForbiddenSymbolNameAddon.java @@ -59,7 +59,7 @@ protected void handle(String grammarName, String addon, String prodName, List> - * A*, A+, A? - * A min = 0, A max = 5, A max = * + * {@code A>} + * {@code A*, A+, A?} + * {@code A min = 0, A max = 5, A max = *} * because these cases cannot be handled in the generator so far and will generate the wrong type */ public class NoNestedGenericsInAdditionalAttributes implements GrammarASTMCGrammarCoCo { @@ -68,7 +68,7 @@ protected void findMultipleGenericAttributes(List astAdd } /** - * for e.g. A> + * for e.g. {@code A>} */ protected boolean hasNestedGeneric(ASTMCType mcType){ return((ASTMCGenericType) mcType).getMCTypeArgumentList() @@ -78,7 +78,7 @@ protected boolean hasNestedGeneric(ASTMCType mcType){ } /** - * for e.g. A*, A+, A? + * for e.g. {@code A*}, {@code A+}, {@code A?} */ protected boolean hasGenericIteration(ASTAdditionalAttribute astAdditionalAttribute){ return astAdditionalAttribute.getCard().getIteration() == STAR || astAdditionalAttribute.getCard().getIteration() == PLUS || @@ -86,7 +86,7 @@ protected boolean hasGenericIteration(ASTAdditionalAttribute astAdditionalAttrib } /** - * for e.g. A min=0, A max=2, A max=* + * for e.g. {@code A min=0}, {@code A max=2}, {@code A max=*} */ protected boolean hasGenericMaxValue(ASTAdditionalAttribute astAdditionalAttribute){ return (astAdditionalAttribute.getCard().isPresentMax() && ("*".equals(astAdditionalAttribute.getCard().getMax()) || @@ -96,7 +96,9 @@ protected boolean hasGenericMaxValue(ASTAdditionalAttribute astAdditionalAttribu protected void logError(String ruleName, String grammarName, String prodName, ASTAdditionalAttribute astAdditionalAttribute) { Log.error(ERROR_CODE + String.format(ERROR_MSG_FORMAT, ruleName, grammarName, prodName, - printASTAdditionalAttribute(astAdditionalAttribute))); + printASTAdditionalAttribute(astAdditionalAttribute)), + astAdditionalAttribute.get_SourcePositionStart(), + astAdditionalAttribute.get_SourcePositionEnd()); } protected String printASTAdditionalAttribute(ASTAdditionalAttribute astAdditionalAttribute) { diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingAdditionalAttributes.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingAdditionalAttributes.java index 585837effa..f1e5dda232 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingAdditionalAttributes.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingAdditionalAttributes.java @@ -30,7 +30,7 @@ public void check(ASTMCGrammar a) { for (AdditionalAttributeSymbol ad: attributes) { if (superAttributes.stream().filter(m -> ad.getName().equals(m.getName()) && ad.isIsAstAttr()==m.isIsAstAttr()).count()>1) { - Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, ad.getName(), prodSymbol.getName())); + Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, ad.getName(), prodSymbol.getName()), ad.getSourcePosition()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingEnumNTs.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingEnumNTs.java index 9ba722dfb3..56fc9570f4 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingEnumNTs.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingEnumNTs.java @@ -37,7 +37,9 @@ public void check(ASTMCGrammar a) { for (ASTProd p : prods) { Optional typeSymbol = grammarSymbol.getInheritedProd(p.getName()); if (typeSymbol.isPresent() && typeSymbol.get().isIsEnum()) { - Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, p.getName())); + Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, p.getName()), + p.get_SourcePositionStart(), + p.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingInterfaceNTs.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingInterfaceNTs.java index c4edf4aa99..8059fd7399 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingInterfaceNTs.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/OverridingInterfaceNTs.java @@ -39,7 +39,7 @@ public void check(ASTMCGrammar a) { for (MCGrammarSymbol s : grammarSymbols) { Optional typeSymbol = s.getProd(p.getName()); if (typeSymbol.isPresent() && typeSymbol.get().isIsInterface()) { - Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, typeSymbol.get().getName())); + Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, typeSymbol.get().getName()), p.get_SourcePositionStart()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ReferenceSymbolSameAttributeVisitor.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ReferenceSymbolSameAttributeVisitor.java index a17934debb..f8865b75c7 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ReferenceSymbolSameAttributeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ReferenceSymbolSameAttributeVisitor.java @@ -4,7 +4,7 @@ import de.monticore.grammar.grammar._visitor.GrammarVisitor2; import de.se_rwth.commons.logging.Log; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; public class ReferenceSymbolSameAttributeVisitor implements GrammarVisitor2 { @@ -12,7 +12,7 @@ public class ReferenceSymbolSameAttributeVisitor implements GrammarVisitor2 { public static final String ERROR_CODE = "0xA4100"; public static final String ERROR_MSG_FORMAT = " The attributes with the UsageName %s, cannot reference to the different symbols %s and %s."; - protected Map map = new HashMap<>(); + protected Map map = new LinkedHashMap<>(); @Override public void visit(de.monticore.grammar.grammar._ast.ASTNonTerminal node) { diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/RuleComponentsCompatible.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/RuleComponentsCompatible.java index 85cb84b86a..d80909e3a3 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/RuleComponentsCompatible.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/RuleComponentsCompatible.java @@ -10,8 +10,8 @@ /** * checks for each prod if there exist RuleComponents which have the same usageName but do not have compatible types * not compatible if: - * -> one NonTerminal and one Terminal - * -> two different NonTerminal types + * - one NonTerminal and one Terminal + * - two different NonTerminal types */ public class RuleComponentsCompatible implements GrammarASTProdCoCo { diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ScopeProdOverwrittenByScope.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ScopeProdOverwrittenByScope.java index f5c48c5e34..0375918b1d 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ScopeProdOverwrittenByScope.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/ScopeProdOverwrittenByScope.java @@ -39,7 +39,7 @@ public void check(ASTMCGrammar node) { if (superProd.isPresent() && superProd.get().isIsScopeSpanning() && prod.isIsScopeSpanning()) { // log error if both prod define a scope themselves Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, superProd.get().getName(), superGrammar.getName(), - prod.getName(), grammarSymbol.getName())); + prod.getName(), grammarSymbol.getName()), prod.getSourcePosition()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/SymbolProdOverwrittenBySymbol.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/SymbolProdOverwrittenBySymbol.java index c0ea1ca93f..200f771b99 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/SymbolProdOverwrittenBySymbol.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/SymbolProdOverwrittenBySymbol.java @@ -39,7 +39,7 @@ public void check(ASTMCGrammar node) { if (superProd.isPresent() && superProd.get().isIsSymbolDefinition() && prod.isIsSymbolDefinition()) { // log error if both prod define a symbol themselves Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, superProd.get().getName(), superGrammar.getName(), - prod.getName(), grammarSymbol.getName())); + prod.getName(), grammarSymbol.getName()), prod.getSourcePosition()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/UniqueProdNamesForComp.java b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/UniqueProdNamesForComp.java index 32ab305c17..d17afa8610 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/cocos/UniqueProdNamesForComp.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/cocos/UniqueProdNamesForComp.java @@ -8,8 +8,8 @@ import de.monticore.grammar.grammar._symboltable.ProdSymbol; import de.se_rwth.commons.logging.Log; -import java.util.HashMap; -import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -28,21 +28,21 @@ public class UniqueProdNamesForComp implements GrammarASTMCGrammarCoCo { @Override public void check(ASTMCGrammar a) { MCGrammarSymbol grammarSymbol = a.getSymbol(); - Map> symbolsInGrammars = new HashMap<>(); + Map> symbolsInGrammars = new LinkedHashMap<>(); // Collect all productions defined in super grammars for (MCGrammarSymbol superGrammar : grammarSymbol.getAllSuperGrammars()) { for (ProdSymbol ps : superGrammar.getProds()) { - symbolsInGrammars.computeIfAbsent(ps.getName(), s1 -> new HashSet<>()).add(superGrammar); + symbolsInGrammars.computeIfAbsent(ps.getName(), s1 -> new LinkedHashSet<>()).add(superGrammar); } } // and in the grammar itself for (ProdSymbol ps : grammarSymbol.getProds()) { - symbolsInGrammars.computeIfAbsent(ps.getName(), s1 -> new HashSet<>()).add(grammarSymbol); + symbolsInGrammars.computeIfAbsent(ps.getName(), s1 -> new LinkedHashSet<>()).add(grammarSymbol); } for (Map.Entry> e : symbolsInGrammars.entrySet()) { // Remove overriden production false-positives - for (MCGrammarSymbol g : new HashSet<>(e.getValue())) { + for (MCGrammarSymbol g : new LinkedHashSet<>(e.getValue())) { e.getValue().removeAll(g.getAllSuperGrammars()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/MCGrammarSymbol.java b/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/MCGrammarSymbol.java index 66a0b6c0c5..d7482b3c3b 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/MCGrammarSymbol.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/MCGrammarSymbol.java @@ -2,6 +2,7 @@ package de.monticore.grammar.grammar._symboltable; +import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -15,7 +16,6 @@ import java.util.*; import static com.google.common.collect.ImmutableList.copyOf; -import static de.se_rwth.commons.logging.Log.errorIfNull; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toList; @@ -84,7 +84,7 @@ public List getAllSuperGrammars() { } public void addSuperGrammar(MCGrammarSymbolSurrogate superGrammarRef) { - this.superGrammars.add(errorIfNull(superGrammarRef)); + this.superGrammars.add(Preconditions.checkNotNull(superGrammarRef)); } public Collection getProds() { diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/MCGrammarSymbolBuilder.java b/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/MCGrammarSymbolBuilder.java index c183c28c76..cdd8c7c194 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/MCGrammarSymbolBuilder.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/MCGrammarSymbolBuilder.java @@ -1,17 +1,17 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.grammar.grammar._symboltable; +import com.google.common.base.Preconditions; + import java.util.ArrayList; import java.util.List; -import static de.se_rwth.commons.logging.Log.errorIfNull; - public class MCGrammarSymbolBuilder extends MCGrammarSymbolBuilderTOP { protected final List superGrammars = new ArrayList<>(); public void addSuperGrammar(MCGrammarSymbolSurrogate superGrammarRef) { - this.superGrammars.add(errorIfNull(superGrammarRef)); + this.superGrammars.add(Preconditions.checkNotNull(superGrammarRef)); } public MCGrammarSymbol build(){ diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/ProdSymbol.java b/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/ProdSymbol.java index 4e00e710ff..da267bf78e 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/ProdSymbol.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/grammar/_symboltable/ProdSymbol.java @@ -3,11 +3,12 @@ package de.monticore.grammar.grammar._symboltable; +import com.google.common.base.Preconditions; + import java.util.ArrayList; import java.util.List; import static com.google.common.collect.ImmutableList.copyOf; -import static de.se_rwth.commons.logging.Log.errorIfNull; public class ProdSymbol extends ProdSymbolTOP { @@ -41,7 +42,7 @@ public List getProdComponents() { } public void addSuperProd(ProdSymbolSurrogate superProdRef) { - this.superProds.add(errorIfNull(superProdRef)); + this.superProds.add(Preconditions.checkNotNull(superProdRef)); } public List getSuperProds() { @@ -49,7 +50,7 @@ public List getSuperProds() { } public void addSuperInterfaceProd(ProdSymbolSurrogate superInterfaceProdRef) { - this.superInterfaceProds.add(errorIfNull(superInterfaceProdRef)); + this.superInterfaceProds.add(Preconditions.checkNotNull(superInterfaceProdRef)); } public List getSuperInterfaceProds() { @@ -57,7 +58,7 @@ public List getSuperInterfaceProds() { } public void addAstSuperClass(ProdSymbolSurrogate ref) { - astSuperClasses.add(errorIfNull(ref)); + astSuperClasses.add(Preconditions.checkNotNull(ref)); } public List getAstSuperClasses() { @@ -65,7 +66,7 @@ public List getAstSuperClasses() { } public void addAstSuperInterface(ProdSymbolSurrogate ref) { - astSuperInterfaces.add(errorIfNull(ref)); + astSuperInterfaces.add(Preconditions.checkNotNull(ref)); } public List getAstSuperInterfaces() { diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_parser/GrammarTransformer.java b/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_parser/GrammarTransformer.java index 99d3bb7ec3..8b92ee0023 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_parser/GrammarTransformer.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_parser/GrammarTransformer.java @@ -14,7 +14,7 @@ import java.io.IOException; import java.io.StringReader; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; @@ -36,10 +36,10 @@ public static void transform(ASTMCGrammar grammar) { /** * The shortcut NonTerminalSeparator is replaced by the detailed description. - * Example: List(Element || ',')* ==> (List:Element (',' List:Element)+) + * Example: {@code List(Element || ',')* ==> (List:Element (',' List:Element)+)} */ public static void removeNonTerminalSeparators(ASTMCGrammar grammar) { - Map map = new HashMap(); + Map map = new LinkedHashMap(); RuleComponentListFinder componentListTransformer = new RuleComponentListFinder(map); Grammar_WithConceptsTraverser traverser = Grammar_WithConceptsMill.traverser(); @@ -69,9 +69,7 @@ public static void removeNonTerminalSeparators(ASTMCGrammar grammar) { /** * Append suffix "List" to the names of multi-valued att * Append suffix "List" to * the names of multi-valued attributes (NonTerminals and attributesinAst) if - * no usage names were set. Examples: Name ("." Name&)* ==> names:Name ("." - * names:Name&)* (State | Transition)* ==> (states:State | - * transitions:Transition)* + * no usage names were set. Examples: {@code Name ("." Name&)* ==> names:Name ("." names:Name&)* (State | Transition)* ==> (states:State | transitions:Transition)*} */ public static void uncapitalizeMultivaluedAttributes(ASTMCGrammar grammar) { grammar.getASTRuleList().forEach(c -> transformAttributesInAST(c)); diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsPhasedSTC.java b/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsPhasedSTC.java index 57b4b51bb5..e9e8a30a20 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsPhasedSTC.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsPhasedSTC.java @@ -1,6 +1,9 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.grammar.grammar_withconcepts._symboltable; +import de.monticore.grammar.concepts.antlr.antlr._ast.ASTConceptAntlr; +import de.monticore.grammar.concepts.antlr.antlr._visitor.AntlrHandler; +import de.monticore.grammar.concepts.antlr.antlr._visitor.AntlrTraverser; import de.monticore.grammar.grammar._ast.ASTMCGrammar; import de.monticore.grammar.grammar._symboltable.GrammarSTCompleteTypes; import de.monticore.grammar.grammar_withconcepts.Grammar_WithConceptsMill; @@ -29,6 +32,7 @@ public Grammar_WithConceptsPhasedSTC(){ traverser.add4JavaLight(new JavaLightSTCompleteTypes()); traverser.add4MCCommonStatements(new MCCommonStatementsSTCompleteTypes()); traverser.add4MCVarDeclarationStatements(new MCVarDeclarationStatementsSTCompleteTypes()); + traverser.setAntlrHandler(new DoNotTCJavaCode()); priorityList.add(traverser); } @@ -38,4 +42,24 @@ public IGrammar_WithConceptsArtifactScope createFromAST(ASTMCGrammar node){ return as; } + // Explicitly do not check the JavaCode of ConceptAntlr (as we can't TC it without knowing the java classpath) + // required since the 7.7.0 -> 7.8.0 update + // https://git.rwth-aachen.de/monticore/monticore/-/issues/4842 + protected static class DoNotTCJavaCode implements AntlrHandler { + protected AntlrTraverser realThis; + @Override + public AntlrTraverser getTraverser() { + return realThis; + } + + @Override + public void setTraverser(AntlrTraverser traverser) { + this.realThis = traverser; + } + + @Override + public void traverse(ASTConceptAntlr node) { + // do nothing! + } + } } diff --git a/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsScopesGenitor.java b/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsScopesGenitor.java index 6aa85ad7f2..6e2f40ccca 100644 --- a/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsScopesGenitor.java +++ b/monticore-grammar/src/main/java/de/monticore/grammar/grammar_withconcepts/_symboltable/Grammar_WithConceptsScopesGenitor.java @@ -1,6 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.grammar.grammar_withconcepts._symboltable; +import com.google.common.base.Preconditions; import de.monticore.symboltable.ImportStatement; import de.se_rwth.commons.Names; import de.se_rwth.commons.logging.Log; @@ -24,7 +25,7 @@ public Grammar_WithConceptsScopesGenitor() { * @return the first scope that was created */ public Grammar_WithConceptsArtifactScope createFromAST(de.monticore.grammar.grammar._ast.ASTMCGrammar rootNode) { - Log.errorIfNull(rootNode, "0xA7FE4 Error by creating of the Grammar_WithConceptsScopesGenitor symbol table: top ast node is null"); + Preconditions.checkNotNull(rootNode, "0xA7FE4 Error by creating of the Grammar_WithConceptsScopesGenitor symbol table: top ast node is null"); List imports = new ArrayList<>(); rootNode.getImportStatementList().stream().forEach(i -> imports.add(new ImportStatement(i.getQName(), i.isStar()))); Grammar_WithConceptsArtifactScope artifactScope = new Grammar_WithConceptsArtifactScope(Optional.empty(), Names.getQualifiedName(rootNode.getPackageList()), imports); diff --git a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/ConstructorNoAccessModifierPair.java b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/ConstructorNoAccessModifierPair.java index 1edfc44e9f..7a13ce852b 100644 --- a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/ConstructorNoAccessModifierPair.java +++ b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/ConstructorNoAccessModifierPair.java @@ -11,7 +11,7 @@ import de.se_rwth.commons.logging.Log; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; diff --git a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/ConstructorNoDuplicateModifier.java b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/ConstructorNoDuplicateModifier.java index de510c483b..3e69862c33 100644 --- a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/ConstructorNoDuplicateModifier.java +++ b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/ConstructorNoDuplicateModifier.java @@ -9,7 +9,7 @@ import de.se_rwth.commons.logging.Log; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -26,8 +26,8 @@ protected String prettyprint(ASTMCModifier a) { } public Set findDuplicates(List listContainingDuplicates) { - final Set setToReturn = new HashSet<>(); - final Set set1 = new HashSet<>(); + final Set setToReturn = new LinkedHashSet<>(); + final Set set1 = new LinkedHashSet<>(); for (String yourString : listContainingDuplicates) { if (!set1.add(yourString)) { diff --git a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodExceptionThrows.java b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodExceptionThrows.java index 3a456d81e3..39c1d95720 100644 --- a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodExceptionThrows.java +++ b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodExceptionThrows.java @@ -18,7 +18,7 @@ public class MethodExceptionThrows implements JavaLightASTMethodDeclarationCoCo @Override public void check(ASTMethodDeclaration node) { if (node.isPresentThrows()) { - SymTypeExpression throwable = SymTypeExpressionFactory.createTypeObject("java.lang.Throwable", node.getEnclosingScope()); + SymTypeExpression throwable = SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.lang.Throwable", node.getEnclosingScope()); for (SymTypeExpression exception : node.getSymbol().getExceptionsList()) { if (!TypeCheck.isSubtypeOf(exception, throwable)) { Log.error(String.format(ERROR_CODE + ERROR_MSG_FORMAT, exception.print()), diff --git a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodFormalParametersDifferentName.java b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodFormalParametersDifferentName.java index 5ffb8679b2..8385f4aa88 100644 --- a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodFormalParametersDifferentName.java +++ b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodFormalParametersDifferentName.java @@ -9,7 +9,7 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; public class MethodFormalParametersDifferentName implements JavaLightASTMethodDeclarationCoCo { @@ -21,7 +21,7 @@ public class MethodFormalParametersDifferentName implements JavaLightASTMethodDe //JLS3 8.4.1-1 @Override public void check(ASTMethodDeclaration node) { - Collection names = new HashSet<>(); + Collection names = new LinkedHashSet<>(); if (node.getFormalParameters().isPresentFormalParameterListing()) { if(node.getFormalParameters().getFormalParameterListing().isPresentLastFormalParameter()){ names.add(node.getFormalParameters().getFormalParameterListing().getLastFormalParameter() diff --git a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodNoDuplicateModifier.java b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodNoDuplicateModifier.java index 77894a6a7b..54e7a48d56 100644 --- a/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodNoDuplicateModifier.java +++ b/monticore-grammar/src/main/java/de/monticore/javalight/cocos/MethodNoDuplicateModifier.java @@ -9,7 +9,7 @@ import de.se_rwth.commons.logging.Log; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -26,8 +26,8 @@ protected String prettyprint(ASTMCModifier a) { } public Set findDuplicates(List listContainingDuplicates) { - final Set setToReturn = new HashSet<>(); - final Set set1 = new HashSet<>(); + final Set setToReturn = new LinkedHashSet<>(); + final Set set1 = new LinkedHashSet<>(); for (String modifierName : listContainingDuplicates) { if (!set1.add(modifierName)) { diff --git a/monticore-grammar/src/main/java/de/monticore/literals/MCLiteralsDecoder.java b/monticore-grammar/src/main/java/de/monticore/literals/MCLiteralsDecoder.java index f400cf5891..c7ab3291c8 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/MCLiteralsDecoder.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/MCLiteralsDecoder.java @@ -3,6 +3,7 @@ package de.monticore.literals; import de.se_rwth.commons.logging.Log; +import org.apache.commons.lang3.StringEscapeUtils; /** * This class provides methods for converting literals. The LiteralsHelper is a singleton. @@ -57,26 +58,7 @@ else if (s.charAt(0) == '\\' && s.charAt(1) == 'u') { // unicode * @return decoded string */ public static String decodeString(String s) { - StringBuilder ret = new StringBuilder(); - String in = s; - - while (in.length() != 0) { - if (in.charAt(0) == '\\') { - if (in.charAt(1) == 'u') { // unicode - ret.append(decodeChar(in.substring(0, 6))); - in = in.substring(6); - } - else { // escape sequence - ret.append(decodeChar(in.substring(0, 2))); - in = in.substring(2); - } - } - else { // single char - ret.append(in.charAt(0)); - in = in.substring(1); - } - } - return ret.toString(); + return StringEscapeUtils.unescapeJava(s); } /** diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicDoubleLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicDoubleLiteralRangeCoCo.java index 8e5b1bc9e6..b3cca2c2d9 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicDoubleLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicDoubleLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public BasicDoubleLiteralRangeCoCo(BigDecimal min, BigDecimal max){ public void check(ASTBasicDoubleLiteral node) { BigDecimal nodeValue = new BigDecimal(node.getSource()); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicFloatLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicFloatLiteralRangeCoCo.java index 16dcc5a59a..208509b3e9 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicFloatLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicFloatLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public BasicFloatLiteralRangeCoCo(BigDecimal min, BigDecimal max){ public void check(ASTBasicFloatLiteral node) { BigDecimal nodeValue = new BigDecimal(node.getSource().substring(0, node.getSource().length()-1)); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicLongLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicLongLiteralRangeCoCo.java index 90ce3113a0..5a550ea44b 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicLongLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/BasicLongLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public BasicLongLiteralRangeCoCo(BigInteger min, BigInteger max){ public void check(ASTBasicLongLiteral node) { BigInteger nodeValue = new BigInteger(node.getSource().substring(0, node.getSource().length()-1)); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/NatLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/NatLiteralRangeCoCo.java index b62d7139ad..88e501db09 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/NatLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/NatLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public NatLiteralRangeCoCo(BigInteger min, BigInteger max){ public void check(ASTNatLiteral node) { BigInteger nodeValue = new BigInteger(node.getSource()); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/NoLineBreaksInStringLiteralCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/NoLineBreaksInStringLiteralCoCo.java index 63176f72bf..8081b08df3 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/NoLineBreaksInStringLiteralCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/NoLineBreaksInStringLiteralCoCo.java @@ -13,7 +13,9 @@ public class NoLineBreaksInStringLiteralCoCo implements MCCommonLiteralsASTStrin @Override public void check(ASTStringLiteral node) { if (node.getValue().contains("\n") || node.getValue().contains("\r")) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, node.getValue())); + Log.error(String.format(ERROR_CODE + ERROR_MSG, node.getValue()), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicDoubleLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicDoubleLiteralRangeCoCo.java index 5509a0eef4..6ceef84946 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicDoubleLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicDoubleLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public SignedBasicDoubleLiteralRangeCoCo(BigDecimal min, BigDecimal max){ public void check(ASTSignedBasicDoubleLiteral node) { BigDecimal nodeValue = new BigDecimal(node.getSource()); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicFloatLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicFloatLiteralRangeCoCo.java index 36d978ec4a..a56ab42d78 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicFloatLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicFloatLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public SignedBasicFloatLiteralRangeCoCo(BigDecimal min, BigDecimal max){ public void check(ASTSignedBasicFloatLiteral node) { BigDecimal nodeValue = new BigDecimal(node.getSource().substring(0, node.getSource().length()-1)); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicLongLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicLongLiteralRangeCoCo.java index 4f67c246a9..08e7766f38 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicLongLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedBasicLongLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public SignedBasicLongLiteralRangeCoCo(BigInteger min, BigInteger max){ public void check(ASTSignedBasicLongLiteral node) { BigInteger nodeValue = new BigInteger(node.getSource().substring(0, node.getSource().length()-1)); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedNatLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedNatLiteralRangeCoCo.java index 9fd5693f9a..80a21f15c9 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedNatLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mccommonliterals/cocos/SignedNatLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public SignedNatLiteralRangeCoCo(BigInteger min, BigInteger max){ public void check(ASTSignedNatLiteral node) { BigInteger nodeValue = new BigInteger(node.getSource()); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/_visitor/MCJavaLiteralsInterpreter.java b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/_visitor/MCJavaLiteralsInterpreter.java new file mode 100644 index 0000000000..527ccaa649 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/_visitor/MCJavaLiteralsInterpreter.java @@ -0,0 +1,38 @@ +package de.monticore.literals.mcjavaliterals._visitor; + +import de.monticore.interpreter.ModelInterpreter; +import de.monticore.interpreter.MIValue; +import de.monticore.literals.mcjavaliterals._ast.*; + +import static de.monticore.interpreter.MIValueFactory.createValue; + +public class MCJavaLiteralsInterpreter extends MCJavaLiteralsInterpreterTOP { + + public MCJavaLiteralsInterpreter() { + super(); + } + + public MCJavaLiteralsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + @Override + public MIValue interpret(ASTIntLiteral node) { + return createValue(node.getValue()); + } + + @Override + public MIValue interpret(ASTLongLiteral node) { + return createValue(node.getValue()); + } + + @Override + public MIValue interpret(ASTFloatLiteral node) { + return createValue(node.getValue()); + } + + @Override + public MIValue interpret(ASTDoubleLiteral node) { + return createValue(node.getValue()); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/DoubleLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/DoubleLiteralRangeCoCo.java index a9d698bc0e..5db84a9930 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/DoubleLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/DoubleLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public DoubleLiteralRangeCoCo(BigDecimal min, BigDecimal max){ public void check(ASTDoubleLiteral node) { BigDecimal nodeValue = new BigDecimal(node.getSource()); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/FloatLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/FloatLiteralRangeCoCo.java index dce6846477..61383aca81 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/FloatLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/FloatLiteralRangeCoCo.java @@ -30,7 +30,9 @@ public FloatLiteralRangeCoCo(BigDecimal min, BigDecimal max){ public void check(ASTFloatLiteral node) { BigDecimal nodeValue = new BigDecimal(node.getSource().substring(0, node.getSource().length()-1)); if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/IntLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/IntLiteralRangeCoCo.java index 747d480147..095f79a43a 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/IntLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/IntLiteralRangeCoCo.java @@ -43,7 +43,9 @@ public void check(ASTIntLiteral node) { nodeValue = new BigInteger(node.getSource()); } if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/LongLiteralRangeCoCo.java b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/LongLiteralRangeCoCo.java index e02c724b26..b95c92f6bc 100644 --- a/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/LongLiteralRangeCoCo.java +++ b/monticore-grammar/src/main/java/de/monticore/literals/mcjavaliterals/cocos/LongLiteralRangeCoCo.java @@ -44,7 +44,9 @@ public void check(ASTLongLiteral node) { nodeValue = new BigInteger(source); } if(nodeValue.compareTo(this.min) < 0 || nodeValue.compareTo(this.max) > 0) { - Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max)); + Log.error(String.format(ERROR_CODE + ERROR_MSG, nodeValue, min, max), + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/cocos/SetComprehensionHasGenerator.java b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/cocos/SetComprehensionHasGenerator.java index 068fe36295..15f42eb50c 100644 --- a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/cocos/SetComprehensionHasGenerator.java +++ b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/cocos/SetComprehensionHasGenerator.java @@ -18,7 +18,9 @@ public void check(ASTSetComprehension node) { } } Log.error( - "0xOCL24 SetComprehension requires at least one generator or a variable Declaration"); + "0xOCL24 SetComprehension requires at least one generator or a variable Declaration", + node.get_SourcePositionStart(), + node.get_SourcePositionEnd()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/symboltable/SetExpressionsSymbolTableCompleter.java b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/symboltable/SetExpressionsSymbolTableCompleter.java index 53b3ebe2d9..d95eb8b356 100644 --- a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/symboltable/SetExpressionsSymbolTableCompleter.java +++ b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/symboltable/SetExpressionsSymbolTableCompleter.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.ocl.setexpressions.symboltable; +import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.ocl.setexpressions._ast.ASTGeneratorDeclaration; import de.monticore.ocl.setexpressions._ast.ASTSetVariableDeclaration; import de.monticore.ocl.setexpressions._symboltable.ISetExpressionsScope; @@ -14,18 +15,28 @@ import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.check.TypeCheckResult; +import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mccollectiontypes.types3.MCCollectionSymTypeRelations; +import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; +import static de.monticore.types.check.SymTypeExpressionFactory.createObscureType; + public class SetExpressionsSymbolTableCompleter implements SetExpressionsVisitor2, BasicSymbolsVisitor2, SetExpressionsHandler { + protected static final String LOG_NAME = + SetExpressionsSymbolTableCompleter.class.getName(); + + @Deprecated IDerive deriver; + @Deprecated ISynthesize synthesizer; protected SetExpressionsTraverser traverser; + @Deprecated public void setDeriver(IDerive deriver) { if (deriver != null) { this.deriver = deriver; @@ -35,6 +46,7 @@ public void setDeriver(IDerive deriver) { } } + @Deprecated public void setSynthesizer(ISynthesize synthesizer) { if (synthesizer != null) { this.synthesizer = synthesizer; @@ -77,8 +89,9 @@ protected void initialize_SetVariableDeclaration( if (ast.isPresentMCType()) { ast.getMCType().setEnclosingScope(symbol.getEnclosingScope()); ast.getMCType().accept(getTraverser()); - final TypeCheckResult typeResult = synthesizer.synthesizeType(ast.getMCType()); - if (!typeResult.isPresentResult()) { + SymTypeExpression mcType = synth(ast.getMCType()); + if (mcType.isObscureType()) { + // TC already logged error, though Log.error("0xA3027 The type " + ast.getMCType().printType() + " of the object " + ast.getName() + " could not be calculated", @@ -86,28 +99,31 @@ protected void initialize_SetVariableDeclaration( ast.get_SourcePositionEnd() ); } - else { - symbol.setType(typeResult.getResult()); - } + symbol.setType(mcType); } else { if (ast.isPresentExpression()) { ast.getExpression().accept(getTraverser()); - final TypeCheckResult tcr_expr = deriver.deriveType(ast.getExpression()); - if (tcr_expr.isPresentResult()) { - symbol.setType(tcr_expr.getResult()); - } - else { + SymTypeExpression tcr_expr = derive(ast.getExpression()); + if (tcr_expr.isObscureType()) { + // TC already logged error, though Log.error("0xA3026 The type of the object " + ast.getName() + " could not be calculated", ast.get_SourcePositionStart(), ast.get_SourcePositionEnd() ); } + symbol.setType(tcr_expr); } else { + Log.debug("No type given for VariableDeclaration " + + ast.getName() + ", thus selecting Object", + ast.get_SourcePositionStart(), + ast.get_SourcePositionEnd(), + LOG_NAME + ); symbol.setType( - SymTypeExpressionFactory.createTypeObject("Object", ast.getEnclosingScope())); + SymTypeExpressionFactory.createTypeObjectViaSurrogate("Object", ast.getEnclosingScope())); } } } @@ -122,8 +138,9 @@ protected void initialize_GeneratorDeclaration(VariableSymbol symbol, ASTGenerat if (ast.isPresentMCType()) { ast.getMCType().setEnclosingScope(symbol.getEnclosingScope()); ast.getMCType().accept(getTraverser()); - final TypeCheckResult typeResult = synthesizer.synthesizeType(ast.getMCType()); - if (!typeResult.isPresentResult()) { + SymTypeExpression mcType = synth(ast.getMCType()); + if (mcType.isObscureType()) { + // TC already logged error, though Log.error("0xA3023 The type " + ast.getMCType().printType() + " of the object " + ast.getName() + " could not be calculated", @@ -131,20 +148,20 @@ protected void initialize_GeneratorDeclaration(VariableSymbol symbol, ASTGenerat ast.get_SourcePositionEnd() ); } - else { - symbol.setType(typeResult.getResult()); - } + symbol.setType(mcType); } else { - final TypeCheckResult typeResult = deriver.deriveType(ast.getExpression()); - if (!typeResult.isPresentResult() || typeResult.getResult().isObscureType()) { + SymTypeExpression exprType = derive(ast.getExpression()); + if (exprType.isObscureType()) { Log.error("0xA3024 The type of the object " + ast.getName() + " could not be calculated", ast.get_SourcePositionStart(), ast.get_SourcePositionEnd() ); } - else if (typeResult.getResult().isPrimitive()) { + // warn: heuristic, not actually checking for a collection type, + // as this concept does not exist in the general case + else if (!exprType.isGenericType()) { Log.error("0xA3025 Expression of object " + ast.getName() + " has to be a collection", ast.get_SourcePositionStart(), @@ -153,9 +170,43 @@ else if (typeResult.getResult().isPrimitive()) { } else { SymTypeExpression result = MCCollectionSymTypeRelations - .getCollectionElementType(typeResult.getResult()); + .getCollectionElementType(exprType); symbol.setType(result); } } } + + // allow deprecated code, will be removed with TC1 + + private SymTypeExpression synth(ASTMCType mcType) { + // allow deprecated code + if (synthesizer != null) { + TypeCheckResult tcr = synthesizer.synthesizeType(mcType); + if (!tcr.isPresentResult()) { + return createObscureType(); + } + else { + return tcr.getResult(); + } + } + else { + return TypeCheck3.symTypeFromAST(mcType); + } + } + + private SymTypeExpression derive(ASTExpression expr) { + // allow deprecated code + if (deriver != null) { + TypeCheckResult tcr = deriver.deriveType(expr); + if (!tcr.isPresentResult()) { + return createObscureType(); + } + else { + return tcr.getResult(); + } + } + else { + return TypeCheck3.typeOf(expr); + } + } } diff --git a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/types3/SetExpressionsTypeVisitor.java b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/types3/SetExpressionsTypeVisitor.java index c3457c8ac4..9e06acc149 100644 --- a/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/types3/SetExpressionsTypeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/ocl/setexpressions/types3/SetExpressionsTypeVisitor.java @@ -498,21 +498,7 @@ else if (getType4Ast().hasTypeOfExpression(expr)) { @Override public void endVisit(ASTSetValueRange expr) { - SymTypeExpression leftResult = getType4Ast().getPartialTypeOfExpr(expr.getLowerBound()); - SymTypeExpression rightResult = getType4Ast().getPartialTypeOfExpr(expr.getUpperBound()); - if (!leftResult.isObscureType() && !rightResult.isObscureType()) { - if (!isIntegralType(normalize(leftResult)) - || !isIntegralType(normalize(rightResult))) { - Log.error( - "0xFD217 bounds in SetValueRange " - + "are not integral types, but have to be, got " - + leftResult.printFullName() - + " and " - + rightResult.printFullName(), - expr.get_SourcePositionStart(), - expr.get_SourcePositionEnd()); - } - } + assertRangeContainsIntegrals(expr); } // hook points @@ -530,7 +516,7 @@ protected boolean isSetOrListCollection(SymTypeExpression type) { /** * Get all expressions within the set enumeration. - * E.g.: "{1, 2..4}" -> "1","2","4" + * E.g.: {@code "{1, 2..4}" -> "1","2","4"} * Returns empty on error (will have been logged) */ protected Optional> getContainedExpressions(ASTSetEnumeration expr) { @@ -562,7 +548,7 @@ else if (SetExpressionsMill.typeDispatcher().isSetExpressionsASTSetValueRange(cI /** * Get all expressions' types within the set enumeration. * They need to be stored in Type4Ast before calling this. - * E.g.: "{1, 2..4}" -> int, int, int + * E.g.: {@code "{1, 2..4}" -> int, int, int} * May contain Obscure (error will have been logged). */ protected List getContainedExpressionTypes(ASTSetEnumeration expr) { diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/AssertIsValid.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/AssertIsValid.java index 1827b1df34..e25a22c36b 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/AssertIsValid.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/AssertIsValid.java @@ -5,62 +5,37 @@ import de.monticore.statements.mcassertstatements._ast.ASTAssertStatement; import de.monticore.statements.mcassertstatements._cocos.MCAssertStatementsASTAssertStatementCoCo; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class AssertIsValid implements MCAssertStatementsASTAssertStatementCoCo { - + public static final String ERROR_CODE = "0xA0901"; - + public static final String ERROR_MSG_FORMAT = "Assert-statement must be of boolean type."; - - public static final String ERROR_CODE_2 = "0xA0902"; - - public static final String ERROR_MSG_FORMAT_2 = "Assert-statement must not be of void type."; - TypeCalculator typeCheck; + public static final String ERROR_CODE_2 = "0xA0902"; - /** - * @deprecated use default constructor - */ - @Deprecated - public AssertIsValid(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } + public static final String ERROR_MSG_FORMAT_2 = "Assert-statement must not be of void type."; @Override public void check(ASTAssertStatement node) { Preconditions.checkNotNull(node); - SymTypeExpression assertion; + SymTypeExpression assertion = TypeCheck3.typeOf(node.getAssertion()); - if (typeCheck != null) { - // support deprecated behavior - assertion = typeCheck.typeOf(node.getAssertion()); - } else { - assertion = TypeCheck3.typeOf(node.getAssertion()); - } - - if(!SymTypeRelations.isBoolean(assertion)){ - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.getAssertion().get_SourcePositionStart()); + if (!assertion.isObscureType() && !SymTypeRelations.isBoolean(assertion)) { + Log.error(ERROR_CODE + " " + ERROR_MSG_FORMAT, node.getAssertion().get_SourcePositionStart()); } - if(node.isPresentMessage()) { + if (node.isPresentMessage()) { - SymTypeExpression message; - - if (typeCheck != null) { - // support deprecated behavior - message = typeCheck.typeOf(node.getMessage()); - } else { - message = TypeCheck3.typeOf(node.getMessage()); - } + SymTypeExpression message = TypeCheck3.typeOf(node.getMessage()); - if (message.isVoidType()) { - Log.error(ERROR_CODE_2 + ERROR_MSG_FORMAT_2, node.getMessage().get_SourcePositionStart()); + if (!message.isObscureType() && message.isVoidType()) { + Log.error(ERROR_CODE_2 + " " + ERROR_MSG_FORMAT_2, node.getMessage().get_SourcePositionStart()); } } } -} \ No newline at end of file +} diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/CatchIsValid.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/CatchIsValid.java index cafcfec350..9a5b2ebdf2 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/CatchIsValid.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/CatchIsValid.java @@ -6,38 +6,29 @@ import de.monticore.statements.mcexceptionstatements._cocos.MCExceptionStatementsASTCatchClauseCoCo; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.se_rwth.commons.logging.Log; public class CatchIsValid implements MCExceptionStatementsASTCatchClauseCoCo { - - public static final String ERROR_CODE = "0xA0903"; - - public static final String ERROR_MSG_FORMAT = "Parameter in catch-statement has to be throwable or subtype of it."; - /** - * @deprecated use default constructor - */ - @Deprecated - public CatchIsValid(TypeCalculator typeCheck) { } + public static final String ERROR_CODE = "0xA0903"; - public CatchIsValid() { } + public static final String ERROR_MSG_FORMAT = "Parameter in catch-statement has to be throwable or subtype of it."; @Override public void check(ASTCatchClause node) { Preconditions.checkNotNull(node); - - SymTypeExpression throwable = SymTypeExpressionFactory.createTypeObject("java.lang.Throwable", node.getEnclosingScope()); - + + SymTypeExpression throwable = SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.lang.Throwable", node.getEnclosingScope()); + for (int i = 0; i < node.getCatchTypeList().sizeMCQualifiedNames(); i++) { String name = node.getCatchTypeList().getMCQualifiedName(i).getQName(); - - SymTypeExpression result = SymTypeExpressionFactory.createTypeObject(name, node.getEnclosingScope()); - + + SymTypeExpression result = SymTypeExpressionFactory.createTypeObjectViaSurrogate(name, node.getEnclosingScope()); + if (!SymTypeRelations.isSubTypeOf(result, throwable)) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); + Log.error(ERROR_CODE + " " + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } } } -} \ No newline at end of file +} diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/DoWhileConditionHasBooleanType.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/DoWhileConditionHasBooleanType.java index 84374dfedd..dfe5668302 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/DoWhileConditionHasBooleanType.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/DoWhileConditionHasBooleanType.java @@ -5,46 +5,24 @@ import de.monticore.statements.mccommonstatements._ast.ASTDoWhileStatement; import de.monticore.statements.mccommonstatements._cocos.MCCommonStatementsASTDoWhileStatementCoCo; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class DoWhileConditionHasBooleanType implements MCCommonStatementsASTDoWhileStatementCoCo { - @Deprecated - TypeCalculator typeCheck; - public static final String ERROR_CODE = "0xA0905"; public static final String ERROR_MSG_FORMAT = "Condition in do-statement must be a boolean expression."; - /** - * @deprecated use default constructor - */ - @Deprecated - public DoWhileConditionHasBooleanType(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } - - public DoWhileConditionHasBooleanType() { } - @Override public void check(ASTDoWhileStatement node) { Preconditions.checkNotNull(node); - SymTypeExpression result; + SymTypeExpression result = TypeCheck3.typeOf(node.getCondition()); - if (typeCheck != null) { - // support deprecated behavior - result = typeCheck.typeOf(node.getCondition()); - } else { - result = TypeCheck3.typeOf(node.getCondition()); + if (!result.isObscureType() && !SymTypeRelations.isBoolean(result)) { + Log.error(ERROR_CODE + " " + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } - - if (!SymTypeRelations.isBoolean(result)) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); - } - } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ExpressionStatementIsValid.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ExpressionStatementIsValid.java index 38a71d8c47..868f6cabdf 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ExpressionStatementIsValid.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ExpressionStatementIsValid.java @@ -4,40 +4,14 @@ import com.google.common.base.Preconditions; import de.monticore.statements.mccommonstatements._ast.ASTExpressionStatement; import de.monticore.statements.mccommonstatements._cocos.MCCommonStatementsASTExpressionStatementCoCo; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.TypeCheck3; public class ExpressionStatementIsValid implements MCCommonStatementsASTExpressionStatementCoCo { - @Deprecated - protected TypeCalculator typeCheck; - - /** - * @deprecated use default constructor - */ - @Deprecated - public ExpressionStatementIsValid(TypeCalculator typeCheck) { - Preconditions.checkNotNull(typeCheck); - - this.typeCheck = typeCheck; - } - - public ExpressionStatementIsValid() { } - - @Deprecated - protected TypeCalculator getTypeCheck() { - return this.typeCheck; - } - @Override public void check(ASTExpressionStatement node) { Preconditions.checkNotNull(node); - if (typeCheck != null) { - // support deprecated behavior - this.getTypeCheck().typeOf(node.getExpression()); - } else { - TypeCheck3.typeOf(node.getExpression()); - } + TypeCheck3.typeOf(node.getExpression()); } } diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ForConditionHasBooleanType.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ForConditionHasBooleanType.java index 95768e3c51..a66a70c1c3 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ForConditionHasBooleanType.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ForConditionHasBooleanType.java @@ -6,49 +6,24 @@ import de.monticore.statements.mccommonstatements._ast.ASTForStatement; import de.monticore.statements.mccommonstatements._cocos.MCCommonStatementsASTForStatementCoCo; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class ForConditionHasBooleanType implements MCCommonStatementsASTForStatementCoCo { - @Deprecated - TypeCalculator typeCheck; - public static final String ERROR_CODE = "0xA0906"; public static final String ERROR_MSG_FORMAT = "Condition of for-loop must be a boolean expression."; - /** - * @deprecated use default constructor - */ - @Deprecated - public ForConditionHasBooleanType(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } - - public ForConditionHasBooleanType() { } - @Override public void check(ASTForStatement node) { Preconditions.checkNotNull(node); - // todo replace with typedispatcher as soon as issues are fixed - if (!(node.getForControl() instanceof ASTCommonForControl)) { - return; - } - SymTypeExpression result; - - if (typeCheck != null) { - // support deprecated behavior - result = typeCheck.typeOf(((ASTCommonForControl) node.getForControl()).getCondition()); - } else { - result = TypeCheck3.typeOf(((ASTCommonForControl) node.getForControl()).getCondition()); - } + SymTypeExpression result = TypeCheck3.typeOf(((ASTCommonForControl) node.getForControl()).getCondition()); - if (!SymTypeRelations.isBoolean(result)) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); + if (!result.isObscureType() && !SymTypeRelations.isBoolean(result)) { + Log.error(ERROR_CODE + " " + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ForEachIsValid.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ForEachIsValid.java index 15950fe625..c4e1244612 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ForEachIsValid.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ForEachIsValid.java @@ -16,7 +16,7 @@ public class ForEachIsValid implements MCCommonStatementsASTEnhancedForControlCo @Deprecated TypeCalculator typeCheck; - public static final String ERROR_CODE = "0xA0907 "; + public static final String ERROR_CODE = "0xA0907"; public static final String ERROR_MSG_FORMAT = "For-each loop expression must be an array of subtype of list."; @@ -28,28 +28,22 @@ public ForEachIsValid(TypeCalculator typeCheck) { this.typeCheck = typeCheck; } - public ForEachIsValid() { } + public ForEachIsValid() { + } @Override public void check(ASTEnhancedForControl node) { Preconditions.checkNotNull(node); - SymTypeExpression expression; - - if (typeCheck != null) { - // support deprecated behavior - expression = typeCheck.typeOf(node.getExpression()); - } else { - expression = TypeCheck3.typeOf(node.getExpression()); - } + SymTypeExpression expression = TypeCheck3.typeOf(node.getExpression()); - SymTypeExpression arrays = SymTypeExpressionFactory.createTypeObject("java.util.Arrays", node.getEnclosingScope()); - SymTypeExpression lists = SymTypeExpressionFactory.createTypeObject("java.lang.Iterable", node.getEnclosingScope()); + SymTypeExpression arrays = SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.util.Arrays", node.getEnclosingScope()); + SymTypeExpression lists = SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.lang.Iterable", node.getEnclosingScope()); - if (!SymTypeRelations.isSubTypeOf(expression, arrays)) { - if (!SymTypeRelations.isSubTypeOf(expression, lists)) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); - } + if (!expression.isObscureType() + && !SymTypeRelations.isSubTypeOf(expression, arrays) + && !SymTypeRelations.isSubTypeOf(expression, lists)) { + Log.error(ERROR_CODE + " " + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/IfConditionHasBooleanType.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/IfConditionHasBooleanType.java index 44165eec9c..c134b240da 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/IfConditionHasBooleanType.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/IfConditionHasBooleanType.java @@ -5,46 +5,25 @@ import de.monticore.statements.mccommonstatements._ast.ASTIfStatement; import de.monticore.statements.mccommonstatements._cocos.MCCommonStatementsASTIfStatementCoCo; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class IfConditionHasBooleanType implements MCCommonStatementsASTIfStatementCoCo { - @Deprecated - TypeCalculator typeCheck; - public static final String ERROR_CODE = "0xA0909"; - public static final String ERROR_MSG_FORMAT = " Condition in if-statement must be a boolean expression."; - - /** - * @deprecated use default constructor - */ - @Deprecated - public IfConditionHasBooleanType(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } - - public IfConditionHasBooleanType() { } + public static final String ERROR_MSG_FORMAT = "Condition in if-statement must be a boolean expression."; //JLS3 14.9-1 @Override public void check(ASTIfStatement node) { Preconditions.checkNotNull(node); - SymTypeExpression result; - - if (typeCheck != null) { - // support deprecated behavior - result = typeCheck.typeOf(node.getCondition()); - } else { - result = TypeCheck3.typeOf(node.getCondition()); - } + SymTypeExpression result = TypeCheck3.typeOf(node.getCondition()); - if (!SymTypeRelations.isBoolean(result)) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); + if (!result.isObscureType() && !SymTypeRelations.isBoolean(result)) { + Log.error(ERROR_CODE + " " + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ResourceInTryStatementCloseable.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ResourceInTryStatementCloseable.java index 6eef2379b5..f5e640c12e 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ResourceInTryStatementCloseable.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ResourceInTryStatementCloseable.java @@ -7,49 +7,29 @@ import de.monticore.statements.mcexceptionstatements._cocos.MCExceptionStatementsASTTryStatement3CoCo; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class ResourceInTryStatementCloseable implements MCExceptionStatementsASTTryStatement3CoCo { - @Deprecated - TypeCalculator typeCheck; - public static final String ERROR_CODE = "0xA0920"; - public static final String ERROR_MSG_FORMAT = " Resource in try-statement must be closeable or subtype of it."; - - /** - * @deprecated use default constructor - */ - @Deprecated - public ResourceInTryStatementCloseable(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } + public static final String ERROR_MSG_FORMAT = "Resource in try-statement must be closeable or subtype of it."; - public ResourceInTryStatementCloseable() { } @Override public void check(ASTTryStatement3 node) { Preconditions.checkNotNull(node); - SymTypeExpression closeable = SymTypeExpressionFactory.createTypeObject("java.io.Closeable", node.getEnclosingScope()); + SymTypeExpression closeable = SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.io.Closeable", node.getEnclosingScope()); for (ASTTryLocalVariableDeclaration dec : node.getTryLocalVariableDeclarationList()) { - SymTypeExpression expression; - - if (typeCheck != null) { - // support deprecated behavior - expression = typeCheck.typeOf(dec.getExpression()); - } else { - expression = TypeCheck3.typeOf(dec.getExpression()); - } + SymTypeExpression expression = TypeCheck3.typeOf(dec.getExpression()); - if (!SymTypeRelations.isSubTypeOf(expression, closeable)) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); + if (!expression.isObscureType() && !SymTypeRelations.isSubTypeOf(expression, closeable)) { + Log.error(ERROR_CODE + " " + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/SwitchStatementValid.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/SwitchStatementValid.java index b513563088..1cc1217df0 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/SwitchStatementValid.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/SwitchStatementValid.java @@ -6,16 +6,12 @@ import de.monticore.statements.mccommonstatements._cocos.MCCommonStatementsASTSwitchStatementCoCo; import de.monticore.symbols.oosymbols.OOSymbolsMill; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class SwitchStatementValid implements MCCommonStatementsASTSwitchStatementCoCo { - @Deprecated - TypeCalculator typeCheck; - public static final String ERROR_CODE = "0xA0917"; public static final String ERROR_MSG_FORMAT = @@ -23,38 +19,19 @@ public class SwitchStatementValid implements MCCommonStatementsASTSwitchStatemen "char, byte, short, int, Character, Byte, Short, " + "Integer, or an enum type."; - /** - * @deprecated use default constructor - */ - @Deprecated - public SwitchStatementValid(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } - - public SwitchStatementValid() { - this(null); - } - //JLS3 14.11 @Override public void check(ASTSwitchStatement node) { Preconditions.checkNotNull(node); - SymTypeExpression result; - - if (typeCheck != null) { - // support deprecated behavior - result = typeCheck.typeOf(node.getExpression()); - } else { - result = TypeCheck3.typeOf(node.getExpression()); - } + SymTypeExpression result = TypeCheck3.typeOf(node.getExpression()); - if (!(SymTypeRelations.isChar(result) || SymTypeRelations.isByte(result) + if (!result.isObscureType() + && !(SymTypeRelations.isChar(result) || SymTypeRelations.isByte(result) || SymTypeRelations.isShort(result) || SymTypeRelations.isInt(result) || isEnumMember(result))) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); + Log.error(ERROR_CODE + " " +ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } - } public boolean isEnumMember(SymTypeExpression ste) { diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/SynchronizedArgIsReftype.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/SynchronizedArgIsReftype.java index 54d5f7ffb0..aa2f8c4368 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/SynchronizedArgIsReftype.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/SynchronizedArgIsReftype.java @@ -5,44 +5,23 @@ import de.monticore.statements.mcsynchronizedstatements._ast.ASTSynchronizedStatement; import de.monticore.statements.mcsynchronizedstatements._cocos.MCSynchronizedStatementsASTSynchronizedStatementCoCo; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class SynchronizedArgIsReftype implements MCSynchronizedStatementsASTSynchronizedStatementCoCo { - @Deprecated - TypeCalculator typeCheck; - - public static final String ERROR_CODE = "0xA0918 "; + public static final String ERROR_CODE = "0xA0918"; public static final String ERROR_MSG_FORMAT = "Expression in synchronized-statement must have a reference type."; - /** - * @deprecated use default constructor - */ - @Deprecated - public SynchronizedArgIsReftype(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } - - public SynchronizedArgIsReftype() { } - @Override public void check(ASTSynchronizedStatement node) { Preconditions.checkNotNull(node); - SymTypeExpression result; - - if (typeCheck != null) { - // support deprecated behavior - result = typeCheck.typeOf(node.getExpression()); - } else { - result = TypeCheck3.typeOf(node.getExpression()); - } + SymTypeExpression result = TypeCheck3.typeOf(node.getExpression()); - if (!result.isObjectType()) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); + if (!result.isObscureType() && !result.isObjectType()) { + Log.error(ERROR_CODE + " " + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ThrowIsValid.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ThrowIsValid.java index 863f7412a5..428ff85301 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ThrowIsValid.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/ThrowIsValid.java @@ -6,49 +6,27 @@ import de.monticore.statements.mcexceptionstatements._cocos.MCExceptionStatementsASTThrowStatementCoCo; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class ThrowIsValid implements MCExceptionStatementsASTThrowStatementCoCo { - @Deprecated - TypeCalculator typeCheck; - public static final String ERROR_CODE = "0xA0918"; - public static final String ERROR_MSG_FORMAT = " Exception in throw-statement must be Throwable or subtype of it."; - - /** - * @deprecated use default constructor - */ - @Deprecated - public ThrowIsValid(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } - - public ThrowIsValid() { } + public static final String ERROR_MSG_FORMAT = "Exception in throw-statement must be Throwable or subtype of it."; //JLS3 14.18-1 @Override public void check(ASTThrowStatement node) { Preconditions.checkNotNull(node); - SymTypeExpression throwable = SymTypeExpressionFactory.createTypeObject("java.lang.Throwable", node.getEnclosingScope()); + SymTypeExpression throwable = SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.lang.Throwable", node.getEnclosingScope()); - SymTypeExpression expression; + SymTypeExpression expression = TypeCheck3.typeOf(node.getExpression()); - if (typeCheck != null) { - // support deprecated behavior - expression = typeCheck.typeOf(node.getExpression()); - } else { - expression = TypeCheck3.typeOf(node.getExpression()); + if (!expression.isObscureType() && !SymTypeRelations.isSubTypeOf(expression, throwable)) { + Log.error(ERROR_CODE + " " +ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } - - if (!SymTypeRelations.isSubTypeOf(expression, throwable)) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); - } - } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/WhileConditionHasBooleanType.java b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/WhileConditionHasBooleanType.java index cb0dfcf33a..2d299f6d5e 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/WhileConditionHasBooleanType.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mccommonstatements/cocos/WhileConditionHasBooleanType.java @@ -5,46 +5,25 @@ import de.monticore.statements.mccommonstatements._ast.ASTWhileStatement; import de.monticore.statements.mccommonstatements._cocos.MCCommonStatementsASTWhileStatementCoCo; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types.check.TypeCalculator; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; public class WhileConditionHasBooleanType implements MCCommonStatementsASTWhileStatementCoCo { - @Deprecated - TypeCalculator typeCheck; - public static final String ERROR_CODE = "0xA0919"; public static final String ERROR_MSG_FORMAT = "Condition in while-statement must be a boolean expression."; - /** - * @deprecated use default constructor - */ - @Deprecated - public WhileConditionHasBooleanType(TypeCalculator typeCheck) { - this.typeCheck = typeCheck; - } - - public WhileConditionHasBooleanType() { } - //JLS3 14.12-1 @Override public void check(ASTWhileStatement node) { Preconditions.checkNotNull(node); - SymTypeExpression result; - - if (typeCheck != null) { - // support deprecated behavior - result = typeCheck.typeOf(node.getCondition()); - } else { - result = TypeCheck3.typeOf(node.getCondition()); - } + SymTypeExpression result = TypeCheck3.typeOf(node.getCondition()); - if (!SymTypeRelations.isBoolean(result)) { - Log.error(ERROR_CODE + ERROR_MSG_FORMAT, node.get_SourcePositionStart()); + if (!result.isObscureType() && !SymTypeRelations.isBoolean(result)) { + Log.error(ERROR_CODE + " " +ERROR_MSG_FORMAT, node.get_SourcePositionStart()); } } } \ No newline at end of file diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_cocos/VarDeclarationInitializationHasCorrectType.java b/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_cocos/VarDeclarationInitializationHasCorrectType.java index 3e357c99c2..b1f5aa38ec 100644 --- a/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_cocos/VarDeclarationInitializationHasCorrectType.java +++ b/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_cocos/VarDeclarationInitializationHasCorrectType.java @@ -5,7 +5,7 @@ import de.monticore.statements.mcvardeclarationstatements.MCVarDeclarationStatementsMill; import de.monticore.statements.mcvardeclarationstatements._ast.ASTSimpleInit; import de.monticore.statements.mcvardeclarationstatements._ast.ASTVariableDeclarator; -import de.monticore.types.check.*; +import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.TypeCheck3; import de.se_rwth.commons.logging.Log; @@ -14,89 +14,44 @@ * Checks that the initialization expressions of variable declaration statements are compatible to the types of the * variables. */ -public class VarDeclarationInitializationHasCorrectType - implements MCVarDeclarationStatementsASTVariableDeclaratorCoCo { - - /** - * Used to derive the {@link SymTypeExpression} to which initialization expressions evaluate to. - */ - @Deprecated - protected IDerive typeDeriver; +public class VarDeclarationInitializationHasCorrectType implements MCVarDeclarationStatementsASTVariableDeclaratorCoCo { /** * Indicates that the type of the initialization expression is not compatible with the type of the assigned variable. */ public static final String ERROR_CODE = "0xA0921"; - /** - * Indicates that the initialization expression does not evaluate to a value, but to a type name. Example: - * {@code String foo = String;} - */ - public static final String TYPE_REF_ASSIGNMENT_ERROR_CODE = "0xA0922"; - public static final String ERROR_MSG_FORMAT = "Incompatible type '%s' of the initialization expression for variable '%s' " + "that is of type '%s'."; - public static final String TYPE_REF_ASSIGNMENT_ERROR_MSG_FORMAT = "The initialization expression for variable " + - "'%s' represents the type '%s'. As types do not evaluate to values, they can not be used in assignments / " + - "initializations."; - - /** - * @param typeDeriver Used to derive the {@link SymTypeExpression} to which initialization expressions evaluate to. - * @deprecated use default constructor - */ - public VarDeclarationInitializationHasCorrectType(IDerive typeDeriver) { - this.typeDeriver = typeDeriver; - } - - public VarDeclarationInitializationHasCorrectType() { - } - @Override public void check(ASTVariableDeclarator node) { - if(!node.isPresentVariableInit() || !(node.getVariableInit() instanceof ASTSimpleInit)) { + if (!node.isPresentVariableInit() || !(node.getVariableInit() instanceof ASTSimpleInit)) { return; // We can only check initializations of the form of expressions (as defined in SimpleInit). - - } else if(!node.getDeclarator().isPresentSymbol()) { + } + if (!node.getDeclarator().isPresentSymbol()) { Log.error(String.format("Could not find a symbol for variable '%s', thus can not check coco '%s'. Check " + - "whether you have run the symbol table creation before running this coco.", - node.getDeclarator().getName(), this.getClass().getSimpleName())); + "whether you have run the symbol table creation before running this coco.", + node.getDeclarator().getName(), this.getClass().getSimpleName()), node.get_SourcePositionStart(), node.get_SourcePositionEnd()); } else { // Proceed with checking the coco SymTypeExpression varType = node.getDeclarator().getSymbol().getType(); - SymTypeExpression initType; - if (typeDeriver != null) { - // support deprecated behavior - TypeCheckResult initResult = typeDeriver.deriveType(((ASTSimpleInit) node.getVariableInit()).getExpression()); - if (initResult.isPresentResult()) { - if (initResult.isType()) { - Log.error(TYPE_REF_ASSIGNMENT_ERROR_CODE + " " + String.format(TYPE_REF_ASSIGNMENT_ERROR_MSG_FORMAT, - node.getDeclarator().getName(), initResult.getResult().print())); - } - initType = initResult.getResult(); - } - else { - initType = SymTypeExpressionFactory.createObscureType(); - } - } - else { - ASTExpression initExpr = MCVarDeclarationStatementsMill.typeDispatcher() - .asMCVarDeclarationStatementsASTSimpleInit(node.getVariableInit()) - .getExpression(); - initType = TypeCheck3.typeOf(initExpr, varType); - } + ASTExpression initExpr = MCVarDeclarationStatementsMill.typeDispatcher() + .asMCVarDeclarationStatementsASTSimpleInit(node.getVariableInit()) + .getExpression(); + SymTypeExpression initType = TypeCheck3.typeOf(initExpr, varType); if (initType.isObscureType()) { // The error is already printed by the IDerive visitors, thus we would spam the log if we would log an error // again. Therefore, we only leave a note in the debug log. Log.debug(String.format("As the initialization expression for variable '%s' at %s is invalid, coco '%s' " + - "will not be checked.", + "will not be checked.", node.getDeclarator().getName(), node.get_SourcePositionStart(), this.getClass().getSimpleName()), "Cocos"); } else if (!SymTypeRelations.isCompatible(varType, initType)) { Log.error(ERROR_CODE + " " + String.format(ERROR_MSG_FORMAT, - initType.printFullName(), node.getDeclarator().getName(), varType.printFullName())); + initType.printFullName(), node.getDeclarator().getName(), varType.printFullName())); } } } diff --git a/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_cocos/VarDeclarationNameAlreadyDefinedInScope.java b/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_cocos/VarDeclarationNameAlreadyDefinedInScope.java new file mode 100644 index 0000000000..b489ab7870 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/statements/mcvardeclarationstatements/_cocos/VarDeclarationNameAlreadyDefinedInScope.java @@ -0,0 +1,49 @@ +package de.monticore.statements.mcvardeclarationstatements._cocos; + +import de.monticore.statements.mcvardeclarationstatements._ast.ASTVariableDeclarator; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symboltable.modifiers.AccessModifier; +import de.se_rwth.commons.logging.Log; + +import java.util.List; + +/** + * Checks whether the variable name has already been defined in the local scope. + * Logs an error for _each_ variable declaration (with the same name). + */ +public class VarDeclarationNameAlreadyDefinedInScope implements MCVarDeclarationStatementsASTVariableDeclaratorCoCo { + + /** + * Indicates that the name of the variable has already been used in the scope + * This will produce one error for _each_ variable declaration (with the same name) + */ + public static final String ERROR_CODE = "0xA0923"; + + public static final String ERROR_MSG_FORMAT = "Variable '%s' is already defined in the scope."; + + public static final String ERROR_CODE_MISSING_SYMBOL = "0xA0924"; + + @Override + public void check(ASTVariableDeclarator node) { + if (!node.getDeclarator().isPresentSymbol()) { + Log.error(String.format(ERROR_CODE_MISSING_SYMBOL + " Could not find a symbol for variable '%s', thus can not check coco '%s'. Check " + + "whether you have run the symbol table creation before running this coco.", + node.getDeclarator().getName(), this.getClass().getSimpleName()), + node.get_SourcePositionStart(), node.get_SourcePositionEnd()); + return; + } + + List localVarSymbols = node.getEnclosingScope().resolveVariableLocallyMany( + false, + node.getDeclarator().getName(), + AccessModifier.ALL_INCLUSION, + (v) -> v != node.getDeclarator().getSymbol() + ); + + if (!localVarSymbols.isEmpty()) { + Log.error(ERROR_CODE + " " + String.format(ERROR_MSG_FORMAT, + node.getDeclarator().getName()), + node.get_SourcePositionStart(), node.get_SourcePositionEnd()); + } + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/basicsymbols/_symboltable/IBasicSymbolsScope.java b/monticore-grammar/src/main/java/de/monticore/symbols/basicsymbols/_symboltable/IBasicSymbolsScope.java index 3c3285624a..675893a56a 100644 --- a/monticore-grammar/src/main/java/de/monticore/symbols/basicsymbols/_symboltable/IBasicSymbolsScope.java +++ b/monticore-grammar/src/main/java/de/monticore/symbols/basicsymbols/_symboltable/IBasicSymbolsScope.java @@ -12,7 +12,7 @@ public interface IBasicSymbolsScope extends IBasicSymbolsScopeTOP { /** * returns whether a type variable is bound within this scope - * e.g. class C {} // T is bound within the class + * e.g. {@code class C {}} // T is bound within the class */ default boolean isTypeVariableBound(TypeVarSymbol typeVar) { List localVars = resolveTypeVarLocallyMany( diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentType2TypeSymbolAdapter.java b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentType2TypeSymbolAdapter.java new file mode 100644 index 0000000000..0458e3960b --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentType2TypeSymbolAdapter.java @@ -0,0 +1,69 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import com.google.common.base.Preconditions; +import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; +import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; +import de.monticore.symboltable.modifiers.BasicAccessModifier; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.se_rwth.commons.SourcePosition; +import org.checkerframework.checker.nullness.qual.NonNull; + +import java.util.stream.Collectors; + +public class ComponentType2TypeSymbolAdapter extends TypeSymbol { + + protected ComponentTypeSymbol adaptee; + + public ComponentType2TypeSymbolAdapter(@NonNull ComponentTypeSymbol adaptee) { + super(Preconditions.checkNotNull(adaptee).getName()); + this.adaptee = adaptee; + this.accessModifier = BasicAccessModifier.PUBLIC; + this.spannedScope = adaptee.getSpannedScope(); + this.superTypes = adaptee.getSuperComponentsList().stream().map(c -> { + if (!c.isGenericComponentType()) { + return SymTypeExpressionFactory.createTypeObject(new ComponentType2TypeSymbolAdapter(c.getTypeInfo())); + } else { + return SymTypeExpressionFactory.createGenerics( + new ComponentType2TypeSymbolAdapter(c.getTypeInfo()), c.asGenericComponentType().getTypeBindingsAsList() + ); + } + }).collect(Collectors.toList()); + } + + public ComponentTypeSymbol getAdaptee() { + return adaptee; + } + + @Override + public void setName(@NonNull String name) { + Preconditions.checkNotNull(name); + Preconditions.checkArgument(!name.isBlank()); + this.getAdaptee().setName(name); + } + + @Override + public String getName() { + return this.getAdaptee().getName(); + } + + @Override + public String getFullName() { + return this.getAdaptee().getFullName(); + } + + @Override + public IBasicSymbolsScope getSpannedScope() { + return this.getAdaptee().getSpannedScope(); + } + + @Override + public IBasicSymbolsScope getEnclosingScope() { + return this.getAdaptee().getEnclosingScope(); + } + + @Override + public SourcePosition getSourcePosition() { + return this.getAdaptee().getSourcePosition(); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbol.java b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbol.java index 126757dafb..bbae36a4d7 100644 --- a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbol.java +++ b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbol.java @@ -61,7 +61,7 @@ public Optional getPort(@NonNull String name) { * exists. Does consider inherited ports if {@code searchSuper} is set * to true. * - * @param name the name of the port + * @param name the name of the port * @param searchSuper whether to consider ports of super components * @return the port with the given name wrapped in an {@code Optional} or * an empty {@code Optional} if no such port exists. @@ -107,7 +107,7 @@ public Optional getIncomingPort(@NonNull String name) { * exists. Does consider inherited ports if {@code searchSuper} is set * to true. * - * @param name the name of the port + * @param name the name of the port * @param searchSuper whether to consider ports of super components * @return the incoming port with the given name wrapped in an * {@code Optional} or an empty {@code Optional} if no such port exists @@ -153,7 +153,7 @@ public Optional getOutgoingPort(@NonNull String name) { * if it exists. Does consider inherited ports if {@code searchSuper} is set * to true. * - * @param name the name of the port + * @param name the name of the port * @param searchSuper whether to consider ports of super components * @return the outgoing port with the given name wrapped in an * {@code Optional} or an empty {@code Optional} if no such port exists @@ -289,31 +289,55 @@ public boolean isAtomic() { /** * Helper function that transitively determines the start of the refinement chain.
- * + *

* Example: A refines B, C; B refines D; C refines D; - * The unique start is D.
- * + * The unique start is D.
+ *

* A component without explicit refinements is itself the start on the chain. If there does not exist an unique * start (A refines B, C and B, C are unrefined) we throw an error. */ public Optional getRefinementStart() { - if(getRefinementsList() == null || getRefinementsList().isEmpty()) { + if (getRefinementsList() == null || getRefinementsList().isEmpty()) { return Optional.of(this); - } - else { + } else { var candidates = getRefinementsList().stream() .map(CompKindExpression::getTypeInfo) .map(ComponentTypeSymbol::getRefinementStart) // Recursion .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toSet()); - if(candidates.size() == 1) { + if (candidates.size() == 1) { return candidates.stream().findFirst(); - } - else { + } else { Log.warn("Could not determine a single root component in the refinement chain."); return Optional.empty(); } } } + + /** + * @return a {@code List} of the fields of this component type. + */ + public List getFields() { + return this.getSpannedScope().getLocalVariableSymbols().stream() + .filter(f -> !(f instanceof Port2VariableAdapter)) + .filter(f -> !(f instanceof Subcomponent2VariableAdapter)) + .filter(f -> !(getParameterList().contains(f))) + .collect(Collectors.toList()); + } + + /** + * Searches the fields of this component type for a field with the given name. Returns an {@code + * Optional} of a field of this component type with the given name, or an empty {@code Optional} + * if no such field exists. Throws an {@link IllegalArgumentException} if the given name is + * {@code null}. + * + * @param name the name of the field. + * @return an {@code Optional} of a field of this component type with the given name, or an + * empty {@code Optional} if no such field exists. + */ + public Optional getField(@NonNull String name) { + Preconditions.checkNotNull(name); + return this.getFields().stream().filter(field -> field.getName().equals(name)).findFirst(); + } } diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolBuilder.java b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolBuilder.java new file mode 100644 index 0000000000..2e43bb920c --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolBuilder.java @@ -0,0 +1,83 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import com.google.common.base.Preconditions; +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import org.checkerframework.checker.nullness.qual.NonNull; + +import java.util.List; + +public class ComponentTypeSymbolBuilder extends ComponentTypeSymbolBuilderTOP { + + protected List typeParameters; + + public ComponentTypeSymbolBuilder() { + super(); + } + + @Override + public ComponentTypeSymbolBuilder setName(@NonNull String name) { + Preconditions.checkNotNull(name); + return super.setName(name); + } + + @Override + public ComponentTypeSymbolBuilder setSpannedScope(@NonNull ICompSymbolsScope spannedScope) { + Preconditions.checkNotNull(spannedScope); + return super.setSpannedScope(spannedScope); + } + + public List getTypeParameters() { + return this.typeParameters; + } + + public ComponentTypeSymbolBuilder setTypeParameters(@NonNull List typeParameters) { + Preconditions.checkNotNull(typeParameters); + Preconditions.checkArgument(!typeParameters.contains(null)); + this.typeParameters = typeParameters; + return this.realBuilder; + } + + @Override + public ComponentTypeSymbol build() { + Preconditions.checkState(isValid()); + return doBuild(new ComponentTypeSymbol(this.name)); + } + + protected ComponentTypeSymbol doBuild(@NonNull ComponentTypeSymbol symbol) { + Preconditions.checkNotNull(symbol); + Preconditions.checkState(isValid()); + symbol.setSuperComponentsList(this.superComponents); + symbol.setRefinementsList(this.refinements); + symbol.setName(this.name); + symbol.setFullName(this.fullName); + symbol.setPackageName(this.packageName); + if (this.astNode.isPresent()) { + symbol.setAstNode(this.astNode.get()); + } else { + symbol.setAstNodeAbsent(); + } + symbol.setAccessModifier(this.accessModifier); + symbol.setEnclosingScope(this.enclosingScope); + symbol.setSpannedScope(this.spannedScope); + if (this.parameter != null) { + this.parameter.forEach(this.getSpannedScope()::add); + symbol.addAllParameter(this.parameter); + } + symbol.setNumOptParams(this.numOptParams); + if (this.typeParameters != null) { + this.getTypeParameters().forEach(symbol.getSpannedScope()::add); + } + return symbol; + } + + @Override + public boolean isValid() { + return this.name != null + && this.spannedScope != null; + } + + protected final boolean isValidNumOptParams() { + return this.parameter.size() >= this.numOptParams; + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolDeSer.java b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolDeSer.java index 0822c23137..e2400a6a40 100644 --- a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolDeSer.java +++ b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolDeSer.java @@ -42,11 +42,6 @@ protected CompKindExpressionDeSer getCompTypeExprDeSer() { return compTypeExprDeSer; } - @Override - protected void deserializeAddons(ComponentTypeSymbol symbol, JsonObject symbolJson) { - symbol.getParameterList().forEach(symbol.getSpannedScope()::add); - } - @Override protected void serializeSuperComponents(@NonNull List superComponents, @NonNull CompSymbolsSymbols2Json s2j) { @@ -94,8 +89,8 @@ protected List deserializeParameter(JsonObject symbolJson) { parameterResult.add(paramSym); } else { Log.error(String.format( - "0xD0101 Malformed json, parameter '%s' of unsupported kind '%s'", - param.getAsJsonObject().getStringMember(JsonDeSers.NAME), paramJsonKind + "0xD0101 Malformed json, parameter '%s' of unsupported kind '%s'", + param.getAsJsonObject().getStringMember(JsonDeSers.NAME), paramJsonKind )); } } diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolSurrogate.java b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolSurrogate.java new file mode 100644 index 0000000000..32279419b0 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolSurrogate.java @@ -0,0 +1,30 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import de.monticore.symbols.compsymbols._ast.ASTComponentType; +import org.checkerframework.checker.nullness.qual.NonNull; + +import java.util.Set; + +public class ComponentTypeSymbolSurrogate extends ComponentTypeSymbolSurrogateTOP { + + public ComponentTypeSymbolSurrogate(@NonNull String name) { + super(name); + } + + @Override + public Set getAllPorts() { + if (!checkLazyLoadDelegate()) { + return super.getAllPorts(); + } + return lazyLoadDelegate().getAllPorts(); + } + + @Override + public ASTComponentType getAstNode() { + if (!checkLazyLoadDelegate()) { + return super.getAstNode(); + } + return lazyLoadDelegate().getAstNode(); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/Port2VariableAdapter.java b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/Port2VariableAdapter.java new file mode 100644 index 0000000000..8f8fca9b69 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/Port2VariableAdapter.java @@ -0,0 +1,88 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import com.google.common.base.Preconditions; +import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symboltable.modifiers.BasicAccessModifier; +import de.monticore.types.check.SymTypeExpression; +import de.se_rwth.commons.SourcePosition; +import org.checkerframework.checker.nullness.qual.NonNull; + +/** + * Adapts {@link PortSymbol}s to {@link VariableSymbol}s, e.g., so that they can + * easily be referred to from expressions. + */ +public class Port2VariableAdapter extends VariableSymbol { + + protected PortSymbol adaptee; + + public Port2VariableAdapter(@NonNull PortSymbol adaptee) { + super(Preconditions.checkNotNull(adaptee).getName()); + this.adaptee = adaptee; + this.accessModifier = BasicAccessModifier.PUBLIC; + } + + public PortSymbol getAdaptee() { + return adaptee; + } + + @Override + public void setName(@NonNull String name) { + Preconditions.checkNotNull(name); + Preconditions.checkArgument(!name.isBlank()); + this.getAdaptee().setName(name); + } + + @Override + public String getName() { + return this.getAdaptee().getName(); + } + + @Override + public String getFullName() { + return this.getAdaptee().getFullName(); + } + + @Override + public void setType(@NonNull SymTypeExpression type) { + Preconditions.checkNotNull(type); + this.getAdaptee().setType(type); + } + + @Override + public SymTypeExpression getType() { + return this.getAdaptee().getType(); + } + + @Override + public boolean isIsReadOnly() { + return this.getAdaptee().isIncoming(); + } + + @Override + public IBasicSymbolsScope getEnclosingScope() { + return this.getAdaptee().getEnclosingScope(); + } + + @Override + public SourcePosition getSourcePosition() { + return this.getAdaptee().getSourcePosition(); + } + + @Override + public Port2VariableAdapter deepClone() { + Port2VariableAdapter clone = new Port2VariableAdapter(this.getAdaptee()); + clone.setAccessModifier(this.getAccessModifier()); + clone.setEnclosingScope(this.getEnclosingScope()); + clone.setFullName(this.getFullName()); + clone.setIsReadOnly(this.isIsReadOnly()); + if (this.isPresentAstNode()) { + clone.setAstNode(this.getAstNode()); + } + if (this.getType() != null) { + clone.setType(this.getType().deepClone()); + } + return clone; + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/PortSymbol.java b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/PortSymbol.java index b24d411247..f2066aa0dd 100644 --- a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/PortSymbol.java +++ b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/PortSymbol.java @@ -15,11 +15,11 @@ protected PortSymbol(String name) { } /** - * @param name the name of this port. - * @param incoming whether the port is incoming. - * @param outgoing whether the port is outgoing. - * @param type the type of this port. - * @param timing the timing of this port. + * @param name the name of this port. + * @param incoming whether the port is incoming. + * @param outgoing whether the port is outgoing. + * @param type the type of this port. + * @param timing the timing of this port. */ protected PortSymbol(String name, boolean incoming, @@ -49,7 +49,7 @@ public void setType(@NonNull SymTypeExpression type) { public TypeSymbol getTypeInfo() { return this.getType().getTypeInfo() instanceof TypeSymbolSurrogate ? - ((TypeSymbolSurrogate) this.getType().getTypeInfo()).lazyLoadDelegate() : this.getType().getTypeInfo(); + ((TypeSymbolSurrogate) this.getType().getTypeInfo()).lazyLoadDelegate() : this.getType().getTypeInfo(); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/Subcomponent2VariableAdapter.java b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/Subcomponent2VariableAdapter.java new file mode 100644 index 0000000000..9d3f985d98 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/symbols/compsymbols/_symboltable/Subcomponent2VariableAdapter.java @@ -0,0 +1,84 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import com.google.common.base.Preconditions; +import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symboltable.modifiers.BasicAccessModifier; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.se_rwth.commons.SourcePosition; +import org.checkerframework.checker.nullness.qual.NonNull; + +/** + * Adapts {@link SubcomponentSymbol}s to {@link VariableSymbol}s, e.g., so that they can + * easily be referred to from expressions. + */ +public class Subcomponent2VariableAdapter extends VariableSymbol { + + protected SubcomponentSymbol adaptee; + + public Subcomponent2VariableAdapter(@NonNull SubcomponentSymbol adaptee) { + super(Preconditions.checkNotNull(adaptee).getName()); + this.adaptee = adaptee; + this.accessModifier = BasicAccessModifier.PRIVATE; + } + + public SubcomponentSymbol getAdaptee() { + return adaptee; + } + + @Override + public void setName(@NonNull String name) { + Preconditions.checkNotNull(name); + Preconditions.checkArgument(!name.isBlank()); + this.getAdaptee().setName(name); + } + + @Override + public String getName() { + return this.getAdaptee().getName(); + } + + @Override + public String getFullName() { + return this.getAdaptee().getFullName(); + } + + @Override + public void setType(@NonNull SymTypeExpression type) { + throw new RuntimeException(); + } + + @Override + public SymTypeExpression getType() { + if (!adaptee.isTypePresent()) return SymTypeExpressionFactory.createObscureType(); + if (!adaptee.getType().isGenericComponentType()) { + return SymTypeExpressionFactory.createTypeObject(new ComponentType2TypeSymbolAdapter(adaptee.getType().getTypeInfo())); + } else { + return SymTypeExpressionFactory.createGenerics( + new ComponentType2TypeSymbolAdapter(adaptee.getType().getTypeInfo()), adaptee.getType().asGenericComponentType().getTypeBindingsAsList() + ); + } + } + + @Override + public boolean isIsReadOnly() { + return true; + } + + @Override + public IBasicSymbolsScope getEnclosingScope() { + return this.getAdaptee().getEnclosingScope(); + } + + @Override + public SourcePosition getSourcePosition() { + return this.getAdaptee().getSourcePosition(); + } + + @Override + public Subcomponent2VariableAdapter deepClone() { + return new Subcomponent2VariableAdapter(this.getAdaptee()); + } +} diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/oosymbols/_symboltable/FieldSymbol.java b/monticore-grammar/src/main/java/de/monticore/symbols/oosymbols/_symboltable/FieldSymbol.java index 69455fde38..d29dbee6f2 100644 --- a/monticore-grammar/src/main/java/de/monticore/symbols/oosymbols/_symboltable/FieldSymbol.java +++ b/monticore-grammar/src/main/java/de/monticore/symbols/oosymbols/_symboltable/FieldSymbol.java @@ -28,6 +28,7 @@ public FieldSymbol deepClone(){ clone.setIsPublic(this.isPublic); clone.setIsStatic(this.isStatic); clone.setIsFinal(this.isFinal); + clone.setIsEnumConstant(this.isEnumConstant); clone.setIsDerived(this.isDerived); clone.setIsReadOnly(this.isReadOnly); if(isPresentAstNode()) { diff --git a/monticore-grammar/src/main/java/de/monticore/symbols/oosymbols/types3/OOSymbolsSymTypeRelations.java b/monticore-grammar/src/main/java/de/monticore/symbols/oosymbols/types3/OOSymbolsSymTypeRelations.java new file mode 100644 index 0000000000..08cf4aca52 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/symbols/oosymbols/types3/OOSymbolsSymTypeRelations.java @@ -0,0 +1,258 @@ +// (c) https://github.com/MontiCore/monticore +package de.monticore.symbols.oosymbols.types3; + +import com.google.common.base.Preconditions; +import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; +import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; +import de.monticore.symbols.oosymbols.OOSymbolsMill; +import de.monticore.symbols.oosymbols._symboltable.FieldSymbol; +import de.monticore.symbols.oosymbols._symboltable.MethodSymbol; +import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; +import de.monticore.symboltable.ISymbol; +import de.monticore.symboltable.modifiers.AccessModifier; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypeOfFunction; +import de.monticore.types3.util.OOWithinTypeBasicSymbolsResolver; +import de.se_rwth.commons.logging.Log; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * relations for SymTypes of wrt. OOSymbols, + * e.g, isEnum, etc. + * Mostly used as convenience instead of the required, e.g., + *

    + *
  1. checking if a symbol exists
  2. + *
  3. checking if the symbol is a OOSymbol
  4. + *
  5. typeDispatch the symbol to the OOSymbols variant
  6. + *
  7. actually checking a value
  8. + *
+ * Note: this does not contain AccessModifier or similar, + * as those are related to the resolver and not the SymTypeExpressions. + */ +public class OOSymbolsSymTypeRelations { + + protected static final String LOG_NAME = + OOSymbolsSymTypeRelations.class.getName(); + + protected static OOSymbolsSymTypeRelations delegate; + + // methods + + public static boolean isClass(SymTypeExpression type) { + return getDelegate()._isClass(type); + } + + protected boolean _isClass(SymTypeExpression type) { + return getOOTypeSymbolIfAvailable(type) + .map(OOTypeSymbol::isIsClass) + .orElse(false); + } + + public static boolean isInterface(SymTypeExpression type) { + return getDelegate()._isInterface(type); + } + + protected boolean _isInterface(SymTypeExpression type) { + return getOOTypeSymbolIfAvailable(type) + .map(OOTypeSymbol::isIsInterface) + .orElse(false); + } + + public static boolean isEnum(SymTypeExpression type) { + return getDelegate()._isEnum(type); + } + + protected boolean _isEnum(SymTypeExpression type) { + return getOOTypeSymbolIfAvailable(type) + .map(OOTypeSymbol::isIsEnum) + .orElse(false); + } + + /** + * Checks if the type is a functional interface + * and returns the abstract method. + * S. JLS 21 9.8 + * + * @return the abstract method of the type iff the type is a functional interface + */ + public static Optional getAbstractFunctionOfFunctionalInterFace( + SymTypeExpression type + ) { + return getDelegate()._getAbstractFunctionOfFunctionalInterFace(type); + } + + protected Optional _getAbstractFunctionOfFunctionalInterFace( + SymTypeExpression type + ) { + Optional res; + if (!isInterface(type)) { + res = Optional.empty(); + } + else { + // cannot filter for abstract during resolving, + // as the method could be overridden + Map> name2AbstractMethods = + OOWithinTypeBasicSymbolsResolver.getAllFunctions( + type, AccessModifier.ALL_INCLUSION, fs -> true + ); + List methods = + name2AbstractMethods.values().stream() + .flatMap(List::stream) + .collect(Collectors.toList()); + List abstractMethods = methods.stream() + .filter(m -> OOSymbolsMill.typeDispatcher() + .isOOSymbolsMethod(m.getSymbol()) + ) + .filter(m -> OOSymbolsMill.typeDispatcher() + .asOOSymbolsMethod(m.getSymbol()).isIsAbstract() + ) + .collect(Collectors.toList()); + if (abstractMethods.size() == 1) { + res = Optional.of(abstractMethods.get(0)); + } + else { + res = Optional.empty(); + } + } + return res; + } + + /** + * whether the source of the type is an enum constant. + * s.a. {@link de.monticore.types.check.SymTypeSourceInfo#getSourceSymbol()} + */ + public static boolean sourceIsEnumConstant(SymTypeExpression type) { + return getDelegate()._sourceIsEnumConstant(type); + } + + protected boolean _sourceIsEnumConstant(SymTypeExpression type) { + return getSourceFieldSymbolIfAvailable(type) + .map(FieldSymbol::isIsEnumConstant) + .orElse(false); + } + + public static boolean isMethod(SymTypeExpression type) { + return getDelegate()._isMethod(type); + } + + protected boolean _isMethod(SymTypeExpression type) { + return getMethodSymbolIfAvailable(type) + .map(MethodSymbol::isIsMethod) + .orElse(false); + } + + public static boolean isConstructor(SymTypeExpression type) { + return getDelegate()._isConstructor(type); + } + + protected boolean _isConstructor(SymTypeExpression type) { + return getMethodSymbolIfAvailable(type) + .map(MethodSymbol::isIsConstructor) + .orElse(false); + } + + // Helper + + protected Optional getOOTypeSymbolIfAvailable( + SymTypeExpression type + ) { + Optional res; + if (type.hasTypeInfo()) { + TypeSymbol typeSymbol = type.getTypeInfo(); + if (OOSymbolsMill.typeDispatcher().isOOSymbolsOOType(typeSymbol)) { + res = Optional.of( + OOSymbolsMill.typeDispatcher().asOOSymbolsOOType(typeSymbol) + ); + } + else { + res = Optional.empty(); + } + } + else { + res = Optional.empty(); + } + return res; + } + + protected Optional getMethodSymbolIfAvailable( + SymTypeExpression type + ) { + Optional res; + if (type.isFunctionType()) { + SymTypeOfFunction func = type.asFunctionType(); + if (func.hasSymbol()) { + FunctionSymbol funcSym = func.getSymbol(); + if (OOSymbolsMill.typeDispatcher().isOOSymbolsMethod(funcSym)) { + res = Optional.of( + OOSymbolsMill.typeDispatcher().asOOSymbolsMethod(funcSym) + ); + } + else { + res = Optional.empty(); + } + } + else { + res = Optional.empty(); + } + } + else { + res = Optional.empty(); + } + return res; + } + + protected Optional getSourceFieldSymbolIfAvailable( + SymTypeExpression type + ) { + Optional res; + if (type.getSourceInfo().getSourceSymbol().isPresent()) { + ISymbol sourceSymbol = type.getSourceInfo().getSourceSymbol().get(); + if (OOSymbolsMill.typeDispatcher().isOOSymbolsField(sourceSymbol)) { + res = Optional.of( + OOSymbolsMill.typeDispatcher().asOOSymbolsField(sourceSymbol) + ); + } + else { + res = Optional.empty(); + } + } + else { + res = Optional.empty(); + } + if (res.isEmpty()) { + Log.trace("tried getting source symbol of a SymTypeExpression of " + + type.printFullName() + ", but there was none" + + ", this may influence further calculations." + , LOG_NAME + ); + } + return res; + } + + // static delegate + + public static void init() { + Log.trace("init default OOSymbolsSymTypeRelations", "TypeCheck setup"); + setDelegate(new OOSymbolsSymTypeRelations()); + } + + public static void reset() { + OOSymbolsSymTypeRelations.delegate = null; + } + + protected static void setDelegate(OOSymbolsSymTypeRelations newDelegate) { + OOSymbolsSymTypeRelations.delegate = Preconditions.checkNotNull(newDelegate); + } + + protected static OOSymbolsSymTypeRelations getDelegate() { + if (OOSymbolsSymTypeRelations.delegate == null) { + init(); + } + return OOSymbolsSymTypeRelations.delegate; + } + +} diff --git a/monticore-grammar/src/main/java/de/monticore/tagging/SimpleSymbolTagger.java b/monticore-grammar/src/main/java/de/monticore/tagging/SimpleSymbolTagger.java index 882375134d..5523614701 100644 --- a/monticore-grammar/src/main/java/de/monticore/tagging/SimpleSymbolTagger.java +++ b/monticore-grammar/src/main/java/de/monticore/tagging/SimpleSymbolTagger.java @@ -152,7 +152,7 @@ protected List getScopeDifferences(IScope scope, IScope target) { } /** - * Computes a (new) FQN->[ASTTargetElement] mapping of an ASTTagUnit + * Computes a (new) {@code FQN->[ASTTargetElement]} mapping of an ASTTagUnit */ protected TagFQNMapping computeFQNMapping(ASTTagUnit tagUnit) { Map> fqnMapping = new LinkedHashMap<>(); @@ -201,7 +201,7 @@ public void endVisit(ASTContext node) { /** * Buffering iterator of type A with an element of flattening. - * calls {@link #doWork(B)} when demanded and iterates on the doWorks return value. + * calls ProgressiveIterator#doWork(B) when demanded and iterates on the doWorks return value. */ protected abstract static class ProgressiveIterator implements Iterator { // With a buffer of target elements diff --git a/monticore-grammar/src/main/java/de/monticore/tagging/TagRepository.java b/monticore-grammar/src/main/java/de/monticore/tagging/TagRepository.java index 080f9278b8..327bc2a219 100644 --- a/monticore-grammar/src/main/java/de/monticore/tagging/TagRepository.java +++ b/monticore-grammar/src/main/java/de/monticore/tagging/TagRepository.java @@ -8,17 +8,17 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; public class TagRepository { // A cache for tag models loaded from files - protected static Map loadedFileTags = new HashMap<>(); + protected static Map loadedFileTags = new LinkedHashMap<>(); // And a cache for temporary tag models - protected static Map loadedTags = new HashMap<>(); + protected static Map loadedTags = new LinkedHashMap<>(); /** * Load a new tag model into this repository diff --git a/monticore-grammar/src/main/java/de/monticore/tagging/conforms/TagData.java b/monticore-grammar/src/main/java/de/monticore/tagging/conforms/TagData.java index 48fb020a7f..96631b33ff 100644 --- a/monticore-grammar/src/main/java/de/monticore/tagging/conforms/TagData.java +++ b/monticore-grammar/src/main/java/de/monticore/tagging/conforms/TagData.java @@ -9,7 +9,7 @@ * Recursive data structure for hierarchical tag definition */ public class TagData { - protected final Map inner = new HashMap<>(); + protected final Map inner = new LinkedHashMap<>(); protected final List tags = new ArrayList<>(); diff --git a/monticore-grammar/src/main/java/de/monticore/tagging/conforms/TagSchemaData.java b/monticore-grammar/src/main/java/de/monticore/tagging/conforms/TagSchemaData.java index c0fea39af3..705153f995 100644 --- a/monticore-grammar/src/main/java/de/monticore/tagging/conforms/TagSchemaData.java +++ b/monticore-grammar/src/main/java/de/monticore/tagging/conforms/TagSchemaData.java @@ -9,13 +9,13 @@ import java.util.*; /** - * Stores data of TagTypeSymbols in a [NonTerminal => [TagTypeSymbols]] form + * Stores data of TagTypeSymbols in a [NonTerminal => [TagTypeSymbols]] form */ public class TagSchemaData { - protected Map> simpleTagTypes = new HashMap<>(); - protected Map> valuedTagTypes = new HashMap<>(); - protected Map> enumeratedTagTypes = new HashMap<>(); - protected Map> complexTagTypes = new HashMap<>(); + protected Map> simpleTagTypes = new LinkedHashMap<>(); + protected Map> valuedTagTypes = new LinkedHashMap<>(); + protected Map> enumeratedTagTypes = new LinkedHashMap<>(); + protected Map> complexTagTypes = new LinkedHashMap<>(); public final static String WILDCARD = "___WILDCARD_TAG_TYPE_%"; diff --git a/monticore-grammar/src/main/java/de/monticore/tagging/tagschema/TagSchemaAfterParseTrafo.java b/monticore-grammar/src/main/java/de/monticore/tagging/tagschema/TagSchemaAfterParseTrafo.java index 8463b67296..d16a01ca82 100644 --- a/monticore-grammar/src/main/java/de/monticore/tagging/tagschema/TagSchemaAfterParseTrafo.java +++ b/monticore-grammar/src/main/java/de/monticore/tagging/tagschema/TagSchemaAfterParseTrafo.java @@ -6,8 +6,8 @@ import de.monticore.tagging.tagschema._visitor.TagSchemaVisitor2; import de.se_rwth.commons.logging.Log; -import java.util.HashMap; -import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; @@ -19,11 +19,11 @@ public class TagSchemaAfterParseTrafo { protected TagSchemaTraverser traverser; // TagType => Scope - protected Map tagScopeMap = new HashMap<>(); + protected Map tagScopeMap = new LinkedHashMap<>(); // Ensure all tagtypes of the same name are of the same kind (simple, valued, enumerated, ...) - protected Map> tagKindMap = new HashMap<>(); + protected Map> tagKindMap = new LinkedHashMap<>(); - protected Set markedForDeletion = new HashSet<>(); + protected Set markedForDeletion = new LinkedHashSet<>(); public TagSchemaAfterParseTrafo() { this.traverser = TagSchemaMill.traverser(); diff --git a/monticore-grammar/src/main/java/de/monticore/tf/grammartransformation/CollectCoCoInformationState.java b/monticore-grammar/src/main/java/de/monticore/tf/grammartransformation/CollectCoCoInformationState.java index fcbd859be0..7094f9980f 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/grammartransformation/CollectCoCoInformationState.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/grammartransformation/CollectCoCoInformationState.java @@ -3,7 +3,7 @@ import com.google.common.collect.Sets; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Set; @@ -11,8 +11,8 @@ public class CollectCoCoInformationState { private int parentNest = 0; private boolean rhs = false; - private Set varsOnLHS = new HashSet(); - private Set varsOnRHS = new HashSet(); + private Set varsOnLHS = new LinkedHashSet(); + private Set varsOnRHS = new LinkedHashSet(); private int repElements = 0; private int negElements = 0; diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrulegeneration/_ast/ASTTransformationStructure.java b/monticore-grammar/src/main/java/de/monticore/tf/odrulegeneration/_ast/ASTTransformationStructure.java index a5aab20a36..fdea7842cb 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrulegeneration/_ast/ASTTransformationStructure.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrulegeneration/_ast/ASTTransformationStructure.java @@ -1,8 +1,8 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.tf.odrulegeneration._ast; -import java.util.HashMap; -import java.util.List; +import java.util.*; +import java.util.stream.Collectors; public class ASTTransformationStructure extends ASTTransformationStructureTOP { @@ -70,5 +70,36 @@ public HashMap> getFoldingHash () { public void setFoldingHash (HashMap> foldingHash) { this.foldingHash = foldingHash; } - + + public List getCompositionDependencyNames(ASTMatchingObject object) { + return this.getPattern().getLinkConditionsList().stream().filter( + l -> l.getLinktype().equals("composition") && l.getDependency().getContent() + .equals(object.getObjectName())).map(ASTCondition::getObjectName) + .collect(Collectors.toList()); + } + + public Map getReplacementChangeMapping() { + Map replacementChangeMapping = new HashMap<>(); + this.getReplacement().getChangesList().stream().filter(ASTChange::isPresentValue) + .filter(x -> x.getValue().charAt(0) == '_').forEach(change -> { + String truncValueName = + change.getValue().substring(1, change.getValue().lastIndexOf("_")); + replacementChangeMapping.put(change.getObjectName(), truncValueName); + }); + return replacementChangeMapping; + } + + public Set getAllInnerNonOptionalNames(List allObjects, + ASTMatchingObject matchObject) { + Set result = new HashSet<>(); + for (String innerLinkObjectName : matchObject.getInnerLinkObjectNamesList()) { + ASTMatchingObject innerLinkObject = this.getPattern().getMatchingObjectsList().stream() + .filter(f -> f.getObjectName().equals(innerLinkObjectName)).findFirst().get(); + if (!innerLinkObject.isOptObject()) { + result.add(innerLinkObjectName); + } + result.addAll(getAllInnerNonOptionalNames(allObjects, innerLinkObject)); + } + return result; + } } diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/DifferenceFinder.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/DifferenceFinder.java index 4359399fb9..a7cf845d4a 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/DifferenceFinder.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/DifferenceFinder.java @@ -43,7 +43,7 @@ private static class ChangePair { private List unchangedLinks = new LinkedList<>(); private ASTODDefinition lhs; - private HashMap> toCreateObjectsAttr = new HashMap(); + private LinkedHashMap> toCreateObjectsAttr = new LinkedHashMap(); private HierarchyHelper hierarchyHelper; diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/HierarchyHelper.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/HierarchyHelper.java index 329f7f8e24..529c421c3f 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/HierarchyHelper.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/HierarchyHelper.java @@ -20,9 +20,9 @@ public final class HierarchyHelper { private ASTODDefinition lhs; private Optional rhs = Optional.empty(); - private Map> listChildPairs = new HashMap<>(); - private Map> listChildPairsLhs = new HashMap<>(); - private Map> listChildPairsWithOptionals = new HashMap<>(); + private Map> listChildPairs = new LinkedHashMap<>(); + private Map> listChildPairsLhs = new LinkedHashMap<>(); + private Map> listChildPairsWithOptionals = new LinkedHashMap<>(); private List listChildNames = new ArrayList<>(); private List listChildNamesLhs = new ArrayList<>(); @@ -52,7 +52,7 @@ public HierarchyHelper(ASTODRule astodRule) { listChildPairsWithOptionals = getListChildPairsWithOptionals(lhs.getODObjectList()); Map> rhsListChildPairs = rhs.isPresent() ? - getListChildPairs(rhs.get().getODObjectList()) : new HashMap<>(); + getListChildPairs(rhs.get().getODObjectList()) : new LinkedHashMap<>(); for (String key : rhsListChildPairs.keySet()) { // Every list on the lhs is also on the rhs // If there are objects to create in a list put them to the Map @@ -146,7 +146,7 @@ public void addCustomImports(String customImport) { */ private Map> getListChildPairs( List objects) { - Map> result = new HashMap<>(); + Map> result = new LinkedHashMap<>(); List childs; List innerObjects; // Search for every List in the given Objects @@ -173,7 +173,7 @@ private Map> getListChildPairs( private Map> getListChildPairsWithOptionals( List objects) { - Map> result = new HashMap<>(); + Map> result = new LinkedHashMap<>(); List childs; List innerObjects; // Search for every List in the given Objects diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/ODBuildOrder.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/ODBuildOrder.java index 71f317be50..359cec0e3e 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/ODBuildOrder.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/ODBuildOrder.java @@ -4,14 +4,14 @@ import de.monticore.tf.odrules._ast.ASTODLink; import de.monticore.tf.odrules._ast.ASTODObject; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; public class ODBuildOrder { public class ObjectTrees { - private HashMap nodes = new HashMap<>(); + private LinkedHashMap nodes = new LinkedHashMap<>(); public class ObjectNode { private ObjectNode parent; @@ -64,8 +64,8 @@ public ODBuildOrder(List objects, List links) { calculateBuildOrder(); } - public HashMap> getBuildAttrs() { - HashMap> buildAttrs = new HashMap<>(); + public LinkedHashMap> getBuildAttrs() { + LinkedHashMap> buildAttrs = new LinkedHashMap<>(); for(ASTODObject o : buildOrder) { buildAttrs.put(o, trees.nodes.get(o.getName()).attrs); diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/ODRuleCodeGenerator.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/ODRuleCodeGenerator.java index 030c88b648..8491a84dcc 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/ODRuleCodeGenerator.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/ODRuleCodeGenerator.java @@ -346,7 +346,7 @@ protected boolean isObjectVariable(String var) { */ protected static Map getAllDependVars(List subConstraints) { - Map allDependVars = new HashMap<>(); + Map allDependVars = new LinkedHashMap<>(); for (ODSubConstraint subConstraint : subConstraints) { for (ASTMatchingObject object : subConstraint.dependVars) { String objectName = object.getObjectName(); @@ -519,7 +519,7 @@ protected String generateConstraintExpression(ASTODRule ast) { } protected List generateVariables(ASTODRule ast) { - Collection collectedNames = new HashSet<>(); + Collection collectedNames = new LinkedHashSet<>(); List variables = calculateVariablesFor(Util.getAllODObjects(ast.getLhs()), collectedNames); if (ast.isPresentRhs()) { @@ -626,8 +626,8 @@ protected ASTVariable generateVariable(ASTODObject obj, ASTODAttribute attr) { return variable.build(); } - protected HashMap> generateFoldingHash(ASTODRule ast) { - HashMap> result = new HashMap>(); + protected LinkedHashMap> generateFoldingHash(ASTODRule ast) { + LinkedHashMap> result = new LinkedHashMap>(); // create an (initially empty) sequence for all objects for (ASTODObject odObject : Util.getAllODObjects(ast.getLhs())) { result.put(odObject.getName(), new ArrayList()); @@ -648,7 +648,7 @@ protected HashMap> generateFoldingHash(ASTODRule ast) { protected ASTReplacement generateReplacement(List changes) { ASTReplacementBuilder replacement = ODRuleGenerationMill.replacementBuilder(); - Map requirementNames = new HashMap(); + Map requirementNames = new LinkedHashMap(); replacement.setRequirementsList(generateRequirements(changes, requirementNames)); replacement.setChangesList(generateChanges(changes, requirementNames)); replacement.setCreateObjectsList(generateCreateObjects(changes)); diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/AddSuffixToOptionalsVisitor.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/AddSuffixToOptionalsVisitor.java index d5043e52b4..87cd01305d 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/AddSuffixToOptionalsVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/AddSuffixToOptionalsVisitor.java @@ -13,7 +13,7 @@ import de.monticore.tf.odrules.HierarchyHelper; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -34,7 +34,7 @@ public AddSuffixToOptionalsVisitor(List lhsObjects, Hierarchy super(); this.hierarchyHelper = hierarchyHelper; this.lhsObjects = lhsObjects; - handledNodes = new HashSet<>(); + handledNodes = new LinkedHashSet<>(); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindDependVarsVisitor.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindDependVarsVisitor.java index e79c0d6c5e..efb147c705 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindDependVarsVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindDependVarsVisitor.java @@ -5,7 +5,7 @@ import de.monticore.expressions.expressionsbasis._visitor.ExpressionsBasisVisitor2; import de.monticore.tf.odrulegeneration._ast.ASTMatchingObject; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -23,7 +23,7 @@ public class FindDependVarsVisitor implements public FindDependVarsVisitor(List lhsObjects){ super(); this.lhsObjects = lhsObjects; - dependVars = new HashSet<>(); + dependVars = new LinkedHashSet<>(); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindOptionalsVisitor.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindOptionalsVisitor.java index 9e9a6b1a2e..e8c68682b4 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindOptionalsVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindOptionalsVisitor.java @@ -6,7 +6,7 @@ import de.monticore.tf.odrulegeneration._ast.ASTMatchingObject; import de.monticore.tf.odrules.HierarchyHelper; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -26,7 +26,7 @@ public FindOptionalsVisitor(List lhsObjects, HierarchyHelper super(); this.hierarchyHelper = hierarchyHelper; this.lhsObjects = lhsObjects; - optVars = new HashSet<>(); + optVars = new LinkedHashSet<>(); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindSubExpressionVisitor.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindSubExpressionVisitor.java index f407331320..fdd2a8d659 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindSubExpressionVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/FindSubExpressionVisitor.java @@ -10,7 +10,7 @@ * Created by Alexander Wilts on 16.01.2017. * * This visitor calculates if the given expression contains any further subExpressions. - * A subExpression is every expression, that does not contain any further '&&' or '||' operators. + * A subExpression is every expression, that does not contain any further {@code &&} or {@code ||} operators. */ public class FindSubExpressionVisitor implements CommonExpressionsVisitor2 { diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/InsertIsPresentChecksVisitor.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/InsertIsPresentChecksVisitor.java index eb510e92db..f78f79f86e 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/InsertIsPresentChecksVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/InsertIsPresentChecksVisitor.java @@ -31,8 +31,8 @@ *

* Examples for normal variable $A and optional variable $O: *

- * $A && $O results in $A && (!$O.isPresent || isValid($O)) - * $A || $O results in $A || ($O.isPresent && isValid($O)) + * {@code $A && $O} results in {@code $A && (!$O.isPresent || isValid($O))} + * {@code $A} || $O results in {@code $A || ($O.isPresent && isValid($O))} */ public class InsertIsPresentChecksVisitor implements CommonExpressionsVisitor2 { diff --git a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/ODSubConstraint.java b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/ODSubConstraint.java index 7fe3f6a56e..99d4ff2785 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/ODSubConstraint.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/odrules/subConstraints/ODSubConstraint.java @@ -3,7 +3,7 @@ import de.monticore.tf.odrulegeneration._ast.ASTMatchingObject; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Set; /** @@ -50,6 +50,6 @@ public String getConstrExprFor(String dependencyName){ } public ODSubConstraint() { - dependVars = new HashSet<>(); + dependVars = new LinkedHashSet<>(); } } diff --git a/monticore-grammar/src/main/java/de/monticore/tf/ruletranslation/ODRuleNameGenerator.java b/monticore-grammar/src/main/java/de/monticore/tf/ruletranslation/ODRuleNameGenerator.java index 9b64904843..02230e48a8 100644 --- a/monticore-grammar/src/main/java/de/monticore/tf/ruletranslation/ODRuleNameGenerator.java +++ b/monticore-grammar/src/main/java/de/monticore/tf/ruletranslation/ODRuleNameGenerator.java @@ -5,7 +5,7 @@ import de.se_rwth.commons.StringTransformations; import de.monticore.tf.ast.*; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -14,8 +14,8 @@ */ public class ODRuleNameGenerator { - private Map generatedNames = new HashMap<>(); - private Map, Integer> numberOfElements = new HashMap<>(); + private Map generatedNames = new LinkedHashMap<>(); + private Map, Integer> numberOfElements = new LinkedHashMap<>(); public String getNameForElement(ITFObject element, Map parents) { ASTNode parent = parents.get(element); diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/AbstractDerive.java b/monticore-grammar/src/main/java/de/monticore/types/check/AbstractDerive.java index 36b2cefed0..95e9564d4e 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/AbstractDerive.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/AbstractDerive.java @@ -5,6 +5,11 @@ import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; import de.monticore.visitor.ITraverser; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public abstract class AbstractDerive implements IDerive { protected ITraverser traverser; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/AbstractDeriveFromExpression.java b/monticore-grammar/src/main/java/de/monticore/types/check/AbstractDeriveFromExpression.java index cc8bd2c672..a6fb8ca3b3 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/AbstractDeriveFromExpression.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/AbstractDeriveFromExpression.java @@ -18,6 +18,11 @@ import static de.monticore.types.check.TypeCheck.isDouble; import static de.monticore.types.check.TypeCheck.isLong; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public abstract class AbstractDeriveFromExpression { public abstract ExpressionsBasisTraverser getTraverser(); diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/AbstractSynthesize.java b/monticore-grammar/src/main/java/de/monticore/types/check/AbstractSynthesize.java index 525f8caeb6..6300f6f2ef 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/AbstractSynthesize.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/AbstractSynthesize.java @@ -6,6 +6,11 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.visitor.ITraverser; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public abstract class AbstractSynthesize implements ISynthesize { protected ITraverser traverser; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/AbstractSynthesizeFromType.java b/monticore-grammar/src/main/java/de/monticore/types/check/AbstractSynthesizeFromType.java index cf517bd9ed..ce5f82abc0 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/AbstractSynthesizeFromType.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/AbstractSynthesizeFromType.java @@ -9,6 +9,11 @@ import java.util.List; import java.util.Optional; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public abstract class AbstractSynthesizeFromType { public abstract MCBasicTypesTraverser getTraverser(); diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/CompKindExpression.java b/monticore-grammar/src/main/java/de/monticore/types/check/CompKindExpression.java index a009d69973..53c968351c 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/CompKindExpression.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/CompKindExpression.java @@ -3,10 +3,8 @@ import com.google.common.base.Preconditions; import de.monticore.ast.ASTNode; -import de.monticore.expressions.assignmentexpressions._ast.ASTAssignmentExpression; -import de.monticore.expressions.expressionsbasis._ast.ASTExpression; -import de.monticore.expressions.expressionsbasis._ast.ASTNameExpression; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.compsymbols._ast.ASTSubcomponentArgument; import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; import de.se_rwth.commons.logging.Log; @@ -25,21 +23,21 @@ public abstract class CompKindExpression { protected final ComponentTypeSymbol component; - protected LinkedHashMap parameterBindings; - protected List arguments; + protected LinkedHashMap parameterBindings; + protected List arguments; protected Optional sourceNode; /** * @return a {@code List} of the configuration arguments of this component. */ - public List getArguments() { + public List getArguments() { return this.arguments; } /** * @param argument the configuration argument to add to this component. */ - public void addArgument(ASTExpression argument) { + public void addArgument(ASTSubcomponentArgument argument) { Preconditions.checkNotNull(argument); this.arguments.add(argument); } @@ -64,7 +62,7 @@ public CompKindOfComponentType asComponentType() { } /** - * Am I a generic component type? (such as "C") + * Am I a generic component type? (such as {@code C}) * (default: no) */ public boolean isGenericComponentType() { @@ -84,46 +82,44 @@ public CompKindOfGenericComponentType asGenericComponentType() { /** * @param arguments the configuration arguments to add to this component. - * @see this#addArgument(ASTExpression) + * @see CompKindExpression#addArgument(ASTSubcomponentArgument) */ - public void addArgument(List arguments) { + public void addArgument(List arguments) { Preconditions.checkNotNull(arguments); Preconditions.checkArgument(!arguments.contains(null)); - for (ASTExpression argument : arguments) { + for (ASTSubcomponentArgument argument : arguments) { this.addArgument(argument); } } - public Optional getParamBindingFor(VariableSymbol var) { + public Optional getParamBindingFor(VariableSymbol var) { Preconditions.checkNotNull(var); return Optional.ofNullable(this.getParamBindings().get(var)); } - public Map getParamBindings() { + public Map getParamBindings() { return Collections.unmodifiableMap(this.parameterBindings); } - public List getParamBindingsAsList() { + public List getParamBindingsAsList() { return new ArrayList<>(this.getParamBindings().values()); } public void bindParams() { - List parameterArguments = this.getArguments(); + List parameterArguments = this.getArguments(); int firstKeywordArgument = 0; - LinkedHashMap keywordExpressionMap = new LinkedHashMap<>(); - LinkedHashMap parameterBindings = new LinkedHashMap<>(); + LinkedHashMap keywordExpressionMap = new LinkedHashMap<>(); + LinkedHashMap parameterBindings = new LinkedHashMap<>(); // We know LinkedHashMaps are ordered by insertion time. As we rely on the fact that the ordering of the // arguments is consistent with the ordering in the map, the following iteration ensures it: for (int i = 0; i < this.getTypeInfo().getParameterList().size(); i++) { if (i < parameterArguments.size()) // Deal with wrong number of parameters through cocos - if (parameterArguments.get(i) instanceof ASTAssignmentExpression - && ((ASTAssignmentExpression) parameterArguments.get(i)).getLeft() instanceof ASTNameExpression) { - keywordExpressionMap.put(((ASTNameExpression) ((ASTAssignmentExpression) parameterArguments.get(i)) - .getLeft()).getName(), parameterArguments.get(i)); - } else { + if (!parameterArguments.get(i).isPresentName()) { parameterBindings.put(this.getTypeInfo().getParameterList().get(i), parameterArguments.get(i)); firstKeywordArgument++; + } else { + keywordExpressionMap.put(parameterArguments.get(i).getName(), parameterArguments.get(i)); } } @@ -215,6 +211,8 @@ public ComponentTypeSymbol getTypeInfo() { */ public abstract Optional getTypeOfParameter(String parameterName); + public abstract List> getParameterTypes(); + public CompKindExpression deepClone() { return deepClone(getTypeInfo()); } diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/CompKindOfComponentType.java b/monticore-grammar/src/main/java/de/monticore/types/check/CompKindOfComponentType.java index 1024fe3b86..ea5bee2dbf 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/CompKindOfComponentType.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/CompKindOfComponentType.java @@ -2,6 +2,7 @@ package de.monticore.types.check; import com.google.common.base.Preconditions; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbolTOP; import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; import de.monticore.symbols.compsymbols._symboltable.PortSymbol; @@ -9,6 +10,7 @@ import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; /** * Represents a component expression that is solely defined by the component symbol. @@ -56,6 +58,14 @@ public Optional getTypeOfParameter(@NonNull String name) { return this.getTypeInfo().getParameter(name).map(VariableSymbolTOP::getType); } + @Override + public List> getParameterTypes() { + return this.getTypeInfo().getParameterList() + .stream().map(VariableSymbol::getType) + .map(Optional::of) + .collect(Collectors.toList()); + } + @Override public CompKindOfComponentType deepClone(@NonNull ComponentTypeSymbol component) { CompKindOfComponentType clone = new CompKindOfComponentType(component); diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/CompKindOfGenericComponentType.java b/monticore-grammar/src/main/java/de/monticore/types/check/CompKindOfGenericComponentType.java index 32bd08dfde..42aec0118f 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/CompKindOfGenericComponentType.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/CompKindOfGenericComponentType.java @@ -5,7 +5,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; -import de.monticore.symbols.basicsymbols._symboltable.VariableSymbolTOP; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; import de.monticore.symbols.compsymbols._symboltable.PortSymbol; import org.checkerframework.checker.nullness.qual.NonNull; @@ -93,7 +93,23 @@ public String printFullName() { @Override public List getSuperComponents() { - return this.getTypeInfo().getSuperComponentsList(); + ComponentTypeSymbol rawType = this.getTypeInfo(); + if (rawType.isEmptySuperComponents()) { + return rawType.getSuperComponentsList(); + } + + return rawType.getSuperComponentsList().stream().map(unboundParentExpr -> { + if (unboundParentExpr.isComponentType()) { + return unboundParentExpr; + } else if (unboundParentExpr.isGenericComponentType()) { + return unboundParentExpr.asGenericComponentType().bindTypeParameter(this.getTypeVarBindings()); + } else { + throw new UnsupportedOperationException("Encountered a type expression for components that is not known." + + String.format(" (We only know '%s' and '%s')", + CompKindOfComponentType.class.getName(), CompKindOfGenericComponentType.class.getName() + ) + ); + }}).collect(Collectors.toList()); } @Override @@ -122,12 +138,21 @@ public Optional getTypeOfParameter(@NonNull String parameterN SymTypeExpression unboundParamType = this.getTypeInfo() .getParameter(parameterName) - .map(VariableSymbolTOP::getType) + .map(VariableSymbol::getType) .orElseThrow(NoSuchElementException::new); return this.createBoundTypeExpression(unboundParamType); } + @Override + public List> getParameterTypes() { + List unbound = this.getTypeInfo().getParameterList() + .stream().map(VariableSymbol::getType) + .collect(Collectors.toList()); + + return this.createBoundTypeExpression(unbound); + } + public Optional getTypeBindingFor(@NonNull TypeVarSymbol typeVar) { Preconditions.checkNotNull(typeVar); return Optional.ofNullable(this.getTypeVarBindings().get(typeVar)); @@ -212,4 +237,9 @@ protected Optional createBoundTypeExpression(@NonNull SymType return Optional.of(boundSymType); } } + + protected List> createBoundTypeExpression(@NonNull List typeExprS) { + Preconditions.checkNotNull(typeExprS); + return typeExprS.stream().map(this::createBoundTypeExpression).collect(Collectors.toList()); + } } diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfAssignmentExpressions.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfAssignmentExpressions.java index 8e416379e6..9050b77408 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfAssignmentExpressions.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfAssignmentExpressions.java @@ -23,7 +23,10 @@ /** * This Visitor can calculate a SymTypeExpression (type) for the expressions in AssignmentExpressions * It can be combined with other expressions in your language by creating a DelegatorVisitor + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfAssignmentExpressions extends AbstractDeriveFromExpression implements AssignmentExpressionsVisitor2, AssignmentExpressionsHandler { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfBSCommonExpressions.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfBSCommonExpressions.java index 8ad095ebc5..17261d7056 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfBSCommonExpressions.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfBSCommonExpressions.java @@ -30,7 +30,10 @@ * For an OO language, use {@link de.monticore.types.check.DeriveSymTypeOfCommonExpressions} instead, which * extends the functionality of this class so that it may be used in an OO-context as well. * It can be combined with other expressions in your language by creating a DelegatorVisitor + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfBSCommonExpressions extends AbstractDeriveFromExpression implements CommonExpressionsVisitor2, CommonExpressionsHandler { protected CommonExpressionsTraverser traverser; @@ -1035,7 +1038,7 @@ protected void calculateMethodReturnTypeBasedOnSignature(List ca ASTCallExpression callExpr, List argTypes) { List functions = new ArrayList<>(); - Map symTypeToSymbol = new HashMap<>(); + Map symTypeToSymbol = new LinkedHashMap<>(); for(FunctionSymbol functionSymbol : candidates) { SymTypeOfFunction function = functionSymbol.getFunctionType(); functions.add(function); @@ -1121,7 +1124,7 @@ protected List chooseMostSpecificFunction(List specificityMap = new HashMap<>(); + Map specificityMap = new LinkedHashMap<>(); List mostSpecific = Lists.newArrayList(candidates.get(0)); for(SymTypeOfFunction function: candidates) { int[] specificity = new int[args.size()]; @@ -1176,7 +1179,7 @@ protected List filterModifiersFunctions(List fun } /** - * helper method for <=, >=, <, > -> calculates the result of these expressions + * helper method for {@code <=, >=, <, > ->} calculates the result of these expressions */ protected SymTypeExpression calculateTypeCompare(SymTypeExpression left, SymTypeExpression right, String op, SourcePosition pos) { // if the left and the right part of the expression are numerics, @@ -1300,12 +1303,12 @@ protected SymTypeExpression getCorrectResultArrayExpression(IExpressionsBasisSco //determine whether the result has to be a constant, generic or object if (arrayResult.getTypeInfo().getTypeParameterList().isEmpty()) { //if the return type is a primitive - if (SymTypePrimitive.boxMap.containsKey(arrayResult.getTypeInfo().getName())) { + if (arrayResult.isPrimitive()) { wholeResult = SymTypeExpressionFactory.createPrimitive(arrayResult.getTypeInfo().getName()); } else { //if the return type is an object - wholeResult = SymTypeExpressionFactory.createTypeObject(arrayResult.getTypeInfo().getName(), getScope(scope)); + wholeResult = SymTypeExpressionFactory.createTypeObjectViaSurrogate(arrayResult.getTypeInfo().getName(), getScope(scope)); } } else { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfBitExpressions.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfBitExpressions.java index f98a86fc61..58cc22d9e2 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfBitExpressions.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfBitExpressions.java @@ -12,7 +12,10 @@ /** * This Visitor can calculate a SymTypeExpression (type) for the expressions in BitExpressions * It can be combined with other expressions in your language by creating a DelegatorVisitor + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfBitExpressions extends AbstractDeriveFromExpression implements BitExpressionsVisitor2, BitExpressionsHandler { protected BitExpressionsTraverser traverser; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfCommonExpressions.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfCommonExpressions.java index 2378faf5eb..6f31b51bb7 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfCommonExpressions.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfCommonExpressions.java @@ -18,7 +18,10 @@ * It is the OO extension of the class {@link de.monticore.types.check.DeriveSymTypeOfBSCommonExpressions} and adds OO * functionalities like modifiers to the derivation of a SymTypeExpression. * It can be combined with other expressions in your language by creating a DelegatorVisitor + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfCommonExpressions extends DeriveSymTypeOfBSCommonExpressions { @Override diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfExpression.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfExpression.java index 796e593a5b..d0e6d28994 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfExpression.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfExpression.java @@ -19,7 +19,10 @@ /** * This Visitor can calculate a SymTypeExpression (type) for the expressions in ExpressionsBasis * It can be combined with other expressions in your language by creating a DelegatorVisitor + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfExpression extends AbstractDeriveFromExpression implements ExpressionsBasisVisitor2, ExpressionsBasisHandler { public IBasicSymbolsScope getScope (IExpressionsBasisScope expressionsBasisScope){ diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfJavaClassExpressions.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfJavaClassExpressions.java index c42589beef..e8f2400937 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfJavaClassExpressions.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfJavaClassExpressions.java @@ -27,7 +27,10 @@ /** * This Visitor can calculate a SymTypeExpression (type) for the expressions in JavaClassExpressions * It can be combined with other expressions in your language by creating a DelegatorVisitor + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfJavaClassExpressions extends AbstractDeriveFromExpression implements JavaClassExpressionsVisitor2, JavaClassExpressionsHandler { protected JavaClassExpressionsTraverser traverser; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfLambdaExpressions.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfLambdaExpressions.java index e2cb920ec2..151e423e83 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfLambdaExpressions.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfLambdaExpressions.java @@ -15,7 +15,10 @@ /** * This Visitor can calculate a SymTypeExpression (type) for the expressions in LambdaExpressions * It can be combined with other expressions in your language by creating a DelegatorVisitor + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfLambdaExpressions extends AbstractDeriveFromExpression implements LambdaExpressionsVisitor2, LambdaExpressionsHandler { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfLiterals.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfLiterals.java index 43b553dedc..2c498035f7 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfLiterals.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfLiterals.java @@ -13,7 +13,10 @@ * (Function 2b) * i.e. for * literals/MCLiteralsBasis.mc4 + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfLiterals implements MCLiteralsBasisVisitor2 { public IBasicSymbolsScope getScope (IMCLiteralsBasisScope mcLiteralsBasisScope){ diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfMCCommonLiterals.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfMCCommonLiterals.java index 98f76742b8..c1fda79a33 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfMCCommonLiterals.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfMCCommonLiterals.java @@ -16,7 +16,10 @@ * (Function 2b) * i.e. for * literals/MCLiteralsBasis.mc4 + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfMCCommonLiterals extends DeriveSymTypeOfLiterals implements MCCommonLiteralsVisitor2 { protected TypeCheckResult typeCheckResult; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfMCJavaLiterals.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfMCJavaLiterals.java index 6da2fb2a85..416175393b 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfMCJavaLiterals.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfMCJavaLiterals.java @@ -8,6 +8,11 @@ import de.monticore.literals.mcjavaliterals._visitor.MCJavaLiteralsVisitor2; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; + /** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public class DeriveSymTypeOfMCJavaLiterals extends DeriveSymTypeOfMCCommonLiterals implements MCJavaLiteralsVisitor2 { protected TypeCheckResult typeCheckResult; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfUglyExpressions.java b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfUglyExpressions.java index 04331716e5..af10265c23 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfUglyExpressions.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/DeriveSymTypeOfUglyExpressions.java @@ -28,7 +28,10 @@ /** * This Visitor can calculate a SymTypeExpression (type) for the expressions in JavaClassExpressions * It can be combined with other expressions in your language by creating a DelegatorVisitor + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class DeriveSymTypeOfUglyExpressions extends AbstractDeriveFromExpression implements UglyExpressionsVisitor2, UglyExpressionsHandler { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCArrayTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCArrayTypes.java index ac4fdb5ab1..ce310df2fc 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCArrayTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCArrayTypes.java @@ -9,6 +9,11 @@ import java.util.Optional; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public class FullSynthesizeFromMCArrayTypes extends AbstractSynthesize { public FullSynthesizeFromMCArrayTypes(){ diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCBasicTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCBasicTypes.java index 5fcc2bab4c..2ec9b8623e 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCBasicTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCBasicTypes.java @@ -9,6 +9,11 @@ import java.util.Optional; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public class FullSynthesizeFromMCBasicTypes extends AbstractSynthesize { public FullSynthesizeFromMCBasicTypes(){ diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCCollectionTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCCollectionTypes.java index c463165537..a211108932 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCCollectionTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCCollectionTypes.java @@ -5,6 +5,11 @@ import de.monticore.types.mccollectiontypes.MCCollectionTypesMill; import de.monticore.types.mccollectiontypes._visitor.MCCollectionTypesTraverser; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public class FullSynthesizeFromMCCollectionTypes extends AbstractSynthesize { public FullSynthesizeFromMCCollectionTypes(){ diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCFullGenericTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCFullGenericTypes.java index 474cc2d436..9a5a5950c8 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCFullGenericTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCFullGenericTypes.java @@ -4,6 +4,11 @@ import de.monticore.types.mcfullgenerictypes.MCFullGenericTypesMill; import de.monticore.types.mcfullgenerictypes._visitor.MCFullGenericTypesTraverser; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public class FullSynthesizeFromMCFullGenericTypes extends AbstractSynthesize { public FullSynthesizeFromMCFullGenericTypes(){ diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCFunctionTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCFunctionTypes.java index e5449fce72..1896426430 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCFunctionTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCFunctionTypes.java @@ -4,6 +4,11 @@ import de.monticore.types.mcfunctiontypes.MCFunctionTypesMill; import de.monticore.types.mcfunctiontypes._visitor.MCFunctionTypesTraverser; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public class FullSynthesizeFromMCFunctionTypes extends AbstractSynthesize { public FullSynthesizeFromMCFunctionTypes() { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCSimpleGenericTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCSimpleGenericTypes.java index bfbaa6b6b5..090449a9e1 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCSimpleGenericTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/FullSynthesizeFromMCSimpleGenericTypes.java @@ -9,6 +9,11 @@ import java.util.Optional; +/** + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. + */ +@Deprecated public class FullSynthesizeFromMCSimpleGenericTypes extends AbstractSynthesize { public FullSynthesizeFromMCSimpleGenericTypes(){ diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/ISynthesizeComponent.java b/monticore-grammar/src/main/java/de/monticore/types/check/ISynthesizeComponent.java index 3bfd7cdfae..a56bf9b247 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/ISynthesizeComponent.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/ISynthesizeComponent.java @@ -3,6 +3,7 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mcbasictypes._visitor.MCBasicTypesTraverser; +import de.se_rwth.commons.logging.Log; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.Optional; @@ -30,6 +31,12 @@ public interface ISynthesizeComponent { default Optional synthesize(@NonNull ASTMCType mcType) { this.init(); mcType.accept(this.getTraverser()); - return this.getResult(); + Optional res = this.getResult(); + if (res.isEmpty()) { + Log.error(String.format("0xD0104 Cannot resolve component '%s'", mcType.printType()), + mcType.get_SourcePositionStart(), mcType.get_SourcePositionEnd() + ); + } + return res; } } diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/ITypeRelations.java b/monticore-grammar/src/main/java/de/monticore/types/check/ITypeRelations.java index a5929fb5ea..60f5697c38 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/ITypeRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/ITypeRelations.java @@ -21,10 +21,10 @@ public interface ITypeRelations { * compatible("Person", "Student") (uni-directional) *

* Incompatible: - * !compatible("double", "int") (in all directions) + * {@code !compatible("double", "int")} (in all directions) *

* The concrete Typechecker has to decide on further issues, like - * !compatible("List", "List") + * {@code !compatible("List", "List")} * where e.g. Java and OCL/P differ in their answers * * @param left Super-Type @@ -43,7 +43,7 @@ public interface ITypeRelations { /** * calculate the minimum inheritance distance from the specific type to the general type - * e.g. C extends B extends A => object of type C has distance of 2 to object of type A + * e.g. C extends B extends A: object of type C has distance of 2 to object of type A * object of type B has distance of 1 to object of type A * object of type A has distance of 0 to object of type A * diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SIUnitBasic.java b/monticore-grammar/src/main/java/de/monticore/types/check/SIUnitBasic.java index 7836d2dbf9..eedae9029a 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SIUnitBasic.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SIUnitBasic.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.se_rwth.commons.logging.Log; public class SIUnitBasic { @@ -16,8 +17,8 @@ public SIUnitBasic( String prefix, int exponent ) { - this.dimension = Log.errorIfNull(dimension); - this.prefix = Log.errorIfNull(prefix); + this.dimension = Preconditions.checkNotNull(dimension); + this.prefix = Preconditions.checkNotNull(prefix); this.exponent = exponent; } diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeArray.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeArray.java index f81b916e7b..6d174cfc19 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeArray.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeArray.java @@ -1,18 +1,19 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbolSurrogate; import de.monticore.types3.ISymTypeVisitor; import de.se_rwth.commons.logging.Log; /** - * Arrays of a certain dimension (>= 1) + * Arrays of a certain dimension ({@code >= 1}) */ public class SymTypeArray extends SymTypeExpression { /** - * An arrayType has a dimension (>= 1) + * An arrayType has a dimension ({@code >= 1}) */ protected int dim; @@ -30,7 +31,7 @@ public class SymTypeArray extends SymTypeExpression { * @param argument Argument Type * @param typeSymbol loader for the Type-Symbol that defines this type */ - @Deprecated + @Deprecated(forRemoval = true) public SymTypeArray(TypeSymbol typeSymbol, int dim, SymTypeExpression argument) { this.typeSymbol = typeSymbol; this.dim = dim; @@ -39,7 +40,7 @@ public SymTypeArray(TypeSymbol typeSymbol, int dim, SymTypeExpression argument) public SymTypeArray(SymTypeExpression argument, int dim) { this.dim = dim; - this.argument = argument; + this.argument = Preconditions.checkNotNull(argument); } // ------------------------------------------------------------------ Functions diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeExpression.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeExpression.java index 2aaf3173b2..4e47307d9e 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeExpression.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeExpression.java @@ -8,10 +8,10 @@ import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.symbols.oosymbols.OOSymbolsMill; import de.monticore.symbols.oosymbols._symboltable.*; -import de.monticore.symboltable.ISymbol; import de.monticore.symboltable.modifiers.AccessModifier; import de.monticore.types3.ISymTypeVisitor; import de.monticore.types3.util.SymTypeDeepCloneVisitor; +import de.monticore.types3.util.SymTypeExpressionComparator; import de.monticore.types3.util.SymTypePrintFullNameVisitor; import de.monticore.types3.util.SymTypePrintVisitor; import de.se_rwth.commons.logging.Log; @@ -25,19 +25,20 @@ * It shares common functionality * (such as comparison, printing) */ -public abstract class SymTypeExpression { +public abstract class SymTypeExpression + implements Comparable { protected static final String LOG_NAME = "SymTypeExpression"; /** - * print: Conversion to a compact string, such as "int", "Person", "List< A >" + * print: Conversion to a compact string, such as {@code "int"}, {@code "Person"}, {@code "List< A >"} */ public String print() { return new SymTypePrintVisitor().calculate(this); } /** - * printFullName: prints the full name of the symbol, such as "java.util.List" + * printFullName: prints the full name of the symbol, such as {@code "java.util.List"} * @return */ public String printFullName() { @@ -58,7 +59,7 @@ protected String printAsJson() { * pseudo types like typeVariables * @deprecated not well-thought-out and unused */ - @Deprecated + @Deprecated(forRemoval = true) public boolean isValidType() { return true; } @@ -72,24 +73,22 @@ public boolean isPrimitive() { } public SymTypePrimitive asPrimitive() { - Log.error("0xFDAA0 internal error: " + throw new UnsupportedOperationException("0xFDAA0 internal error: " + "tried to convert non-primitive to a primitive." + " Actual: " + this.printFullName()); - return null; } /** - * Am I a generic type? (such as "List") + * Am I a generic type? (such as {@code "List"}) */ public boolean isGenericType() { return false; } public SymTypeOfGenerics asGenericType() { - Log.error("0xFDAA1 internal error: " + throw new UnsupportedOperationException("0xFDAA1 internal error: " + "tried to convert non-generic to a generic." + " Actual: " + this.printFullName()); - return null; } /** @@ -100,10 +99,9 @@ public boolean isTypeVariable() { } public SymTypeVariable asTypeVariable() { - Log.error("0xFDAA2 internal error: " + throw new UnsupportedOperationException("0xFDAA2 internal error: " + "tried to convert non-bound-type-variable to a bound-type-variable." + " Actual: " + this.printFullName()); - return null; } /** @@ -114,10 +112,9 @@ public boolean isInferenceVariable() { } public SymTypeInferenceVariable asInferenceVariable() { - Log.error("0xFDAAF internal error: " + throw new UnsupportedOperationException("0xFDAAF internal error: " + "tried to convert non-inference-variable to an inference-variable." + " Actual: " + this.printFullName()); - return null; } /** @@ -128,10 +125,9 @@ public boolean isArrayType() { } public SymTypeArray asArrayType() { - Log.error("0xFDAA3 internal error: " + throw new UnsupportedOperationException("0xFDAA3 internal error: " + "tried to convert non-array to an array." + " Actual: " + this.printFullName()); - return null; } /** @@ -142,10 +138,9 @@ public boolean isVoidType() { } public SymTypeVoid asVoidType() { - Log.error("0xFDAA4 internal error: " + throw new UnsupportedOperationException("0xFDAA4 internal error: " + "tried to convert non-void-type to a void type." + " Actual: " + this.printFullName()); - return null; } /** @@ -156,10 +151,9 @@ public boolean isNullType() { } public SymTypeOfNull asNullType() { - Log.error("0xFDAA5 internal error: " + throw new UnsupportedOperationException("0xFDAA5 internal error: " + "tried to convert non-null-type to a null-type." + " Actual: " + this.printFullName()); - return null; } /** @@ -170,10 +164,9 @@ public boolean isObjectType() { } public SymTypeOfObject asObjectType() { - Log.error("0xFDAA6 internal error: " + throw new UnsupportedOperationException("0xFDAA6 internal error: " + "tried to convert non-object-type to an object-type." + " Actual: " + this.printFullName()); - return null; } /** @@ -184,49 +177,49 @@ public boolean isRegExType() { } public SymTypeOfRegEx asRegExType() { - Log.error("0xFDAAC internal error: " + throw new UnsupportedOperationException("0xFDAAC internal error: " + "tried to convert non-regex-type to a regex type." + " Actual: " + this.printFullName()); - return null; } /** - * Am I a function type (e.g. "String -> Integer") + * Am I a function type (e.g. {@code "String -> Integer"}) */ public boolean isFunctionType() { return false; } public SymTypeOfFunction asFunctionType() { - Log.error("0xFDAA7 internal error: " + throw new UnsupportedOperationException("0xFDAA7 internal error: " + "tried to convert non-function-type to a function type." + " Actual: " + this.printFullName()); - return null; } - // Am I an SIUnit type (e.g., "km/h") + /** + * Am I an SIUnit type (e.g., "[km/h]") + */ public boolean isSIUnitType() { return false; } public SymTypeOfSIUnit asSIUnitType() { - Log.error("0xFDAAC internal error: " + throw new UnsupportedOperationException("0xFDAAC internal error: " + "tried to convert non-SIUnit type to a SIUnit type." + " Actual: " + this.printFullName()); - return null; } - // Am I a numeric with SIUnit type (e.g., "km/h") + /** + * Am I a numeric with SIUnit type (e.g., {@code "[km/h]"}) + */ public boolean isNumericWithSIUnitType() { return false; } public SymTypeOfNumericWithSIUnit asNumericWithSIUnitType() { - Log.error("0xFDAAD internal error: " + throw new UnsupportedOperationException("0xFDAAD internal error: " + "tried to convert non-numeric-with-SIUnit type " + "to a numeric-with-SIUnit type." + " Actual: " + this.printFullName()); - return null; } /** @@ -237,10 +230,9 @@ public boolean isTupleType() { } public SymTypeOfTuple asTupleType() { - Log.error("0xFDAAE internal error: " + throw new UnsupportedOperationException("0xFDAAE internal error: " + "tried to convert non-tuple-type to a tuple type." + " Actual: " + this.printFullName()); - return null; } /** @@ -251,24 +243,22 @@ public boolean isUnionType() { } public SymTypeOfUnion asUnionType() { - Log.error("0xFDAA8 internal error: " + throw new UnsupportedOperationException("0xFDAA8 internal error: " + "tried to convert non-union-type to a union-type." + " Actual: " + this.printFullName()); - return null; } /** - * Am I an intersection type (e.g. "(A&B)") + * Am I an intersection type (e.g. {@code "(A&B)"}) */ public boolean isIntersectionType() { return false; } public SymTypeOfIntersection asIntersectionType() { - Log.error("0xFDAA9 internal error: " + throw new UnsupportedOperationException("0xFDAA9 internal error: " + "tried to convert non-intersection-type to an intersection-type." + " Actual: " + this.printFullName()); - return null; } /** @@ -279,10 +269,9 @@ public boolean isObscureType() { } public SymTypeObscure asObscureType() { - Log.error("0xFDAAA internal error: " + throw new UnsupportedOperationException("0xFDAAA internal error: " + "tried to convert non-obscure-type to an obscure-type." + " Actual: " + this.printFullName()); - return null; } /** @@ -293,10 +282,9 @@ public boolean isWildcard() { } public SymTypeOfWildcard asWildcard() { - Log.error("0xFDAAB internal error: " + throw new UnsupportedOperationException("0xFDAAB internal error: " + "tried to convert non-wildcard-type to a wildcard-type." + " Actual: " + this.printFullName()); - return null; } public SymTypeExpression deepClone() { @@ -305,10 +293,15 @@ public SymTypeExpression deepClone() { public abstract boolean deepEquals(SymTypeExpression sym); - @Deprecated + @Override + public int compareTo(SymTypeExpression o) { + return SymTypeExpressionComparator.compareSymTypeExpressions(this, o); + } + + @Deprecated(forRemoval = true) protected List functionList = new ArrayList<>(); -@Deprecated +@Deprecated(forRemoval = true) public List getMethodList(String methodName, boolean abstractTc) { return getMethodList(methodName, abstractTc, AccessModifier.ALL_INCLUSION); } @@ -317,7 +310,10 @@ public List getMethodList(String methodName, boolean abstractTc) * returns the list of methods the SymTypeExpression can access and * filters these for a method with specific name * the last calculated type in the type check was no type + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} */ + @Deprecated(forRemoval = true) public List getMethodList(String methodname, boolean abstractTc, AccessModifier modifier){ functionList.clear(); //get methods from the typesymbol @@ -325,7 +321,7 @@ public List getMethodList(String methodname, boolean abstractTc, return transformMethodList(methodname,methods); } -@Deprecated +@Deprecated(forRemoval = true) public List getCorrectMethods(String methodName, boolean outerIsType, boolean abstractTc) { return getCorrectMethods(methodName, outerIsType, abstractTc, AccessModifier.ALL_INCLUSION); } @@ -342,8 +338,11 @@ public List getCorrectMethods(String methodName, boolean outerIs * false if it was an instance * @param abstractTc true if the tc is not used for object-oriented languages * @return the correct methods for the specific case + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} */ - protected List getCorrectMethods(String methodName, + @Deprecated(forRemoval = true) + protected List getCorrectMethods(String methodName, boolean outerIsType, boolean abstractTc, AccessModifier modifier){ if(!abstractTc) { List functions = getTypeInfo().getSpannedScope() @@ -388,7 +387,10 @@ protected List getCorrectMethods(String methodName, * @param methodName name of the method we search for * @param functions methods that need to be transformed * @return transformed methods + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} */ + @Deprecated(forRemoval = true) protected List transformMethodList(String methodName, List functions){ List matchingMethods = new ArrayList<>(); for(FunctionSymbol method: functions){ @@ -420,7 +422,7 @@ protected List transformMethodList(String methodName, List typeVariableArguments = getTypeInfo().getTypeParameterList(); - Map map = new HashMap<>(); + Map map = new LinkedHashMap<>(); if(arguments.size()!=typeVariableArguments.size()){ Log.error("0xA1300 Different number of type arguments in TypeSymbol and SymTypeExpression"); } @@ -468,11 +470,15 @@ protected List transformMethodList(String methodName, List replaceMap){ //empty so it only needs to be overridden by some SymTypeExpressions } -@Deprecated +@Deprecated(forRemoval = true) public List getMethodList(String methodName, boolean outerIsType, boolean abstractTc) { return getMethodList(methodName, outerIsType, abstractTc, AccessModifier.ALL_INCLUSION); } @@ -485,7 +491,10 @@ public List getMethodList(String methodName, boolean outerIsType * @param outerIsType true if the last result was a type, false * if it was an instance * @return the correct methods for the specific case + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} */ + @Deprecated(forRemoval = true) public List getMethodList(String methodName, boolean outerIsType, boolean abstractTc, AccessModifier modifier) { functionList.clear(); @@ -494,7 +503,7 @@ public List getMethodList(String methodName, return transformMethodList(methodName,methods); } -@Deprecated +@Deprecated(forRemoval = true) public List getFieldList(String fieldName, boolean abstractTc){ return getFieldList(fieldName, abstractTc, AccessModifier.ALL_INCLUSION); } @@ -502,14 +511,17 @@ public List getFieldList(String fieldName, boolean abstractTc){ /** * returns the list of fields the SymTypeExpression can access * and filters these for a field with specific name + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} */ + @Deprecated(forRemoval = true) public List getFieldList(String fieldName, boolean abstractTc, AccessModifier modifier){ //get methods from the typesymbol List fields = getCorrectFields(fieldName,false, abstractTc, modifier); return transformFieldList(fieldName,fields); } -@Deprecated +@Deprecated(forRemoval = true) public List getFieldList(String fieldName, boolean outerIsType, boolean abstractTc){ return getFieldList(fieldName, outerIsType, abstractTc, AccessModifier.ALL_INCLUSION); } @@ -522,15 +534,18 @@ public List getFieldList(String fieldName, boolean outerIsType, * @param outerIsType true if the last result was a type, * false if it was an instance * @return the correct fields for the specific case + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} */ - public List getFieldList(String fieldName, + @Deprecated(forRemoval = true) + public List getFieldList(String fieldName, boolean outerIsType, boolean abstractTc, AccessModifier modifier) { List fields = getCorrectFields(fieldName, outerIsType, abstractTc, modifier); return transformFieldList(fieldName,fields); } - @Deprecated + @Deprecated(forRemoval = true) public List getCorrectFields(String fieldName, boolean outerIsType, boolean abstractTc){ return getCorrectFields(fieldName, outerIsType, abstractTc, AccessModifier.ALL_INCLUSION); } @@ -546,8 +561,11 @@ public List getCorrectFields(String fieldName, boolean outerIsTy * @param outerIsType true if last result of type check was type, * false if it was an instance * @return the correct fields for the specific case + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} */ - protected List getCorrectFields(String fieldName, + @Deprecated(forRemoval = true) + protected List getCorrectFields(String fieldName, boolean outerIsType, boolean abstractTc, AccessModifier modifier) { if(!abstractTc) { List variables = getTypeInfo().getSpannedScope() @@ -591,8 +609,11 @@ protected List getCorrectFields(String fieldName, * @param fieldName name of the field we search for * @param fields fields that need to be transformed * @return transformed fields + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} */ - protected List transformFieldList(String fieldName, + @Deprecated(forRemoval = true) + protected List transformFieldList(String fieldName, List fields) { List fieldList = new ArrayList<>(); //filter fields @@ -610,7 +631,7 @@ protected List transformFieldList(String fieldName, ((SymTypeOfGenerics)this.deepClone()).getArgumentList(); List typeVariableArguments = getTypeInfo().getTypeParameterList(); - Map map = new HashMap<>(); + Map map = new LinkedHashMap<>(); if(arguments.size()!=typeVariableArguments.size()){ Log.error("0xA1301 Different number of type arguments in TypeSymbol and SymTypeExpression"); } @@ -644,7 +665,7 @@ protected List transformFieldList(String fieldName, * @deprecated TypeSymbols are to be found in the corresponding subclasses, * however, not every subclass will have a type symbol */ - @Deprecated + @Deprecated(forRemoval = true) protected TypeSymbol typeSymbol; /** @@ -673,11 +694,11 @@ public TypeSymbol getTypeInfo() { if(typeSymbol != null) { return typeSymbol; } - Log.error("0xFDFDF internal error: getTypeInfo called," - + "but no typeinfo available. Presumably hasTypeInfo() missing?" + throw new UnsupportedOperationException( + "0xFDFDF internal error: getTypeInfo called" + + ", but no typeinfo available. Presumably hasTypeInfo() missing?" + " Type: " + printFullName() ); - return null; } protected SymTypeSourceInfo sourceInfo = new SymTypeSourceInfo(); diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeExpressionFactory.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeExpressionFactory.java index d1b2cfec36..01b957dd65 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeExpressionFactory.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeExpressionFactory.java @@ -37,9 +37,10 @@ public class SymTypeExpressionFactory { /** * createTypeVariable vor Variables - * @deprecated -> create a symbol and use it to create a SymTypeVariable + * @deprecated create a symbol and use it to create a SymTypeVariable + * {@link #createTypeVariable(TypeVarSymbol)} */ - @Deprecated + @Deprecated(forRemoval = true) public static SymTypeVariable createTypeVariable(String name, IBasicSymbolsScope scope) { TypeVarSymbol typeSymbol = new TypeVarSymbol(name); typeSymbol.setEnclosingScope(scope); @@ -50,7 +51,10 @@ public static SymTypeVariable createTypeVariable(TypeVarSymbol typeVarSymbol) { return new SymTypeVariable(typeVarSymbol); } - @Deprecated + /** + * @deprecated ALWAYS use TypeVarSymbols to create TypeVariables + */ + @Deprecated(forRemoval = true) public static SymTypeVariable createTypeVariable(TypeSymbol typeSymbol) { return new SymTypeVariable(typeSymbol); } @@ -131,9 +135,27 @@ public static SymTypeOfObject createTypeObject(TypeSymbol typeSymbol) { } /** - * for ObjectTypes, as e.g. "Person" + * @deprecated did hide the usage of surrogate, and leads to questionable code + * consider using + * {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver#resolveType(IBasicSymbolsScope, String)}, + * of creating a Surrogate explicitly (only if required) */ + @Deprecated(forRemoval = true) public static SymTypeOfObject createTypeObject(String name, IBasicSymbolsScope enclosingScope) { + return createTypeObjectViaSurrogate(name, enclosingScope); + } + + /** + * Warn: most of the time, you don't want this, as Surrogates should be avoided + * creates a TypeSymbolSurrogate + * and a SymTypeOfObject based on the surrogate + * @deprecated most current usages are wrong and have to be changed in the future! + * Currently considered to be removed, + * unless this functionality is required often enough + * (alternative: explicitly create a Surrogate and call {@link #createTypeObject(TypeSymbol)}) + */ + @Deprecated + public static SymTypeOfObject createTypeObjectViaSurrogate(String name, IBasicSymbolsScope enclosingScope) { TypeSymbol typeSymbol = new TypeSymbolSurrogate(name); typeSymbol.setEnclosingScope(enclosingScope); return new SymTypeOfObject(typeSymbol); @@ -168,14 +190,14 @@ public static SymTypeOfNull createTypeOfNull() { /** * creates an array-Type Expression - * @deprecated arrays do not have an type symbol * @param typeSymbol * @param dim the dimension of the array * @param argument the argument type (of the elements) * @return * @deprecated arrays do not have a type symbol + * use {@link #createTypeArray(SymTypeExpression, int)} */ - @Deprecated + @Deprecated(forRemoval = true) public static SymTypeArray createTypeArray(TypeSymbol typeSymbol, int dim, SymTypeExpression argument) { return new SymTypeArray(typeSymbol, dim, argument); @@ -183,8 +205,9 @@ public static SymTypeArray createTypeArray(TypeSymbol typeSymbol, int dim, /** * @deprecated arrays do not have a name + * use {@link #createTypeArray(SymTypeExpression, int)} */ - @Deprecated + @Deprecated(forRemoval = true) public static SymTypeArray createTypeArray(String name, IBasicSymbolsScope typeSymbolsScope, int dim, SymTypeExpression argument) { TypeSymbol typeSymbol = new TypeSymbolSurrogate(name); @@ -196,6 +219,15 @@ public static SymTypeArray createTypeArray(SymTypeExpression argument, int dim) return new SymTypeArray(argument, dim); } + /** + * @deprecated misused all the time, bad name; + * More often than not, one does not create a SymTypeExpression + * based solely on a symbol, consider either using + * {@link de.monticore.types3.TypeCheck3#symTypeFromAST(de.monticore.types.mcbasictypes._ast.ASTMCType)}, + * {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver#resolveType(IBasicSymbolsScope, String)}, + * or any other method in this class. + */ + @Deprecated(forRemoval = true) public static SymTypeExpression createTypeExpression(TypeSymbol typeSymbol) { SymTypeExpression o; if(PRIMITIVE_LIST.contains(typeSymbol.getName())){ @@ -207,7 +239,7 @@ public static SymTypeExpression createTypeExpression(TypeSymbol typeSymbol) { } else if (typeSymbol.getTypeParameterList().isEmpty()) { o = createTypeObject(typeSymbol); } else { - o = createGenerics(typeSymbol); + o = createGenericsDeclaredType(typeSymbol); } return o; } @@ -222,7 +254,7 @@ public static SymTypeExpression createTypeExpression(TypeSymbol typeSymbol) { * @deprecated use TypeCheck to get SymTypeExpressions from MCTypes, * this method is rather incorrect/incomplete */ - @Deprecated + @Deprecated(forRemoval = true) public static SymTypeExpression createTypeExpression(String name, IBasicSymbolsScope scope) { SymTypeExpression o; if ("void".equals(name)) { @@ -238,11 +270,12 @@ public static SymTypeExpression createTypeExpression(String name, IBasicSymbolsS } else if (scope!=null && scope.resolveTypeVar(name).isPresent()){ o = createTypeVariable(name, scope); }else { - o = createTypeObject(name, scope); + o = createTypeObjectViaSurrogate(name, scope); } return o; } + @Deprecated(forRemoval = true) protected static SymTypeExpression createArrayFromString(String type, IBasicSymbolsScope scope){ //berechne Typen vom Array per createTypeExpression, berechne Dimension von Array durch Anzahl der Klammerpaare am Ende int countDim = 0; @@ -262,6 +295,7 @@ protected static SymTypeExpression createArrayFromString(String type, IBasicSymb return createTypeArray(typeWithoutGenericsAndBraces, scope, countDim, createTypeExpression(typeWithoutBraces, scope)); } + @Deprecated(forRemoval = true) protected static SymTypeExpression createGenericsFromString(String type, IBasicSymbolsScope scope) { int start = type.indexOf("<"); if (start == -1) { @@ -278,6 +312,7 @@ protected static SymTypeExpression createGenericsFromString(String type, IBasicS * If that method for example received {@code Map>} this Method should get {@code [String, List]} as parameter * @param inBrackets list of generics nested one level */ + @Deprecated(forRemoval = true) protected static List getSubGenerics(List inBrackets, IBasicSymbolsScope scope){ return inBrackets.stream() .map(String::trim) @@ -287,10 +322,11 @@ protected static List getSubGenerics(List inBrackets, /** * splits the type-string along commas, but only on such that are on the first depth of generics - * @param type type-string, like {@code Map>} + * @param type type-string, like {@code Map>} * @param start first occurrence of an opening generic - * @return all first sub-generics as a list, like {@code [Double; HashMap]} + * @return all first sub-generics as a list, like {@code [Double; LinkedHashMap]} */ + @Deprecated(forRemoval = true) protected static List iterateBrackets(String type, int start){ List list = new ArrayList<>(); int depth = 0; @@ -310,21 +346,30 @@ protected static List iterateBrackets(String type, int start){ return list; } - - /** - * createGenerics: for a generic Type + * Hint: this is usually(!) not what you want, + * s.a. {@link #createGenerics(TypeSymbol, List)} * - * @return + * @return the declared type, e.g., {@code Map}, + * with K and V being (bound) TypeVariables */ - public static SymTypeOfGenerics createGenerics(TypeSymbol typeSymbol) { + public static SymTypeOfGenerics createGenericsDeclaredType(TypeSymbol typeSymbol) { List parameters = typeSymbol.getTypeParameterList().stream() - .map(tp -> createFromSymbol(tp)) + .map(tp -> createTypeVariable(tp)) .collect(Collectors.toList()); return createGenerics(typeSymbol, parameters); } + /** + * @deprecated bad name, tends to be misused, + * s.a. {@link #createGenericsDeclaredType(TypeSymbol)} + */ + @Deprecated(forRemoval = true) + public static SymTypeOfGenerics createGenerics(TypeSymbol typeSymbol) { + return createGenericsDeclaredType(typeSymbol); + } + public static SymTypeOfGenerics createGenerics(TypeSymbol typeSymbol, List arguments) { return new SymTypeOfGenerics(typeSymbol, arguments); @@ -337,11 +382,17 @@ public static SymTypeOfGenerics createGenerics(TypeSymbol typeSymbol, /** * createGenerics: is created using the enclosing Scope to ask for the appropriate symbol. + * @deprecated hides surrogate usage, see other `createGenerics`-methods */ + @Deprecated(forRemoval = true) public static SymTypeOfGenerics createGenerics(String name, IBasicSymbolsScope enclosingScope) { return createGenerics(name, enclosingScope, Lists.newArrayList()); } + /** + * @deprecated hides surrogate usage, see other `createGenerics`-methods + */ + @Deprecated(forRemoval = true) public static SymTypeOfGenerics createGenerics(String name, IBasicSymbolsScope enclosingScope, List arguments) { TypeSymbol typeSymbol = new TypeSymbolSurrogate(name); @@ -349,22 +400,33 @@ public static SymTypeOfGenerics createGenerics(String name, IBasicSymbolsScope e return createGenerics(typeSymbol, arguments); } + /** + * @deprecated hides surrogate usage, see other `createGenerics`-methods + */ + @Deprecated(forRemoval = true) public static SymTypeOfGenerics createGenerics(String name, IBasicSymbolsScope enclosingScope, SymTypeExpression... arguments) { return createGenerics(name, enclosingScope, Arrays.asList(arguments)); } + /** + * Warning: usually not what you want, except when resolving, + * consider using + * {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver#resolveType(IBasicSymbolsScope, String)}, + * {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver#resolveType(SymTypeExpression, String, de.monticore.symboltable.modifiers.AccessModifier, java.util.function.Predicate)}, + * or other methods of this class + * whenever appropriate + */ public static SymTypeExpression createFromSymbol(TypeSymbol typeSymbol) { - IBasicSymbolsTypeDispatcher typeDispatcher = - BasicSymbolsMill.typeDispatcher(); - if(typeDispatcher.isBasicSymbolsTypeVar(typeSymbol)) { + // TODO: use TypeDispatcher as soon as it is fixed + if(typeSymbol instanceof TypeVarSymbol) { return createTypeVariable((TypeVarSymbol) typeSymbol); } if(typeSymbol.getSpannedScope().getLocalTypeVarSymbols().isEmpty()) { return createTypeObject(typeSymbol); } else { - return createGenerics(typeSymbol); + return createGenericsDeclaredType(typeSymbol); } } diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeInferenceVariable.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeInferenceVariable.java index 5308b677be..2e7e72d6cf 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeInferenceVariable.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeInferenceVariable.java @@ -3,6 +3,7 @@ import de.monticore.types3.ISymTypeVisitor; import de.se_rwth.commons.logging.Log; +import com.google.common.base.Preconditions; import java.util.concurrent.atomic.AtomicInteger; @@ -31,9 +32,9 @@ public SymTypeInferenceVariable( SymTypeExpression upperBound ) { this.id = getUniqueID(); - this.idStr = Log.errorIfNull(idStr); - this.lowerBound = Log.errorIfNull(lowerBound); - this.upperBound = Log.errorIfNull(upperBound); + this.idStr = Preconditions.checkNotNull(idStr); + this.lowerBound = Preconditions.checkNotNull(lowerBound); + this.upperBound = Preconditions.checkNotNull(upperBound); } /** @@ -46,9 +47,9 @@ public SymTypeInferenceVariable( SymTypeExpression upperBound ) { this.id = id; - this.idStr = Log.errorIfNull(idStr); - this.lowerBound = Log.errorIfNull(lowerBound); - this.upperBound = Log.errorIfNull(upperBound); + this.idStr = Preconditions.checkNotNull(idStr); + this.lowerBound = Preconditions.checkNotNull(lowerBound); + this.upperBound = Preconditions.checkNotNull(upperBound); } public SymTypeExpression getLowerBound() { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfFunction.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfFunction.java index 68765ef87d..7c2a53a25d 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfFunction.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfFunction.java @@ -1,6 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; @@ -10,7 +11,6 @@ import de.monticore.types3.generics.TypeParameterRelations; import de.monticore.types3.generics.bounds.Bound; import de.monticore.types3.generics.util.BoundResolution; -import de.monticore.types3.util.SymTypeExpressionComparator; import de.se_rwth.commons.logging.Log; import java.util.ArrayList; @@ -32,14 +32,14 @@ /** * SymTypeOfFunction stores any kind of Function, - * such as List::get, obj::getX, i -> i + 2 + * such as {@code List::get}, {@code obj::getX}, {@code i -> i + 2} */ public class SymTypeOfFunction extends SymTypeExpression { /** * @deprecated only required for the deprecated type symbol */ - @Deprecated + @Deprecated(forRemoval = true) public static final String TYPESYMBOL_NAME = "function"; /** @@ -76,6 +76,8 @@ public SymTypeOfFunction( SymTypeExpression returnType, List argumentTypes, boolean elliptic) { + Preconditions.checkNotNull(returnType); + Preconditions.checkNotNull(argumentTypes); super.typeSymbol = new TypeSymbol(TYPESYMBOL_NAME); super.typeSymbol.setEnclosingScope(BasicSymbolsMill.scope()); super.typeSymbol.setSpannedScope(BasicSymbolsMill.scope()); @@ -88,7 +90,7 @@ public SymTypeOfFunction( /** * @deprecated the other constructor is to be used */ - @Deprecated + @Deprecated(forRemoval = true) public SymTypeOfFunction(SymTypeExpression returnType, List argumentTypes, boolean elliptic) { this(null, returnType, argumentTypes, elliptic); @@ -178,7 +180,7 @@ public FunctionSymbol getSymbol() { /** * returns whether the specified amount of arguments can be accepted - * E.g., (P, int...) -> int can accept 1,2,3,... arguments, but not 0 + * E.g., {@code (P, int...) -> int} can accept 1,2,3,... arguments, but not 0 */ public boolean canHaveArity(int arity) { return ((isElliptic() && sizeArgumentTypes() - 1 <= arity) @@ -187,7 +189,7 @@ public boolean canHaveArity(int arity) { /** * returns a clone, with the arity fixed to the specified number - * E.g., (P, int...) -> int with arity of 3 is (P, int, int) -> int + * E.g., {@code (P, int...) -> int} with arity of 3 is {@code (P, int, int) -> int} */ public SymTypeOfFunction getWithFixedArity(int arity) { SymTypeOfFunction clone = (SymTypeOfFunction) deepClone(); @@ -220,24 +222,22 @@ public SymTypeOfFunction getDeclaredType() { protected Map getTypeVariableReplaceMap() { - Map replaceMap = - new TreeMap<>(new SymTypeExpressionComparator()); + Map replaceMap = new TreeMap<>(); if (hasSymbol()) { // skolem variables: List infVars = TypeParameterRelations.getIncludedInferenceVariables(this); Map infVar2Skolem = - new TreeMap<>(new SymTypeExpressionComparator()); + new TreeMap<>(); for (SymTypeInferenceVariable infVar : infVars) { infVar2Skolem.put(infVar, - SymTypeExpressionFactory.createTypeObject( + SymTypeExpressionFactory.createTypeObjectViaSurrogate( "Skolem#" + infVar.print(), BasicSymbolsMill.scope() ) ); } - Map skolem2infVar = - new TreeMap<>(new SymTypeExpressionComparator()); + Map skolem2infVar = new TreeMap<>(); infVar2Skolem.forEach((k, v) -> skolem2infVar.put(v, k)); SymTypeOfFunction thisWithSkolems = TypeParameterRelations .replaceInferenceVariables(this, infVar2Skolem) @@ -250,8 +250,7 @@ protected Map getTypeVariableReplaceMap() { = TypeParameterRelations.getFreeVariableReplaceMap( declType, BasicSymbolsMill.scope() ); - Map freeVar2TypePar = - new TreeMap<>(new SymTypeExpressionComparator()); + Map freeVar2TypePar = new TreeMap<>(); typePar2FreeVar.forEach((k, v) -> freeVar2TypePar.put(v, k)); SymTypeOfFunction declTypeWithFreeVars = TypeParameterRelations .replaceTypeVariables(declType, typePar2FreeVar) @@ -292,11 +291,11 @@ protected Map getTypeVariableReplaceMap() { /** * returns the type arguments for a generic function. - * E.g., given asList, which has the declared Type (T...) -> List - * and this is the instantiation (int, int) -> List, + * E.g., given asList, which has the declared Type {@code (T...) -> List} + * and this is the instantiation {@code (int, int) -> List}, * This will return the argument list [int]. *

- * Warning: if the instantiation is, e.g., (Person, Car) -> List, + * Warning: if the instantiation is, e.g., {@code (Person, Car) -> List}, * no correct list of arguments can be calculated. *

* Not to be confused with getArgumentTypes, diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfGenerics.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfGenerics.java index 963598afd3..cdc8b6c4c8 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfGenerics.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfGenerics.java @@ -1,6 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbolSurrogate; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; @@ -16,38 +17,38 @@ /** * SymTypeOfGenerics stores any kind of TypeConstructor applied - * to Arguments, such as Map< int,Person > - * List, List< Set< List< a >>>. + * to Arguments, such as {@code Map< int,Person >} + * {@code List, List< Set< List< a >>>}. * This subsumes all kinds of generic Types from several of the * MC-Type grammars. */ public class SymTypeOfGenerics extends SymTypeExpression { /** - * Map for unboxing generic types (e.g. "java.util.Collection" -> "Collection") + * Map for unboxing generic types (e.g. {@code "java.util.Collection" -> "Collection"}) */ - @Deprecated + @Deprecated(forRemoval = true) public static final Map unboxMap; /** - * Map for boxing generic types (e.g. "Collection" -> "java.util.Collection") + * Map for boxing generic types (e.g. {@code "Collection" -> "java.util.Collection"}) * Results are fully qualified. */ - @Deprecated + @Deprecated(forRemoval = true) public static final Map boxMap; /** * initializing the maps */ static { - Map unboxMap_temp = new HashMap(); + Map unboxMap_temp = new LinkedHashMap(); unboxMap_temp.put("java.util.Optional", "Optional"); unboxMap_temp.put("java.util.Set", "Set"); unboxMap_temp.put("java.util.List", "List"); unboxMap_temp.put("java.util.Map","Map"); unboxMap = Collections.unmodifiableMap(unboxMap_temp); - Map boxMap_temp = new HashMap(); + Map boxMap_temp = new LinkedHashMap(); boxMap_temp.put("Optional", "java.util.Optional"); boxMap_temp.put("Set", "java.util.Set"); boxMap_temp.put("List", "java.util.List"); @@ -56,13 +57,13 @@ public class SymTypeOfGenerics extends SymTypeExpression { } /** - * unboxing generic types (e.g. "java.util.Collection" -> "Collection"). + * unboxing generic types (e.g. {@code "java.util.Collection" -> "Collection"}). * otherwise return is unchanged * @deprecated use SymTypeUnboxingVisitor * @param type * @return */ - @Deprecated + @Deprecated(forRemoval = true) public static String unbox(SymTypeOfGenerics type){ List arguments = type.getArgumentList(); StringBuilder r = new StringBuilder().append('<'); @@ -78,23 +79,23 @@ public static String unbox(SymTypeOfGenerics type){ } } r.append(">"); - if (unboxMap.containsKey(type.printTypeWithoutTypeArgument())) { - return unboxMap.get(type.printTypeWithoutTypeArgument()) + r.toString(); + if (unboxMap.containsKey(type.getTypeConstructorFullName())) { + return unboxMap.get(type.getTypeConstructorFullName()) + r.toString(); } else { - return type.printTypeWithoutTypeArgument() + r.toString(); + return type.getTypeConstructorFullName() + r.toString(); } } /** - * Boxing generic types (e.g. "Collection" -> "java.util.Collection") + * Boxing generic types (e.g. {@code "Collection" -> "java.util.Collection"}) * Results are fully qualified. * Otherwise return is unchanged * @deprecated use SymtypeBoxingVisitor * @param type * @return */ - @Deprecated + @Deprecated(forRemoval = true) public static String box(SymTypeOfGenerics type){ List arguments = type.getArgumentList(); StringBuilder r = new StringBuilder().append('<'); @@ -110,11 +111,11 @@ public static String box(SymTypeOfGenerics type){ } } r.append(">"); - if (boxMap.containsKey(type.printTypeWithoutTypeArgument())) { - return boxMap.get(type.printTypeWithoutTypeArgument()) + r.toString(); + if (boxMap.containsKey(type.getTypeConstructorFullName())) { + return boxMap.get(type.getTypeConstructorFullName()) + r.toString(); } else { - return type.printTypeWithoutTypeArgument() + r.toString(); + return type.getTypeConstructorFullName() + r.toString(); } } @@ -129,7 +130,7 @@ public static String box(SymTypeOfGenerics type){ * @deprecated use SymTypeExpressionFactory * The Factory then uses the constructor below */ - @Deprecated + @Deprecated(forRemoval = true) public SymTypeOfGenerics(TypeSymbol typeSymbol) { this(typeSymbol, new LinkedList<>()); } @@ -138,8 +139,8 @@ public SymTypeOfGenerics(TypeSymbol typeSymbol) { * Constructor with all parameters that are stored: */ public SymTypeOfGenerics(TypeSymbol typeSymbol, List arguments) { - this.typeSymbol = typeSymbol; - this.arguments = arguments; + this.typeSymbol = Preconditions.checkNotNull(typeSymbol); + this.arguments = Preconditions.checkNotNull(arguments); } @Override @@ -158,16 +159,18 @@ public String getTypeConstructorFullName() { /** * @deprecated same as the the other 2 methods even in spec? + * use {@link #getTypeConstructorFullName()} */ - @Deprecated + @Deprecated(forRemoval = true) public String printTypeWithoutTypeArgument(){ - return this.getFullName(); + return getTypeConstructorFullName(); } /** * @deprecated same as the the other 2 methods even in spec? + * use {@link #getTypeConstructorFullName()} */ - @Deprecated + @Deprecated(forRemoval = true) public String getFullName() { return getTypeConstructorFullName(); } @@ -175,8 +178,10 @@ public String getFullName() { /** * getBaseName: get the unqualified Name (no ., no Package) * @deprecated unused outside of tests, but not required for tests + * use {@link de.se_rwth.commons.Names} instead, + * or {@code getTypeInfo().getName()} */ - @Deprecated + @Deprecated(forRemoval = true) public String getBaseName() { String[] parts = getTypeConstructorFullName().split("\\."); return parts[parts.length - 1]; @@ -197,10 +202,7 @@ public boolean deepEqualsWithoutArguments(SymTypeExpression sym) { return false; } SymTypeOfGenerics symGen = (SymTypeOfGenerics) sym; - if(!this.typeSymbol.getEnclosingScope().equals(symGen.typeSymbol.getEnclosingScope())){ - return false; - } - if(!this.typeSymbol.getName().equals(symGen.typeSymbol.getName())){ + if (!this.getTypeInfo().equals(symGen.getTypeInfo())) { return false; } return true; @@ -228,7 +230,7 @@ public boolean deepEquals(SymTypeExpression sym){ /** * returns the declared type, - * e.g., for List, this will return List where T is a type variable. + * e.g., for {@code List}, this will return {@code List} where T is a type variable. */ public SymTypeOfGenerics getDeclaredType() { List typeParams = getTypeInfo().getTypeParameterList() @@ -240,8 +242,8 @@ public SymTypeOfGenerics getDeclaredType() { public Map getTypeVariableReplaceMap() { List typeVars = getTypeInfo().getTypeParameterList(); List arguments = getArgumentList(); - Map replaceMap = new HashMap<>(); - // empty List, e.g. new HashMap<>(); + Map replaceMap = new LinkedHashMap<>(); + // empty List, e.g. new LinkedHashMap<>(); if (arguments.size() == 0) { // no-op } @@ -267,6 +269,11 @@ else if (arguments.size() != typeVars.size()) { return replaceMap; } + /** + * @deprecated use {@link de.monticore.types3.util.WithinTypeBasicSymbolsResolver} + * or {@link de.monticore.types3.util.WithinScopeBasicSymbolsResolver} + */ + @Deprecated(forRemoval = true) @Override public void replaceTypeVariables(Map replaceMap) { for(int i = 0; i intersectedTypes; public SymTypeOfIntersection(Collection types) { - this.intersectedTypes = new HashSet<>(); + Preconditions.checkNotNull(types); + this.intersectedTypes = new LinkedHashSet<>(); this.intersectedTypes.addAll(types); } - @Override - public boolean isValidType() { - return streamIntersectedTypes().allMatch(SymTypeExpression::isValidType); - } - @Override public boolean isIntersectionType() { return true; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfIntersectionDeSer.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfIntersectionDeSer.java index d5c8477673..42db49ecdd 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfIntersectionDeSer.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfIntersectionDeSer.java @@ -8,7 +8,7 @@ import de.monticore.symboltable.serialization.json.JsonObject; import de.se_rwth.commons.logging.Log; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; public class SymTypeOfIntersectionDeSer { @@ -48,7 +48,7 @@ public SymTypeOfIntersection deserialize(JsonObject serialized, IBasicSymbolsSco if (serialized.hasMember(SERIALIZED_TYPES)) { List intersectedTypesList = SymTypeExpressionDeSer.deserializeListMember(SERIALIZED_TYPES, serialized, enclosingScope); - return SymTypeExpressionFactory.createIntersection(new HashSet<>(intersectedTypesList)); + return SymTypeExpressionFactory.createIntersection(new LinkedHashSet<>(intersectedTypesList)); } Log.error( "0x9E2F7 Internal error: Loading ill-structured SymTab: missing " diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfNumericWithSIUnit.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfNumericWithSIUnit.java index 4c53ea626b..9d5a3097cc 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfNumericWithSIUnit.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfNumericWithSIUnit.java @@ -2,6 +2,7 @@ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.types3.ISymTypeVisitor; import de.se_rwth.commons.logging.Log; @@ -20,8 +21,8 @@ public SymTypeOfNumericWithSIUnit( SymTypeOfSIUnit siUnitType, SymTypeExpression numericType ) { - this.siUnitType = Log.errorIfNull(siUnitType); - this.numericType = Log.errorIfNull(numericType); + this.siUnitType = Preconditions.checkNotNull(siUnitType); + this.numericType = Preconditions.checkNotNull(numericType); } public SymTypeOfSIUnit getSIUnitType() { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfObject.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfObject.java index 6ca8ce7823..1bd0d40b18 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfObject.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfObject.java @@ -1,8 +1,10 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.types3.ISymTypeVisitor; +import de.se_rwth.commons.logging.Log; /** * An objectType is a full qualified class name. @@ -18,11 +20,13 @@ public class SymTypeOfObject extends SymTypeExpression { */ public SymTypeOfObject(TypeSymbol typeSymbol) { + Preconditions.checkNotNull(typeSymbol); this.typeSymbol = typeSymbol; } @Override public boolean hasTypeInfo() { + // should allways be true return typeSymbol != null; } @@ -36,7 +40,7 @@ public TypeSymbol getTypeInfo() { * one may add a getObjFullName() or similar if required * also, seems unused in our main projects */ - @Deprecated + @Deprecated(forRemoval = true) public String getObjName() { return typeSymbol.getFullName(); } @@ -44,7 +48,7 @@ public String getObjName() { /** * @deprecated unused in main projects */ - @Deprecated + @Deprecated(forRemoval = true) public void setObjName(String objname) { this.typeSymbol.setName(objname); } @@ -52,8 +56,10 @@ public void setObjName(String objname) { /** * getBaseName: get the unqualified Name (no ., no Package) * @deprecated unused outside of tests, but not required for tests + * use {@link de.se_rwth.commons.Names} instead, + * or {@code getTypeInfo().getName()} */ - @Deprecated + @Deprecated(forRemoval = true) public String getBaseName() { String[] parts = getObjName().split("\\."); return parts[parts.length - 1]; @@ -73,13 +79,7 @@ public boolean deepEquals(SymTypeExpression sym){ return false; } SymTypeOfObject symCon = (SymTypeOfObject) sym; - if(this.typeSymbol == null ||symCon.typeSymbol ==null){ - return false; - } - if(!this.typeSymbol.getEnclosingScope().equals(symCon.typeSymbol.getEnclosingScope())){ - return false; - } - if(!this.typeSymbol.getName().equals(symCon.typeSymbol.getName())){ + if (!this.getTypeInfo().equals(symCon.getTypeInfo())) { return false; } return true; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfObjectDeSer.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfObjectDeSer.java index e34cea73ee..e9b1406717 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfObjectDeSer.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfObjectDeSer.java @@ -20,7 +20,7 @@ public String serialize(SymTypeOfObject toSerialize) { JsonPrinter jp = new JsonPrinter(); jp.beginObject(); jp.member(JsonDeSers.KIND, SERIALIZED_KIND); - jp.member(SERIALIZED_OBJNAME, toSerialize.getObjName()); + jp.member(SERIALIZED_OBJNAME, toSerialize.printFullName()); jp.endObject(); return jp.getContent(); } diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfRegEx.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfRegEx.java index 331ecc4e06..84d3ab02e2 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfRegEx.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfRegEx.java @@ -1,14 +1,16 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.types3.ISymTypeVisitor; +import de.se_rwth.commons.logging.Log; public class SymTypeOfRegEx extends SymTypeExpression { protected String regex; public SymTypeOfRegEx(String regex) { - this.regex = regex; + this.regex = Preconditions.checkNotNull(regex); } public String getRegExString() { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfSIUnit.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfSIUnit.java index 33770d25a8..e8c235e192 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfSIUnit.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfSIUnit.java @@ -1,8 +1,8 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.types3.ISymTypeVisitor; - import java.util.ArrayList; import java.util.List; @@ -19,6 +19,8 @@ public SymTypeOfSIUnit( List numerator, List denominator ) { + Preconditions.checkNotNull(numerator); + Preconditions.checkNotNull(denominator); this.numerator = new ArrayList<>(numerator); this.denominator = new ArrayList<>(denominator); } diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfTuple.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfTuple.java index a70f12037d..90e8f18a5a 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfTuple.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfTuple.java @@ -1,6 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.types3.ISymTypeVisitor; import de.se_rwth.commons.logging.Log; @@ -23,7 +24,7 @@ public class SymTypeOfTuple extends SymTypeExpression { protected List types; public SymTypeOfTuple(List types) { - this.types = Log.errorIfNull(types); + this.types = Preconditions.checkNotNull(types); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfUnion.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfUnion.java index c65f46a208..5d269501b5 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfUnion.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfUnion.java @@ -1,12 +1,14 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.types3.ISymTypeVisitor; +import de.se_rwth.commons.logging.Log; import java.util.Collection; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Iterator; import java.util.Set; import java.util.Spliterator; @@ -25,18 +27,14 @@ public class SymTypeOfUnion extends SymTypeExpression { protected Set unionizedTypes; public SymTypeOfUnion(Collection types) { + Preconditions.checkNotNull(types); super.typeSymbol = new TypeSymbol(DEFAULT_TYPESYMBOL_NAME); super.typeSymbol.setEnclosingScope(BasicSymbolsMill.globalScope()); super.typeSymbol.setSpannedScope(BasicSymbolsMill.scope()); - this.unionizedTypes = new HashSet<>(); + this.unionizedTypes = new LinkedHashSet<>(); this.unionizedTypes.addAll(types); } - @Override - public boolean isValidType() { - return streamUnionizedTypes().allMatch(SymTypeExpression::isValidType); - } - @Override public boolean isUnionType() { return true; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfUnionDeSer.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfUnionDeSer.java index 784d2a8d8e..9de2b2af0e 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfUnionDeSer.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfUnionDeSer.java @@ -8,7 +8,7 @@ import de.monticore.symboltable.serialization.json.JsonObject; import de.se_rwth.commons.logging.Log; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; public class SymTypeOfUnionDeSer { @@ -49,7 +49,7 @@ public SymTypeOfUnion deserialize(JsonObject serialized, IBasicSymbolsScope encl List unionizedTypesList = SymTypeExpressionDeSer.deserializeListMember( SERIALIZED_TYPES, serialized, enclosingScope); - return SymTypeExpressionFactory.createUnion(new HashSet<>(unionizedTypesList)); + return SymTypeExpressionFactory.createUnion(new LinkedHashSet<>(unionizedTypesList)); } Log.error( "0x9E2F7 Internal error: Loading ill-structured SymTab: missing " diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfWildcard.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfWildcard.java index dfc3db404f..b267523b66 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfWildcard.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeOfWildcard.java @@ -14,7 +14,7 @@ public class SymTypeOfWildcard extends SymTypeExpression { * @deprecated use the Factory, * the Factory uses the constructor below */ - @Deprecated + @Deprecated(forRemoval = true) public SymTypeOfWildcard(){ } diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypePrimitive.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypePrimitive.java index 2f14bb11d7..15c43a2f71 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypePrimitive.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypePrimitive.java @@ -1,12 +1,14 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.types3.ISymTypeVisitor; +import de.se_rwth.commons.logging.Log; import java.util.Arrays; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Collections; @@ -16,11 +18,13 @@ public class SymTypePrimitive extends SymTypeExpression { protected TypeSymbol typeSymbol; public SymTypePrimitive(TypeSymbol typeSymbol) { + Preconditions.checkNotNull(typeSymbol); this.typeSymbol = typeSymbol; } @Override public boolean hasTypeInfo() { + // should always return true return typeSymbol != null; } @@ -33,6 +37,10 @@ public String getPrimitiveName() { return typeSymbol.getName(); } + /** + * @deprecated use {@link de.monticore.types3.SymTypeRelations#box(SymTypeExpression)} + */ + @Deprecated(forRemoval = true) public String getBoxedPrimitiveName() { return box(typeSymbol.getName()); } @@ -40,7 +48,7 @@ public String getBoxedPrimitiveName() { /** * @deprecated only used in 1 test ONCE... in our main projects */ - @Deprecated + @Deprecated(forRemoval = true) public String getBaseOfBoxedName() { String[] parts = box(typeSymbol.getName()).split("\\."); return parts[parts.length - 1]; @@ -49,7 +57,7 @@ public String getBaseOfBoxedName() { /** * @deprecated only used in tests in our main projects */ - @Deprecated + @Deprecated(forRemoval = true) public void setPrimitiveName(String constName){ typeSymbol.setName(constName); } @@ -59,7 +67,7 @@ public void setPrimitiveName(String constName){ * (on purpose not implemented as enum) * @deprecated cannot assume fixed set for all languages */ - @Deprecated + @Deprecated(forRemoval = true) public static final List primitiveTypes = Collections.unmodifiableList(Arrays.asList( BasicSymbolsMill.BOOLEAN, @@ -75,23 +83,23 @@ public void setPrimitiveName(String constName){ )); /** - * Map for unboxing const types (e.g. "java.lang.Boolean" -> "boolean") + * Map for unboxing const types (e.g. "java.lang.Boolean" -> "boolean") */ - @Deprecated + @Deprecated(forRemoval = true) public static final Map unboxMap; /** - * Map for boxing const types (e.g. "boolean" -> "java.lang.Boolean") + * Map for boxing const types (e.g. "boolean" -> "java.lang.Boolean") * Results are fully qualified. */ - @Deprecated + @Deprecated(forRemoval = true) public static final Map boxMap; /** * initializing the maps */ static { - Map unboxMap_temp = new HashMap(); + Map unboxMap_temp = new LinkedHashMap(); unboxMap_temp.put("java.lang.Boolean", "boolean"); unboxMap_temp.put("java.lang.Byte", "byte"); unboxMap_temp.put("java.lang.Character", "char"); @@ -112,7 +120,7 @@ public void setPrimitiveName(String constName){ unboxMap_temp.put("Double", "double"); unboxMap = Collections.unmodifiableMap(unboxMap_temp); - Map boxMap_temp = new HashMap(); + Map boxMap_temp = new LinkedHashMap(); boxMap_temp.put("boolean", "java.lang.Boolean"); boxMap_temp.put("byte", "java.lang.Byte"); boxMap_temp.put("char", "java.lang.Character"); @@ -127,13 +135,13 @@ public void setPrimitiveName(String constName){ } /** - * unboxing const types (e.g. "java.lang.Boolean" -> "boolean"). + * unboxing const types (e.g. {@code "java.lang.Boolean" -> "boolean"}). * otherwise return is unchanged - * @deprecated use SymTypeUnboxingVisitor + * @deprecated use SymTypeRelations * @param boxedName * @return */ - @Deprecated + @Deprecated(forRemoval = true) public static String unbox(String boxedName) { if (unboxMap.containsKey(boxedName)) return unboxMap.get(boxedName); @@ -142,14 +150,14 @@ public static String unbox(String boxedName) { } /** - * Boxing const types (e.g. "boolean" -> "java.lang.Boolean") + * Boxing const types (e.g. {@code "boolean" -> "java.lang.Boolean"}) * Results are fully qualified. * Otherwise return is unchanged - * @deprecated use SymTypeBoxingVisitor + * @deprecated use SymTypeRelations * @param unboxedName * @return */ - @Deprecated + @Deprecated(forRemoval = true) public static String box(String unboxedName) { if (boxMap.containsKey(unboxedName)) return boxMap.get(unboxedName); @@ -197,10 +205,10 @@ public boolean deepEquals(SymTypeExpression sym){ return false; } SymTypePrimitive symPrim = (SymTypePrimitive) sym; - if(!this.typeSymbol.getName().equals(symPrim.typeSymbol.getName())){ + if(!this.getTypeInfo().equals(symPrim.getTypeInfo())){ return false; } - return this.print().equals(symPrim.print()); + return true; } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeVariable.java b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeVariable.java index 30cecf7e9f..b23ceb5022 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeVariable.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SymTypeVariable.java @@ -1,13 +1,14 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.check; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; import de.monticore.types3.ISymTypeVisitor; import de.monticore.types3.SymTypeRelations; import de.se_rwth.commons.logging.Log; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Optional; import java.util.Set; @@ -18,10 +19,10 @@ public class SymTypeVariable extends SymTypeExpression { protected TypeVarSymbol typeVarSymbol; public SymTypeVariable(TypeVarSymbol typeSymbol) { - this.typeVarSymbol = Log.errorIfNull(typeSymbol); + this.typeVarSymbol = Preconditions.checkNotNull(typeSymbol); } - @Deprecated + @Deprecated(forRemoval = true) public SymTypeVariable(TypeSymbol typeSymbol) { this.typeSymbol = typeSymbol; if (typeSymbol instanceof TypeVarSymbol) { @@ -32,7 +33,7 @@ public SymTypeVariable(TypeSymbol typeSymbol) { /** * @deprecated (should) return true */ - @Deprecated + @Deprecated(forRemoval = true) public boolean hasTypeVarSymbol() { return typeVarSymbol != null; } @@ -151,7 +152,9 @@ public SymTypeVariable deepClone() { * Similar to deepEquals, but only checks * whether the variables are supposed to be the same variable. * E.g., bounds are ignored + * @deprecated leftover of old version, simply use deepEquals() instead. */ + @Deprecated(forRemoval = true) public boolean denotesSameVar(SymTypeExpression other) { if (!other.isTypeVariable()) { return false; @@ -201,7 +204,7 @@ public boolean deepEquals(SymTypeExpression sym) { return true; } SymTypeVariable symVar = (SymTypeVariable) sym; - if (!denotesSameVar(symVar)) { + if (!getTypeVarSymbol().equals(symVar.getTypeVarSymbol())) { return false; } return true; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeCompKindFromMCBasicTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeCompKindFromMCBasicTypes.java index f6764719d9..a304dc16f2 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeCompKindFromMCBasicTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeCompKindFromMCBasicTypes.java @@ -50,9 +50,6 @@ public void handle(@NonNull ASTMCQualifiedType node) { List comp = enclScope.resolveComponentTypeMany(node.getMCQualifiedName().getQName()); if (comp.isEmpty()) { - Log.error(String.format("0xD0104 Cannot resolve component '%s'", node.getMCQualifiedName().getQName()), - node.get_SourcePositionStart(), node.get_SourcePositionEnd() - ); this.resultWrapper.setResultAbsent(); } else { CompKindExpression result = new CompKindOfComponentType(comp.get(0)); diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeCompKindFromMCSimpleGenericTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeCompKindFromMCSimpleGenericTypes.java index 35d97dae21..ecbf75a2ad 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeCompKindFromMCSimpleGenericTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeCompKindFromMCSimpleGenericTypes.java @@ -5,18 +5,17 @@ import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; import de.monticore.symbols.compsymbols._symboltable.ICompSymbolsScope; import de.monticore.types.mcbasictypes._ast.ASTMCType; -import de.monticore.types.mccollectiontypes._ast.ASTMCBasicTypeArgument; -import de.monticore.types.mccollectiontypes._ast.ASTMCPrimitiveTypeArgument; import de.monticore.types.mccollectiontypes._ast.ASTMCTypeArgument; import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericType; -import de.monticore.types.mcsimplegenerictypes._ast.ASTMCCustomTypeArgument; import de.monticore.types.mcsimplegenerictypes._visitor.MCSimpleGenericTypesHandler; import de.monticore.types.mcsimplegenerictypes._visitor.MCSimpleGenericTypesTraverser; import de.monticore.types3.TypeCheck3; +import de.se_rwth.commons.logging.Log; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; /** @@ -60,9 +59,16 @@ public void handle(@NonNull ASTMCBasicGenericType mcType) { if (compSym.isEmpty()) { this.resultWrapper.setResultAbsent(); } else { + if (compSym.size() > 1) { + Log.error(String.format( + "0xD0105 Ambiguous reference, both '%s' and '%s' match'", + compSym.get(0).getFullName(), compSym.get(1).getFullName()), + mcType.get_SourcePositionStart(), mcType.get_SourcePositionEnd() + ); + } List typeArgExpressions = typeArgumentsToTypes(mcType.getMCTypeArgumentList()).stream() - .map(TypeCheck3::symTypeFromAST) - .collect(Collectors.toList()); + .map(TypeCheck3::symTypeFromAST) + .collect(Collectors.toList()); CompKindExpression result = new CompKindOfGenericComponentType(compSym.get(0), typeArgExpressions); result.setSourceNode(mcType); @@ -79,14 +85,13 @@ protected List typeArgumentsToTypes(@NonNull List List types = new ArrayList<>(typeArgs.size()); for (ASTMCTypeArgument typeArg : typeArgs) { - if (typeArg instanceof ASTMCBasicTypeArgument) { - types.add(((ASTMCBasicTypeArgument) typeArg).getMCQualifiedType()); - } else if (typeArg instanceof ASTMCPrimitiveTypeArgument) { - types.add(((ASTMCPrimitiveTypeArgument) typeArg).getMCPrimitiveType()); - } else if (typeArg instanceof ASTMCCustomTypeArgument) { - types.add(((ASTMCCustomTypeArgument) typeArg).getMCType()); + Optional type = typeArg.getMCTypeOpt(); + if (type.isPresent()) { + types.add(type.get()); } else { - throw new IllegalStateException(); + Log.error("0xD0106 Used an unsupported type argument for component. " + + "You can not use WildCards as type arguments," + + "such as GenericType."); } } return types; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCArrayTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCArrayTypes.java index 265d909a2d..92f9aa976c 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCArrayTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCArrayTypes.java @@ -12,7 +12,10 @@ * Visitor for Derivation of SymType from MCArrayTypes * i.e. for * types/MCArrayTypes.mc4 + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class SynthesizeSymTypeFromMCArrayTypes extends AbstractSynthesizeFromType implements MCArrayTypesVisitor2, MCArrayTypesHandler { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCBasicTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCBasicTypes.java index 9525f9c2a8..1e550a075e 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCBasicTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCBasicTypes.java @@ -20,7 +20,10 @@ * Visitor for Derivation of SymType from MCBasicTypes * i.e. for * types/MCBasicTypes.mc4 + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class SynthesizeSymTypeFromMCBasicTypes extends AbstractSynthesizeFromType implements MCBasicTypesVisitor2, MCBasicTypesHandler { protected MCBasicTypesTraverser traverser; diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCCollectionTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCCollectionTypes.java index 507eb54170..58b973bb20 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCCollectionTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCCollectionTypes.java @@ -15,7 +15,10 @@ * Visitor for Derivation of SymType from MCBasicTypes * i.e. for * types/MCBasicTypes.mc4 + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class SynthesizeSymTypeFromMCCollectionTypes extends AbstractSynthesizeFromType implements MCCollectionTypesVisitor2, MCCollectionTypesHandler { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCFullGenericTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCFullGenericTypes.java index c416a95eed..7d392a46a3 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCFullGenericTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCFullGenericTypes.java @@ -12,7 +12,10 @@ * Visitor for Derivation of SymType from MCFullGenericTypes * i.e. for * types/MCFullGenericTypes.mc4 + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class SynthesizeSymTypeFromMCFullGenericTypes extends AbstractSynthesizeFromType implements MCFullGenericTypesVisitor2, MCFullGenericTypesHandler { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCFunctionTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCFunctionTypes.java index ad249682dd..7ac3fb2288 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCFunctionTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCFunctionTypes.java @@ -17,7 +17,10 @@ * Visitor for Derivation of SymType from MCFunctionTypes * i.e. for * types/MCFunctionTypes.mc4 + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class SynthesizeSymTypeFromMCFunctionTypes extends AbstractSynthesizeFromType implements MCFunctionTypesVisitor2, MCFunctionTypesHandler { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCSimpleGenericTypes.java b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCSimpleGenericTypes.java index 55eb073b9f..0aecc16cd2 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCSimpleGenericTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/SynthesizeSymTypeFromMCSimpleGenericTypes.java @@ -21,7 +21,10 @@ * Visitor for Derivation of SymType from MCSimpleGenericTypes * i.e. for * types/MCSimpleGenericTypes.mc4 + * @deprecated part of typecheck1, + * use {@link de.monticore.types3.TypeCheck3} instead. */ +@Deprecated public class SynthesizeSymTypeFromMCSimpleGenericTypes extends AbstractSynthesizeFromType implements MCSimpleGenericTypesVisitor2, MCSimpleGenericTypesHandler { diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/TypeCheck.md b/monticore-grammar/src/main/java/de/monticore/types/check/TypeCheck.md index 92ad72c271..d4ca8a6b58 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/TypeCheck.md +++ b/monticore-grammar/src/main/java/de/monticore/types/check/TypeCheck.md @@ -1,6 +1,13 @@ - + +# Deprecation + +!!! warning "TypeCheck1 has been deprecated." + + Please refer to [TypeSystem3](../../types3/TypeSystem3.md). + +## Deprecated Documentation In MontiCore, the TypeCheck is used to calculate the SymTypeExpression of a set of expressions, types and literals. This is made possible by traversing the AST of an expression, type or literal, calculating the SymTypeExpression of its @@ -137,15 +144,15 @@ public void check(ASTExpression expr){ ``` An example for the case that a plus expression needs to return 'int' can be found -[here](https://github.com/MontiCore/monticore/blob/opendev/monticore-test/monticore-grammar-it/src/main/java/mc/typescalculator/myownlanguage/_cocos/PlusExpressionReturnsInt.java). +[here](../../../../../../../../monticore-test/monticore-grammar-it/src/main/java/mc/typescalculator/myownlanguage/_cocos/PlusExpressionReturnsInt.java). ## Further Information * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../../../../../grammars/de/monticore/Grammars.md) +* [Best Practices](../../../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-grammar/src/main/java/de/monticore/types/check/TypeRelations.java b/monticore-grammar/src/main/java/de/monticore/types/check/TypeRelations.java index 6a4170f079..76fb4e563c 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/check/TypeRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types/check/TypeRelations.java @@ -10,7 +10,9 @@ /** * This Class provides the default implementation of {@link ITypeRelations} + * @deprecated use {@link de.monticore.types3.SymTypeRelations} */ +@Deprecated public class TypeRelations implements ITypeRelations { @Override @@ -106,8 +108,8 @@ protected boolean isSubtypeOfRec(SymTypeExpression subType, SymTypeExpression su if (type.isGenericType() && superType.isGenericType()) { SymTypeOfGenerics typeGen = (SymTypeOfGenerics) type; SymTypeOfGenerics supTypeGen = (SymTypeOfGenerics) superType; - if (typeGen.printTypeWithoutTypeArgument() - .equals(supTypeGen.printTypeWithoutTypeArgument()) + if (typeGen.getTypeConstructorFullName() + .equals(supTypeGen.getTypeConstructorFullName()) && typeGen.sizeArguments() == supTypeGen.sizeArguments()) { boolean success = true; for (int i = 0; i < typeGen.sizeArguments(); i++) { diff --git a/monticore-grammar/src/main/java/de/monticore/types/mcbasictypes/_ast/ASTMCReturnType.java b/monticore-grammar/src/main/java/de/monticore/types/mcbasictypes/_ast/ASTMCReturnType.java index e0903c65ca..a01e20f8a2 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/mcbasictypes/_ast/ASTMCReturnType.java +++ b/monticore-grammar/src/main/java/de/monticore/types/mcbasictypes/_ast/ASTMCReturnType.java @@ -8,7 +8,7 @@ public ASTMCReturnType() { } /** - * Conversion to a compact string, such as "int", "Person", "List< A >" + * Conversion to a compact string, such as {@code "int"}, {@code "Person"}, {@code "List< A >"} */ public String printType() { return MCBasicTypesMill.prettyPrint(this, false); diff --git a/monticore-grammar/src/main/java/de/monticore/types/mcbasictypes/_ast/ASTMCType.java b/monticore-grammar/src/main/java/de/monticore/types/mcbasictypes/_ast/ASTMCType.java index 18697d71ca..c6795017d3 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/mcbasictypes/_ast/ASTMCType.java +++ b/monticore-grammar/src/main/java/de/monticore/types/mcbasictypes/_ast/ASTMCType.java @@ -9,7 +9,7 @@ public interface ASTMCType extends ASTMCTypeTOP { /** - * Conversion to a compact string, such as "int", "Person", "List< A >" + * Conversion to a compact string, such as {@code "int"}, {@code "Person"}, {@code "List< A >"} */ default String printType() { return MCBasicTypesMill.prettyPrint(this, false); diff --git a/monticore-grammar/src/main/java/de/monticore/types/mccollectiontypes/_ast/ASTMCTypeArgument.java b/monticore-grammar/src/main/java/de/monticore/types/mccollectiontypes/_ast/ASTMCTypeArgument.java index b92a79d595..eb0056e33f 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/mccollectiontypes/_ast/ASTMCTypeArgument.java +++ b/monticore-grammar/src/main/java/de/monticore/types/mccollectiontypes/_ast/ASTMCTypeArgument.java @@ -11,7 +11,7 @@ public interface ASTMCTypeArgument extends ASTMCTypeArgumentTOP { Optional getMCTypeOpt(); /** - * Conversion to a compact string, such as "int", "Person", "List< A >" + * Conversion to a compact string, such as {@code "int"}, {@code "Person"}, {@code "List< A >"} */ default String printType() { return MCCollectionTypesMill.prettyPrint(this, false); diff --git a/monticore-grammar/src/main/java/de/monticore/types/mccollectiontypes/types3/MCCollectionSymTypeRelations.java b/monticore-grammar/src/main/java/de/monticore/types/mccollectiontypes/types3/MCCollectionSymTypeRelations.java index 8e716da09c..e80e81bc54 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/mccollectiontypes/types3/MCCollectionSymTypeRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types/mccollectiontypes/types3/MCCollectionSymTypeRelations.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types.mccollectiontypes.types3; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.check.SymTypeOfGenerics; @@ -139,7 +140,7 @@ public static void reset() { } protected static void setDelegate(MCCollectionSymTypeRelations newDelegate) { - MCCollectionSymTypeRelations.delegate = Log.errorIfNull(newDelegate); + MCCollectionSymTypeRelations.delegate = Preconditions.checkNotNull(newDelegate); } protected static MCCollectionSymTypeRelations getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types/mcsimplegenerictypes/types3/MCSimpleGenericTypesTypeVisitor.java b/monticore-grammar/src/main/java/de/monticore/types/mcsimplegenerictypes/types3/MCSimpleGenericTypesTypeVisitor.java index e7c2677969..efe45c51d0 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/mcsimplegenerictypes/types3/MCSimpleGenericTypesTypeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types/mcsimplegenerictypes/types3/MCSimpleGenericTypesTypeVisitor.java @@ -3,7 +3,6 @@ import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; -import de.monticore.symboltable.modifiers.AccessModifier; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.mccollectiontypes._ast.ASTMCGenericType; @@ -24,7 +23,7 @@ public class MCSimpleGenericTypesTypeVisitor extends AbstractTypeVisitor @Override public void endVisit(ASTMCBasicGenericType genericType) { - SymTypeExpression symType = null; + SymTypeExpression symType; List arguments = new LinkedList<>(); boolean obscure = false; for (int i = 0; i < genericType.sizeMCTypeArguments(); i++) { @@ -37,7 +36,6 @@ public void endVisit(ASTMCBasicGenericType genericType) { genericType.get_SourcePositionStart(), genericType.get_SourcePositionEnd() ); - return; } SymTypeExpression argSymType = getType4Ast().getPartialTypeOfTypeId(arg); arguments.add(argSymType); @@ -57,15 +55,14 @@ public void endVisit(ASTMCBasicGenericType genericType) { genericType.get_SourcePositionStart(), genericType.get_SourcePositionEnd() ); - getType4Ast().setTypeOfTypeIdentifier(genericType, - SymTypeExpressionFactory.createObscureType()); + symType = SymTypeExpressionFactory.createObscureType(); } else { Optional type = getAsBasicSymbolsScope(genericType.getEnclosingScope()) .resolveType(genericType.printWithoutTypeArguments()); if (type.isPresent()) { - if (type.get().getTypeParameterList().size() == 0) { + if (type.get().getTypeParameterList().isEmpty()) { Log.error("0xB5487 expected a generic type, but \"" + type.get().getFullName() + "\" contains no type variables", @@ -74,7 +71,7 @@ public void endVisit(ASTMCBasicGenericType genericType) { ); } if (type.get().getTypeParameterList().size() != arguments.size() - && arguments.size() != 0) { + && !arguments.isEmpty()) { // we only allow 0 arguments for, e.g., "new ArrayList<>()" // in most cases we expect the arguments to be set Log.error("0xB5864 The generic type \"" @@ -93,17 +90,17 @@ public void endVisit(ASTMCBasicGenericType genericType) { symType = handleIfNotFound(genericType, arguments); } } - if (null != symType) { - getType4Ast().setTypeOfTypeIdentifier(genericType, symType); - genericType.setDefiningSymbol(symType.getTypeInfo()); - } } else { // one of the type arguments could not be synthesized // => the generic type itself cannot be synthesized correctly - getType4Ast().setTypeOfTypeIdentifier(genericType, - SymTypeExpressionFactory.createObscureType()); + symType = SymTypeExpressionFactory.createObscureType(); + } + + if (symType.hasTypeInfo()) { + genericType.setDefiningSymbol(symType.getTypeInfo()); } + getType4Ast().setTypeOfTypeIdentifier(genericType, symType); } @Override diff --git a/monticore-grammar/src/main/java/de/monticore/types/mcstructuraltypes/types3/MCStructuralTypesTypeVisitor.java b/monticore-grammar/src/main/java/de/monticore/types/mcstructuraltypes/types3/MCStructuralTypesTypeVisitor.java index a7e96cc8be..14c6466d4f 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/mcstructuraltypes/types3/MCStructuralTypesTypeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types/mcstructuraltypes/types3/MCStructuralTypesTypeVisitor.java @@ -122,7 +122,7 @@ protected List transformUnionTree2List(ASTMCType mcType) { * this is a specific kind of type normalization, * which also reduces the complexity of the type printed, * which is the reason this has been added here. - * E.g., given A & B & C, (A & B & C) is printed rather than ((A & B) & C). + * E.g., given {@code A & B & C}, {@code (A & B & C)} is printed rather than {@code ((A & B) & C)}. */ protected List transformIntersectionTree2List(ASTMCType mcType) { List result = new ArrayList<>(); diff --git a/monticore-grammar/src/main/java/de/monticore/types/typeparameters/_symboltable/TypeParametersSTCompleteTypes.java b/monticore-grammar/src/main/java/de/monticore/types/typeparameters/_symboltable/TypeParametersSTCompleteTypes.java index 458dcd5320..89beab8d66 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/typeparameters/_symboltable/TypeParametersSTCompleteTypes.java +++ b/monticore-grammar/src/main/java/de/monticore/types/typeparameters/_symboltable/TypeParametersSTCompleteTypes.java @@ -5,6 +5,7 @@ import de.monticore.types.typeparameters._ast.ASTTypeParameter; import de.monticore.types.typeparameters._visitor.TypeParametersVisitor2; import de.monticore.types3.ITypeCalculator; +import de.monticore.types3.TypeCheck3; import java.util.ArrayList; import java.util.List; @@ -14,8 +15,13 @@ */ public class TypeParametersSTCompleteTypes implements TypeParametersVisitor2 { + @Deprecated ITypeCalculator tc; - + + public TypeParametersSTCompleteTypes() { + } + + @Deprecated public TypeParametersSTCompleteTypes(ITypeCalculator tc) { this.tc = tc; } @@ -24,7 +30,12 @@ public TypeParametersSTCompleteTypes(ITypeCalculator tc) { public void visit(ASTTypeParameter node) { List bounds = new ArrayList<>(); for (ASTMCType astTypeBound : node.getMCTypeList()) { - bounds.add(tc.symTypeFromAST(astTypeBound)); + // deprecated behavior: + if (tc != null) { + bounds.add(tc.symTypeFromAST(astTypeBound)); + } else { + bounds.add(TypeCheck3.symTypeFromAST(astTypeBound)); + } } // error logged if obscure node.getSymbol().setSuperTypesList(bounds); diff --git a/monticore-grammar/src/main/java/de/monticore/types/typeparameters/cocos/TypeParameterNoCyclicInheritance.java b/monticore-grammar/src/main/java/de/monticore/types/typeparameters/cocos/TypeParameterNoCyclicInheritance.java index 72c3834c4d..f470a3a8f4 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/typeparameters/cocos/TypeParameterNoCyclicInheritance.java +++ b/monticore-grammar/src/main/java/de/monticore/types/typeparameters/cocos/TypeParameterNoCyclicInheritance.java @@ -15,7 +15,7 @@ /** * Finds instances of circular inheritance, - * e.g., + * e.g., {@code } */ public class TypeParameterNoCyclicInheritance implements TypeParametersASTTypeParameterCoCo { diff --git a/monticore-grammar/src/main/java/de/monticore/types/typeparameters/cocos/TypeParametersHaveUniqueNames.java b/monticore-grammar/src/main/java/de/monticore/types/typeparameters/cocos/TypeParametersHaveUniqueNames.java index b48ce2376c..48ea51e315 100644 --- a/monticore-grammar/src/main/java/de/monticore/types/typeparameters/cocos/TypeParametersHaveUniqueNames.java +++ b/monticore-grammar/src/main/java/de/monticore/types/typeparameters/cocos/TypeParametersHaveUniqueNames.java @@ -7,7 +7,7 @@ import de.monticore.types.typeparameters._cocos.TypeParametersASTTypeParametersCoCo; import de.se_rwth.commons.logging.Log; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -32,8 +32,8 @@ public void check(ASTTypeParameters node) { // Helper protected Set findDuplicates(List listContainingDuplicates) { - final Set setToReturn = new HashSet<>(); - final Set set1 = new HashSet<>(); + final Set setToReturn = new LinkedHashSet<>(); + final Set set1 = new LinkedHashSet<>(); for (String modifierName : listContainingDuplicates) { if (!set1.add(modifierName)) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/ISymTypeRelations.java b/monticore-grammar/src/main/java/de/monticore/types3/ISymTypeRelations.java index be5224ecda..05fc011637 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/ISymTypeRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/ISymTypeRelations.java @@ -20,9 +20,9 @@ public interface ISymTypeRelations { /** * whether the assignee can be assigned to by the assigner, * e.g., assignment operator: x = 2, - * -> type of x and type of 2 need to be compatible, - * e.g., functions call: (float -> void)(2), - * -> float and type of 2 need to be compatible + * type of x and type of 2 need to be compatible, + * e.g., functions call: {@code (float -> void)(2)}, + * float and type of 2 need to be compatible */ boolean isCompatible(SymTypeExpression assignee, SymTypeExpression assigner); @@ -51,22 +51,22 @@ public interface ISymTypeRelations { /** * Boxes SymTypeExpressions, * including, but not limited to, Java primitive boxing - * e.g., int -> java.lang.Integer - * e.g., List -> java.util.List + * e.g., {@code int -> java.lang.Integer} + * e.g., {@code List -> java.util.List} */ SymTypeExpression box(SymTypeExpression unboxed); /** * Unboxes SymTypeExpressions, * including, but not limited to, Java primitive unboxing - * e.g., java.lang.Integer -> int - * e.g., java.util.List -> List + * e.g., {@code java.lang.Integer -> int} + * e.g., {@code java.util.List -> List} */ SymTypeExpression unbox(SymTypeExpression boxed); /** * normalizes the SymTypeExpression, - * e.g., (A & B[])[] -> (A[] & B[][]) + * e.g., {@code (A & B[])[] -> (A[] & B[][])} *

* Within our type systems, each type has ONE normalized representation. * This can be used to, e.g., compare SymTypeExpressions @@ -98,8 +98,8 @@ default Optional leastUpperBound( * calculates the one promoted numeric type, * ignoring the specifics of the context * s. Java spec. 20 5.6 - * e.g., short -> int - * e.g., byte, float -> float + * e.g., {@code short -> int} + * e.g., {@code byte, float -> float} */ SymTypeExpression numericPromotion(List types); diff --git a/monticore-grammar/src/main/java/de/monticore/types3/SymTypeRelations.java b/monticore-grammar/src/main/java/de/monticore/types3/SymTypeRelations.java index e4c73f2387..08cc85bb9b 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/SymTypeRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/SymTypeRelations.java @@ -1,6 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.generics.bounds.Bound; import de.monticore.types3.util.SymTypeRelationsDefaultDelegatee; @@ -28,9 +29,9 @@ public abstract class SymTypeRelations { /** * whether the target can be assigned to by the source, * e.g., assignment operator: x = 2, - * -> type of x and type of 2 need to be compatible, - * e.g., function call: (float -> void)(2), - * -> float and type of 2 need to be compatible. + * type of x and type of 2 need to be compatible, + * e.g., function call: {@code (float -> void)(2)}, + * float and type of 2 need to be compatible. */ public static boolean isCompatible( SymTypeExpression target, @@ -121,8 +122,8 @@ protected abstract Optional _leastUpperBound( /** * Boxes SymTypeExpressions, * including, but not limited to, Java primitive boxing - * e.g., int -> java.lang.Integer - * e.g., List -> java.util.List + * e.g., {@code int -> java.lang.Integer} + * e.g., {@code List -> java.util.List} */ public static SymTypeExpression box(SymTypeExpression unboxed) { return getDelegate()._box(unboxed); @@ -133,8 +134,8 @@ public static SymTypeExpression box(SymTypeExpression unboxed) { /** * Unboxes SymTypeExpressions, * including, but not limited to, Java primitive unboxing - * e.g., java.lang.Integer -> int - * e.g., java.util.List -> List + * e.g., {@code java.lang.Integer -> int} + * e.g., {@code java.util.List -> List} */ public static SymTypeExpression unbox(SymTypeExpression boxed) { return getDelegate()._unbox(boxed); @@ -144,7 +145,7 @@ public static SymTypeExpression unbox(SymTypeExpression boxed) { /** * normalizes the SymTypeExpression, - * e.g., (A & B[])[] -> (A[] & B[][]) + * e.g., {@code (A & B[])[] -> (A[] & B[][])} *

* Within our type systems, each type has ONE normalized representation. * This can be used to, e.g., compare SymTypeExpressions @@ -161,8 +162,8 @@ public static SymTypeExpression normalize(SymTypeExpression type) { * calculates the one promoted numeric type, * ignoring the specifics of the context * s. Java spec. 20 5.6 - * e.g., short -> int - * e.g., byte, float -> float + * e.g., {@code short -> int} + * e.g., {@code byte, float -> float} */ public static SymTypeExpression numericPromotion( List types @@ -389,7 +390,7 @@ public static void reset() { } protected static void setDelegate(SymTypeRelations newDelegate) { - SymTypeRelations.delegate = Log.errorIfNull(newDelegate); + SymTypeRelations.delegate = Preconditions.checkNotNull(newDelegate); } protected static SymTypeRelations getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/Type4Ast.java b/monticore-grammar/src/main/java/de/monticore/types3/Type4Ast.java index cdb670db35..497dd2a18b 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/Type4Ast.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/Type4Ast.java @@ -22,7 +22,7 @@ import de.se_rwth.commons.logging.Log; import org.apache.commons.io.FilenameUtils; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -45,7 +45,7 @@ public class Type4Ast { * strictly seperated from the map for type identifiers * we use ASTNode to support non-ASTExpression Nodes (e.g., literals) * however, we do NOT support non-expression ASTNodes, - * e.g. in MyClass.myMethod() -> the "MyClass" is not an expression by itself + * e.g. in MyClass.myMethod(): the "MyClass" is not an expression by itself */ protected Map expr2type; @@ -71,8 +71,8 @@ public Type4Ast() { } public void reset() { - expr2type = new HashMap<>(); - typeID2type = new HashMap<>(); + expr2type = new LinkedHashMap<>(); + typeID2type = new LinkedHashMap<>(); } /** diff --git a/monticore-grammar/src/main/java/de/monticore/types3/TypeCalculator3.java b/monticore-grammar/src/main/java/de/monticore/types3/TypeCalculator3.java index 5ccdb829ac..a254eee3f6 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/TypeCalculator3.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/TypeCalculator3.java @@ -1,5 +1,6 @@ package de.monticore.types3; +import com.google.common.base.Preconditions; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; import de.monticore.types.check.SymTypeExpression; @@ -37,9 +38,9 @@ public TypeCalculator3( Type4Ast type4Ast, InferenceContext4Ast ctx4Ast ) { - this.typeTraverser = Log.errorIfNull(typeTraverser); - this.type4Ast = Log.errorIfNull(type4Ast); - this.ctx4Ast = Log.errorIfNull(ctx4Ast); + this.typeTraverser = Preconditions.checkNotNull(typeTraverser); + this.type4Ast = Preconditions.checkNotNull(type4Ast); + this.ctx4Ast = Preconditions.checkNotNull(ctx4Ast); } public ITraverser getTypeTraverser() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/TypeCheck3.java b/monticore-grammar/src/main/java/de/monticore/types3/TypeCheck3.java index 3193a04800..f153e9534a 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/TypeCheck3.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/TypeCheck3.java @@ -1,5 +1,6 @@ package de.monticore.types3; +import com.google.common.base.Preconditions; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; import de.monticore.types.check.SymTypeExpression; @@ -95,13 +96,13 @@ public static SymTypeExpression typeOf(ASTExpression expr) { * Derives the type of the expression, * using the expected target type as additional information. *

- * E.g.: List myList = []; // [] returns an empty list + * E.g.: {@code List myList = [];} // [] returns an empty list * Here, the type of [] is to be calculated. * Without target type, it is known that a List is returned. * However, the type argument of List is unknown. - * Using the target type List as additional information, + * Using the target type {@code List} as additional information, * allows to additionally derive the type argument int, - * resulting in deriving List to be the expression []'s type. + * resulting in deriving {@code List} to be the expression []'s type. *

* Note: it is up to the concrete implementation, * whether the target type is used. @@ -155,7 +156,7 @@ protected abstract SymTypeExpression _typeOf( ); protected static void setDelegate(TypeCheck3 delegate) { - TypeCheck3.delegate = Log.errorIfNull(delegate); + TypeCheck3.delegate = Preconditions.checkNotNull(delegate); } protected static void resetDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/TypeSystem3.md b/monticore-grammar/src/main/java/de/monticore/types3/TypeSystem3.md index 88b4b2da9a..17e344972e 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/TypeSystem3.md +++ b/monticore-grammar/src/main/java/de/monticore/types3/TypeSystem3.md @@ -69,6 +69,8 @@ and combining their information to the SymTypeExpression currently calculated. * Functionality to work with SymTypeExpressions, Expressions * [SymTypeRelations](SymTypeRelations.java) (relations over SymTypeExpressions, e.g., `isSubTypeOf`, `isCompatible`) + * [OOSymbolsSymTypeRelations](../symbols/oosymbols/types3/OOSymbolsSymTypeRelations.java) + (relations wrt. OOSymbols, e.g., `isInterface`, `isEnum`) * [MCCollectionSymTypeRelations](../types/mccollectiontypes/types3/MCCollectionSymTypeRelations.java) (relations over MCCollection SymTypeExpressions, e.g., `isList`) * [FunctionRelations](util/FunctionRelations.java) @@ -195,6 +197,7 @@ while the SymTypeExpressions represent a type usage There is only one type definition, but there can be many type usages. The SymTypeExpression knows its corresponding Symbol (if applicable): + * SymTypeOfGenerics, SymTypeOfObject, SymTypePrimitive, and SymTypeVariable know their corresponding TypeSymbol * SymTypeOfFunction _may_ have a corresponding FunctionSymbol @@ -215,6 +218,7 @@ Thus, multiple identical SymTypeExpressions can be used at the same time. In MontiCore, the type system implementations have multiple usages. For example: + * writing context conditions; The CoCos reduce a set of models to those, that adhere to the typing rules of the language. @@ -315,6 +319,7 @@ s.a. [Given Infrastructure](#given-infrastructure-in-monticore); The following are further classes, that are unlikely to be required to be modified for a given language. They still use the same static delegate pattern. + * [FunctionRelations](util/FunctionRelations.java), * [SIUnitTypeRelations](util/SIUnitTypeRelations.java), * [TypeContextCalculator](util/TypeContextCalculator.java), @@ -383,6 +388,7 @@ To check relations of SymTypeExpressions, the SymTypeExpressions are passed to the corresponding method of SymTypeRelations or one of its subclasses. A non-exhaustive List of relation methods: + * `boolean isCompatible(SymTypeExpression assignee, SymTypeExpression assigner)` (whether an assignment is allowed in the type system) * `boolean isSubTypeOf(SymTypeExpression subType, SymTypeExpression)` @@ -426,8 +432,8 @@ This is done to allow reuse of CoCos between languages. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) * [TypeCheck1 Readme](../types/check/TypeCheck.md) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../../../../grammars/de/monticore/Grammars.md) +* [Best Practices](../../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/Generics.md b/monticore-grammar/src/main/java/de/monticore/types3/generics/Generics.md index ada14a0b3c..623ccc54bb 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/Generics.md +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/Generics.md @@ -114,6 +114,9 @@ To this end, MontiCore provides a type inference algorithm. * [SetExpressionsCTTIVisitor](../../ocl/setexpressions/types3/SetExpressionsCTTIVisitor.java) (calculates the SymTypeExpressions for the expressions in the grammar SetExpressions) + * [TupleExpressionsCTTIVisitor](../../expressions/tupleexpressions/types3/TupleExpressionsCTTIVisitor.java) + (calculates the SymTypeExpressions for the expressions + in the grammar TupleExpressions) * [UglyExpressionsCTTIVisitor](../../expressions/uglyexpressions/types3/UglyExpressionsCTTIVisitor.java) (calculates the SymTypeExpressions for the expressions in the grammar UglyExpressions) @@ -156,6 +159,7 @@ The return type of `f` in the statement `f();` has no bounds, it can be any type. As such, `#TOP` is used to represent this. More often than not, a type of `#TOP` suggests that a type/function has not been used "to their full potential": + * some information goes unused (for `f` it is the return value), or * e.g., in the comparison of an empty List and Set `[] == {}` the potential to store values in the collections goes unused. @@ -235,6 +239,7 @@ This data is stored, as there are circumstances there the target type information is not available (e.g., inside some CoCos). It holds that + * Each ASTExpression has exactly one target type * Each ASTExpression has exactly one type. In the case of a language with variability, special care has to be taken to diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/TypeParameterRelations.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/TypeParameterRelations.java index dec299b1dd..d5cc2b1a2e 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/TypeParameterRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/TypeParameterRelations.java @@ -1,5 +1,6 @@ package de.monticore.types3.generics; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeInferenceVariable; @@ -27,8 +28,8 @@ public abstract class TypeParameterRelations { /** * replaces bound TypeVariables using a given map - * e.g., T, {T->int,U->float} -> int - * e.g., List, {T->int} -> List + * e.g., {@code T, {T->int,U->float} -> int} + * e.g., {@code List, {T->int} -> List} */ public static SymTypeExpression replaceTypeVariables( SymTypeExpression type, @@ -44,8 +45,8 @@ protected abstract SymTypeExpression _replaceTypeVariables( /** * replaces InferenceVariables using a given map - * e.g., a, {a->int,b->float} -> int - * e.g., List, {a->int} -> List + * e.g., {@code a, {a->int,b->float} -> int} + * e.g., {@code List, {a->int} -> List} */ public static SymTypeExpression replaceInferenceVariables( SymTypeExpression type, @@ -165,7 +166,7 @@ public static void reset() { } protected static void setDelegate(TypeParameterRelations newDelegate) { - TypeParameterRelations.delegate = Log.errorIfNull(newDelegate); + TypeParameterRelations.delegate = Preconditions.checkNotNull(newDelegate); } protected static TypeParameterRelations getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/Bound.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/Bound.java index cb98b1d8e5..b902666d97 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/Bound.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/Bound.java @@ -18,30 +18,71 @@ * the instantiations will then be calculated by * {@link BoundResolution}. */ -public abstract class Bound { +public abstract class Bound + implements Comparable { public boolean isCaptureBound() { return false; } + public CaptureBound asCaptureBound() { + throw new UnsupportedOperationException( + "Tried to convert bound " + print() + + " to CaptureBound, which it is not." + ); + } + public boolean isSubTypingBound() { return false; } + public SubTypingBound asSubTypingBound() { + throw new UnsupportedOperationException( + "Tried to convert bound " + print() + + " to SubTypingBound, which it is not." + ); + } + public boolean isTypeCompatibilityBound() { return false; } + public TypeCompatibilityBound asTypeCompatibilityBound() { + throw new UnsupportedOperationException( + "Tried to convert bound " + print() + + " to TypeCompatibilityBound, which it is not." + ); + } + public boolean isTypeEqualityBound() { return false; } + public TypeEqualityBound asTypeEqualityBound() { + throw new UnsupportedOperationException( + "Tried to convert bound " + print() + + " to TypeEqualityBound, which it is not." + ); + } + public boolean isUnsatisfiableBound() { return false; } + public UnsatisfiableBound asUnsatisfiableBound() { + throw new UnsupportedOperationException( + "Tried to convert bound " + print() + + " to UnsatisfiableBound, which it is not." + ); + } + public abstract boolean deepEquals(Bound other); + @Override + public int compareTo(Bound o) { + return BoundComparator.compareBounds(this, o); + } + /** * returns a human-readable String, e.g., for the log */ diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/BoundComparator.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/BoundComparator.java new file mode 100644 index 0000000000..e6cd485f47 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/BoundComparator.java @@ -0,0 +1,163 @@ +// (c) https://github.com/MontiCore/monticore +package de.monticore.types3.generics.bounds; + +import com.google.common.base.Preconditions; +import de.se_rwth.commons.logging.Log; + +import java.util.Comparator; + +import static de.monticore.types3.util.SymTypeExpressionComparator.compareSymTypeExpressions; + +public class BoundComparator implements Comparator { + + protected static BoundComparator delegate; + + public static int compareBounds(Bound b1, Bound b2) { + return getDelegate().compare(b1, b2); + } + + @Override + public int compare(Bound b1, Bound b2) { + Preconditions.checkNotNull(b1); + Preconditions.checkNotNull(b2); + + int res; + + int orderOfSubType1 = getOrderOfSubType(b1); + int orderOfSubType2 = getOrderOfSubType(b2); + int subTypeOrdering = Integer.compare(orderOfSubType1, orderOfSubType2); + + if (subTypeOrdering != 0) { + res = subTypeOrdering; + } + else if (b1.isCaptureBound() && b2.isCaptureBound()) { + res = compareCaptureBounds(b1.asCaptureBound(), b2.asCaptureBound()); + } + else if (b1.isSubTypingBound() && b2.isSubTypingBound()) { + res = compareSubTypingBounds(b1.asSubTypingBound(), b2.asSubTypingBound()); + } + else if (b1.isTypeCompatibilityBound() && b2.isTypeCompatibilityBound()) { + res = compareTypeCompatibilityBounds(b1.asTypeCompatibilityBound(), b2.asTypeCompatibilityBound()); + } + else if (b1.isTypeEqualityBound() && b2.isTypeEqualityBound()) { + res = compareTypeEqualityBounds(b1.asTypeEqualityBound(), b2.asTypeEqualityBound()); + } + else if (b1.isUnsatisfiableBound() && b2.isUnsatisfiableBound()) { + res = compareUnsatisfiableBounds(b1.asUnsatisfiableBound(), b2.asUnsatisfiableBound()); + } + else { + throwUnimplemented(); + res = -42; + } + + return res; + } + + protected int getOrderOfSubType(Bound bound) { + if (bound.isUnsatisfiableBound()) { + return 0; + } + else if (bound.isTypeEqualityBound()) { + return 1; + } + else if (bound.isSubTypingBound()) { + return 2; + } + else if (bound.isTypeCompatibilityBound()) { + return 3; + } + else if (bound.isCaptureBound()) { + return 4; + } + else { + throwUnimplemented(); + return -42; + } + } + + protected int compareCaptureBounds(CaptureBound b1, CaptureBound b2) { + int res; + int placeHolderComp = compareSymTypeExpressions(b1.getPlaceHolder(), b2.getPlaceHolder()); + if (placeHolderComp != 0) { + res = placeHolderComp; + } + else { + res = compareSymTypeExpressions(b1.getToBeCaptured(), b2.getToBeCaptured()); + } + return res; + } + + protected int compareSubTypingBounds(SubTypingBound b1, SubTypingBound b2) { + int res; + int subTypeComp = compareSymTypeExpressions(b1.getSubType(), b2.getSubType()); + if (subTypeComp != 0) { + res = subTypeComp; + } + else { + res = compareSymTypeExpressions(b1.getSuperType(), b2.getSuperType()); + } + return res; + } + + protected int compareTypeCompatibilityBounds(TypeCompatibilityBound b1, TypeCompatibilityBound b2) { + int res; + int sourceComp = compareSymTypeExpressions(b1.getSourceType(), b2.getSourceType()); + if (sourceComp != 0) { + res = sourceComp; + } + else { + res = compareSymTypeExpressions(b1.getTargetType(), b2.getTargetType()); + } + return res; + } + + protected int compareTypeEqualityBounds(TypeEqualityBound b1, TypeEqualityBound b2) { + int res; + int first = compareSymTypeExpressions(b1.getFirstType(), b2.getFirstType()); + if (first != 0) { + res = first; + } + else { + res = compareSymTypeExpressions(b1.getSecondType(), b2.getSecondType()); + } + return res; + } + + protected int compareUnsatisfiableBounds(UnsatisfiableBound b1, UnsatisfiableBound b2) { + return b1.getDescription().compareTo(b2.getDescription()); + } + + // helper + + /** + * This is not expected to be ever called. + */ + protected void throwUnimplemented() throws UnsupportedOperationException { + throw new UnsupportedOperationException( + "0xFD662 unimplemented comparison." + ); + } + + // static delegate + + public static void init() { + Log.trace("init default BoundComparator", "TypeCheck setup"); + setDelegate(new BoundComparator()); + } + + public static void reset() { + BoundComparator.delegate = null; + } + + protected static void setDelegate(BoundComparator newDelegate) { + BoundComparator.delegate = Preconditions.checkNotNull(newDelegate); + } + + protected static BoundComparator getDelegate() { + if (BoundComparator.delegate == null) { + init(); + } + return BoundComparator.delegate; + } + +} diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/CaptureBound.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/CaptureBound.java index 209a577a32..409c35352f 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/CaptureBound.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/CaptureBound.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.generics.bounds; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.check.SymTypeInferenceVariable; @@ -8,7 +9,6 @@ import de.monticore.types.check.SymTypeOfGenerics; import de.monticore.types.check.SymTypeVariable; import de.monticore.types3.generics.TypeParameterRelations; -import de.monticore.types3.util.SymTypeExpressionComparator; import de.se_rwth.commons.logging.Log; import java.util.ArrayList; @@ -32,7 +32,7 @@ public class CaptureBound extends Bound { public CaptureBound( SymTypeExpression toBeCaptured ) { - Log.errorIfNull(toBeCaptured); + Preconditions.checkNotNull(toBeCaptured); if (!toBeCaptured.isGenericType() && !toBeCaptured.isFunctionType()) { Log.error("0xFD229 internal error: " + "tried to create CaptureBound with unsupported type " @@ -56,6 +56,11 @@ public boolean isCaptureBound() { return true; } + @Override + public CaptureBound asCaptureBound() { + return this; + } + @Override public boolean deepEquals(Bound other) { if (this == other) { @@ -82,7 +87,7 @@ public List getIncludedTypes() { /** * returns the inference variables created for this bound, - * e.g., for bound G = capture(G), this will return [a1,a2]. + * e.g., for bound {@code G = capture(G)}, this will return [a1,a2]. * s. Java Spec 21 5.1.10. * They include the implied bounds according to Java Spec 21 18.1.3. */ @@ -95,7 +100,7 @@ public List getInferenceVariables() { /** * returns the type arguments to be captured for this bound, - * e.g., for bound G = capture(G), this will return [A1,A2]. + * e.g., for bound {@code G = capture(G)}, this will return {@code [A1,A2]}. */ public List getTypeArguments() { return getTypeArguments(toBeCaptured); @@ -103,7 +108,7 @@ public List getTypeArguments() { /** * returns the type parameters of the declared type - * e.g., for bound G = capture(G) with G declared with + * e.g., for bound {@code G = capture(G)} with G declared with * type parameters [P1,P2], this will return [P1,P2]. */ public List getTypeParameters() { @@ -117,7 +122,7 @@ public List getTypeParameters() { /** * returns the declared bounds with the type parameters * replaced by the inference variables, - * e.g., for bound G = capture(G) with G declared with + * e.g., for bound {@code G = capture(G)} with G declared with * type parameters [P1,P2] and corresponding (upper) bounds [B1,B2], * this will return [B1,B2][P1:=a1,P2:=a2]. * S. Java Spec 21 18.3.2 @@ -137,7 +142,7 @@ t, getTypeParameter2InferenceVarMap() /** * returns the mapping from type parameters to inference variables - * e.g., for bound G = capture(G) with G declared with + * e.g., for bound {@code G = capture(G)} with G declared with * type parameters [P1,P2], this will return [P1:=a1,P2:=a2]. * S. Java Spec 21 18.3.2 */ @@ -149,8 +154,7 @@ public Map getTypeParameter2Inference List typeParams = getTypeArguments(declType).stream() .map(SymTypeExpression::asTypeVariable) .collect(Collectors.toList()); - Map param2InfVar = - new TreeMap<>(new SymTypeExpressionComparator()); + Map param2InfVar = new TreeMap<>(); for (int i = 0; i < typeParams.size(); i++) { param2InfVar.put(typeParams.get(i), infVars.get(i)); } @@ -197,7 +201,7 @@ protected SymTypeExpression calculatePlaceHolder(SymTypeExpression type) { .stream().map(SymTypeExpression::asTypeVariable) .collect(Collectors.toList()); Map infVarReplaceMap = - new TreeMap<>(new SymTypeExpressionComparator()); + new TreeMap<>(); for (SymTypeVariable typeParam : typeParams) { infVarReplaceMap.put(typeParam, SymTypeExpressionFactory.createInferenceVariable( diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/SubTypingBound.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/SubTypingBound.java index 34f0a7b951..7a4cced989 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/SubTypingBound.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/SubTypingBound.java @@ -41,6 +41,11 @@ public boolean isSubTypingBound() { return true; } + @Override + public SubTypingBound asSubTypingBound() { + return this; + } + @Override public boolean deepEquals(Bound other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/TypeCompatibilityBound.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/TypeCompatibilityBound.java index 6b4f316637..dd179ff009 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/TypeCompatibilityBound.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/TypeCompatibilityBound.java @@ -65,6 +65,11 @@ public boolean isTypeCompatibilityBound() { return true; } + @Override + public TypeCompatibilityBound asTypeCompatibilityBound() { + return this; + } + @Override public boolean deepEquals(Bound other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/TypeEqualityBound.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/TypeEqualityBound.java index f245e91e87..53908bc687 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/TypeEqualityBound.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/TypeEqualityBound.java @@ -91,6 +91,11 @@ public boolean isTypeEqualityBound() { return true; } + @Override + public TypeEqualityBound asTypeEqualityBound() { + return this; + } + @Override public boolean deepEquals(Bound other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/UnsatisfiableBound.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/UnsatisfiableBound.java index 4ec6781304..dbc22576b2 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/UnsatisfiableBound.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/bounds/UnsatisfiableBound.java @@ -27,6 +27,11 @@ public boolean isUnsatisfiableBound() { return true; } + @Override + public UnsatisfiableBound asUnsatisfiableBound() { + return this; + } + @Override public boolean deepEquals(Bound other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/BoundWrapperConstraint.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/BoundWrapperConstraint.java index 6946f817e5..224a88fd0c 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/BoundWrapperConstraint.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/BoundWrapperConstraint.java @@ -1,10 +1,9 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.generics.constraints; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.generics.bounds.Bound; -import de.se_rwth.commons.logging.Log; - import java.util.List; /** @@ -19,7 +18,7 @@ public class BoundWrapperConstraint extends Constraint { public BoundWrapperConstraint( Bound bound ) { - this.bound = Log.errorIfNull(bound); + this.bound = Preconditions.checkNotNull(bound); } public Bound getBound() { @@ -31,6 +30,11 @@ public boolean isBoundWrapperConstraint() { return true; } + @Override + public BoundWrapperConstraint asBoundWrapperConstraint() { + return this; + } + @Override public boolean deepEquals(Constraint other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/Constraint.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/Constraint.java index 903ea7ff69..d04884f815 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/Constraint.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/Constraint.java @@ -12,30 +12,71 @@ * Constraints lead to {@link de.monticore.types3.generics.bounds.Bound}s, * by means of {@link ConstraintReduction}. */ -public abstract class Constraint { +public abstract class Constraint + implements Comparable { public boolean isBoundWrapperConstraint() { return false; } + public BoundWrapperConstraint asBoundWrapperConstraint() { + throw new UnsupportedOperationException( + "Tried to convert constraint " + print() + + " to BoundWrapperConstraint, which it is not." + ); + } + public boolean isExpressionCompatibilityConstraint() { return false; } + public ExpressionCompatibilityConstraint asExpressionCompatibilityConstraint() { + throw new UnsupportedOperationException( + "Tried to convert constraint " + print() + + " to ExpressionCompatibilityConstraint, which it is not." + ); + } + public boolean isSubTypingConstraint() { return false; } + public SubTypingConstraint asSubTypingConstraint() { + throw new UnsupportedOperationException( + "Tried to convert constraint " + print() + + " to SubTypingConstraint, which it is not." + ); + } + public boolean isTypeCompatibilityConstraint() { return false; } + public TypeCompatibilityConstraint asTypeCompatibilityConstraint() { + throw new UnsupportedOperationException( + "Tried to convert constraint " + print() + + " to TypeCompatibilityConstraint, which it is not." + ); + } + public boolean isTypeEqualityConstraint() { return false; } + public TypeEqualityConstraint asTypeEqualityConstraint() { + throw new UnsupportedOperationException( + "Tried to convert constraint " + print() + + " to TypeEqualityConstraint, which it is not." + ); + } + public abstract boolean deepEquals(Constraint other); + @Override + public int compareTo(Constraint o) { + return ConstraintComparator.compareConstraints(this, o); + } + /** * returns a human-readable String, e.g., for the log */ diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/ConstraintComparator.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/ConstraintComparator.java new file mode 100644 index 0000000000..24291fcd57 --- /dev/null +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/ConstraintComparator.java @@ -0,0 +1,255 @@ +// (c) https://github.com/MontiCore/monticore +package de.monticore.types3.generics.constraints; + +import com.google.common.base.Preconditions; +import de.monticore.ast.ASTNode; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.se_rwth.commons.SourcePosition; +import de.se_rwth.commons.logging.Log; + +import java.util.Comparator; +import java.util.Optional; + +import static de.monticore.types3.generics.bounds.BoundComparator.compareBounds; +import static de.monticore.types3.util.SymTypeExpressionComparator.compareSymTypeExpressions; + +public class ConstraintComparator implements Comparator { + + protected static ConstraintComparator delegate; + + public static int compareConstraints(Constraint c1, Constraint c2) { + return getDelegate().compare(c1, c2); + } + + @Override + public int compare(Constraint c1, Constraint c2) { + Preconditions.checkNotNull(c1); + Preconditions.checkNotNull(c2); + + int res; + + int orderOfSubType1 = getOrderOfSubType(c1); + int orderOfSubType2 = getOrderOfSubType(c2); + int subTypeOrdering = Integer.compare(orderOfSubType1, orderOfSubType2); + + if (subTypeOrdering != 0) { + res = subTypeOrdering; + } + else if (c1.isBoundWrapperConstraint() && c2.isBoundWrapperConstraint()) { + res = compareBoundWrapperConstraints( + c1.asBoundWrapperConstraint(), c2.asBoundWrapperConstraint()); + } + else if (c1.isExpressionCompatibilityConstraint() && c2.isExpressionCompatibilityConstraint()) { + res = compareExpressionCompatibilityConstraints( + c1.asExpressionCompatibilityConstraint(), + c2.asExpressionCompatibilityConstraint() + ); + } + else if (c1.isSubTypingConstraint() && c2.isSubTypingConstraint()) { + res = compareSubTypingConstraints( + c1.asSubTypingConstraint(), + c2.asSubTypingConstraint() + ); + } + else if (c1.isTypeCompatibilityConstraint() && c2.isTypeCompatibilityConstraint()) { + res = compareTypeCompatibilityConstraints( + c1.asTypeCompatibilityConstraint(), + c2.asTypeCompatibilityConstraint() + ); + } + else if (c1.isTypeEqualityConstraint() && c2.isTypeEqualityConstraint()) { + res = compareTypeEqualityConstraints( + c1.asTypeEqualityConstraint(), + c2.asTypeEqualityConstraint() + ); + } + else { + throwUnimplemented(); + res = -42; + } + + return res; + } + + protected int getOrderOfSubType(Constraint constraint) { + if (constraint.isBoundWrapperConstraint()) { + return 0; + } + else if (constraint.isTypeEqualityConstraint()) { + return 1; + } + else if (constraint.isSubTypingConstraint()) { + return 2; + } + else if (constraint.isTypeCompatibilityConstraint()) { + return 3; + } + else if (constraint.isExpressionCompatibilityConstraint()) { + return 4; + } + else { + throwUnimplemented(); + return -42; + } + } + + protected int compareBoundWrapperConstraints( + BoundWrapperConstraint c1, + BoundWrapperConstraint c2 + ) { + return compareBounds(c1.getBound(), c2.getBound()); + } + + protected int compareExpressionCompatibilityConstraints( + ExpressionCompatibilityConstraint c1, + ExpressionCompatibilityConstraint c2 + ) { + int res; + int exprComp = compareASTNodes(c1.getExpr(), c2.getExpr()); + if (exprComp != 0) { + res = exprComp; + } + else { + res = compareSymTypeExpressions(c1.getTargetType(), c2.getTargetType()); + } + return res; + } + + protected int compareASTNodes(ASTNode n1, ASTNode n2) { + int res; + int startComp = compareSourcePositionInASTNode(n1, n2, true); + if (startComp != 0) { + res = startComp; + } + else { + int endComp = compareSourcePositionInASTNode(n1, n2, false); + if (endComp != 0) { + res = endComp; + } + else { + // highly inefficient, only used if required. + String printed1 = BasicSymbolsMill.prettyPrint(n1, true); + String printed2 = BasicSymbolsMill.prettyPrint(n2, true); + res = printed1.compareTo(printed2); + } + } + return res; + } + + /** + * compares either start or end source positions of the ASTNodes. + */ + protected int compareSourcePositionInASTNode(ASTNode n1, ASTNode n2, boolean start) { + int res; + Optional pos1; + Optional pos2; + if (start) { + pos1 = n1.isPresent_SourcePositionStart() + ? Optional.of(n1.get_SourcePositionStart()) + : Optional.empty(); + pos2 = n2.isPresent_SourcePositionStart() + ? Optional.of(n2.get_SourcePositionStart()) + : Optional.empty(); + } + else { + pos1 = n1.isPresent_SourcePositionEnd() + ? Optional.of(n1.get_SourcePositionEnd()) + : Optional.empty(); + pos2 = n2.isPresent_SourcePositionEnd() + ? Optional.of(n2.get_SourcePositionEnd()) + : Optional.empty(); + } + if (pos1.isPresent() && pos2.isPresent()) { + res = pos1.get().compareTo(pos2.get()); + } + else if (pos1.isPresent()) { + res = -1; + } + else if (pos2.isPresent()) { + res = 1; + } + else { + res = 0; + } + return res; + } + + protected int compareSubTypingConstraints( + SubTypingConstraint c1, + SubTypingConstraint c2 + ) { + int res; + int subTypeComp = compareSymTypeExpressions(c1.getSubType(), c2.getSubType()); + if (subTypeComp != 0) { + res = subTypeComp; + } + else { + res = compareSymTypeExpressions(c1.getSuperType(), c2.getSuperType()); + } + return res; + } + + protected int compareTypeCompatibilityConstraints( + TypeCompatibilityConstraint c1, + TypeCompatibilityConstraint c2 + ) { + int res; + int sourceComp = compareSymTypeExpressions(c1.getSourceType(), c2.getSourceType()); + if (sourceComp != 0) { + res = sourceComp; + } + else { + res = compareSymTypeExpressions(c1.getTargetType(), c2.getTargetType()); + } + return res; + } + + protected int compareTypeEqualityConstraints( + TypeEqualityConstraint c1, + TypeEqualityConstraint c2 + ) { + int res; + int first = compareSymTypeExpressions(c1.getFirstType(), c2.getFirstType()); + if (first != 0) { + res = first; + } + else { + res = compareSymTypeExpressions(c1.getSecondType(), c2.getSecondType()); + } + return res; + } + + // helper + + /** + * This is not expected to be ever called. + */ + protected void throwUnimplemented() throws UnsupportedOperationException { + throw new UnsupportedOperationException( + "0xFD663 unimplemented comparison." + ); + } + + // static delegate + + public static void init() { + Log.trace("init default ConstraintComparator", "TypeCheck setup"); + setDelegate(new ConstraintComparator()); + } + + public static void reset() { + ConstraintComparator.delegate = null; + } + + protected static void setDelegate(ConstraintComparator newDelegate) { + ConstraintComparator.delegate = Preconditions.checkNotNull(newDelegate); + } + + protected static ConstraintComparator getDelegate() { + if (ConstraintComparator.delegate == null) { + init(); + } + return ConstraintComparator.delegate; + } + +} diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/ExpressionCompatibilityConstraint.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/ExpressionCompatibilityConstraint.java index 172487b8f1..1701b20176 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/ExpressionCompatibilityConstraint.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/ExpressionCompatibilityConstraint.java @@ -1,10 +1,9 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.generics.constraints; +import com.google.common.base.Preconditions; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.types.check.SymTypeExpression; -import de.se_rwth.commons.logging.Log; - import java.util.List; public class ExpressionCompatibilityConstraint extends Constraint { @@ -16,8 +15,8 @@ public ExpressionCompatibilityConstraint( ASTExpression expr, SymTypeExpression targetType ) { - this.expr = Log.errorIfNull(expr); - this.targetType = Log.errorIfNull(targetType); + this.expr = Preconditions.checkNotNull(expr); + this.targetType = Preconditions.checkNotNull(targetType); } public ASTExpression getExpr() { @@ -33,6 +32,11 @@ public boolean isExpressionCompatibilityConstraint() { return true; } + @Override + public ExpressionCompatibilityConstraint asExpressionCompatibilityConstraint() { + return this; + } + @Override public boolean deepEquals(Constraint other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/SubTypingConstraint.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/SubTypingConstraint.java index 7bc7a93e54..097a17314b 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/SubTypingConstraint.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/SubTypingConstraint.java @@ -31,6 +31,11 @@ public boolean isSubTypingConstraint() { return true; } + @Override + public SubTypingConstraint asSubTypingConstraint() { + return this; + } + @Override public boolean deepEquals(Constraint other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/TypeCompatibilityConstraint.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/TypeCompatibilityConstraint.java index 82d07f9cd1..1243311087 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/TypeCompatibilityConstraint.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/TypeCompatibilityConstraint.java @@ -53,6 +53,11 @@ public boolean isTypeCompatibilityConstraint() { return true; } + @Override + public TypeCompatibilityConstraint asTypeCompatibilityConstraint() { + return this; + } + @Override public boolean deepEquals(Constraint other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/TypeEqualityConstraint.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/TypeEqualityConstraint.java index 336e2a3550..bb86755cbf 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/TypeEqualityConstraint.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/constraints/TypeEqualityConstraint.java @@ -31,6 +31,11 @@ public boolean isTypeEqualityConstraint() { return true; } + @Override + public TypeEqualityConstraint asTypeEqualityConstraint() { + return this; + } + @Override public boolean deepEquals(Constraint other) { if (this == other) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/context/InferenceContext4Ast.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/context/InferenceContext4Ast.java index 647e0e40e2..906bb9ad80 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/context/InferenceContext4Ast.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/context/InferenceContext4Ast.java @@ -11,7 +11,7 @@ import de.se_rwth.commons.logging.Log; import org.apache.commons.io.FilenameUtils; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -56,8 +56,8 @@ public InferenceContext4Ast() { } public void reset() { - expr2ctx = new HashMap<>(); - expr2resolved = new HashMap<>(); + expr2ctx = new LinkedHashMap<>(); + expr2resolved = new LinkedHashMap<>(); } /** diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/context/InferenceResult.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/context/InferenceResult.java index 38d2d1dfea..37672d3805 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/context/InferenceResult.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/context/InferenceResult.java @@ -78,8 +78,8 @@ public boolean hasResolvedNonInvocationType() { /** * A function, either required by an invocation, or by assignment, e.g., - * (a?b:c)(1) // here, b and c are required to be functions - * (int) -> void f = a; // here, a is required to be a function + * {@code (a?b:c)(1)} // here, b and c are required to be functions + * {@code (int) -> void f = a;} // here, a is required to be a function * Only call if {@link #hasResolvedFunction()} returns true. */ public SymTypeOfFunction getResolvedFunction() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/BoundIncorporation.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/BoundIncorporation.java index 0b9ae274c6..a28807ed89 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/BoundIncorporation.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/BoundIncorporation.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.generics.util; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.check.SymTypeInferenceVariable; @@ -23,7 +24,6 @@ import de.monticore.types3.generics.constraints.TypeCompatibilityConstraint; import de.monticore.types3.generics.constraints.TypeEqualityConstraint; import de.monticore.types3.util.SymTypeCollectionVisitor; -import de.monticore.types3.util.SymTypeExpressionComparator; import de.se_rwth.commons.logging.Log; import java.util.ArrayList; @@ -747,9 +747,9 @@ protected Optional incorporateNonSymmetrical(CaptureBound bCap, Type * {@link #incorporateNonSymmetrical(SubTypingBound, SubTypingBound)}, * {@link #incorporateNonSymmetrical(TypeCompatibilityBound, TypeCompatibilityBound)}, * {@link #incorporate(SubTypingBound, TypeCompatibilityBound)}. - * Given a <: A and a <: B, due to them being supertypes of the same type, + * Given {@code a <: A and a <: B}, due to them being supertypes of the same type, * constraints follow, - * e.g., List and List lead to the constraint . + * e.g., {@code List} and {@code List} lead to the constraint {@code }. * If different rules apply (e.g., in OCL), * then this method could be overwritten. * However, as of now it is simply assumed that @@ -758,7 +758,7 @@ protected Optional incorporateNonSymmetrical(CaptureBound bCap, Type * which may or may not get unintuitive in combination with boxing. *

* For TypeCompatibilityBounds, we assume the same rules, - * e.g. a --> A and a <: A results in . + * e.g. {@code a --> A} and {@code a <: A} results in {@code }. * This may need to be overridden for type systems with more flexible * compatibility rules, but we currently do not assume there to be a need * for such a system, this seems to be a sane restriction to make. @@ -1013,10 +1013,10 @@ else if (commonSuperTypesWithoutInfVars.stream().anyMatch( *

* note: this allows combinations without common super types, * e.g., A and B (each without any supertypes). - * This is due to there being the type (A & B), + * This is due to there being the type {@code (A & B)}, * which may exist in a modeling language, * e.g., A and B being interfaces in Java-esque languages. - * One could add rules like A & B cannot exists + * One could add rules like {@code A & B} cannot exists * if they are classes (and not interfaces) * here (by overriding this method); * However, alternatively (and probably the simpler choice), @@ -1031,7 +1031,7 @@ protected List getCommonSuperTypeConstraints( List constraints = new ArrayList<>(); // get all paths Map>> startType2Paths = - new TreeMap<>(new SymTypeExpressionComparator()); + new TreeMap<>(); for (SymTypeExpression startType : startTypes) { startType2Paths.put(startType, getNominalSuperTypePaths(startType)); } @@ -1138,12 +1138,14 @@ protected SymTypeInferenceVariable createFreshVariable() { protected String printConstraints(List constraints) { return constraints.stream() + .sorted() .map(Constraint::print) .collect(Collectors.joining(System.lineSeparator())); } protected String printBounds(List bounds) { return bounds.stream() + .sorted() .map(Bound::print) .collect(Collectors.joining(System.lineSeparator())); } @@ -1160,7 +1162,7 @@ public static void reset() { } protected static void setDelegate(BoundIncorporation newDelegate) { - BoundIncorporation.delegate = Log.errorIfNull(newDelegate); + BoundIncorporation.delegate = Preconditions.checkNotNull(newDelegate); } protected static BoundIncorporation getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/BoundResolution.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/BoundResolution.java index af0d611fc5..c3897bd568 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/BoundResolution.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/BoundResolution.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.generics.util; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.check.SymTypeInferenceVariable; @@ -12,13 +13,12 @@ import de.monticore.types3.generics.bounds.TypeCompatibilityBound; import de.monticore.types3.generics.bounds.TypeEqualityBound; import de.monticore.types3.generics.constraints.Constraint; -import de.monticore.types3.util.SymTypeExpressionComparator; import de.se_rwth.commons.logging.Log; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -85,23 +85,45 @@ protected Optional> _resolve( List toBeResolved ) { return recursiveResolve( - newBounds, oldBounds, toBeResolved, Collections.emptySet() + newBounds, oldBounds, toBeResolved, false ); } /** - * @param lastSetOfUninstantiated used to stop infinite recursion + * @param createdNewInferenceVariablesLastIteration used to stop infinite recursion */ protected Optional> recursiveResolve( List newBounds, List oldBounds, List toBeResolved, - Collection lastSetOfUninstantiated + boolean createdNewInferenceVariablesLastIteration ) { // shortcut reducing log if (newBounds.isEmpty() && oldBounds.isEmpty()) { - return Optional.of(new HashMap<>()); + return Optional.of(new LinkedHashMap<>()); } + Log.trace("START resolving bounds;" + + System.lineSeparator() + " * " + + (newBounds.isEmpty() + ? "no new bounds" + : "new bounds:" + System.lineSeparator() + printBounds(newBounds)) + + System.lineSeparator() + " * " + + (oldBounds.isEmpty() + ? "no old bounds" + : "old bounds:" + System.lineSeparator() + printBounds(oldBounds)) + + System.lineSeparator() + " * to be resolved are:" + + (toBeResolved.isEmpty() ? " all inference variables" + : System.lineSeparator() + + toBeResolved.stream() + .map(SymTypeExpression::printFullName) + .collect(Collectors.joining(System.lineSeparator()))) + + (createdNewInferenceVariablesLastIteration ? + System.lineSeparator() + " * temporary inference variables" + + " have been created last iteration" + : "") + , + LOG_NAME + ); Optional> result = Optional.empty(); // get all relevant bounds: reduced bounds @@ -168,8 +190,9 @@ else if (bound.isTypeEqualityBound()) { } else if (bound.isCaptureBound()) { if (var2CaptureBound.containsKey(varBounds.getKey())) { - Log.error("0xFD211 internal error: multiple capture bound " - + "left hand sides for same variable encountered..." + throw new IllegalArgumentException( + "0xFD211 internal error: multiple capture bound " + + "left hand sides for same variable encountered..." ); } var2CaptureBound.put(varBounds.getKey(), (CaptureBound) bound); @@ -210,14 +233,9 @@ else if (bound.isCaptureBound()) { ); } } - // remove skolem variables - for (SymTypeInferenceVariable var : varInterDependencies.keySet()) { - List dependencies = varInterDependencies.get(var); - varInterDependencies.put(var, dependencies); - } // get current instantiations - List varsWithoutInstantiation = new ArrayList<>(); + Set varsWithoutInstantiation = new TreeSet<>(); Map varInstantiations = createSymTypeExprMap(); for (SymTypeInferenceVariable var : varInterDependencies.keySet()) { Optional instantiation = Optional.empty(); @@ -237,22 +255,12 @@ else if (bound.isCaptureBound()) { } } - // stop infinite recursion after an attempt of JLS 21 18.4, lower part. - // s.a. org.eclipse.jdt.internal.compiler.lookup.InferenceContext18 - // ::resolve - if (!lastSetOfUninstantiated.isEmpty()) { - if (varsWithoutInstantiation.containsAll(lastSetOfUninstantiated)) { - // no progress, give up. - return Optional.empty(); - } - } - // find variables to resolve next // based on JLS 21 18.4 // s.a. org.eclipse.jdt.internal.compiler.lookupInferenceContext18 // ::getSmallestVariableSet - List varsToResolveNext; - List varsToResolveNextNotFinal; + Set varsToResolveNext; + Set varsToResolveNextNotFinal; // do not consider vars that should not be instantiated (yet) if (toBeResolved.isEmpty()) { varsToResolveNextNotFinal = varsWithoutInstantiation; @@ -260,24 +268,30 @@ else if (bound.isCaptureBound()) { else { varsToResolveNextNotFinal = varsWithoutInstantiation.stream() .filter(toBeResolved::contains) - .collect(Collectors.toList()); + .collect(Collectors.toCollection(TreeSet::new)); } for (SymTypeInferenceVariable var : varsWithoutInstantiation) { - Set deps = - new TreeSet<>(new SymTypeExpressionComparator()); - deps.add(var);// should not be necessary, just in case - deps.addAll(varInterDependencies.get(var)); - if (deps.size() < varsToResolveNextNotFinal.size()) { - varsToResolveNextNotFinal = new ArrayList<>(deps); + // the variable and its dependencies + // (excluding variables that already have an instantiation) + // In JLS 21 18.4 this set is V + Set varAndDeps = new TreeSet<>(); + varAndDeps.add(var); + varAndDeps.addAll( + varInterDependencies.get(var).stream() + .filter(varsWithoutInstantiation::contains) + .collect(Collectors.toSet()) + ); + if (varAndDeps.size() < varsToResolveNextNotFinal.size()) { + varsToResolveNextNotFinal = varAndDeps; } } if (varsToResolveNextNotFinal.isEmpty() && !varsWithoutInstantiation.isEmpty()) { - Log.error("0xFD318 internal error: " + // not expected to happen, sanity check + throw new IllegalStateException("0xFD318 internal error: " + "found no set of vars to resolve next?" + System.lineSeparator() + printBounds(reducedBounds) ); - return Optional.empty(); } varsToResolveNext = varsToResolveNextNotFinal; @@ -286,13 +300,29 @@ else if (bound.isCaptureBound()) { // Simple method based on LuBs/GlBs if (varsToResolveNext.stream().noneMatch(var2CaptureBound::containsKey)) { List newEqualityBounds = findInstantiationsSimple( - varsToResolveNext, var2LowerBounds, var2UpperBounds, var2SourceBounds, var2TargetBounds - ); - // use the new-found instantiations to reiterate - result = recursiveResolve( - new ArrayList<>(newEqualityBounds), reducedBounds, toBeResolved, - varsWithoutInstantiation + new ArrayList<>(varsToResolveNext), + var2LowerBounds, var2UpperBounds, var2SourceBounds, var2TargetBounds ); + if (!newEqualityBounds.isEmpty()) { + // use the new-found instantiations to reiterate + result = recursiveResolve( + new ArrayList<>(newEqualityBounds), reducedBounds, toBeResolved, + false + ); + } + else if (createdNewInferenceVariablesLastIteration) { + // stop infinite recursion after an attempt of JLS 21 18.4, lower part. + // s.a. org.eclipse.jdt.internal.compiler.lookup.InferenceContext18 + // ::resolve + Log.trace("END resolving bounds; no new bounds have been found" + + " and creation of additional temporary inference variables" + + " led to no results.", + LOG_NAME); + return Optional.empty(); + } + else { + // continue with complex method + } } // Complex method involving the creation of new inference variables // (s. JLS 21 18.4, lower part) @@ -307,9 +337,17 @@ else if (bound.isCaptureBound()) { newInfVars.add(newInfVar); origVar2NewInfVar.put(var, newInfVar); } - for (int i = 0; i < newInfVars.size(); i++) { - SymTypeInferenceVariable newInfVar = newInfVars.get(i); - SymTypeInferenceVariable origVar = varsToResolveNext.get(i); + Log.trace("created new inference variables as replacements:" + + System.lineSeparator() + origVar2NewInfVar.entrySet().stream() + .map(e -> e.getKey().printFullName() + + " := " + e.getValue().printFullName() + ) + .collect(Collectors.joining(System.lineSeparator())), + LOG_NAME + ); + + for (SymTypeInferenceVariable origVar : origVar2NewInfVar.keySet()) { + SymTypeInferenceVariable newInfVar = origVar2NewInfVar.get(origVar); Optional lowerBound = getLubOfProperLowerBounds(var2LowerBounds.get(origVar)); if (lowerBound.isPresent()) { @@ -343,7 +381,8 @@ else if (bound.isCaptureBound()) { // check for bound consistency if (lowerBound.isPresent() && upperBound.isPresent()) { if (!isSubTypeOf(lowerBound.get(), upperBound.get())) { - Log.info("inconsistent bounds for fresh inference variable: " + Log.info("END resolving bounds; " + + "inconsistent bounds for fresh inference variable: " + lowerBound.get().printFullName() + " is not a subtype of " + upperBound.get().printFullName() + "." + " Will stop resolution." @@ -374,7 +413,7 @@ else if (bound.isCaptureBound()) { new ArrayList<>(newInfVarsBounds), reducedBoundsFiltered, toBeResolved, - varsWithoutInstantiation + true ); // remove the temporary inference variables from the result if (potentialResult.isPresent()) { @@ -400,12 +439,12 @@ else if (bound.isCaptureBound()) { } } if (instantiations.isEmpty()) { - Log.error("0xFD410 internal error: " + // not expected to happen, sanity check + throw new IllegalStateException("0xFD410 internal error: " + "expected to find instantiation for " + var.printFullName() + " within bounds" + System.lineSeparator() + printBounds(reducedBounds) ); - return Optional.empty(); } // any instantiation is OK, as at this point the constraints hold // that all the instantiations are pairwise equal. @@ -413,7 +452,8 @@ else if (bound.isCaptureBound()) { var2Instantiation.put(var, instantiations.get(0)); } } - Log.trace("resolution finished with instantiations:" + Log.trace("END resolving bounds; " + + "resolution finished with instantiations:" + var2Instantiation.keySet().stream() .map(k -> System.lineSeparator() + k.printFullName() + " = " + varInstantiations.get(k).printFullName() @@ -647,7 +687,7 @@ SymTypeExpression getGlb(Collection upperBounds) { /** * to be used after incorporation/reduction. * Does only include top-most inference variables, - * e.g., List <: a2, with a1,a2 being inference variables, returns a2. + * e.g., {@code List <: a2}, with a1,a2 being inference variables, returns a2. */ protected List getInferenceVariablesOfBounds(List bounds) { List inferenceVariables = new ArrayList<>(); @@ -752,13 +792,12 @@ else if (bound.isCaptureBound()) { /** * fills the dependency matrix. * any inferenceVariable, which does not have a bound yet, - * has the bound added: TV <: #Top + * has the bound added: {@code TV <: #Top} */ protected Map> completeVarBoundDependencies( Map> varBoundDependencies ) { - Map> completeDependencies = - new TreeMap<>(new SymTypeExpressionComparator()); + Map> completeDependencies = new TreeMap<>(); completeDependencies.putAll(varBoundDependencies); List includedTypes = new ArrayList<>(); for (List bounds : varBoundDependencies.values()) { @@ -766,8 +805,7 @@ protected Map> completeVarBoundDependencie includedTypes.addAll(bound.getIncludedTypes()); } } - Set includedVariables = - new TreeSet<>(new SymTypeExpressionComparator()); + Set includedVariables = new TreeSet<>(); includedVariables.addAll(includedTypes.stream().flatMap(t -> TypeParameterRelations.getIncludedInferenceVariables(t).stream() ).collect(Collectors.toList()) @@ -837,10 +875,13 @@ protected Optional getGlbOfProperUpperBounds( /** * returns a map that does not rely on hashes * (which does not work well with SymTypeExpressions) + * + * @deprecated simply use a {@link TreeMap} */ + @Deprecated(forRemoval = true) protected Map createSymTypeExprMap() { - return new TreeMap<>(new SymTypeExpressionComparator()); + return new TreeMap<>(); } /** @@ -861,6 +902,7 @@ protected void addAllIfNotDuplicate( protected String printBounds(List constraints) { return constraints.stream() + .sorted() .map(Bound::print) .collect(Collectors.joining(System.lineSeparator())); } @@ -877,7 +919,7 @@ public static void reset() { } protected static void setDelegate(BoundResolution newDelegate) { - BoundResolution.delegate = Log.errorIfNull(newDelegate); + BoundResolution.delegate = Preconditions.checkNotNull(newDelegate); } protected static BoundResolution getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/CompileTimeTypeCalculator.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/CompileTimeTypeCalculator.java index 3da14d4969..1b8750dbd4 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/CompileTimeTypeCalculator.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/CompileTimeTypeCalculator.java @@ -1,6 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3.generics.util; +import com.google.common.base.Preconditions; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; @@ -22,13 +23,12 @@ import de.monticore.types3.generics.context.InferenceResult; import de.monticore.types3.generics.context.InferenceVisitorMode; import de.monticore.types3.util.FunctionRelations; -import de.monticore.types3.util.SymTypeExpressionComparator; import de.monticore.visitor.ITraverser; import de.se_rwth.commons.logging.Log; import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -58,9 +58,9 @@ public class CompileTimeTypeCalculator { * and the target type is a function type, * filter the results and replace the free type variables. * E.g.: - * unfiltered type: (T -> byte) & int - * target type: short -> short - * result: short -> byte + * unfiltered type: {@code (T -> byte) & int} + * target type: {@code short -> short} + * result: {@code short -> byte} * * @param resolvedType Free type variables must have been replaced * with inference variables before calling this method. @@ -85,11 +85,11 @@ public static void handleResolvedType( *

* E.g., let the expression be '1 : intStream'; * The Operator ':' can be represented with the function type - * (a, Stream) -> Stream with 'a' being a free type variable. + * {@code (a, Stream) -> Stream} with 'a' being a free type variable. * The arguments of the function will be '1' and 'intStream'. * In this case, this will first calculate the compile-time type - * of the operator to be (int, Stream) -> Stream. - * Therefore, the type of the expression is Stream, + * of the operator to be {@code (int, Stream) -> Stream}. + * Therefore, the type of the expression is {@code Stream}, * which is stored in the type4AstMap. */ public static void handleCall( @@ -239,8 +239,8 @@ protected void _handleCall( } // specifically, a set of functions must have been resolved - if (getNonFunctionOfResolvedType(funcExprType).isPresent() || - getFunctionsOfResolvedType(funcExprType).isEmpty() + if (getNonFunctionOfResolvedType(funcExprTypeNotNormalized).isPresent() || + getFunctionsOfResolvedType(funcExprTypeNotNormalized).isEmpty() ) { Log.error("0xFDAB4 encountered a function call, " + "but the called value does not have a function type, " @@ -255,7 +255,7 @@ protected void _handleCall( // store each function as an inference result. List functions = - getFunctionsOfResolvedType(funcExprType); + getFunctionsOfResolvedType(funcExprTypeNotNormalized); inferenceResults = new ArrayList<>(functions.size()); for (SymTypeOfFunction function : functions) { InferenceResult funcTypeAsInfRes = new InferenceResult(); @@ -405,7 +405,9 @@ else if (inferenceResults.stream().allMatch(infRes -> infRes.getLastInferenceMod callCtx.setInferredTypes(List.of(applicabilityRes)); } else { - Log.error("0xFD114 internal error: unexpected inference results"); + Log.error("0xFD114 internal error: unexpected inference results", + callExpr.get_SourcePositionStart(), + callExpr.get_SourcePositionEnd()); } } @@ -531,6 +533,17 @@ protected InferenceResult inferCalledFunction( if (!funcInfo.hasParameterCount()) { return getResultIfNoFunctionInfoAvailable(resolvedType, inferenceContext); } + // check that arguments have not been calculated to Obscure + for (int i = 0; i < funcInfo.getParameterCount(); i++) { + if (funcInfo.hasArgumentType(i) && + SymTypeRelations.normalize(funcInfo.getArgumentType(i)) + .isObscureType() + ) { + InferenceResult result = new InferenceResult(); + result.setHasErrorOccurred(); + return result; + } + } // we expect a function, thus get only the functions (filter out vars) List resolvedFuncs = @@ -634,7 +647,7 @@ protected InferenceResult inferCalledFunction( * In the PartialFunctionInfo, * given argument-expressions, these are replaced with types, * iff a type can be calculated without access to a target type. - * E.g., "2+3" is replaced with int, but "new Set<>()" is not replaced, + * E.g., {@code "2+3"} is replaced with int, but {@code "new Set<>()"} is not replaced, * as the type is not fully known without a target type. */ protected void replaceExprsWithTypesIffNoTargetTypeRequired( @@ -832,7 +845,7 @@ protected Optional> getApplicableFunctio PartialFunctionInfo funcInfo ) { Map func2InferenceResult = - new HashMap<>(); + new LinkedHashMap<>(); for (SymTypeOfFunction func : potentiallyApplicableFuncs) { InferenceResult result = new InferenceResult(); result.setResolvedFunction(func); @@ -1160,7 +1173,7 @@ protected void fillAndCheckInvocationTypeBounds( ? " with the target type " + funcInfo.getReturnTargetType().printFullName() : "") + "."; - if (infResult.getInvocationType().isEmpty()) { + if (invocationType.isEmpty()) { Log.error("0xFD447 cannot resolve function invocation type" + logInfo + " Bounds:" + System.lineSeparator() + printBounds(infResult.getB4()) @@ -1204,8 +1217,8 @@ protected void fillInvocationTypeBounds( } /** - * Reduces constraints of the form type>. - * WARNING: While type> IS a constraint, + * Reduces constraints of the form {@code type>}. + * WARNING: While {@code type>} IS a constraint, * it is only ever used in this class; * This is used OUTSIDE of * {@link de.monticore.types3.generics.util.ConstraintReduction}, @@ -1357,7 +1370,7 @@ protected void _handlePassThroughExpression( // Helper /** - * Only exists as Java is missing a ()->void functional interface. + * Only exists as Java is missing a {@code ()->void} functional interface. * This is not meant to be used otherwise. * (Runnable is specifically meant to be used for threads) */ @@ -1366,39 +1379,40 @@ public interface Action { void run(); } + /** + * @param resolvedType must not be normalized + * @return List of normalized functions included in the resolved type + */ protected List getFunctionsOfResolvedType( SymTypeExpression resolvedType ) { - List resolvedFuncs; - if (resolvedType.isIntersectionType()) { - resolvedFuncs = - resolvedType.asIntersectionType().getIntersectedTypeSet().stream() - .filter(SymTypeExpression::isFunctionType) - .map(SymTypeExpression::asFunctionType) - .collect(Collectors.toList()); - } - else if (resolvedType.isFunctionType()) { - resolvedFuncs = Collections.singletonList(resolvedType.asFunctionType()); - } - else { - resolvedFuncs = Collections.emptyList(); - } + List resolvedTypesNonNormalized = + splitResolvedType(resolvedType); + List resolvedTypes = + resolvedTypesNonNormalized.stream() + .map(SymTypeRelations::normalize) + .collect(Collectors.toList()); + List resolvedFuncs = resolvedTypes.stream() + .filter(SymTypeExpression::isFunctionType) + .map(SymTypeExpression::asFunctionType) + .collect(Collectors.toList()); return resolvedFuncs; } + /** + * @param resolvedType must not be normalized + * @return the non-function(s) included in the resolved type + */ protected Optional getNonFunctionOfResolvedType( SymTypeExpression resolvedType ) { Optional nonFunctionType; - List resolvedTypes; - if (resolvedType.isIntersectionType()) { - resolvedTypes = new ArrayList<>( - resolvedType.asIntersectionType().getIntersectedTypeSet() - ); - } - else { - resolvedTypes = Collections.singletonList(resolvedType); - } + List resolvedTypesNonNormalized = + splitResolvedType(resolvedType); + List resolvedTypes = + resolvedTypesNonNormalized.stream() + .map(SymTypeRelations::normalize) + .collect(Collectors.toList()); List nonFuncs = resolvedTypes.stream() .filter(Predicate.not(SymTypeExpression::isFunctionType)) .collect(Collectors.toList()); @@ -1418,6 +1432,26 @@ protected Optional getNonFunctionOfResolvedType( return nonFunctionType; } + /** + * splits a (non-normalized) resolved type into it's components + * + * @return a list of non-normalized types + */ + protected List splitResolvedType( + SymTypeExpression resolvedType + ) { + List resolvedTypes; + if (resolvedType.isIntersectionType()) { + resolvedTypes = new ArrayList<>( + resolvedType.asIntersectionType().getIntersectedTypeSet() + ); + } + else { + resolvedTypes = Collections.singletonList(resolvedType); + } + return resolvedTypes; + } + /** * given a resolved function (with inference variables), * returns a map that replaces the type parameters of the declared function @@ -1435,7 +1469,7 @@ protected Map getParamReplaceMap( .map(SymTypeExpression::asTypeVariable) .collect(Collectors.toList()); Map typeParamReplaceMap = - new TreeMap<>(new SymTypeExpressionComparator()); + new TreeMap<>(); for (int i = 0; i < typeParams.size(); i++) { typeParamReplaceMap.put(typeParams.get(i), infVars.get(i)); } @@ -1453,12 +1487,14 @@ protected Map getParamReplaceMap( protected String printBounds(List bounds) { return bounds.stream() + .sorted() .map(Bound::print) .collect(Collectors.joining(System.lineSeparator())); } protected String printConstraints(List constraints) { return constraints.stream() + .sorted() .map(Constraint::print) .collect(Collectors.joining(System.lineSeparator())); } @@ -1494,7 +1530,7 @@ public static void reset() { } protected static void setDelegate(CompileTimeTypeCalculator newDelegate) { - CompileTimeTypeCalculator.delegate = Log.errorIfNull(newDelegate); + CompileTimeTypeCalculator.delegate = Preconditions.checkNotNull(newDelegate); } protected static CompileTimeTypeCalculator getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/ConstraintReduction.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/ConstraintReduction.java index 48517f3d2f..c13623872b 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/ConstraintReduction.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/ConstraintReduction.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.generics.util; +import com.google.common.base.Preconditions; import de.monticore.types3.SymTypeRelations; import de.monticore.types3.generics.bounds.Bound; import de.monticore.types3.generics.constraints.BoundWrapperConstraint; @@ -116,12 +117,14 @@ protected List reduce(TypeEqualityConstraint constraint) { protected String printConstraints(List constraints) { return constraints.stream() + .sorted() .map(Constraint::print) .collect(Collectors.joining(System.lineSeparator())); } protected String printBounds(List constraints) { return constraints.stream() + .sorted() .map(Bound::print) .collect(Collectors.joining(System.lineSeparator())); } @@ -138,7 +141,7 @@ public static void reset() { } protected static void setDelegate(ConstraintReduction newDelegate) { - ConstraintReduction.delegate = Log.errorIfNull(newDelegate); + ConstraintReduction.delegate = Preconditions.checkNotNull(newDelegate); } protected static ConstraintReduction getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/PartialFunctionInfo.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/PartialFunctionInfo.java index f0c1dbe2c3..2c05c03712 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/PartialFunctionInfo.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/PartialFunctionInfo.java @@ -6,7 +6,7 @@ import de.monticore.types.check.SymTypeOfFunction; import java.util.ArrayList; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -22,9 +22,9 @@ public class PartialFunctionInfo { Optional parameterCount = Optional.empty(); - Map argumentExprs = new HashMap<>(); + Map argumentExprs = new LinkedHashMap<>(); - Map argumentTypes = new HashMap<>(); + Map argumentTypes = new LinkedHashMap<>(); public PartialFunctionInfo() { } @@ -150,8 +150,8 @@ public PartialFunctionInfo deepClone() { PartialFunctionInfo clone = new PartialFunctionInfo(); clone.returnTargetType = returnTargetType.map(SymTypeExpression::deepClone); clone.parameterCount = parameterCount.map(Function.identity()); - clone.argumentExprs = new HashMap<>(argumentExprs); - clone.argumentTypes = new HashMap<>(argumentTypes); + clone.argumentExprs = new LinkedHashMap<>(argumentExprs); + clone.argumentTypes = new LinkedHashMap<>(argumentTypes); return clone; } diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeFreeVariableReplaceVisitor.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeFreeVariableReplaceVisitor.java index 206e74f3b0..c237b10881 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeFreeVariableReplaceVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeFreeVariableReplaceVisitor.java @@ -9,7 +9,7 @@ import de.monticore.types.check.SymTypeVariable; import de.monticore.types3.util.SymTypeDeepCloneVisitor; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -61,7 +61,7 @@ public void visit(SymTypeVariable typeVar) { // as containsKey uses equals, we need to go other it ourselves SymTypeInferenceVariable replacement = null; for (SymTypeVariable keyTypeVar : getReplaceMap().keySet()) { - if (typeVar.denotesSameVar(keyTypeVar) && replacement == null) { + if (typeVar.deepEquals(keyTypeVar) && replacement == null) { replacement = getReplaceMap().get(keyTypeVar); } } @@ -85,7 +85,7 @@ public Result calculate( IBasicSymbolsScope enclosingScope ) { Map oldMap = this.replaceMap; - setReplaceMap(new HashMap<>()); + setReplaceMap(new LinkedHashMap<>()); IBasicSymbolsScope oldScope = this.enclosingScope; setEnclosingScope(enclosingScope); diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeInferenceVariableReplaceVisitor.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeInferenceVariableReplaceVisitor.java index f527198b08..09b856d75b 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeInferenceVariableReplaceVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeInferenceVariableReplaceVisitor.java @@ -4,7 +4,6 @@ import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeInferenceVariable; import de.monticore.types3.util.SymTypeDeepCloneVisitor; -import de.monticore.types3.util.SymTypeExpressionComparator; import java.util.Collections; import java.util.Map; @@ -12,8 +11,8 @@ /** * replaces InferenceVariables using a given map - * e.g., a, {a->int,b->float} -> int - * e.g., List, {a->int} -> List + * e.g., {@code a, @code {a->int,b->float} -> int} + * e.g., {@code List, {a->int} -> List} * Usage: * calculate(symType, replaceMap) */ @@ -56,8 +55,7 @@ public SymTypeExpression calculate( ) { Map oldMap = this.replaceMap; // assure that the map used does not rely on hashes - Map newMap = - new TreeMap<>(new SymTypeExpressionComparator()); + Map newMap = new TreeMap<>(); newMap.putAll(replaceMap); setReplaceMap(newMap); SymTypeExpression result = calculate(symType); diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeVariableReplaceVisitor.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeVariableReplaceVisitor.java index 59585c2423..ef2980eff8 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeVariableReplaceVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/SymTypeVariableReplaceVisitor.java @@ -4,7 +4,6 @@ import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeVariable; import de.monticore.types3.util.SymTypeDeepCloneVisitor; -import de.monticore.types3.util.SymTypeExpressionComparator; import java.util.Collections; import java.util.Map; @@ -12,8 +11,8 @@ /** * replaces TypeVariables using a given map - * e.g., T, {T->int,U->float} -> int - * e.g., List, {T->int} -> List + * e.g., T, {@code {T->int,U->float} -> int} + * e.g., {@code List, {T->int} -> List} * Usage: * calculate(symType, replaceMap) */ @@ -38,7 +37,7 @@ public void visit(SymTypeVariable typVar) { // as containsKey uses equals, we need to go other it ourselves boolean inMap = false; for (SymTypeVariable keyTypeVar : getReplaceMap().keySet()) { - if (typVar.denotesSameVar(keyTypeVar) & !inMap) { + if (typVar.deepEquals(keyTypeVar) & !inMap) { pushTransformedSymType(getReplaceMap().get(keyTypeVar)); inMap = true; } @@ -56,8 +55,7 @@ public SymTypeExpression calculate( ) { Map oldMap = this.replaceMap; // assure that the map used does not rely on hashes - Map newMap = - new TreeMap<>(new SymTypeExpressionComparator()); + Map newMap = new TreeMap<>(); newMap.putAll(replaceMap); setReplaceMap(newMap); SymTypeExpression result = calculate(symType); diff --git a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/WildcardCapturer.java b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/WildcardCapturer.java index 3befea5bcd..3c11e7543f 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/generics/util/WildcardCapturer.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/generics/util/WildcardCapturer.java @@ -79,7 +79,7 @@ protected SymTypeOfFunction calculateGetCaptureConverted(SymTypeOfFunction func) * as they have no symbols to get type parameters from. * E.g., * {@code List -> Person f = (xs) -> xs.get(0);} - * the lambda function "is declared with the type" T -> R, + * the lambda function "is declared with the type" {@code T -> R}, * there T and R are type parameters, * and, according to Java Spec 20 15.27.3 the ground target type of * {@code List -> Person} @@ -202,7 +202,7 @@ else if (wildcard.isUpper()) { protected List getTypeParameters(SymTypeOfGenerics gen) { SymTypeOfGenerics declaredType = - SymTypeExpressionFactory.createGenerics(gen.getTypeInfo()); + SymTypeExpressionFactory.createGenericsDeclaredType(gen.getTypeInfo()); List typeParameters = declaredType.getArgumentList() .stream().map(SymTypeExpression::asTypeVariable) .collect(Collectors.toList()); diff --git a/monticore-grammar/src/main/java/de/monticore/types3/streams/StreamSymTypeRelations.java b/monticore-grammar/src/main/java/de/monticore/types3/streams/StreamSymTypeRelations.java index 8f02f218a2..c92d2a1589 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/streams/StreamSymTypeRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/streams/StreamSymTypeRelations.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.streams; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.check.SymTypeOfGenerics; @@ -124,7 +125,7 @@ public static void reset() { } protected static void setDelegate(StreamSymTypeRelations newDelegate) { - StreamSymTypeRelations.delegate = Log.errorIfNull(newDelegate); + StreamSymTypeRelations.delegate = Preconditions.checkNotNull(newDelegate); } protected static StreamSymTypeRelations getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/FunctionRelations.java b/monticore-grammar/src/main/java/de/monticore/types3/util/FunctionRelations.java index f58bf55a0f..89a23f51d0 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/FunctionRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/FunctionRelations.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeInferenceVariable; import de.monticore.types.check.SymTypeOfFunction; @@ -261,7 +262,7 @@ public static void reset() { } protected static void setDelegate(FunctionRelations newDelegate) { - FunctionRelations.delegate = Log.errorIfNull(newDelegate); + FunctionRelations.delegate = Preconditions.checkNotNull(newDelegate); } protected static FunctionRelations getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/LValueRelations.java b/monticore-grammar/src/main/java/de/monticore/types3/util/LValueRelations.java index af3cf38992..cc8d45dc95 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/LValueRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/LValueRelations.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.se_rwth.commons.logging.Log; @@ -57,7 +58,7 @@ public static void reset() { } protected static void setDelegate(LValueRelations newDelegate) { - LValueRelations.delegate = Log.errorIfNull(newDelegate); + LValueRelations.delegate = Preconditions.checkNotNull(newDelegate); } protected static LValueRelations getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/MapBasedTypeCheck3.java b/monticore-grammar/src/main/java/de/monticore/types3/util/MapBasedTypeCheck3.java index 2a0dcd063e..4ee46ec795 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/MapBasedTypeCheck3.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/MapBasedTypeCheck3.java @@ -1,5 +1,6 @@ package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; import de.monticore.types.check.SymTypeExpression; @@ -53,9 +54,9 @@ public MapBasedTypeCheck3( Type4Ast type4Ast, InferenceContext4Ast ctx4Ast ) { - this.typeTraverser = Log.errorIfNull(typeTraverser); - this.type4Ast = Log.errorIfNull(type4Ast); - this.ctx4Ast = Log.errorIfNull(ctx4Ast); + this.typeTraverser = Preconditions.checkNotNull(typeTraverser); + this.type4Ast = Preconditions.checkNotNull(type4Ast); + this.ctx4Ast = Preconditions.checkNotNull(ctx4Ast); } /** diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/NominalSuperTypeCalculator.java b/monticore-grammar/src/main/java/de/monticore/types3/util/NominalSuperTypeCalculator.java index 969bc3d139..5cdf9b8229 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/NominalSuperTypeCalculator.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/NominalSuperTypeCalculator.java @@ -28,8 +28,8 @@ public class NominalSuperTypeCalculator { * Practically, this is meant to be used with object types including generics. * This returns the list of nominal supertypes, * e.g., in Java using extends / implements - * e.g. Collection is an explicit super type of List, - * List is a super type of List, + * e.g. {@code Collection} is an explicit super type of {@code List}, + * {@code List} is a super type of {@code List}, * but not an explicitly defined one. * We consider explicitly defined super types to be the ones * given by the list of super types in the type symbol. diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/OOWithinTypeBasicSymbolsResolver.java b/monticore-grammar/src/main/java/de/monticore/types3/util/OOWithinTypeBasicSymbolsResolver.java index ff1dbc8c98..1c95e25886 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/OOWithinTypeBasicSymbolsResolver.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/OOWithinTypeBasicSymbolsResolver.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; import de.monticore.symbols.oosymbols.OOSymbolsMill; @@ -8,14 +9,15 @@ import de.monticore.symboltable.modifiers.AccessModifier; import de.monticore.symboltable.modifiers.StaticAccessModifier; import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypeInferenceVariable; import de.monticore.types.check.SymTypeOfFunction; +import de.monticore.types.check.SymTypeVariable; +import de.monticore.types3.generics.TypeParameterRelations; import de.se_rwth.commons.logging.Log; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; import java.util.function.Predicate; +import java.util.stream.Collectors; /** * resolves within a type, @@ -82,7 +84,12 @@ protected List _resolveConstructors( // do not search super types for constructors - return resolvedSymTypes; + List symTypesFreeVarsReplaced = resolvedSymTypes.stream() + .map(this::replaceFreeConstructorTypeVariables) + .map(SymTypeExpression::asFunctionType) + .collect(Collectors.toList()); + + return symTypesFreeVarsReplaced; } // Helper @@ -92,19 +99,19 @@ protected List _resolveConstructors( * this filters out constructors */ @Override - protected List resolveFunctionLocally( + protected List resolveFunctionLocallyMany( IBasicSymbolsScope scope, String name, AccessModifier accessModifier, Predicate predicate) { - return super.resolveFunctionLocally( + return super.resolveFunctionLocallyMany( scope, name, accessModifier, predicate.and(Predicate.not(this::isConstructor)) ); } /** - * same as {@link #resolveFunctionLocally} + * same as {@link #resolveFunctionLocallyMany} * but does only returns constructors * * @deprecated is to be made private, use {@link #resolveConstructors} @@ -116,19 +123,27 @@ public List resolveConstructorLocally( AccessModifier accessModifier, Predicate predicate ) { - return super.resolveFunctionLocally( + return super.resolveFunctionLocallyMany( scope, name, removeStaticness(accessModifier), predicate.and(this::isConstructor) ); } - // Helper + protected SymTypeExpression replaceFreeConstructorTypeVariables(SymTypeExpression type) { + // 1. get unbound variable replacement map + Map freeVarMap = + getUnboundVariableReplaceMap(Collections.emptyList(), type); + // 2. actually replace the free variables + SymTypeExpression typeVarsReplaced = + TypeParameterRelations.replaceTypeVariables(type, freeVarMap); + + return typeVarsReplaced; + } protected boolean isConstructor(FunctionSymbol func) { if (OOSymbolsMill.typeDispatcher().isOOSymbolsMethod(func)) { - MethodSymbol method = - OOSymbolsMill.typeDispatcher().asOOSymbolsMethod(func); + MethodSymbol method = OOSymbolsMill.typeDispatcher().asOOSymbolsMethod(func); return method.isIsConstructor(); } return false; @@ -161,7 +176,7 @@ public static void reset() { protected static void setDelegate( OOWithinTypeBasicSymbolsResolver newDelegate ) { - OOWithinTypeBasicSymbolsResolver.delegate = Log.errorIfNull(newDelegate); + OOWithinTypeBasicSymbolsResolver.delegate = Preconditions.checkNotNull(newDelegate); WithinTypeBasicSymbolsResolver.setDelegate(newDelegate); } diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SIUnitTypeRelations.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SIUnitTypeRelations.java index 9496a3817b..0bd0986865 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SIUnitTypeRelations.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SIUnitTypeRelations.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.types.check.SIUnitBasic; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; @@ -12,7 +13,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -38,14 +39,14 @@ public class SIUnitTypeRelations { /** * to convert to base units, e.g., - * Hz -> s^-1 - * J -> m^2*g*s^-2 + * {@code Hz -> s^-1} + * {@code J -> m^2*g*s^-2} */ protected static final Map> conversionTable; // initializes the conversion table static { - Map> conversionTableTmp = new HashMap<>(); + Map> conversionTableTmp = new LinkedHashMap<>(); // already base units: conversionTableTmp.put("m", List.of(createSIBaseUnit("m"))); conversionTableTmp.put("g", List.of(createSIBaseUnit("g"))); @@ -195,10 +196,10 @@ protected boolean _isOfDimensionOne(SymTypeOfSIUnit siUnit) { * (s, m, kg, A, K, mol, cd) * any prefixes are removed (except "k" of kg) * Additionally, only one of each base unit exists in the SymType, e.g., - * kg^2*m*kg -> kg^3*m + * {@code kg^2*m*kg -> kg^3*m} * and every exponent is positive, e.g., - * kg^-2*m^0*s/K^-2 -> s*K^2/kg^2 - *

+ * {@code kg^-2*m^0*s/K^-2 -> s*K^2/kg^2} + *

* this is implemented here (instead of the normalize visitor), * as it requires a lot of domain-specific knowledge / calculations. */ @@ -209,7 +210,7 @@ public static SymTypeOfSIUnit internal_normalize(SymTypeOfSIUnit siUnit) { protected SymTypeOfSIUnit _normalize(SymTypeOfSIUnit siUnit) { SymTypeOfSIUnit siUnitWithBaseUnits = convertToSIBaseUnits(siUnit); // collect all exponents - Map unit2Exp = new HashMap<>(); + Map unit2Exp = new LinkedHashMap<>(); for (String dimension : baseUnitStrings) { unit2Exp.put(dimension, 0); } @@ -397,7 +398,7 @@ public static void reset() { } protected static void setDelegate(SIUnitTypeRelations newDelegate) { - SIUnitTypeRelations.delegate = Log.errorIfNull(newDelegate); + SIUnitTypeRelations.delegate = Preconditions.checkNotNull(newDelegate); } protected static SIUnitTypeRelations getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeBoxingVisitor.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeBoxingVisitor.java index d3cdcd57ae..dc6494422d 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeBoxingVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeBoxingVisitor.java @@ -10,34 +10,34 @@ import de.se_rwth.commons.logging.Log; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; /** * Boxes SymTypeExpressions, * including, but not limited to, Java primitive boxing - * e.g., int -> java.lang.Integer - * e.g., List -> java.util.List + * e.g., {@code int -> java.lang.Integer} + * e.g., {@code List -> java.util.List} * Usage: * calculate(symType) */ public class SymTypeBoxingVisitor extends SymTypeDeepCloneVisitor { /** - * Map for boxing primitive types (e.g. "int" -> "java.lang.Integer") + * Map for boxing primitive types (e.g. {@code "int" -> "java.lang.Integer"}) * Results are fully qualified. */ protected static final Map primitiveBoxMap; /** - * Map for boxing object types (e.g. "String" -> "java.lang.String") + * Map for boxing object types (e.g. {@code "String" -> "java.lang.String"}) * Results are fully qualified. */ protected static final Map objectBoxMap; /** - * Map for boxing generic types (e.g. "List" -> "java.util.List") + * Map for boxing generic types (e.g. {@code "List" -> "java.util.List"}) * Results are fully qualified. */ protected static final Map genericBoxMap; @@ -58,7 +58,7 @@ public Map getGenericBoxMap() { * initializing the maps */ static { - Map primitiveBoxMap_temp = new HashMap<>(); + Map primitiveBoxMap_temp = new LinkedHashMap<>(); primitiveBoxMap_temp.put("boolean", "java.lang.Boolean"); primitiveBoxMap_temp.put("byte", "java.lang.Byte"); primitiveBoxMap_temp.put("char", "java.lang.Character"); @@ -69,11 +69,11 @@ public Map getGenericBoxMap() { primitiveBoxMap_temp.put("short", "java.lang.Short"); primitiveBoxMap = Collections.unmodifiableMap(primitiveBoxMap_temp); - Map objectBoxMap_temp = new HashMap<>(); + Map objectBoxMap_temp = new LinkedHashMap<>(); objectBoxMap_temp.put("String", "java.lang.String"); objectBoxMap = Collections.unmodifiableMap(objectBoxMap_temp); - Map genericBoxMap_temp = new HashMap<>(); + Map genericBoxMap_temp = new LinkedHashMap<>(); genericBoxMap_temp.put("Optional", "java.util.Optional"); genericBoxMap_temp.put("Set", "java.util.Set"); genericBoxMap_temp.put("List", "java.util.List"); diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeCollectionVisitor.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeCollectionVisitor.java index a9b106bb6a..cf0e007b92 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeCollectionVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeCollectionVisitor.java @@ -10,9 +10,9 @@ /** * Collects contained SymTypeExpressions based on a predicate, e.g., - * type: (List, Set>) -> void + * type: {@code (List, Set>) -> void} * predicate: isList - * result: List, List + * result: {@code List, List} * Usage: * calculate(mySymType, predicate) */ diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeCompatibilityCalculator.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeCompatibilityCalculator.java index b28219e03e..2142da2da6 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeCompatibilityCalculator.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeCompatibilityCalculator.java @@ -618,7 +618,7 @@ protected List typeSetConstrainSubTypeOf( // as two unbounded type variable are not subTypes of each other otherwise if (subType.isTypeVariable() && superType.isTypeVariable() && - subType.asTypeVariable().denotesSameVar(superType) + subType.asTypeVariable().deepEquals(superType) ) { result = Collections.emptyList(); } @@ -1251,19 +1251,19 @@ else if (wcA.hasBound() != wcB.hasBound() || wcA.isUpper() != wcB.isUpper()) { * this helper function (currently) is only to check subtyping of generics. * Tuples could be extended in this regard (currently not needed). *

- * Fundamentally, T1 "contains" T2 ("T2 <= T1") + * Fundamentally, T1 "contains" T2 ({@code "T2 <= T1"}) * if the set of types denoted by T1 is (provably) a superSet * of the types denoted by T2. * This translates to the reflexive and transitive closure of (from spec): *

*/ protected List constrainContainsPreNormalized( @@ -1344,7 +1344,7 @@ else if (!subSetType.asWildcard().isUpper()) { } /** - * Reduces a constraint to the constraints , . + * Reduces a constraint {@code } to the constraints {@code , }. * This is not necessarily ideal wrt. resulting messages, * and should be replaced in the future if required. * It will most likely result in incorrect values, @@ -1435,6 +1435,7 @@ protected T boxGenericButNotArguments(T type) { protected String printBounds(List bounds) { return bounds.stream() + .sorted() .map(Bound::print) .collect(Collectors.joining(System.lineSeparator())); } diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeDeepCloneVisitor.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeDeepCloneVisitor.java index 404d77ee81..1f8f36e3c4 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeDeepCloneVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeDeepCloneVisitor.java @@ -7,7 +7,7 @@ import de.se_rwth.commons.logging.Log; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.Stack; @@ -266,7 +266,7 @@ protected List applyToCollection( protected Set applyToCollection( Set symTypes) { - Set transformedTypes = new HashSet<>(); + Set transformedTypes = new LinkedHashSet<>(); for (SymTypeExpression type : symTypes) { type.accept(this); transformedTypes.add(popTransformedSubSymType()); diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeExpressionComparator.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeExpressionComparator.java index 45b6976888..8161d3221a 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeExpressionComparator.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeExpressionComparator.java @@ -1,10 +1,15 @@ +/*(c) https://github.com/MontiCore/monticore*/ package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.symboltable.ISymbol; import de.monticore.types.check.*; import de.se_rwth.commons.logging.Log; import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; /** * A Helper to create (Tree)Maps. @@ -14,242 +19,163 @@ public class SymTypeExpressionComparator implements Comparator { + protected static SymTypeExpressionComparator delegate; + + public static int compareSymTypeExpressions( + SymTypeExpression o1, + SymTypeExpression o2 + ) { + return getDelegate().compare(o1, o2); + } + @Override public int compare(SymTypeExpression o1, SymTypeExpression o2) { - Log.errorIfNull(o1); - Log.errorIfNull(o2); - if (o1.deepEquals(o2)) { - return 0; + Preconditions.checkNotNull(o1); + Preconditions.checkNotNull(o2); + + int res; + + int orderOfSubType1 = getOrderOfSubType(o1); + int orderOfSubType2 = getOrderOfSubType(o2); + int subTypeOrdering = Integer.compare(orderOfSubType1, orderOfSubType2); + + if (subTypeOrdering != 0) { + res = subTypeOrdering; } - else if (o1.isUnionType()) { - if (!o2.isUnionType()) { - return -1; - } - else { - return compareUnion(o1.asUnionType(), o2.asUnionType()); - } + else if (o1.deepEquals(o2)) { + res = 0; } - else if (o2.isUnionType()) { - return 1; + else if (o1.isUnionType() && o2.isUnionType()) { + res = compareUnion(o1.asUnionType(), o2.asUnionType()); } - else if (o1.isIntersectionType()) { - if (!o2.isIntersectionType()) { - return -1; - } - else { - return compareIntersection( - o1.asIntersectionType(), - o2.asIntersectionType() - ); - } + else if (o1.isIntersectionType() && o2.isIntersectionType()) { + res = compareIntersection(o1.asIntersectionType(), o2.asIntersectionType()); } - else if (o2.isIntersectionType()) { - return 1; + else if (o1.isTupleType() && o2.isTupleType()) { + res = compareTuple(o1.asTupleType(), o2.asTupleType()); } - else if (o1.isTupleType()) { - if (!o2.isTupleType()) { - return -1; - } - else { - return compareTuple(o1.asTupleType(), o2.asTupleType()); - } + else if (o1.isFunctionType() && o2.isFunctionType()) { + res = compareFunction(o1.asFunctionType(), o2.asFunctionType()); } - else if (o2.isTupleType()) { - return 1; + else if (o1.isArrayType() && o2.isArrayType()) { + res = compareArray(o1.asArrayType(), o2.asArrayType()); } - else if (o1.isFunctionType()) { - if (!o2.isFunctionType()) { - return -1; - } - else { - return compareFunction(o1.asFunctionType(), o2.asFunctionType()); - } + else if (o1.isPrimitive() && o2.isPrimitive()) { + res = comparePrimitive(o1.asPrimitive(), o2.asPrimitive()); } - else if (o2.isFunctionType()) { - return 1; + else if (o1.isSIUnitType() && o2.isSIUnitType()) { + res = compareSIUnit(o1.asSIUnitType(), o2.asSIUnitType()); } - else if (o1.isArrayType()) { - if (!o2.isArrayType()) { - return -1; - } - else { - return compareArray(o1.asArrayType(), o2.asArrayType()); - } + else if (o1.isNumericWithSIUnitType() && o2.isNumericWithSIUnitType()) { + res = compareNumericWithSIUnit( + o1.asNumericWithSIUnitType(), + o2.asNumericWithSIUnitType() + ); } - else if (o2.isArrayType()) { - return 1; + else if (o1.isRegExType() && o2.isRegExType()) { + res = compareRegEx(o1.asRegExType(), o2.asRegExType()); } - else if (o1.isPrimitive()) { - if (!o2.isPrimitive()) { - return -1; - } - else { - return comparePrimitive(o1.asPrimitive(), o2.asPrimitive()); - } + else if (o1.isObjectType() && o2.isObjectType()) { + res = compareObject(o1.asObjectType(), o2.asObjectType()); } - else if (o2.isPrimitive()) { - return 1; + else if (o1.isGenericType() && o2.isGenericType()) { + res = compareGeneric(o1.asGenericType(), o2.asGenericType()); } - else if (o1.isSIUnitType()) { - if (!o2.isSIUnitType()) { - return -1; - } - else { - return compareSIUnit(o1.asSIUnitType(), o2.asSIUnitType()); - } + else if (o1.isWildcard() && o2.isWildcard()) { + res = compareWildcard(o1.asWildcard(), o2.asWildcard()); } - else if (o2.isSIUnitType()) { - return 1; + else if (o1.isTypeVariable() && o2.isTypeVariable()) { + res = compareTypeVar(o1.asTypeVariable(), o2.asTypeVariable()); } - else if (o1.isNumericWithSIUnitType()) { - if (!o2.isNumericWithSIUnitType()) { - return -1; - } - else { - return compareNumericWithSIUnit( - o1.asNumericWithSIUnitType(), - o2.asNumericWithSIUnitType() - ); - } + else if (o1.isInferenceVariable() && o2.isInferenceVariable()) { + res = compareInfVar(o1.asInferenceVariable(), o2.asInferenceVariable()); } - else if (o2.isNumericWithSIUnitType()) { - return 1; + // null, void, and obscure are handled by deepEquals + else { + throwUnimplemented(); + res = -41; } - else if (o1.isRegExType()) { - if (!o2.isRegExType()) { - return -1; - } - else { - return compareRegEx(o1.asRegExType(), o2.asRegExType()); - } + return res; + } + + protected int getOrderOfSubType(SymTypeExpression type) { + if (type.isObscureType()) { + return 0; } - else if (o2.isRegExType()) { - return 1; + else if (type.isVoidType()) { + return 10; } - else if (o1.isObjectType()) { - if (!o2.isObjectType()) { - return -1; - } - else { - return compareObject(o1.asObjectType(), o2.asObjectType()); - } + else if (type.isNullType()) { + return 20; } - else if (o2.isObjectType()) { - return 1; + else if (type.isPrimitive()) { + return 30; } - else if (o1.isGenericType()) { - if (!o2.isGenericType()) { - return -1; - } - else { - return compareGeneric(o1.asGenericType(), o2.asGenericType()); - } + else if (type.isSIUnitType()) { + return 40; } - else if (o2.isGenericType()) { - return 1; + else if (type.isNumericWithSIUnitType()) { + return 50; } - else if (o1.isWildcard()) { - if (!o2.isWildcard()) { - return -1; - } - else { - return compareWildcard(o1.asWildcard(), o2.asWildcard()); - } + else if (type.isRegExType()) { + return 55; } - else if (o2.isWildcard()) { - return 1; + else if (type.isObjectType()) { + return 60; } - else if (o1.isTypeVariable()) { - if (!o2.isTypeVariable()) { - return -1; - } - else { - return compareTypeVar(o1.asTypeVariable(), o2.asTypeVariable()); - } + else if (type.isGenericType()) { + return 70; } - else if (o2.isTypeVariable()) { - return 1; + else if (type.isArrayType()) { + return 80; } - else if (o1.isInferenceVariable()) { - if (!o2.isInferenceVariable()) { - return -1; - } - else { - return compareInfVar(o1.asInferenceVariable(), o2.asInferenceVariable()); - } + else if (type.isFunctionType()) { + return 90; } - else if (o2.isInferenceVariable()) { - return 1; + else if (type.isTupleType()) { + return 100; } - // the following do not have any further comparisons, - // as two of the same type cannot differ - else if (o1.isNullType()) { - return -1; + else if (type.isUnionType()) { + return 110; } - else if (o2.isNullType()) { - return 1; + else if (type.isIntersectionType()) { + return 120; } - else if (o1.isVoidType()) { - return -1; + else if (type.isTypeVariable()) { + return 130; } - else if (o2.isVoidType()) { - return 1; + else if (type.isInferenceVariable()) { + return 140; } - else if (o1.isObscureType()) { - return -1; + else if (type.isWildcard()) { + return 150; + } + else { + throwUnimplemented(); + return -42; } - return logUnimplemented(); } protected int compareUnion(SymTypeOfUnion o1, SymTypeOfUnion o2) { - if (o1.sizeUnionizedTypes() < o2.sizeUnionizedTypes()) { - return -1; - } - else if (o1.sizeUnionizedTypes() > o2.sizeUnionizedTypes()) { - return 1; - } - else { - return o1.printFullName().compareTo(o2.printFullName()); - } + return compareSets(o1.getUnionizedTypeSet(), o2.getUnionizedTypeSet()); } protected int compareIntersection(SymTypeOfIntersection o1, SymTypeOfIntersection o2) { - if (o1.sizeIntersectedTypes() < o2.sizeIntersectedTypes()) { - return -1; - } - else if (o1.sizeIntersectedTypes() > o2.sizeIntersectedTypes()) { - return 1; - } - else { - return o1.printFullName().compareTo(o2.printFullName()); - } + return compareSets(o1.getIntersectedTypeSet(), o2.getIntersectedTypeSet()); } protected int compareTuple(SymTypeOfTuple o1, SymTypeOfTuple o2) { - if (o1.sizeTypes() < o2.sizeTypes()) { - return -1; - } - else if (o1.sizeTypes() > o2.sizeTypes()) { - return 1; - } - else { - int res; - for (int i = 0; i < o1.sizeTypes(); i++) { - res = compare(o1.getType(i), o2.getType(i)); - if (res != 0) { - return res; - } - } - } - return logUnimplemented(); + return compareLists(o1.getTypeList(), o2.getTypeList()); } protected int compareFunction(SymTypeOfFunction o1, SymTypeOfFunction o2) { - if (o1.sizeArgumentTypes() < o2.sizeArgumentTypes()) { - return -1; + int retTypeComp = compareSymTypeExpressions(o1.getType(), o2.getType()); + if (retTypeComp != 0) { + return retTypeComp; } - else if (o1.sizeArgumentTypes() > o2.sizeArgumentTypes()) { - return 1; + int argsComp = compareLists(o1.getArgumentTypeList(), o2.getArgumentTypeList()); + if (argsComp != 0) { + return argsComp; } else if (o1.isElliptic() && !o2.isElliptic()) { return -1; @@ -257,19 +183,8 @@ else if (o1.isElliptic() && !o2.isElliptic()) { else if (!o1.isElliptic() && o2.isElliptic()) { return 1; } - else { - int res = compare(o1.getType(), o2.getType()); - if (res != 0) { - return res; - } - for (int i = 0; i < o1.sizeArgumentTypes(); i++) { - res = compare(o1.getArgumentType(i), o2.getArgumentType(i)); - if (res != 0) { - return res; - } - } - } - return logUnimplemented(); + throwUnimplemented(); + return -42; } protected int compareArray(SymTypeArray o1, SymTypeArray o2) { @@ -290,7 +205,10 @@ protected int compareSIUnit(SymTypeOfSIUnit o1, SymTypeOfSIUnit o2) { return o1.printFullName().compareTo(o2.printFullName()); } - protected int compareNumericWithSIUnit(SymTypeOfNumericWithSIUnit o1, SymTypeOfNumericWithSIUnit o2) { + protected int compareNumericWithSIUnit( + SymTypeOfNumericWithSIUnit o1, + SymTypeOfNumericWithSIUnit o2 + ) { int res = compare(o1.getNumericType(), o2.getNumericType()); if (res != 0) { return res; @@ -307,20 +225,11 @@ protected int compareObject(SymTypeOfObject o1, SymTypeOfObject o2) { } protected int compareGeneric(SymTypeOfGenerics o1, SymTypeOfGenerics o2) { - if (o1.sizeArguments() > o2.sizeArguments()) { - return -1; + int symComp = compareSymbol(o1.getTypeInfo(), o2.getTypeInfo()); + if (symComp != 0) { + return symComp; } - else if (o1.sizeArguments() < o2.sizeArguments()) { - return 1; - } - int res; - for (int i = 0; i < o1.sizeArguments(); i++) { - res = compare(o1.getArgument(i), o2.getArgument(i)); - if (res != 0) { - return res; - } - } - return compareSymbol(o1.getTypeInfo(), o2.getTypeInfo()); + return compareLists(o1.getArgumentList(), o2.getArgumentList()); } protected int compareWildcard(SymTypeOfWildcard o1, SymTypeOfWildcard o2) { @@ -347,30 +256,138 @@ protected int compareInfVar( SymTypeInferenceVariable o1, SymTypeInferenceVariable o2 ) { - int res = compare(o1.getUpperBound(), o2.getUpperBound()); - if (res != 0) { - return res; + int idComp = Integer.compare(o1._internal_getID(), o2._internal_getID()); + if (idComp != 0) { + return idComp; } - res = compare(o1.getLowerBound(), o2.getLowerBound()); - if (res != 0) { - return res; + int upperComp = compare(o1.getUpperBound(), o2.getUpperBound()); + if (upperComp != 0) { + return upperComp; } - return Integer.compare(o1._internal_getID(), o2._internal_getID()); + int lowerComp = compare(o1.getLowerBound(), o2.getLowerBound()); + if (lowerComp != 0) { + return lowerComp; + } + throwUnimplemented(); + return -42; } protected int compareSymbol(ISymbol o1, ISymbol o2) { - return o1.getFullName().compareTo(o2.getFullName()); + int res; + // note: this case is only to speed comparisons up + // note: this seems VERY unintuitive for a reason; + // symbol delegates introduce odd behavior/issues. + // consider this a hacky workaround rather than a proper solution + if (o1 == o2 || o1.equals(o2) || o2.equals(o1)) { + res = 0; + } + else { + int resName = o1.getFullName().compareTo(o2.getFullName()); + if (resName != 0) { + res = resName; + } + // this is, in most cases, not supposed to happen, + // as functions are differentiated by their types, + // and otherwise, at this position, we would have two distinct symbols + // with the same kind and name. + // This only happens in specific situations, e.g., + // creating a broken symbol table and continuing to check CoCos + // to find further potential issus with the model (s, e.g., MontiArc). + else { + int resPos = o1.getSourcePosition().compareTo(o2.getSourcePosition()); + if (resPos != 0) { + res = resPos; + } + else { + Log.warn("0xFD738 internal warning: " + + "found two symbols with the same name \"" + + o1.getFullName() + "\" and the same source position " + + o1.getSourcePosition().toStringFullPath() + + ", which most likely indicates " + + "a wrong symbol table generation." + + " Alternatively, the symbol comparison implementation " + + "needs to be extended (this is unexpected)." + ); + // just assume that they are identical for now + res = 0; + } + } + } + return res; } // Helper + protected > int compareLists( + List o1, + List o2 + ) { + if (o1.size() < o2.size()) { + return -1; + } + else if (o1.size() > o2.size()) { + return 1; + } + else { + for (int i = 0; i < o1.size(); i++) { + T e1 = o1.get(i); + T e2 = o2.get(i); + int compI = e1.compareTo(e2); + if (compI != 0) { + return compI; + } + } + return 0; + } + } + + protected > int compareSets( + Set o1, + Set o2 + ) { + if (o1.size() < o2.size()) { + return -1; + } + else if (o1.size() > o2.size()) { + return 1; + } + else { + List sorted1 = o1.stream().sorted().collect(Collectors.toList()); + List sorted2 = o2.stream().sorted().collect(Collectors.toList()); + return compareLists(sorted1, sorted2); + } + } + /** - * Logs an error and returns default comparison value; * This is not expected to be ever called. */ - protected int logUnimplemented() { - Log.error("0xFD445 internal error: unimplemented comparison."); - return 0; + protected void throwUnimplemented() throws UnsupportedOperationException { + throw new UnsupportedOperationException( + "0xFD445 unimplemented comparison." + ); + } + + // static delegate + + public static void init() { + Log.trace("init default SymTypeExpressionComparator", "TypeCheck setup"); + setDelegate(new SymTypeExpressionComparator()); + } + + public static void reset() { + SymTypeExpressionComparator.delegate = null; + } + + protected static void setDelegate(SymTypeExpressionComparator newDelegate) { + SymTypeExpressionComparator.delegate = + Preconditions.checkNotNull(newDelegate); + } + + protected static SymTypeExpressionComparator getDelegate() { + if (SymTypeExpressionComparator.delegate == null) { + init(); + } + return SymTypeExpressionComparator.delegate; } } diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeLubCalculator.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeLubCalculator.java index 133aa2e137..27cce8300e 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeLubCalculator.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeLubCalculator.java @@ -9,7 +9,7 @@ import de.monticore.types3.SymTypeRelations; import java.util.Collection; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Iterator; import java.util.List; import java.util.Optional; @@ -44,7 +44,7 @@ public Optional leastUpperBound( // unpack unions Set typesSet_tmp = typeSet; - typeSet = new HashSet<>(); + typeSet = new LinkedHashSet<>(); for (SymTypeExpression type : typesSet_tmp) { if (type.isUnionType()) { typeSet.addAll(((SymTypeOfUnion) type).getUnionizedTypeSet()); @@ -59,7 +59,7 @@ public Optional leastUpperBound( // without removing the top level intersections yet // we can do this as we do not plan to support constraint solving typesSet_tmp = typeSet; - typeSet = new HashSet<>(); + typeSet = new LinkedHashSet<>(); for (SymTypeExpression type : typesSet_tmp) { if (type.isIntersectionType()) { SymTypeOfIntersection inter = (SymTypeOfIntersection) type; @@ -125,13 +125,13 @@ else if (typeSet.stream().allMatch(t -> else { // lub may be an intersection, e.g. two interfaces, // start with intersection of current types - Set acceptedLubs = new HashSet<>(); + Set acceptedLubs = new LinkedHashSet<>(); Set currentPotentialLubs; - Set nextPotentialLubs = new HashSet<>(); + Set nextPotentialLubs = new LinkedHashSet<>(); // unpack intersections typesSet_tmp = typeSet; - typeSet = new HashSet<>(); + typeSet = new LinkedHashSet<>(); for (SymTypeExpression type : typesSet_tmp) { if (type.isUnionType()) { typeSet.addAll(((SymTypeOfUnion) type).getUnionizedTypeSet()); @@ -142,10 +142,10 @@ else if (typeSet.stream().allMatch(t -> } // extract "arrayness" - Set arrayDims = new HashSet<>(); + Set arrayDims = new LinkedHashSet<>(); if (typeSet.stream().allMatch(SymTypeExpression::isArrayType)) { typesSet_tmp = typeSet; - typeSet = new HashSet<>(); + typeSet = new LinkedHashSet<>(); for (SymTypeExpression type : typesSet_tmp) { SymTypeArray array = (SymTypeArray) type; arrayDims.add(array.getDim()); @@ -153,17 +153,17 @@ else if (typeSet.stream().allMatch(t -> } // can only have lub if arrays have the same dimension if (arrayDims.size() == 1) { - currentPotentialLubs = new HashSet<>(typeSet); + currentPotentialLubs = new LinkedHashSet<>(typeSet); } else { - currentPotentialLubs = new HashSet<>(); + currentPotentialLubs = new LinkedHashSet<>(); } } else if (typeSet.stream().noneMatch(SymTypeExpression::isArrayType)) { - currentPotentialLubs = new HashSet<>(typeSet); + currentPotentialLubs = new LinkedHashSet<>(typeSet); } else { - currentPotentialLubs = new HashSet<>(); + currentPotentialLubs = new LinkedHashSet<>(); } // we have no unions, intersections or arrays on the top level @@ -185,7 +185,7 @@ else if (typeSet.stream().noneMatch(SymTypeExpression::isArrayType)) { } acceptedLubs.addAll(currentPotentialLubs); currentPotentialLubs = nextPotentialLubs; - nextPotentialLubs = new HashSet<>(); + nextPotentialLubs = new LinkedHashSet<>(); } // re-add "arrayness" diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeNormalizeVisitor.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeNormalizeVisitor.java index fa48e56f93..1464155a25 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeNormalizeVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeNormalizeVisitor.java @@ -19,7 +19,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; @@ -33,7 +33,7 @@ /** * tries to normalize SymTypeExpressions, * including, but not limited to, unions and intersections - * e.g., (A|A|B) -> A, if A extends B + * e.g., {@code (A|A|B) -> A, if A extends B} * Usage: * calculate(symType) *

@@ -57,7 +57,7 @@ public void visit(SymTypeOfUnion union) { protected SymTypeExpression normalizeUnionWithNormalizedTypes(SymTypeOfUnion union) { // set of already normalized unionized types - Set types = new HashSet<>(union.getUnionizedTypeSet()); + Set types = new LinkedHashSet<>(union.getUnionizedTypeSet()); // remove all occurrences of obscure // (A|B|obscure) -> (A|B) types.removeIf(SymTypeExpression::isObscureType); @@ -72,7 +72,7 @@ protected SymTypeExpression normalizeUnionWithNormalizedTypes(SymTypeOfUnion uni // (A|A|B) -> (A|B) // also no subtypes // (A|B|C) -> (B|C) if A extends B - Set uniqueTypes = new HashSet<>(); + Set uniqueTypes = new LinkedHashSet<>(); for (SymTypeExpression newType : splittedTypes) { boolean shouldAdd = true; // if A extends B, do not add A if B is in union @@ -133,7 +133,7 @@ public void visit(SymTypeOfIntersection intersection) { Set intersectionsWithoutUnions = intersectionOfUnions2UnionOfIntersections(types); // normalize each intersection - Set normalizedUnionTypes = new HashSet<>(); + Set normalizedUnionTypes = new LinkedHashSet<>(); for (SymTypeOfIntersection intersectionWithoutUnion : intersectionsWithoutUnions) { normalizedUnionTypes.add( @@ -162,7 +162,7 @@ protected SymTypeExpression normalizeIntersectionWithoutUnions( } SymTypeExpression normalized; - Set types = new HashSet<>(intersection.getIntersectedTypeSet()); + Set types = new LinkedHashSet<>(intersection.getIntersectedTypeSet()); // no intersection of intersections // (A&(B&C)) -> (A&B&C) Set splittedTypes = splitIntersections(types); @@ -175,7 +175,7 @@ protected SymTypeExpression normalizeIntersectionWithoutUnions( .collect(Collectors.toSet()) .size() > 1 ) { - splittedTypes = new HashSet<>(); + splittedTypes = new LinkedHashSet<>(); splittedTypes.add(SymTypeExpressionFactory.createObscureType()); } } @@ -184,7 +184,7 @@ protected SymTypeExpression normalizeIntersectionWithoutUnions( // (A&A&B) -> (A&B) // also no supertypes // (A&B&C) -> (A&C) if A extends B - Set uniqueTypes = new HashSet<>(); + Set uniqueTypes = new LinkedHashSet<>(); for (SymTypeExpression newType : splittedTypes) { boolean shouldAdd = true; // if A extends B, do not add B if A is in intersection @@ -372,7 +372,7 @@ else if (hasNull) { // as both free and bound variables describe sets of potential types, // they are handled the same for intersecting intersected = intersectedWithoutVars; - Set vars = new HashSet<>(uniqueBoundVars); + Set vars = new LinkedHashSet<>(uniqueBoundVars); vars.addAll(uniqueInfVars); for (SymTypeExpression var : vars) { if (SymTypeRelations.isSubTypeOf(var, intersected)) { @@ -457,6 +457,27 @@ protected SymTypeExpression intersectTupleTypes( return intersected; } + /** + * calculates the intersection of function types. + *

+ * IMPORTANT: This does filter out cases that can occur + * for overloaded functions, e.g., + * {@code intersect(A -> B, (A, A) -> B) = bottom} + * This is relevant if no type inference is used, + * and within type inference itself; + * With this version, + * resolved intersections MUST be split before normalization. + * An alternativ would be to allow the aforementioned kind of intersection, + * But that would lead to allowing values + * that are multiple function references at once. + * This is highly unintuitive and not supported by (most?) major languages. + *

+ * TODO FDr: Figure out if for the non-type-inference version + * the intersection has to be calculated differently (to allow for overloads), + * or if another representation for overloads would be better suited + * (which in turn would probably be turned into an intersection + * for the non-inference version anyway). + */ protected SymTypeExpression intersectFunctionTypes( Collection functions ) { @@ -683,11 +704,11 @@ public void visit(SymTypeOfSIUnit siUnit) { /** * splits up unions - * e.g., {(A|(B|C)),D} -> {A,B,C,D} + * e.g., {@code {(A|(B|C)),D} -> {A,B,C,D}} * used for normalization */ protected Set splitUnions(Set types) { - Set result = new HashSet<>(); + Set result = new LinkedHashSet<>(); for (SymTypeExpression type : types) { if (type.isUnionType()) { SymTypeOfUnion union = (SymTypeOfUnion) type; @@ -702,12 +723,12 @@ protected Set splitUnions(Set types) { /** * splits up intersections - * e.g., {(A&(B&C)),D} -> {A,B,C,D} + * e.g., {@code {(A&(B&C)),D} -> {A,B,C,D}} * used for normalization */ protected Set splitIntersections( Set types) { - Set result = new HashSet<>(); + Set result = new LinkedHashSet<>(); for (SymTypeExpression type : types) { if (type.isIntersectionType()) { SymTypeOfIntersection intersection = (SymTypeOfIntersection) type; @@ -723,7 +744,7 @@ protected Set splitIntersections( /** * takes an intersection, which may contain unions * and creates a union which contains intersections - * A&B&(C|D) -> (A&B&C)|(A&B&D) + * {@code A&B&(C|D) -> (A&B&C)|(A&B&D)} * Note that this only calculates the given intersection, * not the intersection contained within the given intersection. * An additional characteristic to mention is that @@ -732,11 +753,11 @@ protected Set splitIntersections( */ protected Set intersectionOfUnions2UnionOfIntersections( Set intersectedTypes) { - Set intersections = new HashSet<>(); + Set intersections = new LinkedHashSet<>(); if (!intersectedTypes.isEmpty()) { //temporarily make every non-union type in the intersection a union type // (A|B)&C -> (A|B)&(C) - Set unions = new HashSet<>(); + Set unions = new LinkedHashSet<>(); for (SymTypeExpression type : intersectedTypes) { if (type.isUnionType()) { unions.add((SymTypeOfUnion) type); @@ -757,7 +778,7 @@ protected Set intersectionOfUnions2UnionOfIntersections( //now combine the other unions with the already existing intersections for (SymTypeOfUnion union : unions) { Set currentIntersectionSets = intersections; - intersections = new HashSet<>(); + intersections = new LinkedHashSet<>(); for (SymTypeExpression unionizedType : union.getUnionizedTypeSet()) { for (SymTypeOfIntersection oldIntersection : currentIntersectionSets) { SymTypeOfIntersection newIntersection = @@ -781,7 +802,7 @@ protected Set intersectionOfUnions2UnionOfIntersections( /** * Split tuples by unions. - * (A|B,C&D) -> (A,C&D), (B, C&D) + * {@code (A|B,C&D) -> (A,C&D), (B, C&D)} * does not create deep copies. */ protected List splitTupleByUnion(SymTypeOfTuple tuple) { @@ -820,7 +841,7 @@ protected List splitTupleByUnion( /** * Split tuples by intersections. - * (A|B,C&D) -> (A|B,C), (A|B, D) + * {@code (A|B,C&D) -> (A|B,C), (A|B, D)} * does not create deep copies. */ protected List splitTupleByIntersection(SymTypeOfTuple tuple) { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeUnboxingVisitor.java b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeUnboxingVisitor.java index addaea3cc8..f5702beeea 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeUnboxingVisitor.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/SymTypeUnboxingVisitor.java @@ -9,34 +9,34 @@ import de.se_rwth.commons.logging.Log; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; /** * Unboxes SymTypeExpressions, * including, but not limited to, Java primitive unboxing - * e.g., java.lang.Integer -> int - * e.g., java.util.List -> List + * e.g., {@code java.lang.Integer -> int} + * e.g., {@code java.util.List -> List} * Usage: * calculate(symType) */ public class SymTypeUnboxingVisitor extends SymTypeDeepCloneVisitor { /** - * Map for unboxing to primitive types (e.g. "java.lang.Integer" -> "int") + * Map for unboxing to primitive types (e.g. {@code "java.lang.Integer" -> "int"}) * Results are fully qualified. */ protected static final Map primitiveUnboxMap; /** - * Map for unboxing to object types (e.g. "java.lang.String" -> "String") + * Map for unboxing to object types (e.g. {@code "java.lang.String" -> "String"}) * Results are fully qualified. */ protected static final Map objectUnboxMap; /** - * Map for unboxing to generic types (e.g. "java.util.List" -> "List") + * Map for unboxing to generic types (e.g. {@code "java.util.List" -> "List"}) * Results are fully qualified. */ protected static final Map genericUnboxMap; @@ -57,7 +57,7 @@ public Map getGenericUnboxMap() { * initializing the maps */ static { - Map primitiveUnboxMap_temp = new HashMap<>(); + Map primitiveUnboxMap_temp = new LinkedHashMap<>(); primitiveUnboxMap_temp.put("java.lang.Boolean", "boolean"); primitiveUnboxMap_temp.put("java.lang.Byte", "byte"); primitiveUnboxMap_temp.put("java.lang.Character", "char"); @@ -68,11 +68,11 @@ public Map getGenericUnboxMap() { primitiveUnboxMap_temp.put("java.lang.Short", "short"); primitiveUnboxMap = Collections.unmodifiableMap(primitiveUnboxMap_temp); - Map objectUnboxMap_temp = new HashMap<>(); + Map objectUnboxMap_temp = new LinkedHashMap<>(); objectUnboxMap_temp.put("java.lang.String", "String"); objectUnboxMap = Collections.unmodifiableMap(objectUnboxMap_temp); - Map genericUnboxMap_temp = new HashMap<>(); + Map genericUnboxMap_temp = new LinkedHashMap<>(); genericUnboxMap_temp.put("java.util.Optional", "Optional"); genericUnboxMap_temp.put("java.util.Set", "Set"); genericUnboxMap_temp.put("java.util.List", "List"); diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/TypeContextCalculator.java b/monticore-grammar/src/main/java/de/monticore/types3/util/TypeContextCalculator.java index 8cea010eda..c4debc4493 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/TypeContextCalculator.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/TypeContextCalculator.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._util.IBasicSymbolsTypeDispatcher; @@ -39,11 +40,9 @@ protected Optional _getEnclosingType(IScope enclosingScope) { for (IScope scope = enclosingScope; scope != null && enclosingType.isEmpty(); scope = scope.getEnclosingScope()) { - if (scope.isPresentSpanningSymbol() && - getTypeDispatcher().isBasicSymbolsType(scope.getSpanningSymbol())) { - enclosingType = Optional.of( - getTypeDispatcher().asBasicSymbolsType(scope.getSpanningSymbol()) - ); + //TODO: use TypeDispatcher as soon as it is fixed + if (scope.isPresentSpanningSymbol() && scope.getSpanningSymbol() instanceof TypeSymbol) { + enclosingType = Optional.of((TypeSymbol) scope.getSpanningSymbol()); } } return enclosingType; @@ -147,7 +146,7 @@ public static void reset() { } protected static void setDelegate(TypeContextCalculator newDelegate) { - TypeContextCalculator.delegate = Log.errorIfNull(newDelegate); + TypeContextCalculator.delegate = Preconditions.checkNotNull(newDelegate); } protected static TypeContextCalculator getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/TypeVisitorLifting.java b/monticore-grammar/src/main/java/de/monticore/types3/util/TypeVisitorLifting.java index 69ea65bf8d..7b640fc96f 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/TypeVisitorLifting.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/TypeVisitorLifting.java @@ -1,12 +1,13 @@ package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types3.SymTypeRelations; import de.se_rwth.commons.logging.Log; import java.util.Collection; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; @@ -96,7 +97,7 @@ protected Function _liftForUnion( Function func) { return (SymTypeExpression symType) -> { if (symType.isUnionType()) { - Set results = new HashSet<>(); + Set results = new LinkedHashSet<>(); for (SymTypeExpression unionizedType : symType.asUnionType().getUnionizedTypeSet()) { results.add(func.apply(unionizedType)); } @@ -116,7 +117,7 @@ protected BiFunction _l return (SymTypeExpression symType1, SymTypeExpression symType2) -> { Set arguments1; Set arguments2; - Set results = new HashSet<>(); + Set results = new LinkedHashSet<>(); if (symType1.isUnionType()) { arguments1 = symType1.asUnionType().getUnionizedTypeSet(); } @@ -198,7 +199,7 @@ public static void reset() { } protected static void setDelegate(TypeVisitorLifting newDelegate) { - TypeVisitorLifting.delegate = Log.errorIfNull(newDelegate); + TypeVisitorLifting.delegate = Preconditions.checkNotNull(newDelegate); } protected static TypeVisitorLifting getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/TypeVisitorOperatorCalculator.java b/monticore-grammar/src/main/java/de/monticore/types3/util/TypeVisitorOperatorCalculator.java index d4e64424bf..04c1062ff7 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/TypeVisitorOperatorCalculator.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/TypeVisitorOperatorCalculator.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; @@ -208,7 +209,7 @@ else if (isString(leftStr) && isString(rightStr)) { * if the need for more restrictive types is required. *

* Interestingly, this COULD (but should not!) be generalized; - * A function (STE target, STE source) -> STE converted, + * A function (STE target, STE source) -> STE converted, * where source is compatible to target, * and converted is the result of the conversion to the target type, * which is a subType of the target type. @@ -224,7 +225,7 @@ else if (isString(leftStr) && isString(rightStr)) { * (1, 2, 3) + (4, (5, 6)) == (5, 7, 9), * but this gets wierd with * ((1, 2), 3) + (4, (5, 6)) - * -> need to find (int, int, int) first, as it is not on either side. + * -> need to find (int, int, int) first, as it is not on either side. * Other example: int and tuples can be converted to String, * in this case, the following could be allowed: * 1 + (2, 3) // "1(2, 3)" @@ -606,7 +607,7 @@ protected Optional _greaterEqual( } /** - * calculates <, <=, >, => + * calculates {@code <, <=, >, =>} */ protected SymTypeExpression calculateNumericComparison( SymTypeExpression left, @@ -683,7 +684,7 @@ protected Optional _booleanOr( } /** - * calculates &&, || + * calculates {@code &&, ||} */ protected SymTypeExpression calculateConditionalBooleanOp( SymTypeExpression left, @@ -771,7 +772,7 @@ protected Optional _binaryXor( } /** - * calculates &, |, ^ + * calculates {@code &, |, ^} */ protected SymTypeExpression calculateBinaryInfixOp( SymTypeExpression left, @@ -1044,7 +1045,7 @@ public static void reset() { } protected static void setDelegate(TypeVisitorOperatorCalculator newDelegate) { - TypeVisitorOperatorCalculator.delegate = Log.errorIfNull(newDelegate); + TypeVisitorOperatorCalculator.delegate = Preconditions.checkNotNull(newDelegate); } protected static TypeVisitorOperatorCalculator getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/WithinScopeBasicSymbolsResolver.java b/monticore-grammar/src/main/java/de/monticore/types3/util/WithinScopeBasicSymbolsResolver.java index 42c667d04d..d8524c2305 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/WithinScopeBasicSymbolsResolver.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/WithinScopeBasicSymbolsResolver.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; @@ -19,7 +20,8 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; @@ -66,10 +68,10 @@ public static Optional resolveNameAsExpr( protected Optional _resolveNameAsExpr( IBasicSymbolsScope enclosingScope, String name) { - Log.errorIfNull(enclosingScope); - Log.errorIfNull(name); + Preconditions.checkNotNull(enclosingScope); + Preconditions.checkNotNull(name); // collect all (potential) types - Set types = new HashSet<>(); + Set types = new LinkedHashSet<>(); // to circumvent current shortcomings in our resolver, // we resolve with the resolver AND resolve with the within type resolver @@ -170,13 +172,15 @@ protected Optional resolveVariableWithoutSuperTypes( IBasicSymbolsScope enclosingScope, String name ) { - Log.errorIfNull(enclosingScope); - Log.errorIfNull(name); + Preconditions.checkNotNull(enclosingScope); + Preconditions.checkNotNull(name); Optional result; - Optional optVarSym = resolverHotfix( - () -> enclosingScope.resolveVariable( - name, AccessModifier.ALL_INCLUSION, getVariablePredicate() - )); + Optional optVarSym = resolveVariable( + enclosingScope, + name, + AccessModifier.ALL_INCLUSION, + getVariablePredicate() + ); if (optVarSym.isEmpty()) { result = Optional.empty(); } @@ -206,15 +210,14 @@ protected List resolveFunctionsWithoutSuperTypes( IBasicSymbolsScope enclosingScope, String name ) { - Log.errorIfNull(enclosingScope); - Log.errorIfNull(name); - List funcSyms = enclosingScope - .resolveFunctionMany(name, getFunctionPredicate()).stream() - // todo remove creation of a set - // after resolver is fixed to not return duplicates - .collect(Collectors.toSet()) - .stream() - .collect(Collectors.toList()); + Preconditions.checkNotNull(enclosingScope); + Preconditions.checkNotNull(name); + List funcSyms = resolveFunctionMany( + enclosingScope, + name, + AccessModifier.ALL_INCLUSION, + getFunctionPredicate() + ); List funcs = new ArrayList<>(funcSyms.size()); for (FunctionSymbol funcSym : funcSyms) { SymTypeOfFunction funcType = funcSym.getFunctionType(); @@ -235,6 +238,26 @@ protected Predicate getFunctionPredicate() { return f -> true; } + /** + * Does nothing but call {@link IBasicSymbolsScope#resolveFunctionMany(String, AccessModifier, Predicate)}. + * This is an extension point. + * S. a. {@link #resolveType(IBasicSymbolsScope, String, AccessModifier, Predicate)} + */ + protected List resolveFunctionMany( + IBasicSymbolsScope enclosingScope, + String name, + AccessModifier accessModifier, + Predicate predicate + ) { + List functions = enclosingScope + .resolveFunctionMany(name, accessModifier, predicate); + // todo remove creation of a set + // after resolver is fixed to not return duplicates + Set set = new LinkedHashSet<>(functions); + List filtered = new ArrayList<>(set); + return filtered; + } + /** * used to filter variable symbols * this is an extension point @@ -243,6 +266,22 @@ protected Predicate getVariablePredicate() { return v -> true; } + /** + * Does nothing but call {@link IBasicSymbolsScope#resolveVariable(String, AccessModifier, Predicate)}. + * This is an extension point. + * S. a. {@link #resolveType(IBasicSymbolsScope, String, AccessModifier, Predicate)} + */ + protected Optional resolveVariable( + IBasicSymbolsScope enclosingScope, + String name, + AccessModifier accessModifier, + Predicate predicate + ) { + return resolverHotfix(() -> + enclosingScope.resolveVariable(name, accessModifier, predicate) + ); + } + public static Optional resolveType( IBasicSymbolsScope enclosingScope, String name) { @@ -253,8 +292,8 @@ protected Optional _resolveType( IBasicSymbolsScope enclosingScope, String name ) { - Log.errorIfNull(enclosingScope); - Log.errorIfNull(name); + Preconditions.checkNotNull(enclosingScope); + Preconditions.checkNotNull(name); Optional result; // variable Optional optTypeVar; @@ -265,15 +304,21 @@ protected Optional _resolveType( optTypeVar = Optional.empty(); } else { - optTypeVar = resolverHotfix(() -> - enclosingScope.resolveTypeVar( - name, AccessModifier.ALL_INCLUSION, getTypeVarPredicate()) + optTypeVar = resolveTypeVar( + enclosingScope, + name, + AccessModifier.ALL_INCLUSION, + getTypeVarPredicate() ); } // object - Optional optObj = resolverHotfix(() -> - enclosingScope.resolveType(name, AccessModifier.ALL_INCLUSION, - getTypePredicate().and((t -> optTypeVar.map(tv -> tv != t).orElse(true)))) + Optional optObj = resolveType( + enclosingScope, + name, + AccessModifier.ALL_INCLUSION, + getTypePredicate().and(t -> + optTypeVar.map(tv -> tv != t).orElse(true) + ) ); // in Java the type variable is preferred // e.g. class C{class U{} U v;} //new C().v has type Float @@ -325,6 +370,42 @@ protected Predicate getTypePredicate() { return t -> true; } + /** + * Does nothing but call {@link IBasicSymbolsScope#resolveType(String, AccessModifier, Predicate)}. + * This is an extension point. + *

+ * A use case is to, instead of logging an error + * on finding multiple symbols with the same name, + * select one deterministically and continue with it. + * Advantages: + * * One can find more errors in the same run of the tool. + * * One does not get multiple instances of the error + * that multiple symbols exist with the same name + * Disadvantages: + * * One has to rely on the generation of the symboltable + * to already have logged the error of multiple instances of symbols + * with the same name. + * * Error messages are harder to understand, + * as the modeler might not notice this selection, + * does not know about the second Symbol definition, + * and tries to fix an issue that lies elsewhere. + * (Especially, if they don't start at the first reported model error) + *

+ * Due to the low quality of our tooling in several of our languages, + * this is not enabled by default, but must be implemented + * in the specific languages. + */ + protected Optional resolveType( + IBasicSymbolsScope enclosingScope, + String name, + AccessModifier accessModifier, + Predicate typeSymbolPredicate + ) { + return resolverHotfix(() -> + enclosingScope.resolveType(name, accessModifier, typeSymbolPredicate) + ); + } + /** * used to filter type variable symbols * this is an extension point @@ -333,6 +414,22 @@ protected Predicate getTypeVarPredicate() { return tv -> true; } + /** + * Does nothing but call {@link IBasicSymbolsScope#resolveTypeVar(String, AccessModifier, Predicate)}. + * This is an extension point. + * S. a. {@link #resolveType(IBasicSymbolsScope, String, AccessModifier, Predicate)} + */ + protected Optional resolveTypeVar( + IBasicSymbolsScope enclosingScope, + String name, + AccessModifier accessModifier, + Predicate predicate + ) { + return resolverHotfix(() -> + enclosingScope.resolveTypeVar(name, accessModifier, predicate) + ); + } + // Helper /** @@ -344,6 +441,7 @@ protected boolean isNameWithQualifier(String name) { /** * workaround for Resolver throwing Exceptions... + *

+ * This class should be considered a draft/rough prototype. + */ +public class SymTypeExpressionGenerator { + + protected Random rand; + + public SymTypeExpressionGenerator() { + // no fixed seed for monkey testing + rand = new Random(); + } + + public SymTypeExpressionGenerator(long seed) { + rand = new Random(seed); + } + + protected enum SymTypeExpressionKind { + PRIMITIVE, + INFERENCE_VAR, + ARRAY, + NULL, + FUNCTION, + TUPLE, + UNION, + INTERSECTION, + WILDCARD, + + // MUST be the last in the list + // to efficiently remove it from the options + OBSCURE; + } + + protected static final List ALL_KINDS = + List.of(SymTypeExpressionKind.values()); + + protected static final List ALL_KINDS_NO_OBSCURE = + ALL_KINDS.subList(0, ALL_KINDS.size() - 2); + + protected static final List LEAF_KINDS = + List.of( + SymTypeExpressionKind.PRIMITIVE, + SymTypeExpressionKind.INFERENCE_VAR, + SymTypeExpressionKind.NULL, + SymTypeExpressionKind.OBSCURE + ); + + protected static final List LEAF_KINDS_NO_OBSCURE = + LEAF_KINDS.subList(0, LEAF_KINDS.size() - 2); + + protected static final List PRIMITIVES = List.of( + BasicSymbolsMill.BOOLEAN, + BasicSymbolsMill.BYTE, + BasicSymbolsMill.SHORT, + BasicSymbolsMill.CHAR, + BasicSymbolsMill.INT, + BasicSymbolsMill.LONG, + BasicSymbolsMill.FLOAT, + BasicSymbolsMill.DOUBLE + ); + + /** + * + * @param number amount of SymTypeExpressions + * @param maxDepth inclusive + * @param maxWidth exclusive + * @param allowObscure whether Obscure may be contained in the SymtypeExpressions + * @return List of SymTypeExpressions with the given complexity + */ + public List createSymTypeExpressions(int number, int maxDepth, int maxWidth, boolean allowObscure) { + List symTypeExpressions = new ArrayList<>(number); + for (int i = 0; i < number; i++) { + symTypeExpressions.add(createSymTypeExpression(maxDepth, maxWidth, allowObscure)); + } + return symTypeExpressions; + } + + public SymTypeExpression createSymTypeExpression(int maxDepth, int maxWidth, boolean allowObscure) { + SymTypeExpression res; + List possibleKindList; + if (maxDepth <= 0) { + possibleKindList = allowObscure ? LEAF_KINDS : LEAF_KINDS_NO_OBSCURE; + } + else { + possibleKindList = allowObscure ? ALL_KINDS : ALL_KINDS_NO_OBSCURE; + } + int nextDepth = maxDepth - 1; + SymTypeExpressionKind randKind = + possibleKindList.get(rand.nextInt(possibleKindList.size())); + switch (randKind) { + case PRIMITIVE: + String primStr = PRIMITIVES.get(rand.nextInt(PRIMITIVES.size())); + res = createPrimitive(primStr); + break; + case INFERENCE_VAR: + res = createInferenceVariable(); + break; + case ARRAY: + int randDim = rand.nextInt(4) + 1; + res = createTypeArray( + createSymTypeExpression(nextDepth, maxWidth, allowObscure), + randDim + ); + break; + case NULL: + res = createTypeOfNull(); + break; + case FUNCTION: + res = createFunction( + rand.nextBoolean() + ? createSymTypeExpression(nextDepth, maxWidth, allowObscure) + : createTypeVoid(), + createSymTypeExpressions(rand.nextInt(maxWidth), nextDepth, maxWidth, allowObscure), + rand.nextBoolean() + ); + break; + case TUPLE: + res = createTuple( + createSymTypeExpressions(rand.nextInt(maxWidth), nextDepth, maxWidth, allowObscure) + ); + break; + case UNION: + res = createUnion( + createSymTypeExpressions(rand.nextInt(maxWidth), nextDepth, maxWidth, allowObscure) + ); + break; + case INTERSECTION: + res = createIntersection( + createSymTypeExpressions(rand.nextInt(maxWidth), nextDepth, maxWidth, allowObscure) + ); + break; + case WILDCARD: + res = createWildcard( + rand.nextBoolean(), + createSymTypeExpression(nextDepth, maxWidth, allowObscure) + ); + break; + case OBSCURE: + res = createObscureType(); + break; + default: + throw new IllegalStateException(); + } + return res; + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/umlmodifier/ModifierBuilderTest.java b/monticore-grammar/src/test/java/de/monticore/umlmodifier/ModifierBuilderTest.java index cf36817e5f..e0f47cada4 100644 --- a/monticore-grammar/src/test/java/de/monticore/umlmodifier/ModifierBuilderTest.java +++ b/monticore-grammar/src/test/java/de/monticore/umlmodifier/ModifierBuilderTest.java @@ -5,11 +5,10 @@ import de.monticore.umlmodifier._ast.ASTModifierBuilder; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ModifierBuilderTest { @@ -21,16 +20,16 @@ public void before() { @Test public void checkAllOptions() { - Assertions.assertTrue(new ASTModifierBuilder().PUBLIC().build().isPublic()); - Assertions.assertTrue(new ASTModifierBuilder().PRIVATE().build().isPrivate()); - Assertions.assertTrue(new ASTModifierBuilder().PROTECTED().build().isProtected()); - Assertions.assertTrue(new ASTModifierBuilder().FINAL().build().isFinal()); - Assertions.assertTrue(new ASTModifierBuilder().ABSTRACT().build().isAbstract()); - Assertions.assertTrue(new ASTModifierBuilder().LOCAL().build().isLocal()); - Assertions.assertTrue(new ASTModifierBuilder().DERIVED().build().isDerived()); - Assertions.assertTrue(new ASTModifierBuilder().READONLY().build().isReadonly()); - Assertions.assertTrue(new ASTModifierBuilder().STATIC().build().isStatic()); + assertTrue(new ASTModifierBuilder().PUBLIC().build().isPublic()); + assertTrue(new ASTModifierBuilder().PRIVATE().build().isPrivate()); + assertTrue(new ASTModifierBuilder().PROTECTED().build().isProtected()); + assertTrue(new ASTModifierBuilder().FINAL().build().isFinal()); + assertTrue(new ASTModifierBuilder().ABSTRACT().build().isAbstract()); + assertTrue(new ASTModifierBuilder().LOCAL().build().isLocal()); + assertTrue(new ASTModifierBuilder().DERIVED().build().isDerived()); + assertTrue(new ASTModifierBuilder().READONLY().build().isReadonly()); + assertTrue(new ASTModifierBuilder().STATIC().build().isStatic()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/umlmodifier/ModifierPrettyPrintTest.java b/monticore-grammar/src/test/java/de/monticore/umlmodifier/ModifierPrettyPrintTest.java index 3c00dc3cc2..f2d4a2cdda 100644 --- a/monticore-grammar/src/test/java/de/monticore/umlmodifier/ModifierPrettyPrintTest.java +++ b/monticore-grammar/src/test/java/de/monticore/umlmodifier/ModifierPrettyPrintTest.java @@ -4,12 +4,11 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ModifierPrettyPrintTest { @@ -24,24 +23,24 @@ public void before() { @Test public void testLongFormsIndividual() { - Assertions.assertEquals("public", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PUBLIC().build(), false)); - Assertions.assertEquals("private", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PRIVATE().build(), false)); - Assertions.assertEquals("protected", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PROTECTED().build(), false)); - Assertions.assertEquals("final", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().FINAL().build(), false)); - Assertions.assertEquals("abstract", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().ABSTRACT().build(), false)); - Assertions.assertEquals("local", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().LOCAL().build(), false)); - Assertions.assertEquals("derived", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().DERIVED().build(), false)); - Assertions.assertEquals("readonly", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().READONLY().build(), false)); - Assertions.assertEquals("static", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().STATIC().build(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("public", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PUBLIC().build(), false)); + assertEquals("private", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PRIVATE().build(), false)); + assertEquals("protected", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PROTECTED().build(), false)); + assertEquals("final", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().FINAL().build(), false)); + assertEquals("abstract", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().ABSTRACT().build(), false)); + assertEquals("local", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().LOCAL().build(), false)); + assertEquals("derived", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().DERIVED().build(), false)); + assertEquals("readonly", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().READONLY().build(), false)); + assertEquals("static", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().STATIC().build(), false)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLong() { - Assertions.assertEquals("public static", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PUBLIC().STATIC().build(), false)); - Assertions.assertEquals("abstract readonly", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().ABSTRACT().READONLY().build(), false)); - Assertions.assertEquals("protected static", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PROTECTED().STATIC().build(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("public static", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PUBLIC().STATIC().build(), false)); + assertEquals("abstract readonly", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().ABSTRACT().READONLY().build(), false)); + assertEquals("protected static", UMLModifierMill.prettyPrint(UMLModifierMill.modifierBuilder().PROTECTED().STATIC().build(), false)); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/umlstereotype/StereoValueContentTest.java b/monticore-grammar/src/test/java/de/monticore/umlstereotype/StereoValueContentTest.java index f5893f8135..ca481af753 100644 --- a/monticore-grammar/src/test/java/de/monticore/umlstereotype/StereoValueContentTest.java +++ b/monticore-grammar/src/test/java/de/monticore/umlstereotype/StereoValueContentTest.java @@ -6,10 +6,12 @@ import de.se_rwth.commons.logging.LogStub; import org.apache.commons.lang3.StringEscapeUtils; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class StereoValueContentTest { @BeforeEach public void init() { @@ -20,7 +22,7 @@ public void init() { @AfterEach public void postCheck() { - Assertions.assertTrue(LogStub.getFindings().isEmpty()); + assertTrue(LogStub.getFindings().isEmpty()); } @Test @@ -28,7 +30,7 @@ public void testSimpleBuilder() { String input = "Hello world"; var sv = TestMCCommonMill.stereoValueBuilder().setName("Stereo") .setContent(input).build(); - Assertions.assertEquals(input, sv.getContent()); + assertEquals(input, sv.getContent()); } @Test @@ -36,7 +38,7 @@ public void testSimple() { String input = "Hello world"; var sv = TestMCCommonMill.stereoValueBuilder().setName("Stereo").build(); sv.setContent(input); - Assertions.assertEquals(input, sv.getContent()); + assertEquals(input, sv.getContent()); } @Test @@ -44,7 +46,7 @@ public void testQuotationBuilder() { String input = "Hello \"world\""; var sv = TestMCCommonMill.stereoValueBuilder().setName("Stereo") .setContent(input).build(); - Assertions.assertEquals(input, sv.getContent()); + assertEquals(input, sv.getContent()); } @Test @@ -52,7 +54,7 @@ public void testQuotation() { String input = "Hello \"world\""; var sv = TestMCCommonMill.stereoValueBuilder().setName("Stereo").build(); sv.setContent(input); - Assertions.assertEquals(input, sv.getContent()); + assertEquals(input, sv.getContent()); } @Test @@ -60,7 +62,7 @@ public void testBackslashBuilder() { String input = "Hello \\ world,\n hello\\people"; var sv = TestMCCommonMill.stereoValueBuilder().setName("Stereo") .setContent(input).build(); - Assertions.assertEquals(input, sv.getContent()); + assertEquals(input, sv.getContent()); } @Test @@ -68,7 +70,7 @@ public void testBackslash() { String input = "Hello \\ world,\n hello\\people"; var sv = TestMCCommonMill.stereoValueBuilder().setName("Stereo").build(); sv.setContent(input); - Assertions.assertEquals(input, sv.getContent()); + assertEquals(input, sv.getContent()); } @@ -79,7 +81,7 @@ public void testSetTextBuilder() { .setText(MCCommonLiteralsMill.stringLiteralBuilder() .setSource(StringEscapeUtils.escapeJava(input)).build()) .build(); - Assertions.assertEquals(input, sv.getContent()); + assertEquals(input, sv.getContent()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/umlstereotype/cocos/StereoValueIsStringLiteralTest.java b/monticore-grammar/src/test/java/de/monticore/umlstereotype/cocos/StereoValueIsStringLiteralTest.java index fdd5b58629..82d56bb304 100644 --- a/monticore-grammar/src/test/java/de/monticore/umlstereotype/cocos/StereoValueIsStringLiteralTest.java +++ b/monticore-grammar/src/test/java/de/monticore/umlstereotype/cocos/StereoValueIsStringLiteralTest.java @@ -5,13 +5,15 @@ import de.monticore.umlstereotype._ast.ASTStereotype; import de.monticore.umlstereotype._cocos.UMLStereotypeCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Holds tests for {@link StereoValueIsStringLiteral} */ @@ -29,19 +31,19 @@ public void init() { public void checkValid(String expressionString) throws IOException { Optional optAST = parser.parse_StringStereotype(expressionString); - Assertions.assertTrue(optAST.isPresent()); + assertTrue(optAST.isPresent()); Log.getFindings().clear(); checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty(), Log.getFindings().toString()); + assertTrue(Log.getFindings().isEmpty(), Log.getFindings().toString()); } public void checkInvalid(String expressionString) throws IOException { Optional optAST = parser.parse_StringStereotype(expressionString); - Assertions.assertTrue(optAST.isPresent()); + assertTrue(optAST.isPresent()); Log.getFindings().clear(); Log.enableFailQuick(false); checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); + assertFalse(Log.getFindings().isEmpty()); } @Test diff --git a/monticore-grammar/src/test/resources/de/monticore/grammar/cocos/invalid/A4099/A4099.mc4 b/monticore-grammar/src/test/resources/de/monticore/grammar/cocos/invalid/A4099/A4099.mc4 new file mode 100644 index 0000000000..1465e6a818 --- /dev/null +++ b/monticore-grammar/src/test/resources/de/monticore/grammar/cocos/invalid/A4099/A4099.mc4 @@ -0,0 +1,11 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.grammar.cocos.invalid.A4099; + +grammar A4099 { + + StartProd = (A | I)*; + + symbol A = "A"; + + symbol I = "I"; +} \ No newline at end of file diff --git a/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithField.json b/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithField.json new file mode 100644 index 0000000000..bfd8539d90 --- /dev/null +++ b/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithField.json @@ -0,0 +1,18 @@ +{ + "kind": "de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol", + "name": "Comp", + "fullName": "Comp", + "spannedScope": { + "symbols": [ + { + "kind": "de.monticore.symbols.basicsymbols._symboltable.VariableSymbol", + "name": "inst", + "fullName": "Comp.inst", + "type": { + "kind": "de.monticore.types.check.SymTypePrimitive", + "primitiveName": "int" + } + } + ] + } +} \ No newline at end of file diff --git a/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithInner.json b/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithInner.json new file mode 100644 index 0000000000..35eac8ac03 --- /dev/null +++ b/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithInner.json @@ -0,0 +1,14 @@ +{ + "kind": "de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol", + "name": "Comp", + "fullName": "Comp", + "spannedScope": { + "symbols": [ + { + "kind": "de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol", + "name": "inst", + "fullName": "Comp.inst" + } + ] + } +} \ No newline at end of file diff --git a/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithParent.json b/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithRefinement.json similarity index 76% rename from monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithParent.json rename to monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithRefinement.json index 675c4321fd..fb6dd816b8 100644 --- a/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithParent.json +++ b/monticore-grammar/src/test/resources/de/monticore/symbols/compsymbols/_symboltable/WithRefinement.json @@ -2,10 +2,10 @@ "kind": "de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol", "name": "Comp", "fullName": "Comp", - "super": [ + "refinements": [ { "kind": "de.monticore.types.check.CompKindOfComponentType", - "componentTypeName": "Parent" + "componentTypeName": "RefinementCType" } ] } \ No newline at end of file diff --git a/monticore-grammar/src/testFixtures/java/de/monticore/types3/util/DefsTypesForTests.java b/monticore-grammar/src/testFixtures/java/de/monticore/types3/util/DefsTypesForTests.java new file mode 100644 index 0000000000..d77d2f1e3e --- /dev/null +++ b/monticore-grammar/src/testFixtures/java/de/monticore/types3/util/DefsTypesForTests.java @@ -0,0 +1,1280 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.types3.util; + +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; +import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; +import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; +import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.oosymbols.OOSymbolsMill; +import de.monticore.symbols.oosymbols._symboltable.FieldSymbol; +import de.monticore.symbols.oosymbols._symboltable.IOOSymbolsScope; +import de.monticore.symbols.oosymbols._symboltable.MethodSymbol; +import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; +import de.monticore.symboltable.modifiers.AccessModifier; +import de.monticore.types.check.SIUnitBasic; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeObscure; +import de.monticore.types.check.SymTypeOfGenerics; +import de.monticore.types.check.SymTypeOfNull; +import de.monticore.types.check.SymTypeOfNumericWithSIUnit; +import de.monticore.types.check.SymTypeOfObject; +import de.monticore.types.check.SymTypeOfSIUnit; +import de.monticore.types.check.SymTypePrimitive; +import de.monticore.types.check.SymTypeVariable; +import de.monticore.types.check.SymTypeVoid; +import de.se_rwth.commons.logging.Log; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static de.monticore.types.check.SymTypeExpressionFactory.createBottomType; +import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; +import static de.monticore.types.check.SymTypeExpressionFactory.createGenericsDeclaredType; +import static de.monticore.types.check.SymTypeExpressionFactory.createNumericWithSIUnit; +import static de.monticore.types.check.SymTypeExpressionFactory.createPrimitive; +import static de.monticore.types.check.SymTypeExpressionFactory.createSIUnit; +import static de.monticore.types.check.SymTypeExpressionFactory.createSIUnitBasic; +import static de.monticore.types.check.SymTypeExpressionFactory.createTopType; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeVariable; + +/** + * offers one Symbol-Infrastructure + * including Scopes etc. that is used to provide relevant Symbols. + * This infrastructure can be used for testing + */ +public class DefsTypesForTests { + + /** + * Initialization of the structure (can be called again to reinitialize). + */ + public static void setup() { + set_specialSymTypes(); + set_thePrimitives(); + set_boxedPrimitives(); + set_unboxedObjects(); + set_boxedObjects(); + set_unboxedCollections(); + set_boxedCollections(); + set_streams(); + set_genericsRecursive(); + set_objectTypes(); + set_specialObjectTypes(); + set_generics(); + set_specialGenerics(); + set_bottomTopTypes(); + set_siUnitBasic(); + set_siUnitTypes(); + set_numericWithSIUnitTypes(); + } + + /*********************************************************************/ + + /* + * Helpers that efficiently create Scopes + */ + public static IBasicSymbolsScope scope(String name) { + return scope(name, true); + } + + public static IBasicSymbolsScope scope(String name, boolean shadowing) { + IBasicSymbolsScope scope = BasicSymbolsMill.scope(); + scope.setName(name); + scope.setShadowing(shadowing); + scope.setExportingSymbols(true); + return scope; + } + + /*********************************************************************/ + + /** + * add a Scope to a Scope (bidirectional) + */ + public static T inScope(IBasicSymbolsScope p, T s) { + p.addSubScope(s); + return s; + } + + /** + * add a Type to a Scope (bidirectional) + */ + public static TypeSymbol inScope(IBasicSymbolsScope p, TypeSymbol s) { + s.setEnclosingScope(p); + s.getSpannedScope().setEnclosingScope(p); + p.add(s); + p.addSubScope(s.getSpannedScope()); + return s; + } + + public static OOTypeSymbol inScope(IOOSymbolsScope p, OOTypeSymbol s) { + s.setEnclosingScope(p); + s.getSpannedScope().setEnclosingScope(p); + p.add(s); + p.addSubScope(s.getSpannedScope()); + return s; + } + + /** + * add a Variable to a Scope (bidirectional) + */ + public static VariableSymbol inScope(IBasicSymbolsScope p, VariableSymbol s) { + s.setEnclosingScope(p); + p.add(s); + return s; + } + + public static FieldSymbol inScope(IOOSymbolsScope p, FieldSymbol s) { + s.setEnclosingScope(p); + p.add(s); + return s; + } + + /** + * add a Function to a Scope (bidirectional) + */ + public static FunctionSymbol inScope(IBasicSymbolsScope p, FunctionSymbol s) { + s.setEnclosingScope(p); + s.getSpannedScope().setEnclosingScope(p); + p.add(s); + p.addSubScope(s.getSpannedScope()); + return s; + } + + public static MethodSymbol inScope(IOOSymbolsScope p, MethodSymbol s) { + s.setEnclosingScope(p); + s.getSpannedScope().setEnclosingScope(p); + p.add(s); + p.addSubScope(s.getSpannedScope()); + return s; + } + + /** + * add a TypeVariable to a Scope (bidirectional) + */ + public static TypeVarSymbol inScope(IBasicSymbolsScope p, TypeVarSymbol s) { + s.setEnclosingScope(p); + p.add(s); + return s; + } + + /*********************************************************************/ + + /* + * Helpers that efficiently create Symbols + * (which by the way can also later be extended) + */ + + // create TypeSymbols (some defaults apply) + public static TypeSymbol type(String name) { + IBasicSymbolsScope scope = BasicSymbolsMill.scope(); + scope.setShadowing(true); + return BasicSymbolsMill.typeSymbolBuilder() + .setSpannedScope(scope) + .setName(name) + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .build(); + } + + public static TypeSymbol type(String name, + List superTypeList) { + TypeSymbol ts = type(name); + ts.setSuperTypesList(superTypeList); + return ts; + } + + public static TypeSymbol type(String name, + List superTypeList, + List typeVariableList) { + TypeSymbol ts = type(name, superTypeList); + typeVariableList.forEach(tv -> inScope(ts.getSpannedScope(), tv)); + return ts; + } + + public static TypeSymbol type(String name, + List superTypeList, + List typeVariableList, + List functionList, + List variableList) { + TypeSymbol ts = type(name, superTypeList, typeVariableList); + functionList.forEach(fs -> inScope(ts.getSpannedScope(), fs)); + variableList.forEach(vs -> inScope(ts.getSpannedScope(), vs)); + return ts; + } + + // create OOTypeSymbols (some defaults apply) + + public static OOTypeSymbol oOtype(String name) { + IOOSymbolsScope scope = OOSymbolsMill.scope(); + scope.setShadowing(true); + return OOSymbolsMill.oOTypeSymbolBuilder() + .setSpannedScope(scope) + .setName(name) + .setIsPublic(true) + .setIsStatic(true) + .build(); + } + + public static OOTypeSymbol oOtype(String name, + List superTypeList) { + OOTypeSymbol ts = oOtype(name); + ts.setSuperTypesList(superTypeList); + return ts; + } + + public static OOTypeSymbol oOtype(String name, + List superTypeList, + List typeVariableList) { + OOTypeSymbol ts = oOtype(name, superTypeList); + typeVariableList.forEach(tv -> inScope(ts.getSpannedScope(), tv)); + return ts; + } + + public static OOTypeSymbol oOtype(String name, + List superTypeList, + List typeVariableList, + List methodList, + List fieldList) { + OOTypeSymbol ts = oOtype(name, superTypeList, typeVariableList); + methodList.forEach(fs -> inScope(ts.getSpannedScope(), fs)); + fieldList.forEach(vs -> inScope(ts.getSpannedScope(), vs)); + return ts; + } + + // create TypeVarSymbols (some defaults apply) + + public static TypeVarSymbol typeVariable(String name) { + return typeVariable(name, new ArrayList<>()); + } + + public static TypeVarSymbol typeVariable(String name, + List superTypeList) { + return BasicSymbolsMill.typeVarSymbolBuilder() + .setName(name) + .setSuperTypesList(superTypeList) + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); + } + + // create FunctionSymbols (some defaults apply) + + public static FunctionSymbol function(String name, SymTypeExpression returnType, + SymTypeExpression... argumentTypes) { + return function(name, returnType, List.of(argumentTypes)); + } + + public static FunctionSymbol function(String name, SymTypeExpression returnType, + List argumentTypes) { + return function(name, returnType, argumentTypes, false); + } + + public static FunctionSymbol function(String name, SymTypeExpression returnType, + List argumentTypes, boolean elliptic) { + IBasicSymbolsScope scope = BasicSymbolsMill.scope(); + scope.setOrdered(true); + scope.setShadowing(true); + for (int i = 0; i < argumentTypes.size(); i++) { + scope.add( + BasicSymbolsMill.variableSymbolBuilder() + .setType(argumentTypes.get(i)) + .setName("arg" + i) + .build() + ); + } + return BasicSymbolsMill.functionSymbolBuilder() + .setSpannedScope(scope) + .setName(name) + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setType(returnType) + .setIsElliptic(elliptic) + .build(); + } + + // create MethodSymbols (some defaults apply) + + public static MethodSymbol method(String name, SymTypeExpression returnType, + SymTypeExpression... argumentTypes) { + return method(name, returnType, List.of(argumentTypes)); + } + + public static MethodSymbol method(String name, SymTypeExpression returnType, + List argumentTypes) { + return method(name, returnType, argumentTypes, false); + } + + public static MethodSymbol method(String name, SymTypeExpression returnType, + List argumentTypes, boolean elliptic) { + IOOSymbolsScope scope = OOSymbolsMill.scope(); + scope.setOrdered(true); + scope.setShadowing(true); + for (int i = 0; i < argumentTypes.size(); i++) { + scope.add( + OOSymbolsMill.fieldSymbolBuilder() + .setType(argumentTypes.get(i)) + .setName("arg" + i) + .build() + ); + } + return OOSymbolsMill.methodSymbolBuilder() + .setSpannedScope(scope) + .setName(name) + .setType(returnType) + .setIsElliptic(elliptic) + .setIsPublic(true) + .setIsStatic(false) + .build(); + } + + // create VariableSymbols (some defaults apply) + + public static VariableSymbol variable(String name, SymTypeExpression type) { + return BasicSymbolsMill.variableSymbolBuilder() + .setName(name) + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setType(type) + .build(); + } + + // create FieldSymbols (some defaults apply) + + public static FieldSymbol field(String name, SymTypeExpression type) { + return OOSymbolsMill.fieldSymbolBuilder() + .setName(name) + .setType(type) + .setIsPublic(true) + .setIsStatic(false) + .build(); + } + + /*********************************************************************/ + + /* + * This is the predefined Symbol for 'special' types like void + * these are usually the ones with a fixed amount of values + */ + + public static SymTypeOfNull _nullSymType; + + public static SymTypeVoid _voidSymType; + + public static SymTypeObscure _obscureSymType; + + public static void set_specialSymTypes() { + _nullSymType = SymTypeExpressionFactory.createTypeOfNull(); + _voidSymType = SymTypeExpressionFactory.createTypeVoid(); + _obscureSymType = SymTypeExpressionFactory.createObscureType(); + } + + /*********************************************************************/ + + /* + * This is the predefined Symbol for all Primitives, such as "int" + * which has empty Variables and Functions + */ + + public static SymTypePrimitive _intSymType; + + public static SymTypePrimitive _charSymType; + + public static SymTypePrimitive _booleanSymType; + + public static SymTypePrimitive _doubleSymType; + + public static SymTypePrimitive _floatSymType; + + public static SymTypePrimitive _longSymType; + + public static SymTypePrimitive _byteSymType; + + public static SymTypePrimitive _shortSymType; + + public static void set_thePrimitives() { + IBasicSymbolsGlobalScope typeSymbolsScope = BasicSymbolsMill.globalScope(); + if (typeSymbolsScope.resolveType(BasicSymbolsMill.INT).isEmpty()) { + BasicSymbolsMill.initializePrimitives(); + } + _intSymType = createPrimitive( + typeSymbolsScope.resolveType(BasicSymbolsMill.INT).get()); + _charSymType = createPrimitive( + typeSymbolsScope.resolveType(BasicSymbolsMill.CHAR).get()); + _booleanSymType = createPrimitive( + typeSymbolsScope.resolveType(BasicSymbolsMill.BOOLEAN).get()); + _doubleSymType = createPrimitive( + typeSymbolsScope.resolveType(BasicSymbolsMill.DOUBLE).get()); + _floatSymType = createPrimitive( + typeSymbolsScope.resolveType(BasicSymbolsMill.FLOAT).get()); + _longSymType = createPrimitive( + typeSymbolsScope.resolveType(BasicSymbolsMill.LONG).get()); + _byteSymType = createPrimitive( + typeSymbolsScope.resolveType(BasicSymbolsMill.BYTE).get()); + _shortSymType = createPrimitive( + typeSymbolsScope.resolveType(BasicSymbolsMill.SHORT).get()); + } + + /*********************************************************************/ + + /* + * These are the predefined Symbol for boxed Primitives, such as "Integer" + */ + + public static SymTypeOfObject _IntegerSymType; + + public static SymTypeOfObject _CharacterSymType; + + public static SymTypeOfObject _BooleanSymType; + + public static SymTypeOfObject _DoubleSymType; + + public static SymTypeOfObject _FloatSymType; + + public static SymTypeOfObject _LongSymType; + + public static SymTypeOfObject _ByteSymType; + + public static SymTypeOfObject _ShortSymType; + + public static void set_boxedPrimitives() { + IBasicSymbolsScope langScope = createJavaLangScope(); + // create boxed primitives + _IntegerSymType = + createTypeObject(inScope(langScope, type("Integer"))); + _CharacterSymType = + createTypeObject(inScope(langScope, type("Character"))); + _BooleanSymType = + createTypeObject(inScope(langScope, type("Boolean"))); + _DoubleSymType = + createTypeObject(inScope(langScope, type("Double"))); + _FloatSymType = + createTypeObject(inScope(langScope, type("Float"))); + _LongSymType = + createTypeObject(inScope(langScope, type("Long"))); + _ByteSymType = + createTypeObject(inScope(langScope, type("Byte"))); + _ShortSymType = + createTypeObject(inScope(langScope, type("Short"))); + } + + /*********************************************************************/ + + /* + * These are the predefined Symbol for unboxed Objects like "String" + */ + + public static SymTypeOfObject _unboxedString; + + public static void set_unboxedObjects() { + IBasicSymbolsGlobalScope typeSymbolsScope = BasicSymbolsMill.globalScope(); + if (typeSymbolsScope.resolveType(BasicSymbolsMill.STRING).isEmpty()) { + BasicSymbolsMill.initializeString(); + } + _unboxedString = createTypeObject( + typeSymbolsScope.resolveType(BasicSymbolsMill.STRING).get()); + } + + /*********************************************************************/ + + /* + * These are the predefined Symbol for boxed Objects like "String" + */ + + public static SymTypeOfObject _boxedString; + + public static void set_boxedObjects() { + IBasicSymbolsScope langScope = createJavaLangScope(); + _boxedString = createTypeObject(inScope(langScope, type("String"))); + } + + /*********************************************************************/ + + /* + * These are the predefined Symbol for unboxed Collections like "List" + * They have separate setup function as different languages (s. OCL) + * have their own version of some of them + */ + + public static SymTypeOfGenerics _unboxedOptionalSymType; + + public static SymTypeOfGenerics _unboxedSetSymType; + + public static SymTypeOfGenerics _unboxedListSymType; + + public static SymTypeOfGenerics _unboxedMapSymType; + + public static void set_unboxedCollections() { + set_unboxedOptionalSymType(); + set_unboxedSetSymType(); + set_unboxedListSymType(); + set_unboxedMapSymType(); + } + + public static void set_unboxedOptionalSymType() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + TypeVarSymbol optVar = typeVariable("T"); + _unboxedOptionalSymType = createGenerics( + inScope(gs, type("Optional", List.of(), List.of(optVar))), + createTypeVariable(optVar) + ); + } + + public static void set_unboxedSetSymType() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + TypeVarSymbol setVar = typeVariable("T"); + _unboxedSetSymType = createGenerics( + inScope(gs, type("Set", List.of(), List.of(setVar))), + createTypeVariable(setVar) + ); + } + + public static void set_unboxedListSymType() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + TypeVarSymbol listVar = typeVariable("T"); + _unboxedListSymType = createGenerics( + inScope(gs, type("List", List.of(), List.of(listVar))), + createTypeVariable(listVar) + ); + } + + public static void set_unboxedMapSymType() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + TypeVarSymbol mapVar1 = typeVariable("T"); + TypeVarSymbol mapVar2 = typeVariable("U"); + _unboxedMapSymType = createGenerics( + inScope(gs, type("Map", List.of(), List.of(mapVar1, mapVar2))), + createTypeVariable(mapVar1), createTypeVariable(mapVar2) + ); + } + + /*********************************************************************/ + + /* + * These are the predefined Symbol for unboxed Collections like "List" + */ + + public static SymTypeOfGenerics _boxedOptionalSymType; + + public static SymTypeOfGenerics _boxedSetSymType; + + public static SymTypeOfGenerics _boxedListSymType; + + public static SymTypeOfGenerics _boxedMapSymType; + + public static void set_boxedCollections() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + IBasicSymbolsScope javaScope = inScope(gs, scope("java")); + IBasicSymbolsScope utilScope = inScope(javaScope, scope("util")); + TypeVarSymbol optVar = typeVariable("OptT"); + _boxedOptionalSymType = createGenerics( + inScope(utilScope, type("Optional", List.of(), List.of(optVar))), + createTypeVariable(optVar) + ); + TypeVarSymbol setVar = typeVariable("SetT"); + _boxedSetSymType = createGenerics( + inScope(utilScope, type("Set", List.of(), List.of(setVar))), + createTypeVariable(setVar) + ); + TypeVarSymbol listVar = typeVariable("ListT"); + _boxedListSymType = createGenerics( + inScope(utilScope, type("List", List.of(), List.of(listVar))), + createTypeVariable(listVar) + ); + TypeVarSymbol mapVar1 = typeVariable("KeyT"); + TypeVarSymbol mapVar2 = typeVariable("ValueT"); + _boxedMapSymType = createGenerics( + inScope(utilScope, type("Map", List.of(), List.of(mapVar1, mapVar2))), + createTypeVariable(mapVar1), createTypeVariable(mapVar2) + ); + } + + /*********************************************************************/ + + /* + * These are the predefined Symbol for Streams. + * If their symbols cannot be resolved, + * these are null and should not be used. + * The symbols have to be made available + * as they are part of the symbol library. + */ + + public static SymTypeOfGenerics _StreamSymType; + + public static SymTypeOfGenerics _EventStreamSymType; + + public static SymTypeOfGenerics _SyncStreamSymType; + + public static SymTypeOfGenerics _ToptStreamSymType; + + public static SymTypeOfGenerics _UntimedStreamSymType; + + public static void set_streams() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + Optional symbolOpt = gs.resolveType("Stream"); + // load from Symbol Table if present + if (symbolOpt.isPresent()) { + TypeSymbol symbol = symbolOpt.get(); + TypeVarSymbol tvSym = symbol.getTypeParameterList().get(0); + _StreamSymType = createGenerics(symbol, createTypeVariable(tvSym)); + symbol = gs.resolveType("EventStream").get(); + tvSym = symbol.getTypeParameterList().get(0); + _EventStreamSymType = createGenerics(symbol, createTypeVariable(tvSym)); + symbol = gs.resolveType("SyncStream").get(); + tvSym = symbol.getTypeParameterList().get(0); + _SyncStreamSymType = createGenerics(symbol, createTypeVariable(tvSym)); + symbol = gs.resolveType("ToptStream").get(); + tvSym = symbol.getTypeParameterList().get(0); + _ToptStreamSymType = createGenerics(symbol, createTypeVariable(tvSym)); + symbol = gs.resolveType("UntimedStream").get(); + tvSym = symbol.getTypeParameterList().get(0); + _UntimedStreamSymType = createGenerics(symbol, createTypeVariable(tvSym)); + } + else { + Log.trace("Stream could not be resolved," + + " skipping its usual initialization", + "DefsTypesForTests" + ); + TypeVarSymbol streamVar = typeVariable("StreamT"); + _StreamSymType = createGenerics( + inScope(gs, type("Stream", List.of(), List.of(streamVar))), + createTypeVariable(streamVar) + ); + TypeVarSymbol eventStreamVar = typeVariable("EventStreamT"); + SymTypeExpression eventStreamSuperType = createGenerics( + _StreamSymType.getTypeInfo(), + List.of(createTypeVariable(eventStreamVar)) + ); + _EventStreamSymType = createGenerics( + inScope(gs, type( + "EventStream", + List.of(eventStreamSuperType), + List.of(eventStreamVar) + )), + createTypeVariable(eventStreamVar) + ); + TypeVarSymbol syncStreamVar = typeVariable("SyncStreamT"); + SymTypeExpression syncStreamSuperType = createGenerics( + _StreamSymType.getTypeInfo(), + List.of(createTypeVariable(syncStreamVar)) + ); + _SyncStreamSymType = createGenerics( + inScope(gs, type( + "SyncStream", + List.of(syncStreamSuperType), + List.of(syncStreamVar) + )), + createTypeVariable(syncStreamVar) + ); + TypeVarSymbol toptStreamVar = typeVariable("ToptStreamT"); + SymTypeExpression toptStreamSuperType = createGenerics( + _StreamSymType.getTypeInfo(), + List.of(createTypeVariable(toptStreamVar)) + ); + _ToptStreamSymType = createGenerics( + inScope(gs, type( + "ToptStream", + List.of(toptStreamSuperType), + List.of(toptStreamVar) + )), + createTypeVariable(toptStreamVar) + ); + TypeVarSymbol untimedStreamVar = typeVariable("UntimedStreamT"); + SymTypeExpression untimedStreamSuperType = createGenerics( + _StreamSymType.getTypeInfo(), + List.of(createTypeVariable(untimedStreamVar)) + ); + _UntimedStreamSymType = createGenerics( + inScope(gs, type( + "UntimedStream", + List.of(untimedStreamSuperType), + List.of(untimedStreamVar) + )), + createTypeVariable(untimedStreamVar) + ); + } + } + + /*********************************************************************/ + + /* + * These are some predefined Symbols for recursively defined generic types + */ + + /** + * s. simple curiously recurring template pattern + */ + public static SymTypeOfGenerics _simpleCrtSymType; + + // Graph example out of Wild FJ (2015) + //class Node , E extends Edge> + //class Edge , E extends Edge> + //class Graph, E extends Edge> + + public static SymTypeOfGenerics _graphNodeSymType; + + public static SymTypeOfGenerics _graphEdgeSymType; + + public static SymTypeOfGenerics _graphSymType; + + public static void set_genericsRecursive() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + // SimpleCrt> + TypeVarSymbol crtVar = typeVariable("CrtT"); + _simpleCrtSymType = createGenerics( + inScope(gs, type("SimpleCrt", List.of(), List.of(crtVar))), + createTypeVariable(crtVar) + ); + crtVar.addSuperTypes(_simpleCrtSymType); + + // Graph example out of Wild FJ (2015) + TypeSymbol nodeSymbol = inScope(gs, type("Node")); + TypeSymbol edgeSymbol = inScope(gs, type("Edge")); + TypeSymbol graphSymbol = inScope(gs, type("Graph")); + //class Node , E extends Edge> + SymTypeVariable nodeNodeVar = createTypeVariable(typeVariable("NodeN")); + SymTypeVariable nodeEdgeVar = createTypeVariable(typeVariable("NodeE")); + nodeSymbol.getSpannedScope().add(nodeNodeVar.getTypeVarSymbol()); + nodeSymbol.getSpannedScope().add(nodeEdgeVar.getTypeVarSymbol()); + //class Edge , E extends Edge> + SymTypeVariable edgeNodeVar = createTypeVariable(typeVariable("EdgeN")); + SymTypeVariable edgeEdgeVar = createTypeVariable(typeVariable("EdgeE")); + edgeSymbol.getSpannedScope().add(edgeNodeVar.getTypeVarSymbol()); + edgeSymbol.getSpannedScope().add(edgeEdgeVar.getTypeVarSymbol()); + //class Graph, E extends Edge> + SymTypeVariable graphNodeVar = createTypeVariable(typeVariable("GraphN")); + SymTypeVariable graphEdgeVar = createTypeVariable(typeVariable("GraphE")); + graphSymbol.getSpannedScope().add(graphNodeVar.getTypeVarSymbol()); + graphSymbol.getSpannedScope().add(graphEdgeVar.getTypeVarSymbol()); + // TypeVar superTypes + nodeNodeVar.getTypeVarSymbol().addSuperTypes(createGenerics( + nodeSymbol, List.of(nodeNodeVar, nodeEdgeVar) + )); + nodeEdgeVar.getTypeVarSymbol().addSuperTypes(createGenerics( + edgeSymbol, List.of(nodeNodeVar, nodeEdgeVar) + )); + edgeNodeVar.getTypeVarSymbol().addSuperTypes(createGenerics( + nodeSymbol, List.of(edgeNodeVar, edgeEdgeVar) + )); + edgeEdgeVar.getTypeVarSymbol().addSuperTypes(createGenerics( + edgeSymbol, List.of(edgeNodeVar, edgeEdgeVar) + )); + graphNodeVar.getTypeVarSymbol().addSuperTypes(createGenerics( + nodeSymbol, List.of(graphNodeVar, graphEdgeVar) + )); + graphEdgeVar.getTypeVarSymbol().addSuperTypes(createGenerics( + edgeSymbol, List.of(graphNodeVar, graphEdgeVar) + )); + // finally create SymTypeExpressions + _graphNodeSymType = createGenerics(nodeSymbol, nodeNodeVar, nodeEdgeVar); + _graphEdgeSymType = createGenerics(edgeSymbol, edgeNodeVar, edgeEdgeVar); + _graphSymType = createGenerics(graphSymbol, graphNodeVar, graphEdgeVar); + } + + /*********************************************************************/ + + /* + * These are some predefined Symbols for Object Types + */ + + public static SymTypeOfObject _personSymType; + + public static SymTypeOfObject _teachableSymType; + + // student is a subtype of person, teachable + public static SymTypeOfObject _studentSymType; + + // computer science student is a subtype of student; + public static SymTypeOfObject _csStudentSymType; + + // first semester computer science student + // is a subType of computer science student + public static SymTypeOfObject _firstSemesterCsStudentSymType; + + // child is a subtype of person, teachable + public static SymTypeOfObject _childSymType; + + // teacher is a subtype of person + public static SymTypeOfObject _teacherSymType; + + public static SymTypeOfObject _carSymType; + + public static SymTypeOfObject _schoolSymType; + + public static void set_objectTypes() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + _personSymType = createTypeObject(inScope(gs, type("Person"))); + _teachableSymType = createTypeObject(inScope(gs, type("Teachable"))); + _studentSymType = createTypeObject(inScope(gs, + type("Student", List.of(_personSymType, _teachableSymType))) + ); + _csStudentSymType = createTypeObject(inScope(gs, + type("CsStudent", List.of(_studentSymType))) + ); + _firstSemesterCsStudentSymType = createTypeObject(inScope(gs, + type("FirstSemesterCsStudent", List.of(_csStudentSymType))) + ); + _childSymType = createTypeObject(inScope(gs, + type("Child", List.of(_personSymType, _teachableSymType))) + ); + _teacherSymType = createTypeObject(inScope(gs, + type("Teacher", List.of(_personSymType))) + ); + _carSymType = createTypeObject(inScope(gs, type("Car"))); + _schoolSymType = createTypeObject(inScope(gs, type("School"))); + } + + /* + * These are some objects types with special behavior wrt. typechecking + * (s. a. Java Spec) + * (These tend to lie in java.lang) + */ + + public static SymTypeOfObject _ObjectSymType; + + public static SymTypeOfObject _ThrowableSymType; + + public static SymTypeOfObject _VoidSymType; + + // try-with-resource + public static SymTypeOfObject _AutoClosableSymType; + + public static void set_specialObjectTypes() { + IBasicSymbolsScope langScope = createJavaLangScope(); + _ObjectSymType = + createTypeObject(inScope(langScope, type("Object"))); + _ThrowableSymType = + createTypeObject(inScope(langScope, type("Throwable"))); + _VoidSymType = + createTypeObject(inScope(langScope, type("Void"))); + _AutoClosableSymType = + createTypeObject(inScope(langScope, type("AutoClosable"))); + } + + /*********************************************************************/ + + /* + * These are the predefined Symbol for further generics + * in most cases, the collections ought to be enough + */ + + public static SymTypeOfGenerics _linkedListSymType; + + public static SymTypeOfGenerics _hashMapSymType; + + public static void set_generics() { + IBasicSymbolsScope utilScope = + _boxedListSymType.getTypeInfo().getEnclosingScope(); + TypeVarSymbol listVar = typeVariable("LinkedListT"); + _linkedListSymType = createGenericsDeclaredType( + inScope(utilScope, type("LinkedList", + List.of(createGenerics(_boxedListSymType.getTypeInfo(), + createTypeVariable(listVar))), + List.of(listVar) + )) + ); + TypeVarSymbol mapKVar = typeVariable("HashMapK"); + TypeVarSymbol mapVVar = typeVariable("HashMapV"); + _hashMapSymType = createGenericsDeclaredType( + inScope(utilScope, type("HashMap", + List.of(createGenerics( + _boxedMapSymType.getTypeInfo(), + createTypeVariable(mapKVar), + createTypeVariable(mapVVar)) + ), + List.of(mapKVar, mapVVar)) + ) + ); + } + + + /* + * These are some generic types with special behavior wrt. typechecking + * (s. a. Java Spec) + * (These tend to lie in java.lang) + */ + + public static SymTypeOfGenerics _ClassSymType; + + public static SymTypeOfGenerics _IterableSymType; + + public static void set_specialGenerics() { + IBasicSymbolsScope langScope = createJavaLangScope(); + TypeVarSymbol classVar = typeVariable("T"); + _ClassSymType = createGenericsDeclaredType( + inScope(langScope, type("Class", + Collections.emptyList(), + List.of(classVar) + )) + ); + TypeVarSymbol IterableVar = typeVariable("T"); + _IterableSymType = createGenericsDeclaredType( + inScope(langScope, type("Iterable", + Collections.emptyList(), + List.of(classVar) + )) + ); + } + + /*********************************************************************/ + + /* + * These are predefined symbols for bottom and top types + */ + + public static SymTypeExpression _bottomType; + + public static SymTypeExpression _topType; + + public static void set_bottomTopTypes() { + _bottomType = createBottomType(); + _topType = createTopType(); + } + + /*********************************************************************/ + + /* + * These are SIUnitBasics to create SymTypeOfSIUnits + */ + + // The seven base units (kg with and without prefix k) + public static SIUnitBasic _s_SIUnitBasic; + public static SIUnitBasic _m_SIUnitBasic; + public static SIUnitBasic _g_SIUnitBasic; + public static SIUnitBasic _A_SIUnitBasic; + public static SIUnitBasic _K_SIUnitBasic; + public static SIUnitBasic _mol_SIUnitBasic; + public static SIUnitBasic _cd_SIUnitBasic; + public static SIUnitBasic _kg_SIUnitBasic; + // Further supported SIUnitBasics + public static SIUnitBasic _Hz_SIUnitBasic; + public static SIUnitBasic _N_SIUnitBasic; + public static SIUnitBasic _Pa_SIUnitBasic; + public static SIUnitBasic _J_SIUnitBasic; + public static SIUnitBasic _W_SIUnitBasic; + public static SIUnitBasic _C_SIUnitBasic; + public static SIUnitBasic _V_SIUnitBasic; + public static SIUnitBasic _F_SIUnitBasic; + public static SIUnitBasic _Ohm_SIUnitBasic; + public static SIUnitBasic _ohm_SIUnitBasic; + public static SIUnitBasic _S_SIUnitBasic; + public static SIUnitBasic _Wb_SIUnitBasic; + public static SIUnitBasic _T_SIUnitBasic; + public static SIUnitBasic _H_SIUnitBasic; + public static SIUnitBasic _lm_SIUnitBasic; + public static SIUnitBasic _lx_SIUnitBasic; + public static SIUnitBasic _Bq_SIUnitBasic; + public static SIUnitBasic _Gy_SIUnitBasic; + public static SIUnitBasic _Sv_SIUnitBasic; + public static SIUnitBasic _kat_SIUnitBasic; + public static SIUnitBasic _l_SIUnitBasic; + public static SIUnitBasic _L_SIUnitBasic; + public static SIUnitBasic _min_SIUnitBasic; + public static SIUnitBasic _h_SIUnitBasic; + public static SIUnitBasic _d_SIUnitBasic; + public static SIUnitBasic _ha_SIUnitBasic; + public static SIUnitBasic _t_SIUnitBasic; + public static SIUnitBasic _au_SIUnitBasic; + public static SIUnitBasic _eV_SIUnitBasic; + public static SIUnitBasic _Da_SIUnitBasic; + public static SIUnitBasic _u_SIUnitBasic; + public static SIUnitBasic _celsius_SIUnitBasic; + public static SIUnitBasic _fahrenheit_SIUnitBasic; + public static SIUnitBasic _Np_SIUnitBasic; + public static SIUnitBasic _B_SIUnitBasic; + public static SIUnitBasic _dB_SIUnitBasic; + public static SIUnitBasic _degSym_SIUnitBasic; + public static SIUnitBasic _deg_SIUnitBasic; + public static SIUnitBasic _rad_SIUnitBasic; + public static SIUnitBasic _sr_SIUnitBasic; + + public static void set_siUnitBasic() { + _s_SIUnitBasic = createSIUnitBasic("s"); + _m_SIUnitBasic = createSIUnitBasic("m"); + _g_SIUnitBasic = createSIUnitBasic("g"); + _A_SIUnitBasic = createSIUnitBasic("A"); + _K_SIUnitBasic = createSIUnitBasic("K"); + _mol_SIUnitBasic = createSIUnitBasic("mol"); + _cd_SIUnitBasic = createSIUnitBasic("cd"); + _kg_SIUnitBasic = createSIUnitBasic("g", "k", 1); + + _Hz_SIUnitBasic = createSIUnitBasic("Hz"); + _N_SIUnitBasic = createSIUnitBasic("N"); + _Pa_SIUnitBasic = createSIUnitBasic("Pa"); + _J_SIUnitBasic = createSIUnitBasic("J"); + _W_SIUnitBasic = createSIUnitBasic("W"); + _C_SIUnitBasic = createSIUnitBasic("C"); + _V_SIUnitBasic = createSIUnitBasic("V"); + _F_SIUnitBasic = createSIUnitBasic("F"); + _Ohm_SIUnitBasic = createSIUnitBasic("Ohm"); + _ohm_SIUnitBasic = createSIUnitBasic("Ω"); + _S_SIUnitBasic = createSIUnitBasic("S"); + _Wb_SIUnitBasic = createSIUnitBasic("Wb"); + _T_SIUnitBasic = createSIUnitBasic("T"); + _H_SIUnitBasic = createSIUnitBasic("H"); + _lm_SIUnitBasic = createSIUnitBasic("lm"); + _lx_SIUnitBasic = createSIUnitBasic("lx"); + _Bq_SIUnitBasic = createSIUnitBasic("Bq"); + _Gy_SIUnitBasic = createSIUnitBasic("Gy"); + _Sv_SIUnitBasic = createSIUnitBasic("Sv"); + _kat_SIUnitBasic = createSIUnitBasic("kat"); + _l_SIUnitBasic = createSIUnitBasic("l"); + _L_SIUnitBasic = createSIUnitBasic("L"); + _min_SIUnitBasic = createSIUnitBasic("min"); + _h_SIUnitBasic = createSIUnitBasic("h"); + _d_SIUnitBasic = createSIUnitBasic("d"); + _ha_SIUnitBasic = createSIUnitBasic("ha"); + _t_SIUnitBasic = createSIUnitBasic("t"); + _au_SIUnitBasic = createSIUnitBasic("au"); + _eV_SIUnitBasic = createSIUnitBasic("eV"); + _Da_SIUnitBasic = createSIUnitBasic("Da"); + _u_SIUnitBasic = createSIUnitBasic("u"); + _celsius_SIUnitBasic = createSIUnitBasic("ºC"); + _fahrenheit_SIUnitBasic = createSIUnitBasic("ºF"); + _Np_SIUnitBasic = createSIUnitBasic("Np"); + _B_SIUnitBasic = createSIUnitBasic("B"); + _dB_SIUnitBasic = createSIUnitBasic("dB"); + _degSym_SIUnitBasic = createSIUnitBasic("°"); + _deg_SIUnitBasic = createSIUnitBasic("deg"); + _rad_SIUnitBasic = createSIUnitBasic("rad"); + _sr_SIUnitBasic = createSIUnitBasic("sr"); + } + + /*********************************************************************/ + + /* + * These are simple(!) SymTypeOfSIUnits, + * one for each supported SIUnitBasic + * + * Hint: you may instead want SIUnitIteratorForTests + */ + + // The seven base units (kg with and without prefix k) + public static SymTypeOfSIUnit _m_SISymType; + public static SymTypeOfSIUnit _g_SISymType; + public static SymTypeOfSIUnit _s_SISymType; + public static SymTypeOfSIUnit _A_SISymType; + public static SymTypeOfSIUnit _K_SISymType; + public static SymTypeOfSIUnit _mol_SISymType; + public static SymTypeOfSIUnit _cd_SISymType; + public static SymTypeOfSIUnit _kg_SISymType; + // Further supported SIUnits + public static SymTypeOfSIUnit _Hz_SISymType; + public static SymTypeOfSIUnit _N_SISymType; + public static SymTypeOfSIUnit _Pa_SISymType; + public static SymTypeOfSIUnit _J_SISymType; + public static SymTypeOfSIUnit _W_SISymType; + public static SymTypeOfSIUnit _C_SISymType; + public static SymTypeOfSIUnit _V_SISymType; + public static SymTypeOfSIUnit _F_SISymType; + public static SymTypeOfSIUnit _Ohm_SISymType; + public static SymTypeOfSIUnit _ohm_SISymType; + public static SymTypeOfSIUnit _S_SISymType; + public static SymTypeOfSIUnit _Wb_SISymType; + public static SymTypeOfSIUnit _T_SISymType; + public static SymTypeOfSIUnit _H_SISymType; + public static SymTypeOfSIUnit _lm_SISymType; + public static SymTypeOfSIUnit _lx_SISymType; + public static SymTypeOfSIUnit _Bq_SISymType; + public static SymTypeOfSIUnit _Gy_SISymType; + public static SymTypeOfSIUnit _Sv_SISymType; + public static SymTypeOfSIUnit _kat_SISymType; + public static SymTypeOfSIUnit _l_SISymType; + public static SymTypeOfSIUnit _L_SISymType; + public static SymTypeOfSIUnit _min_SISymType; + public static SymTypeOfSIUnit _h_SISymType; + public static SymTypeOfSIUnit _d_SISymType; + public static SymTypeOfSIUnit _ha_SISymType; + public static SymTypeOfSIUnit _t_SISymType; + public static SymTypeOfSIUnit _au_SISymType; + public static SymTypeOfSIUnit _eV_SISymType; + public static SymTypeOfSIUnit _Da_SISymType; + public static SymTypeOfSIUnit _u_SISymType; + public static SymTypeOfSIUnit _celsius_SISymType; + public static SymTypeOfSIUnit _fahrenheit_SISymType; + public static SymTypeOfSIUnit _Np_SISymType; + public static SymTypeOfSIUnit _B_SISymType; + public static SymTypeOfSIUnit _dB_SISymType; + public static SymTypeOfSIUnit _degSym_SISymType; + public static SymTypeOfSIUnit _deg_SISymType; + public static SymTypeOfSIUnit _rad_SISymType; + public static SymTypeOfSIUnit _sr_SISymType; + + public static void set_siUnitTypes() { + _m_SISymType = createSIUnit(List.of(_m_SIUnitBasic), List.of()); + _g_SISymType = createSIUnit(List.of(_g_SIUnitBasic), List.of()); + _s_SISymType = createSIUnit(List.of(_s_SIUnitBasic), List.of()); + _A_SISymType = createSIUnit(List.of(_A_SIUnitBasic), List.of()); + _K_SISymType = createSIUnit(List.of(_K_SIUnitBasic), List.of()); + _mol_SISymType = createSIUnit(List.of(_mol_SIUnitBasic), List.of()); + _cd_SISymType = createSIUnit(List.of(_cd_SIUnitBasic), List.of()); + _kg_SISymType = createSIUnit(List.of(_kg_SIUnitBasic), List.of()); + + _Hz_SISymType = createSIUnit(List.of(_Hz_SIUnitBasic), List.of()); + _N_SISymType = createSIUnit(List.of(_N_SIUnitBasic), List.of()); + _Pa_SISymType = createSIUnit(List.of(_Pa_SIUnitBasic), List.of()); + _J_SISymType = createSIUnit(List.of(_J_SIUnitBasic), List.of()); + _W_SISymType = createSIUnit(List.of(_W_SIUnitBasic), List.of()); + _C_SISymType = createSIUnit(List.of(_C_SIUnitBasic), List.of()); + _V_SISymType = createSIUnit(List.of(_V_SIUnitBasic), List.of()); + _F_SISymType = createSIUnit(List.of(_F_SIUnitBasic), List.of()); + _Ohm_SISymType = createSIUnit(List.of(_Ohm_SIUnitBasic), List.of()); + _ohm_SISymType = createSIUnit(List.of(_ohm_SIUnitBasic), List.of()); + _S_SISymType = createSIUnit(List.of(_S_SIUnitBasic), List.of()); + _Wb_SISymType = createSIUnit(List.of(_Wb_SIUnitBasic), List.of()); + _T_SISymType = createSIUnit(List.of(_T_SIUnitBasic), List.of()); + _H_SISymType = createSIUnit(List.of(_H_SIUnitBasic), List.of()); + _lm_SISymType = createSIUnit(List.of(_lm_SIUnitBasic), List.of()); + _lx_SISymType = createSIUnit(List.of(_lx_SIUnitBasic), List.of()); + _Bq_SISymType = createSIUnit(List.of(_Bq_SIUnitBasic), List.of()); + _Gy_SISymType = createSIUnit(List.of(_Gy_SIUnitBasic), List.of()); + _Sv_SISymType = createSIUnit(List.of(_Sv_SIUnitBasic), List.of()); + _kat_SISymType = createSIUnit(List.of(_kat_SIUnitBasic), List.of()); + _l_SISymType = createSIUnit(List.of(_l_SIUnitBasic), List.of()); + _L_SISymType = createSIUnit(List.of(_L_SIUnitBasic), List.of()); + _min_SISymType = createSIUnit(List.of(_min_SIUnitBasic), List.of()); + _h_SISymType = createSIUnit(List.of(_h_SIUnitBasic), List.of()); + _d_SISymType = createSIUnit(List.of(_d_SIUnitBasic), List.of()); + _ha_SISymType = createSIUnit(List.of(_ha_SIUnitBasic), List.of()); + _t_SISymType = createSIUnit(List.of(_t_SIUnitBasic), List.of()); + _au_SISymType = createSIUnit(List.of(_au_SIUnitBasic), List.of()); + _eV_SISymType = createSIUnit(List.of(_eV_SIUnitBasic), List.of()); + _Da_SISymType = createSIUnit(List.of(_Da_SIUnitBasic), List.of()); + _u_SISymType = createSIUnit(List.of(_u_SIUnitBasic), List.of()); + _celsius_SISymType = createSIUnit(List.of(_celsius_SIUnitBasic), List.of()); + _fahrenheit_SISymType = createSIUnit(List.of(_fahrenheit_SIUnitBasic), List.of()); + _Np_SISymType = createSIUnit(List.of(_Np_SIUnitBasic), List.of()); + _B_SISymType = createSIUnit(List.of(_B_SIUnitBasic), List.of()); + _dB_SISymType = createSIUnit(List.of(_dB_SIUnitBasic), List.of()); + _degSym_SISymType = createSIUnit(List.of(_degSym_SIUnitBasic), List.of()); + _deg_SISymType = createSIUnit(List.of(_deg_SIUnitBasic), List.of()); + _rad_SISymType = createSIUnit(List.of(_rad_SIUnitBasic), List.of()); + _sr_SISymType = createSIUnit(List.of(_sr_SIUnitBasic), List.of()); + } + + /*********************************************************************/ + + /* + * These are simple(!) SymTypeOfNumericWithSIUnits, + * one for each supported SIUnitBasic with int + * + * Hint: you may instead want SIUnitIteratorForTests + */ + + // The seven base units (kg with and without prefix k) + public static SymTypeOfNumericWithSIUnit _m_int_SISymType; + public static SymTypeOfNumericWithSIUnit _g_int_SISymType; + public static SymTypeOfNumericWithSIUnit _s_int_SISymType; + public static SymTypeOfNumericWithSIUnit _A_int_SISymType; + public static SymTypeOfNumericWithSIUnit _K_int_SISymType; + public static SymTypeOfNumericWithSIUnit _mol_int_SISymType; + public static SymTypeOfNumericWithSIUnit _cd_int_SISymType; + public static SymTypeOfNumericWithSIUnit _kg_int_SISymType; + // Further supported SIUnits + public static SymTypeOfNumericWithSIUnit _Hz_int_SISymType; + public static SymTypeOfNumericWithSIUnit _N_int_SISymType; + public static SymTypeOfNumericWithSIUnit _Pa_int_SISymType; + public static SymTypeOfNumericWithSIUnit _J_int_SISymType; + public static SymTypeOfNumericWithSIUnit _W_int_SISymType; + public static SymTypeOfNumericWithSIUnit _C_int_SISymType; + public static SymTypeOfNumericWithSIUnit _V_int_SISymType; + public static SymTypeOfNumericWithSIUnit _F_int_SISymType; + public static SymTypeOfNumericWithSIUnit _Ohm_int_SISymType; + public static SymTypeOfNumericWithSIUnit _ohm_int_SISymType; + public static SymTypeOfNumericWithSIUnit _S_int_SISymType; + public static SymTypeOfNumericWithSIUnit _Wb_int_SISymType; + public static SymTypeOfNumericWithSIUnit _T_int_SISymType; + public static SymTypeOfNumericWithSIUnit _H_int_SISymType; + public static SymTypeOfNumericWithSIUnit _lm_int_SISymType; + public static SymTypeOfNumericWithSIUnit _lx_int_SISymType; + public static SymTypeOfNumericWithSIUnit _Bq_int_SISymType; + public static SymTypeOfNumericWithSIUnit _Gy_int_SISymType; + public static SymTypeOfNumericWithSIUnit _Sv_int_SISymType; + public static SymTypeOfNumericWithSIUnit _kat_int_SISymType; + public static SymTypeOfNumericWithSIUnit _l_int_SISymType; + public static SymTypeOfNumericWithSIUnit _L_int_SISymType; + public static SymTypeOfNumericWithSIUnit _min_int_SISymType; + public static SymTypeOfNumericWithSIUnit _h_int_SISymType; + public static SymTypeOfNumericWithSIUnit _d_int_SISymType; + public static SymTypeOfNumericWithSIUnit _ha_int_SISymType; + public static SymTypeOfNumericWithSIUnit _t_int_SISymType; + public static SymTypeOfNumericWithSIUnit _au_int_SISymType; + public static SymTypeOfNumericWithSIUnit _eV_int_SISymType; + public static SymTypeOfNumericWithSIUnit _Da_int_SISymType; + public static SymTypeOfNumericWithSIUnit _u_int_SISymType; + public static SymTypeOfNumericWithSIUnit _celsius_int_SISymType; + public static SymTypeOfNumericWithSIUnit _fahrenheit_int_SISymType; + public static SymTypeOfNumericWithSIUnit _Np_int_SISymType; + public static SymTypeOfNumericWithSIUnit _B_int_SISymType; + public static SymTypeOfNumericWithSIUnit _dB_int_SISymType; + public static SymTypeOfNumericWithSIUnit _degSym_int_SISymType; + public static SymTypeOfNumericWithSIUnit _deg_int_SISymType; + public static SymTypeOfNumericWithSIUnit _rad_int_SISymType; + public static SymTypeOfNumericWithSIUnit _sr_int_SISymType; + + public static void set_numericWithSIUnitTypes() { + _m_int_SISymType = createNumericWithSIUnit(_m_SISymType, _intSymType); + _g_int_SISymType = createNumericWithSIUnit(_g_SISymType, _intSymType); + _s_int_SISymType = createNumericWithSIUnit(_s_SISymType, _intSymType); + _A_int_SISymType = createNumericWithSIUnit(_A_SISymType, _intSymType); + _K_int_SISymType = createNumericWithSIUnit(_K_SISymType, _intSymType); + _mol_int_SISymType = createNumericWithSIUnit(_mol_SISymType, _intSymType); + _cd_int_SISymType = createNumericWithSIUnit(_cd_SISymType, _intSymType); + _kg_int_SISymType = createNumericWithSIUnit(_kg_SISymType, _intSymType); + + _Hz_int_SISymType = createNumericWithSIUnit(_Hz_SISymType, _intSymType); + _N_int_SISymType = createNumericWithSIUnit(_N_SISymType, _intSymType); + _Pa_int_SISymType = createNumericWithSIUnit(_Pa_SISymType, _intSymType); + _J_int_SISymType = createNumericWithSIUnit(_J_SISymType, _intSymType); + _W_int_SISymType = createNumericWithSIUnit(_W_SISymType, _intSymType); + _C_int_SISymType = createNumericWithSIUnit(_C_SISymType, _intSymType); + _V_int_SISymType = createNumericWithSIUnit(_V_SISymType, _intSymType); + _F_int_SISymType = createNumericWithSIUnit(_F_SISymType, _intSymType); + _Ohm_int_SISymType = createNumericWithSIUnit(_Ohm_SISymType, _intSymType); + _ohm_int_SISymType = createNumericWithSIUnit(_ohm_SISymType, _intSymType); + _S_int_SISymType = createNumericWithSIUnit(_S_SISymType, _intSymType); + _Wb_int_SISymType = createNumericWithSIUnit(_Wb_SISymType, _intSymType); + _T_int_SISymType = createNumericWithSIUnit(_T_SISymType, _intSymType); + _H_int_SISymType = createNumericWithSIUnit(_H_SISymType, _intSymType); + _lm_int_SISymType = createNumericWithSIUnit(_lm_SISymType, _intSymType); + _lx_int_SISymType = createNumericWithSIUnit(_lx_SISymType, _intSymType); + _Bq_int_SISymType = createNumericWithSIUnit(_Bq_SISymType, _intSymType); + _Gy_int_SISymType = createNumericWithSIUnit(_Gy_SISymType, _intSymType); + _Sv_int_SISymType = createNumericWithSIUnit(_Sv_SISymType, _intSymType); + _kat_int_SISymType = createNumericWithSIUnit(_kat_SISymType, _intSymType); + _l_int_SISymType = createNumericWithSIUnit(_l_SISymType, _intSymType); + _L_int_SISymType = createNumericWithSIUnit(_L_SISymType, _intSymType); + _min_int_SISymType = createNumericWithSIUnit(_min_SISymType, _intSymType); + _h_int_SISymType = createNumericWithSIUnit(_h_SISymType, _intSymType); + _d_int_SISymType = createNumericWithSIUnit(_d_SISymType, _intSymType); + _ha_int_SISymType = createNumericWithSIUnit(_ha_SISymType, _intSymType); + _t_int_SISymType = createNumericWithSIUnit(_t_SISymType, _intSymType); + _au_int_SISymType = createNumericWithSIUnit(_au_SISymType, _intSymType); + _eV_int_SISymType = createNumericWithSIUnit(_eV_SISymType, _intSymType); + _Da_int_SISymType = createNumericWithSIUnit(_Da_SISymType, _intSymType); + _u_int_SISymType = createNumericWithSIUnit(_u_SISymType, _intSymType); + _celsius_int_SISymType = createNumericWithSIUnit(_celsius_SISymType, _intSymType); + _fahrenheit_int_SISymType = createNumericWithSIUnit(_fahrenheit_SISymType, _intSymType); + _Np_int_SISymType = createNumericWithSIUnit(_Np_SISymType, _intSymType); + _B_int_SISymType = createNumericWithSIUnit(_B_SISymType, _intSymType); + _dB_int_SISymType = createNumericWithSIUnit(_dB_SISymType, _intSymType); + _degSym_int_SISymType = createNumericWithSIUnit(_degSym_SISymType, _intSymType); + _deg_int_SISymType = createNumericWithSIUnit(_deg_SISymType, _intSymType); + _rad_int_SISymType = createNumericWithSIUnit(_rad_SISymType, _intSymType); + _sr_int_SISymType = createNumericWithSIUnit(_sr_SISymType, _intSymType); + } + + // Helper + + /** + * creates a java.lang scope and adds it to the global scope + */ + protected static IBasicSymbolsScope createJavaLangScope() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + IBasicSymbolsScope javaScope = inScope(gs, scope("java")); + IBasicSymbolsScope langScope = inScope(javaScope, scope("lang")); + return langScope; + } + +} diff --git a/monticore-grammar/src/testFixtures/java/de/monticore/types3/util/DefsVariablesForTests.java b/monticore-grammar/src/testFixtures/java/de/monticore/types3/util/DefsVariablesForTests.java new file mode 100644 index 0000000000..617fcd5c19 --- /dev/null +++ b/monticore-grammar/src/testFixtures/java/de/monticore/types3/util/DefsVariablesForTests.java @@ -0,0 +1,276 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.types3.util; + +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; + +import static de.monticore.types3.util.DefsTypesForTests.*; +import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; + +/** + * creates default variables for type check tests, + * structure of this class is analoge to {@link DefsTypesForTests}, + * each variable represents one type in {@link DefsTypesForTests} + * (as far as applicable, e.g., one cannot create a variable of the null-type). + * The name of the variable is "var[typeArguments][Boxed?][NameOfType]", + * e.g., vardouble, varDouble, varBoxedString, varintBoxedList; + * In case of boxed reference types (e.g., String, List), + * the "Boxed" is added before the name of tne type ("[...]BoxedList") + * In case of generics with type parameters, "int" is added after "var" + * and the type arguments are "int", e.g., "varintList, varintBoxedMap" + *

+ * This class is NOT intended to have variables for all tests, + * if specific variables are needed + * (e.g., specific generics or two variables of the same type), + * they ought to be added in the specific test. + */ +public class DefsVariablesForTests { + + /** + * initializes default variables in the scope + */ + public static void setup() { + setup(BasicSymbolsMill.globalScope()); + } + + /** + * initializes default variables in the scope + */ + public static void setup(IBasicSymbolsScope scope) { + set_thePrimitives(scope); + set_boxedPrimitives(scope); + set_unboxedObjects(scope); + set_boxedObjects(scope); + set_unboxedCollections(scope); + set_boxedCollections(scope); + set_streams(scope); + set_objectTypes(scope); + set_generics(scope); + set_siUnitsWithNumerics(scope); + } + + public static VariableSymbol _booleanVarSym; + + public static VariableSymbol _byteVarSym; + + public static VariableSymbol _charVarSym; + + public static VariableSymbol _shortVarSym; + + public static VariableSymbol _intVarSym; + + public static VariableSymbol _longVarSym; + + public static VariableSymbol _floatVarSym; + + public static VariableSymbol _doubleVarSym; + + public static void set_thePrimitives(IBasicSymbolsScope scope) { + _booleanVarSym = inScope(scope, variable("varboolean", _booleanSymType)); + _byteVarSym = inScope(scope, variable("varbyte", _byteSymType)); + _charVarSym = inScope(scope, variable("varchar", _charSymType)); + _shortVarSym = inScope(scope, variable("varshort", _shortSymType)); + _intVarSym = inScope(scope, variable("varint", _intSymType)); + _longVarSym = inScope(scope, variable("varlong", _longSymType)); + _floatVarSym = inScope(scope, variable("varfloat", _floatSymType)); + _doubleVarSym = inScope(scope, variable("vardouble", _doubleSymType)); + } + + public static VariableSymbol _BooleanVarSym; + + public static VariableSymbol _ByteVarSym; + + public static VariableSymbol _CharacterVarSym; + + public static VariableSymbol _ShortVarSym; + + public static VariableSymbol _IntegerVarSym; + + public static VariableSymbol _LongVarSym; + + public static VariableSymbol _FloatVarSym; + + public static VariableSymbol _DoubleVarSym; + + public static void set_boxedPrimitives(IBasicSymbolsScope scope) { + _BooleanVarSym = inScope(scope, variable("varBoolean", _BooleanSymType)); + _ByteVarSym = inScope(scope, variable("varByte", _ByteSymType)); + _CharacterVarSym = inScope(scope, variable("varCharacter", _CharacterSymType)); + _ShortVarSym = inScope(scope, variable("varShort", _ShortSymType)); + _IntegerVarSym = inScope(scope, variable("varInteger", _IntegerSymType)); + _LongVarSym = inScope(scope, variable("varLong", _LongSymType)); + _FloatVarSym = inScope(scope, variable("varFloat", _FloatSymType)); + _DoubleVarSym = inScope(scope, variable("varDouble", _DoubleSymType)); + } + + public static VariableSymbol _unboxedStringVarSym; + + public static void set_unboxedObjects(IBasicSymbolsScope scope) { + _unboxedStringVarSym = inScope(scope, variable("varString", _unboxedString)); + } + + public static VariableSymbol _boxedStringVarSym; + + public static void set_boxedObjects(IBasicSymbolsScope scope) { + _boxedStringVarSym = inScope(scope, variable("varBoxedString", _boxedString)); + } + + /* + * These are the predefined Symbol for unboxed Collections like "List" + */ + + public static VariableSymbol _intUnboxedOptionalVarSym; + + public static VariableSymbol _intUnboxedSetVarSym; + + public static VariableSymbol _intUnboxedListVarSym; + + public static VariableSymbol _intUnboxedMapVarSym; + + public static void set_unboxedCollections(IBasicSymbolsScope scope) { + _intUnboxedOptionalVarSym = inScope(scope, variable("varintOptional", + createGenerics(_unboxedOptionalSymType.getTypeInfo(), _intSymType))); + _intUnboxedSetVarSym = inScope(scope, variable("varintSet", + createGenerics(_unboxedSetSymType.getTypeInfo(), _intSymType))); + _intUnboxedListVarSym = inScope(scope, variable("varintList", + createGenerics(_unboxedListSymType.getTypeInfo(), _intSymType))); + _intUnboxedMapVarSym = inScope(scope, variable("varintMap", + createGenerics(_unboxedMapSymType.getTypeInfo(), _intSymType, _intSymType))); + } + + /* + * These are the predefined Symbol for unboxed Collections like "List" + */ + + public static VariableSymbol _boxedOptionalVarSym; + + public static VariableSymbol _boxedSetVarSym; + + public static VariableSymbol _boxedListVarSym; + + public static VariableSymbol _boxedMapVarSym; + + public static void set_boxedCollections(IBasicSymbolsScope scope) { + _boxedOptionalVarSym = inScope(scope, variable("varintBoxedOptional", + createGenerics(_boxedOptionalSymType.getTypeInfo(), _intSymType))); + _boxedSetVarSym = inScope(scope, variable("varintBoxedSet", + createGenerics(_boxedSetSymType.getTypeInfo(), _intSymType))); + _boxedListVarSym = inScope(scope, variable("varintBoxedList", + createGenerics(_boxedListSymType.getTypeInfo(), _intSymType))); + _boxedMapVarSym = inScope(scope, variable("varintBoxedMap", + createGenerics(_boxedMapSymType.getTypeInfo(), _intSymType, _intSymType))); + } + + /* + * These are the predefined Symbols for the Streams + */ + + public static VariableSymbol _intStreamVarSym; + + public static VariableSymbol _intEventStreamVarSym; + + public static VariableSymbol _intSyncStreamVarSym; + + public static VariableSymbol _intToptStreamVarSym; + + public static VariableSymbol _intUntimedStreamVarSym; + + public static void set_streams(IBasicSymbolsScope scope) { + _intStreamVarSym = inScope(scope, variable("varintStream", + createGenerics(_StreamSymType.getTypeInfo(), _intSymType))); + _intEventStreamVarSym = inScope(scope, variable("varintEventStream", + createGenerics(_EventStreamSymType.getTypeInfo(), _intSymType))); + _intSyncStreamVarSym = inScope(scope, variable("varintSyncStream", + createGenerics(_SyncStreamSymType.getTypeInfo(), _intSymType))); + _intToptStreamVarSym = inScope(scope, variable("varintToptStream", + createGenerics(_ToptStreamSymType.getTypeInfo(), _intSymType))); + _intUntimedStreamVarSym = inScope(scope, variable("varintUntimedStream", + createGenerics(_UntimedStreamSymType.getTypeInfo(), _intSymType))); + } + + /* + * These are some predefined Symbols for Object Types + */ + + public static VariableSymbol _personVarSym; + + public static VariableSymbol _teachableVarSym; + + public static VariableSymbol _studentVarSym; + + public static VariableSymbol _csStudentVarSym; + + public static VariableSymbol _firstSemesterCsStudentVarSym; + + public static VariableSymbol _childVarSym; + + public static VariableSymbol _teacherVarSym; + + public static VariableSymbol _carVarSym; + + public static VariableSymbol _schoolVarSym; + + public static void set_objectTypes(IBasicSymbolsScope scope) { + _personVarSym = inScope(scope, variable("varPerson", + createTypeObject(_personSymType.getTypeInfo()))); + _teachableVarSym = inScope(scope, variable("varTeachable", + createTypeObject(_teachableSymType.getTypeInfo()))); + _studentVarSym = inScope(scope, variable("varStudent", + createTypeObject(_studentSymType.getTypeInfo()))); + _csStudentVarSym = inScope(scope, variable("varCsStudent", + createTypeObject(_csStudentSymType.getTypeInfo()))); + _firstSemesterCsStudentVarSym = inScope(scope, variable("varFirstSemesterCsStudent", + createTypeObject(_firstSemesterCsStudentSymType.getTypeInfo()))); + _childVarSym = inScope(scope, variable("varChild", + createTypeObject(_childSymType.getTypeInfo()))); + _teacherVarSym = inScope(scope, variable("varTeacher", + createTypeObject(_teacherSymType.getTypeInfo()))); + _carVarSym = inScope(scope, variable("varCar", + createTypeObject(_carSymType.getTypeInfo()))); + _schoolVarSym = inScope(scope, variable("varSchool", + createTypeObject(_schoolSymType.getTypeInfo()))); + } + + /* + * These are the predefined Symbols for further generics + * in most cases, the collections ought to be enough + */ + + public static VariableSymbol _intLinkedListVarSym; + + public static VariableSymbol _intHashMapVarSym; + + public static void set_generics(IBasicSymbolsScope scope) { + _intLinkedListVarSym = inScope(scope, variable("varintLinkedList", + createGenerics(_linkedListSymType.getTypeInfo(), _intSymType))); + _intHashMapVarSym = inScope(scope, variable("varintHashMap", + createGenerics(_hashMapSymType.getTypeInfo(), _intSymType, _intSymType))); + } + + /* + * These are some predefined Symbols for SI units with numerics + */ + + // The seven base units (kg with and without prefix k) + public static VariableSymbol _s_int_SIVarSym; + public static VariableSymbol _m_int_SIVarSym; + public static VariableSymbol _g_int_SIVarSym; + public static VariableSymbol _A_int_SIVarSym; + public static VariableSymbol _K_int_SIVarSym; + public static VariableSymbol _mol_int_SIVarSym; + public static VariableSymbol _cd_int_SIVarSym; + public static VariableSymbol _kg_int_SIVarSym; + + public static void set_siUnitsWithNumerics(IBasicSymbolsScope scope) { + _s_int_SIVarSym = inScope(scope, variable("varintSecond", _s_int_SISymType)); + _m_int_SIVarSym = inScope(scope, variable("varintMetre", _m_int_SISymType)); + _g_int_SIVarSym = inScope(scope, variable("varintGram", _g_int_SISymType)); + _A_int_SIVarSym = inScope(scope, variable("varintAmpere", _A_int_SISymType)); + _K_int_SIVarSym = inScope(scope, variable("varintKelvin", _K_int_SISymType)); + _mol_int_SIVarSym = inScope(scope, variable("varintMole", _mol_int_SISymType)); + _cd_int_SIVarSym = inScope(scope, variable("varintCandela", _cd_int_SISymType)); + _kg_int_SIVarSym = inScope(scope, variable("varintKiloGram", _kg_int_SISymType)); + } +} diff --git a/monticore-libraries/stream-symbols-it/build.gradle b/monticore-libraries/stream-symbols-it/build.gradle index c529c535d7..a5adb3f4f1 100644 --- a/monticore-libraries/stream-symbols-it/build.gradle +++ b/monticore-libraries/stream-symbols-it/build.gradle @@ -14,8 +14,8 @@ dependencies { testImplementation 'de.se_rwth.commons:se-commons-logging:' + se_commons_version testImplementation 'de.se_rwth.commons:se-commons-utilities:' + se_commons_version testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" } test { diff --git a/monticore-libraries/stream-symbols-it/src/test/java/de/monticore/symbols/library/StreamTypeTest.java b/monticore-libraries/stream-symbols-it/src/test/java/de/monticore/symbols/library/StreamTypeTest.java index 957bcea0be..7c961efdbb 100644 --- a/monticore-libraries/stream-symbols-it/src/test/java/de/monticore/symbols/library/StreamTypeTest.java +++ b/monticore-libraries/stream-symbols-it/src/test/java/de/monticore/symbols/library/StreamTypeTest.java @@ -13,7 +13,6 @@ import de.monticore.types3.util.WithinScopeBasicSymbolsResolver; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -25,6 +24,8 @@ import java.util.Optional; import java.util.jar.JarFile; +import static org.junit.jupiter.api.Assertions.*; + public class StreamTypeTest { @BeforeEach @@ -38,9 +39,9 @@ public void init() throws IOException { // workaround to get library path working (in emf) URL streamURL = StreamTypeTest.class.getClassLoader().getResource("Stream.symtabdefinitionsym"); - Assertions.assertNotNull(streamURL); + assertNotNull(streamURL); // need to be expanded if ever false (could be a folder?) - Assertions.assertEquals("jar", streamURL.getProtocol()); + assertEquals("jar", streamURL.getProtocol()); JarURLConnection urlConnection = (JarURLConnection) streamURL.openConnection(); JarFile jar = urlConnection.getJarFile(); Path jarPath = Path.of(jar.getName()); @@ -55,31 +56,40 @@ public void init() throws IOException { public void resolveStreamType() { Optional streamOpt = OOSymbolsMill.globalScope() .resolveType("Stream"); - Assertions.assertTrue(streamOpt.isPresent()); + assertTrue(streamOpt.isPresent()); TypeSymbol stream = streamOpt.get(); - Assertions.assertNotNull(stream.getSpannedScope()); - Assertions.assertEquals(1, stream.getSpannedScope().getTypeVarSymbols().size()); - Assertions.assertEquals(0, Log.getErrorCount()); + assertNotNull(stream.getSpannedScope()); + assertEquals(1, stream.getSpannedScope().getTypeVarSymbols().size()); + assertEquals(0, Log.getErrorCount()); } @Test public void resolveStaticRepeat() { MethodSymbol method = getMethodSymbol("Stream.repeat"); - Assertions.assertEquals(2, method.getParameterList().size()); + assertEquals(2, method.getParameterList().size()); assertIsStreamWithTypeVar(method.getType()); - Assertions.assertTrue(method.isIsStatic()); + assertTrue(method.isIsStatic()); List typeVars = method.getSpannedScope().getLocalTypeVarSymbols(); - Assertions.assertEquals(1, typeVars.size()); - Assertions.assertNotEquals(typeVars.get(0).getName(), "T"); + assertEquals(1, typeVars.size()); + assertNotEquals("T", typeVars.get(0).getName()); } @Test public void resolveStreamMethodLen() { MethodSymbol method = getMethodSymbol("Stream.len"); - Assertions.assertEquals(0, method.getParameterList().size()); - Assertions.assertTrue(method.getEnclosingScope().getSpanningSymbol() instanceof TypeSymbol); - Assertions.assertEquals("Stream", method.getEnclosingScope().getSpanningSymbol().getName()); - Assertions.assertEquals(BasicSymbolsMill.LONG, method.getType().getTypeInfo().getName()); + assertEquals(0, method.getParameterList().size()); + assertInstanceOf(TypeSymbol.class, method.getEnclosingScope().getSpanningSymbol()); + assertEquals("Stream", method.getEnclosingScope().getSpanningSymbol().getName()); + assertEquals(BasicSymbolsMill.LONG, method.getType().getTypeInfo().getName()); + } + + @Test + public void resolveStreamMethodIsEmpty() { + MethodSymbol method = getMethodSymbol("Stream.isEmpty"); + assertEquals(0, method.getParameterList().size()); + assertInstanceOf(TypeSymbol.class, method.getEnclosingScope().getSpanningSymbol()); + assertEquals("Stream", method.getEnclosingScope().getSpanningSymbol().getName()); + assertEquals(BasicSymbolsMill.BOOLEAN, method.getType().getTypeInfo().getName()); } @Test @@ -103,6 +113,7 @@ protected void resolveStaticMethods(String streamType) { } protected void resolveCommonMemberMethods(String streamType) { + testResolveMethod(streamType + ".isEmpty"); testResolveMethod(streamType + ".len"); testResolveMethod(streamType + ".first"); testResolveMethod(streamType + ".dropFirst"); @@ -135,17 +146,17 @@ public void isTypeVarResolvableFromReturn() { } protected void assertIsStreamWithTypeVar(SymTypeExpression type) { - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isGenericType()); - Assertions.assertEquals("Stream", type.getTypeInfo().getName()); - Assertions.assertEquals(1, ((SymTypeOfGenerics) type).getArgumentList().size()); - Assertions.assertTrue(((SymTypeOfGenerics) type).getArgument(0).isTypeVariable()); + assertNotNull(type); + assertTrue(type.isGenericType()); + assertEquals("Stream", type.getTypeInfo().getName()); + assertEquals(1, ((SymTypeOfGenerics) type).getArgumentList().size()); + assertTrue(((SymTypeOfGenerics) type).getArgument(0).isTypeVariable()); } protected void testResolveMethod(String name) { Optional methodType = WithinScopeBasicSymbolsResolver.resolveNameAsExpr(BasicSymbolsMill.globalScope(), name); - Assertions.assertTrue(methodType.isPresent(), name); - Assertions.assertTrue(methodType.get().isFunctionType() + assertTrue(methodType.isPresent(), name); + assertTrue(methodType.get().isFunctionType() || methodType.get().isIntersectionType() ); } diff --git a/monticore-libraries/stream-symbols/build.gradle b/monticore-libraries/stream-symbols/build.gradle index f730fbb39d..fbca4c40ec 100644 --- a/monticore-libraries/stream-symbols/build.gradle +++ b/monticore-libraries/stream-symbols/build.gradle @@ -1,6 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ plugins { - id "de.rwth.se.symtabdefinition" version "$version" + id "de.rwth.se.symtabdefinition" version "$previous_mc_version" + // use previous_mc_version to avoid bootstrapping issue } description = 'MontiCore: Stream Symbols' diff --git a/monticore-libraries/stream-symbols/src/main/symtabdefinition/EventStream.symtabdefinition b/monticore-libraries/stream-symbols/src/main/symtabdefinition/EventStream.symtabdefinition index cc27f21d17..0bd57a0892 100644 --- a/monticore-libraries/stream-symbols/src/main/symtabdefinition/EventStream.symtabdefinition +++ b/monticore-libraries/stream-symbols/src/main/symtabdefinition/EventStream.symtabdefinition @@ -15,7 +15,7 @@ symtabdefinition EventStream { + static EventStream eProjSnd(UntimedStream<(S,U)> list); // ----------- Implementations - + Optional> dropFirst(); + + EventStream dropFirst(); + EventStream take(long n); + EventStream dropMultiple(long n); + EventStream times(long n); // <2>.times(24) diff --git a/monticore-libraries/stream-symbols/src/main/symtabdefinition/Stream.symtabdefinition b/monticore-libraries/stream-symbols/src/main/symtabdefinition/Stream.symtabdefinition index 7b04803446..94d5844b9f 100644 --- a/monticore-libraries/stream-symbols/src/main/symtabdefinition/Stream.symtabdefinition +++ b/monticore-libraries/stream-symbols/src/main/symtabdefinition/Stream.symtabdefinition @@ -3,13 +3,14 @@ symtabdefinition Stream { interface Stream { + long len(); + boolean hasInfiniteLen(); + + boolean isEmpty(); + static Stream repeat(S elem, long n); + static Stream iterate(S -> S elem, S elem); + static Stream projFst(Stream<(S,U)> list); // kann man static umgehen? + static Stream projSnd(Stream<(S,U)> list); - + Optional> dropFirst(); + + Stream dropFirst(); + Stream take(long n); + Stream dropMultiple(long n); diff --git a/monticore-libraries/stream-symbols/src/main/symtabdefinition/SyncStream.symtabdefinition b/monticore-libraries/stream-symbols/src/main/symtabdefinition/SyncStream.symtabdefinition index fb481b8ca8..2527acb55e 100644 --- a/monticore-libraries/stream-symbols/src/main/symtabdefinition/SyncStream.symtabdefinition +++ b/monticore-libraries/stream-symbols/src/main/symtabdefinition/SyncStream.symtabdefinition @@ -6,8 +6,8 @@ import UntimedStream; symtabdefinition SyncStream { class SyncStream implements Stream { - + Optional first(); - + Optional nth(long n); // nicht konform mit TechReport, ist aber sinnvoller + + T first(); + + T nth(long n); + static SyncStream syncRepeat(S elem, long n); + static SyncStream syncIterate(S -> S elem, S elem); @@ -15,7 +15,7 @@ symtabdefinition SyncStream { + static SyncStream syncProjSnd(SyncStream<(S,U)> list); // ----------- Implementations - + Optional> dropFirst(); + + SyncStream dropFirst(); + SyncStream take(long n); + SyncStream dropMultiple(long n); + SyncStream times(long n); // <2>.times(24) diff --git a/monticore-libraries/stream-symbols/src/main/symtabdefinition/ToptStream.symtabdefinition b/monticore-libraries/stream-symbols/src/main/symtabdefinition/ToptStream.symtabdefinition index 15b4e8b1e7..f153e715a3 100644 --- a/monticore-libraries/stream-symbols/src/main/symtabdefinition/ToptStream.symtabdefinition +++ b/monticore-libraries/stream-symbols/src/main/symtabdefinition/ToptStream.symtabdefinition @@ -7,7 +7,7 @@ symtabdefinition ToptStream { class ToptStream implements Stream { + Optional first(); - + Optional nth(long n); // nicht konform mit TechReport, ist aber sinnvoller + + Optional nth(long n); + static ToptStream toptRepeat(S elem, long n); + static ToptStream toptIterate(S -> S elem, S elem); @@ -15,7 +15,7 @@ symtabdefinition ToptStream { + static ToptStream toptProjSnd(ToptStream<(S,U)> list); // ----------- Implementations - + Optional> dropFirst(); + + ToptStream dropFirst(); + ToptStream take(long n); + ToptStream dropMultiple(long n); + ToptStream times(long n); // <2>.times(24) diff --git a/monticore-libraries/stream-symbols/src/main/symtabdefinition/UntimedStream.symtabdefinition b/monticore-libraries/stream-symbols/src/main/symtabdefinition/UntimedStream.symtabdefinition index 356f380d3c..02e70ee857 100644 --- a/monticore-libraries/stream-symbols/src/main/symtabdefinition/UntimedStream.symtabdefinition +++ b/monticore-libraries/stream-symbols/src/main/symtabdefinition/UntimedStream.symtabdefinition @@ -3,8 +3,8 @@ import Stream; symtabdefinition UntimedStream { class UntimedStream implements Stream { - + Optional first(); - + Optional nth(long n); + + T first(); + + T nth(long n); + static UntimedStream uRepeat(S elem, long n); + static UntimedStream uIterate(S -> S elem, S elem); @@ -12,7 +12,7 @@ symtabdefinition UntimedStream { + static UntimedStream uProjSnd(UntimedStream<(S,U)> list); // ----------- Implementations - + Optional> dropFirst(); + + UntimedStream dropFirst(); + UntimedStream take(long n); + UntimedStream dropMultiple(long n); + UntimedStream times(long n); // <2>.times(24) diff --git a/monticore-runtime-emf/build.gradle b/monticore-runtime-emf/build.gradle index 1fa7b86f23..1d66d1b0e2 100644 --- a/monticore-runtime-emf/build.gradle +++ b/monticore-runtime-emf/build.gradle @@ -10,15 +10,15 @@ dependencies { implementation 'org.eclipse.emf:org.eclipse.emf.compare.match:' + emf_compare_version implementation 'org.eclipse.emf:org.eclipse.emf.compare.diff:' + emf_compare_version testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" testImplementation 'org.apache.groovy:groovy:4.0.2' } description = 'MontiCore: EMF Runtime Environment' task testsJar(type: Jar) { - classifier = 'tests' + archiveClassifier = 'tests' from(sourceSets.test.output) } diff --git a/monticore-runtime-emf/src/main/java/de/monticore/emf/util/AST2ModelFiles.java b/monticore-runtime-emf/src/main/java/de/monticore/emf/util/AST2ModelFiles.java index 5080faefbc..0a57fce30a 100644 --- a/monticore-runtime-emf/src/main/java/de/monticore/emf/util/AST2ModelFiles.java +++ b/monticore-runtime-emf/src/main/java/de/monticore/emf/util/AST2ModelFiles.java @@ -5,7 +5,7 @@ import java.io.File; import java.io.IOException; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; @@ -70,7 +70,7 @@ public void serializeASTInstance(ASTENode astNode, String modelName, String inst // Add instance of package to the contents. resource.getContents().add(astNode); // Save the contents of the resource to the file system. - Map options = new HashMap<>(); + Map options = new LinkedHashMap<>(); options.put(XMLResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE); try { resource.save(options); diff --git a/monticore-runtime/build.gradle b/monticore-runtime/build.gradle index 2e72ce5441..b4ccbac6aa 100644 --- a/monticore-runtime/build.gradle +++ b/monticore-runtime/build.gradle @@ -1,6 +1,22 @@ /* (c) https://github.com/MontiCore/monticore */ plugins { id "jacoco" + // this project provides test fixtures. Test fixtures are commonly used to setup the code under test, + // or provide utilities aimed at facilitating the tests of a component + id 'java-test-fixtures' +} + +sourceSets { + test { + resources { + srcDirs += "src/test/java" + includes = ["**/*.ftl"] + } + } + tests.java{ + srcDirs += "$projectDir/src/test/java" + includes = ["**/Assert.java"] + } } configurations { @@ -16,31 +32,98 @@ dependencies { implementation 'de.se_rwth.commons:se-commons-utilities:' + se_commons_version implementation "org.freemarker:freemarker:$freemarker_version" implementation group: 'org.apache.commons', name: 'commons-text', version: '1.10.0' + + testFixturesImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" } -sourceSets { - test { - resources { - srcDirs += "src/test/java" - includes = ["**/*.ftl"] - } - } - tests.java{ - srcDirs += "$projectDir/src/test/java" - includes = ["**/Assert.java"] - } +test { + useJUnitPlatform() } + + description = 'MontiCore: Runtime' java { registerFeature('tests') { usingSourceSet(sourceSets.tests) } + withJavadocJar() +} + +tasks.named("jar") { + dependsOn testsJar +} + +// Workaround for https://github.com/gradle/gradle/issues/20539 +import org.gradle.api.plugins.internal.JvmPluginsHelper +import org.gradle.api.internal.file.FileResolver +import org.gradle.internal.component.external.model.ProjectDerivedCapability +import org.gradle.internal.component.external.model.TestFixturesSupport + +if(GradleVersion.current() < GradleVersion.version("8.5")){ + pluginManager.withPlugin("java-test-fixtures") { + def sourceSet = sourceSets["testFixtures"] + JvmPluginsHelper.configureDocumentationVariantWithArtifact( + sourceSet.sourcesElementsConfigurationName, + TestFixturesSupport.TEST_FIXTURE_SOURCESET_NAME, + DocsType.SOURCES, + [new ProjectDerivedCapability(project, "testFixtures")], + sourceSet.sourcesJarTaskName, + sourceSet.allSource, + components["java"] as AdhocComponentWithVariants, + configurations, + tasks, + objects, + project.services.get(FileResolver) + ) + JvmPluginsHelper.configureDocumentationVariantWithArtifact( + sourceSet.javadocElementsConfigurationName, + TestFixturesSupport.TEST_FIXTURE_SOURCESET_NAME, + DocsType.JAVADOC, + [new ProjectDerivedCapability(project, "testFixtures")], + sourceSet.javadocJarTaskName, + tasks.named(sourceSet.javadocTaskName), + components["java"] as AdhocComponentWithVariants, + configurations, + tasks, + objects, + project.services.get(FileResolver) + ) + } +} else { + pluginManager.withPlugin("java-test-fixtures") { + def sourceSet = sourceSets["testFixtures"] + def caps = [new ProjectDerivedCapability(project, "testFixtures")]; + if (GradleVersion.current() != GradleVersion.version("8.5")) + caps = caps.toSet() + JvmPluginsHelper.createDocumentationVariantWithArtifact( + sourceSet.sourcesElementsConfigurationName, + TestFixturesSupport.TEST_FIXTURE_SOURCESET_NAME, + DocsType.SOURCES, + caps, + sourceSet.sourcesJarTaskName, + sourceSet.allSource, + project + ) + JvmPluginsHelper.createDocumentationVariantWithArtifact( + sourceSet.javadocElementsConfigurationName, + TestFixturesSupport.TEST_FIXTURE_SOURCESET_NAME, + DocsType.JAVADOC, + caps, + sourceSet.javadocJarTaskName, + tasks.named(sourceSet.javadocTaskName), + project + ) + } } +//End Workaround -jar.dependsOn testsJar +tasks.named("build") { + dependsOn javadoc, testFixturesJavadoc +} \ No newline at end of file diff --git a/monticore-runtime/src/main/java/de/monticore/antlr4/MCBuildVisitor.java b/monticore-runtime/src/main/java/de/monticore/antlr4/MCBuildVisitor.java index 553ef60ba5..45b1580670 100644 --- a/monticore-runtime/src/main/java/de/monticore/antlr4/MCBuildVisitor.java +++ b/monticore-runtime/src/main/java/de/monticore/antlr4/MCBuildVisitor.java @@ -174,7 +174,7 @@ public void addFinalComments(ASTNode node, ParserRuleContext ctx) { * Find all (not yet found) hidden/comment tokens * and calls the consumer for each * - * @param addConsumer + * @param addConsumer e.g. {@link ASTNode#add_PreComment(Comment)} * @param start {@link IntervalSet#complement(int, int)} * @param stop {@link IntervalSet#complement(int, int)} */ diff --git a/monticore-runtime/src/main/java/de/monticore/antlr4/MCConcreteParser.java b/monticore-runtime/src/main/java/de/monticore/antlr4/MCConcreteParser.java index cd0af32a7c..312bee61b1 100644 --- a/monticore-runtime/src/main/java/de/monticore/antlr4/MCConcreteParser.java +++ b/monticore-runtime/src/main/java/de/monticore/antlr4/MCConcreteParser.java @@ -46,9 +46,9 @@ public MCConcreteParser() { public abstract Optional parse(Reader reader) throws IOException; /** - * Returns true, if errors occured while parsing + * Returns true, if errors occurred while parsing * - * @return + * @return whether we have errors */ public boolean hasErrors() { return hasErrors; diff --git a/monticore-runtime/src/main/java/de/monticore/antlr4/MCErrorListener.java b/monticore-runtime/src/main/java/de/monticore/antlr4/MCErrorListener.java index 676a962f5f..ebaa164892 100644 --- a/monticore-runtime/src/main/java/de/monticore/antlr4/MCErrorListener.java +++ b/monticore-runtime/src/main/java/de/monticore/antlr4/MCErrorListener.java @@ -58,8 +58,8 @@ && containsRule(((Parser) recognizer).getExpectedTokens(), recognizer.getVocabul // (*): The name might actually be a nokeyword production, i.e., with a semantic predicate // Check for the rules which the ATN would change into using epsilon transitions (to find nokeywor rules) - Set> epsilonRules = new HashSet<>(); - getExpectedRulesWithTokens(recognizer.getATN(), recognizer.getState(), recognizer.getVocabulary(), new HashMap<>(), epsilonRules); + Set> epsilonRules = new LinkedHashSet<>(); + getExpectedRulesWithTokens(recognizer.getATN(), recognizer.getState(), recognizer.getVocabulary(), new LinkedHashMap<>(), epsilonRules); List noKeywordRules = extractNoKeywordTokens(recognizer, epsilonRules); @@ -91,8 +91,8 @@ && containsRule(((Parser) recognizer).getExpectedTokens(), recognizer.getVocabul String expectedTokens = e.getExpectedTokens().toString(recognizer.getVocabulary()); // Check for the rules which the ATN would change into using epsilon transitions - Set> epsilonRules = new HashSet<>(); - getExpectedRulesWithTokens(recognizer.getATN(), e.getOffendingState(), recognizer.getVocabulary(), new HashMap<>(), epsilonRules); + Set> epsilonRules = new LinkedHashSet<>(); + getExpectedRulesWithTokens(recognizer.getATN(), e.getOffendingState(), recognizer.getVocabulary(), new LinkedHashMap<>(), epsilonRules); List noKeywordRules = extractNoKeywordTokens(recognizer, epsilonRules); @@ -128,7 +128,7 @@ && containsRule(((Parser) recognizer).getExpectedTokens(), recognizer.getVocabul parser.setErrors(true); } - private static List extractNoKeywordTokens(Recognizer recognizer, Set> epsilonRules) { + protected static List extractNoKeywordTokens(Recognizer recognizer, Set> epsilonRules) { Pattern nokeywordPattern = Pattern.compile("nokeyword_(.*)_[0-9]*"); // Turn the next expected rules into a human readable format: List noKeywordRules = epsilonRules.stream().map(r -> { @@ -192,7 +192,11 @@ protected String getOffendingLine(String entireInput, int tokenIndex) { /** * Similiar to {@link ATN#getExpectedTokens(int, RuleContext)}, * but we also return the rule numbers - * @param expected a set of ruleIndex -> expected token(s) entries + * @param atn the atn + * @param stateNumber the current state + * @param vocabulary {@link Vocabulary} + * @param visitedStates the already visited states + * @param expected a set of ruleIndex -to- expected token(s) entries * @return whether an empty input is accepted */ public boolean getExpectedRulesWithTokens(ATN atn, int stateNumber, Vocabulary vocabulary, Map visitedStates, Set> expected) { diff --git a/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java b/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java index 01229d32a6..263fd730d4 100644 --- a/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java +++ b/monticore-runtime/src/main/java/de/monticore/ast/ASTNode.java @@ -41,8 +41,7 @@ default public boolean equalsWithComments(Object o) { /** * Compare this object to another Object. Do not take comments into account. This method returns - * the same value as deepEquals(Object o, boolean - * forceSameOrder) method when using the default value for forceSameOrder of each Node. + * the same value as {@link ASTNode#deepEquals(Object, boolean)} method when using the default value for forceSameOrder of each Node. */ default public boolean deepEquals(Object o) { if (o == null) { @@ -57,7 +56,7 @@ default public boolean deepEquals(Object o) { * Compare this object to another Object. Take comments into account. * * @param o the object to compare this node to - * stereotype <<unordered>> in the grammar. + * @return whether both objects deep-equal with comments */ default public boolean deepEqualsWithComments(Object o) { throw new CompareNotSupportedException( @@ -70,7 +69,8 @@ default public boolean deepEqualsWithComments(Object o) { * * @param o the object to compare this node to * @param forceSameOrder consider the order in ancestor lists, even if these lists are of - * stereotype <<unordered>> in the grammar. + * stereotype unordered in the grammar. + * @return whether both objects deep-equal */ default public boolean deepEquals(Object o, boolean forceSameOrder) { if (o == null) { @@ -83,7 +83,7 @@ default public boolean deepEquals(Object o, boolean forceSameOrder) { /** * Compare this object to another Object. Take comments into account. This method returns the same - * value as deepEqualsWithComment(Object o, boolean forceSameOrder) method when using the + * value as {@link ASTNode#deepEqualsWithComments(Object, boolean)} method when using the * default value for forceSameOrder of each Node. */ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) { @@ -200,7 +200,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) /** * Returns the Iterator for the preComment list * - * @return Iterator to iterate over the preComment list + * @return Iterator of comments to iterate over the preComment list */ Iterator iterator_PreComments(); @@ -254,21 +254,21 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) /** * Returns the Spliterator of the preComment list * - * @return Spliterator of the preComment list + * @return Spliterator of the preComment list */ Spliterator spliterator_PreComments(); /** * Returns the Steam of the preComment list * - * @return Steam of the preComment list + * @return Steam of the preComment list */ Stream stream_PreComments(); /** * Returns the parallel Steam of the preComment list * - * @return Steam parallel Stream of the preComment list + * @return parallel Stream of the preComment list */ Stream parallelStream_PreComments(); @@ -338,7 +338,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) /** * Returns the ListIterator of the preComment list * - * @return ListIterator which iterates over the list of preComments + * @return ListIterator which iterates over the list of preComments */ ListIterator listIterator_PreComments(); @@ -346,7 +346,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) * Returns the new preComment list without the removed element at the given index * * @param index where the element should be removed - * @return List where the comment at the index is removed + * @return the Comment previously at the specified position */ Comment remove_PreComment(int index); @@ -355,7 +355,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) * * @param start index of the sublist * @param end index of the sublist - * @return ListIterator which iterates over the list of preComments + * @return ListIterator which iterates over the list of preComments */ List subList_PreComments(int start, int end); @@ -384,7 +384,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) /** * returns the complete preComments list * - * @return List that is contained in the preComment list at the moment + * @return List that is contained in the preComment list at the moment */ List get_PreCommentList(); @@ -392,7 +392,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) * returns a ListIterator of the type Comment for the preComment list * * @param index of the iterator - * @return ListIterator of a special index + * @return ListIterator of a special index */ ListIterator listIterator_PreComments(int index); @@ -463,7 +463,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) /** * Returns the Iterator for the postComment list * - * @return Iterator to iterate over the postComment list + * @return Iterator to iterate over the postComment list */ Iterator iterator_PostComments(); @@ -517,21 +517,21 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) /** * Returns the Spliterator of the postComment list * - * @return Spliterator of the postComment list + * @return Spliterator of the postComment list */ Spliterator spliterator_PostComments(); /** * Returns the Steam of the postComment list * - * @return Steam of the postComment list + * @return Steam of the postComment list */ Stream stream_PostComments(); /** * Returns the parallel Steam of the postComment list * - * @return Steam parallel Stream of the postComment list + * @return Steam parallel Stream of the postComment list */ Stream parallelStream_PostComments(); @@ -601,7 +601,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) /** * Returns the ListIterator of the postComment list * - * @return ListIterator which iterates over the list of postComments + * @return ListIterator which iterates over the list of postComments */ ListIterator listIterator_PostComments(); @@ -609,7 +609,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) * Returns the new postComment list without the removed element at the given index * * @param index where the element should be removed - * @return List where the comment at the index is removed + * @return List where the comment at the index is removed */ Comment remove_PostComment(int index); @@ -618,7 +618,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) * * @param start index of the sublist * @param end index of the sublist - * @return ListIterator which iterates over the list of postComments + * @return ListIterator which iterates over the list of postComments */ List subList_PostComments(int start, int end); @@ -647,7 +647,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) /** * returns the complete postComments list * - * @return List that is contained in the postComment list at the moment + * @return List that is contained in the postComment list at the moment */ List get_PostCommentList(); @@ -655,7 +655,7 @@ default public boolean deepEqualsWithComments(Object o, boolean forceSameOrder) * returns a ListIterator of the type Comment for the postComment list * * @param index of the iterator - * @return ListIterator of a special index + * @return ListIterator of a special index */ ListIterator listIterator_PostComments(int index); diff --git a/monticore-runtime/src/main/java/de/monticore/generating/GeneratorEngine.java b/monticore-runtime/src/main/java/de/monticore/generating/GeneratorEngine.java index ec1dda47e6..8791afac1d 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/GeneratorEngine.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/GeneratorEngine.java @@ -13,6 +13,7 @@ import java.util.Arrays; import java.util.Optional; +import com.google.common.base.Preconditions; import de.monticore.ast.ASTCNode; import de.monticore.ast.ASTNode; import de.monticore.generating.templateengine.TemplateController; @@ -39,7 +40,7 @@ public class GeneratorEngine { protected GeneratorSetup setup; public GeneratorEngine(GeneratorSetup gs) { - Log.errorIfNull(gs); + Preconditions.checkNotNull(gs); this.setup = gs; } @@ -56,9 +57,9 @@ public GeneratorEngine(GeneratorSetup gs) { */ public void generate(String templateName, Path filePath, ASTNode node, Object... templateArguments) { - Log.errorIfNull(node); + Preconditions.checkNotNull(node); checkArgument(!isNullOrEmpty(templateName)); - Log.errorIfNull(filePath); + Preconditions.checkNotNull(filePath); TemplateController tc = setup.getNewTemplateController(templateName); tc.writeArgs(templateName, filePath, node, Arrays.asList(templateArguments)); @@ -76,7 +77,7 @@ public void generate(String templateName, Path filePath, */ public void generateNoA(String templateName, Path filePath, Object... templateArguments) { checkArgument(!isNullOrEmpty(templateName)); - Log.errorIfNull(filePath); + Preconditions.checkNotNull(filePath); TemplateController tc = setup.getNewTemplateController(templateName); ASTCNode dummyAST = new ASTCNode(){ @@ -106,9 +107,9 @@ public void generateNoA(String templateName, Path filePath, Object... templateAr */ public void generate(String templateName, Writer writer, ASTNode node, Object... templateArguments) { - Log.errorIfNull(node); + Preconditions.checkNotNull(node); checkArgument(!isNullOrEmpty(templateName)); - Log.errorIfNull(writer); + Preconditions.checkNotNull(writer); TemplateController tc = setup.getNewTemplateController(templateName); StringBuilder sb = tc.includeArgs(templateName, node, Arrays.asList(templateArguments)); @@ -132,7 +133,7 @@ public void generate(String templateName, Writer writer, */ public void generateNoA(String templateName, Writer writer, Object... templateArguments) { checkArgument(!isNullOrEmpty(templateName)); - Log.errorIfNull(writer); + Preconditions.checkNotNull(writer); TemplateController tc = setup.getNewTemplateController(templateName); StringBuilder sb = tc.includeArgs(templateName, Arrays.asList(templateArguments)); diff --git a/monticore-runtime/src/main/java/de/monticore/generating/GeneratorSetup.java b/monticore-runtime/src/main/java/de/monticore/generating/GeneratorSetup.java index 7d3d1300b9..feb1e0942f 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/GeneratorSetup.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/GeneratorSetup.java @@ -15,10 +15,9 @@ import de.se_rwth.commons.logging.Log; import freemarker.cache.MultiTemplateLoader; import freemarker.cache.TemplateLoader; -import freemarker.core.Macro; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; -import freemarker.template.TemplateMethodModelEx; +import freemarker.template.DefaultObjectWrapperBuilder; import freemarker.template.Version; import java.io.File; @@ -109,9 +108,9 @@ public class GeneratorSetup { public Configuration getConfig() { Configuration config = new Configuration(FREEMARKER_VERSION); - DefaultObjectWrapper o = new DefaultObjectWrapper(FREEMARKER_VERSION); - o.setTreatDefaultMethodsAsBeanMembers(true); - config.setObjectWrapper(o); + DefaultObjectWrapperBuilder oBuilder = new DefaultObjectWrapperBuilder(GeneratorSetup.FREEMARKER_VERSION); + oBuilder.setTreatDefaultMethodsAsBeanMembers(true); + config.setObjectWrapper(oBuilder.build()); // don't look for templateName.de.ftl when templateName.ftl requested config.setLocalizedLookup(false); diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/GlobalExtensionManagement.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/GlobalExtensionManagement.java index e8890864e6..5d7e7fd6bd 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/GlobalExtensionManagement.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/GlobalExtensionManagement.java @@ -2,6 +2,7 @@ package de.monticore.generating.templateengine; +import com.google.common.base.Preconditions; import com.google.common.collect.*; import de.monticore.ast.ASTNode; import de.monticore.generating.templateengine.freemarker.SimpleHashFactory; @@ -72,7 +73,7 @@ public GlobalExtensionManagement() { * @param data list of global data */ public void setGlobalData(SimpleHash data) { - Log.errorIfNull(data); + Preconditions.checkNotNull(data); this.globalData = data; } @@ -108,7 +109,7 @@ public boolean hasGlobalVar(String name) { * @param value the actual content */ public void setGlobalValue(String name, Object value) { - Log.errorIfNull(name); + Preconditions.checkNotNull(name); Reporting.reportSetValue(name, value); globalData.put(name, value); diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/TemplateController.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/TemplateController.java index 5c350f23dd..85765b4512 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/TemplateController.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/TemplateController.java @@ -2,6 +2,7 @@ package de.monticore.generating.templateengine; +import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import de.monticore.ast.ASTNode; @@ -158,15 +159,14 @@ StringBuilder includeWithoutForwarding(String templateName, ASTNode ast) { } /** - * Defines the signature of a template.
- *
+ * Defines the signature of a template. * Note that, due to technical constraints, at first, the current template is * included and the arguments are passed. Second, the signature is defined. * * @param parameterNames the list of the parameter names (=signature) */ public void signature(List parameterNames) { - Log.errorIfNull(parameterNames); + Preconditions.checkNotNull(parameterNames); checkArgument(parameterNames.size() == arguments.size(), "0xA5298 Template '" + templatename + "': Signature size (#" + parameterNames.size() + @@ -348,7 +348,6 @@ public void include(Object empty1, Object empty2) { * * @param templateName full qualified filename * @param ast where we execute the template on - * @return none (= empty string within Freemarker) */ public void write(String templateName, String qualifiedFileName, ASTNode ast) { writeArgs(templateName, qualifiedFileName, config.getDefaultFileExtension(), ast, @@ -374,7 +373,6 @@ public void write(final String templateName, final Path filePath, final ASTNode * * @param templateName full qualified filename * @param ast where we execute the template on - * @return none (= empty string within Freemarker) */ public void writeArgs(final String templateName, final String qualifiedFileName, final String fileExtension, final ASTNode ast, final List templateArguments) { @@ -602,7 +600,7 @@ StringBuilder runInEngine(List passedArguments, Template template, ASTNo * package (of the template it operates on) */ protected String completeQualifiedName(String name) { - Log.errorIfNull(!isNullOrEmpty(name)); + Preconditions.checkNotNull(name); if (name.contains(".")) { return name; diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/FreeMarkerTemplateEngine.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/FreeMarkerTemplateEngine.java index be1fddaf45..82ae9d1409 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/FreeMarkerTemplateEngine.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/FreeMarkerTemplateEngine.java @@ -8,7 +8,7 @@ import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; - +import com.google.common.base.Preconditions; import de.se_rwth.commons.logging.Log; import freemarker.log.Logger; import freemarker.template.Configuration; @@ -26,8 +26,7 @@ public class FreeMarkerTemplateEngine { protected final Configuration configuration; public FreeMarkerTemplateEngine(Configuration configuration) { - this.configuration = Log - .errorIfNull( + this.configuration = Preconditions.checkNotNull( configuration, "0xA4048 Configuration must not be null in FreeMarkerTemplateEngine constructor."); } @@ -64,7 +63,7 @@ public Template loadTemplate(String qualifiedTemplateName) { * @param template the template file */ public void run(StringBuilder buffer, Object data, Template template) { - Log.errorIfNull(template, "0xA0562 The given template must not be null"); + Preconditions.checkNotNull(template, "0xA0562 The given template must not be null"); String seperator = System.getProperty("line.seperator"); Writer w = new Writer() { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/MontiCoreTemplateLoader.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/MontiCoreTemplateLoader.java index 06d0a141c6..8826983eed 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/MontiCoreTemplateLoader.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/MontiCoreTemplateLoader.java @@ -5,6 +5,7 @@ import java.net.URL; import java.util.Optional; +import com.google.common.base.Preconditions; import de.monticore.io.FileReaderWriter; import de.se_rwth.commons.logging.Log; import freemarker.cache.URLTemplateLoader; @@ -25,7 +26,7 @@ public class MontiCoreTemplateLoader extends URLTemplateLoader { * @param classLoader */ public MontiCoreTemplateLoader(ClassLoader classLoader) { - Log.errorIfNull(classLoader, + Preconditions.checkNotNull(classLoader, "0xA4049 ClassLoader must not be null in MontiCoreTemplateLoader constructor."); this.classLoader = classLoader; } diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/SimpleHashFactory.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/SimpleHashFactory.java index 1be1c5381e..5f40677633 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/SimpleHashFactory.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/freemarker/SimpleHashFactory.java @@ -7,7 +7,7 @@ import de.monticore.generating.GeneratorSetup; import freemarker.log.Logger; -import freemarker.template.DefaultObjectWrapper; +import freemarker.template.DefaultObjectWrapperBuilder; import freemarker.template.ObjectWrapper; import freemarker.template.SimpleHash; @@ -19,29 +19,28 @@ */ // STATE SMELL PN public class SimpleHashFactory { - + private static SimpleHashFactory theInstance; - - private SimpleHashFactory() { + + protected SimpleHashFactory() { + theInstance = this; // use empty logger to suppress default free marker log behaviour System.setProperty(Logger.SYSTEM_PROPERTY_NAME_LOGGER_LIBRARY, Logger.LIBRARY_NAME_NONE); } public static SimpleHashFactory getInstance() { if (theInstance == null) { - synchronized (SimpleHashFactory.class) { - theInstance = new SimpleHashFactory(); - } + new SimpleHashFactory(); } return theInstance; } public SimpleHash createSimpleHash() { - return new SimpleHash(new DefaultObjectWrapper(GeneratorSetup.FREEMARKER_VERSION)); + return new SimpleHash(new DefaultObjectWrapperBuilder(GeneratorSetup.FREEMARKER_VERSION).build()); } public SimpleHash createSimpleHash(Map map) { - return new SimpleHash(map, new DefaultObjectWrapper(GeneratorSetup.FREEMARKER_VERSION)); + return new SimpleHash(map, new DefaultObjectWrapperBuilder(GeneratorSetup.FREEMARKER_VERSION).build()); } public SimpleHash createSimpleHash(ObjectWrapper wrapper) { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/ArtifactReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/ArtifactReporter.java index 19d629660a..2622f5f83c 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/ArtifactReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/ArtifactReporter.java @@ -148,8 +148,6 @@ protected Element handleTemplate(String templatename) { } /** - * @see mc.codegen.logging.GenLoggerDefaultClient#logInstantiateStart(java.lang.String, - * java.util.List) */ @Override public void reportInstantiate(String className, List params) { @@ -209,7 +207,7 @@ public void count(Element element) { } /** - * @see mc.codegen.reporting.commons.AReporter#writeHeader() + * @see AReporter#writeHeader() */ @Override protected void writeHeader() { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/ReportingNameHelper.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/ReportingNameHelper.java index cd2bdb1b35..813f9533e3 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/ReportingNameHelper.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/ReportingNameHelper.java @@ -10,7 +10,7 @@ public class ReportingNameHelper { /** * Constructor for de.monticore.generating.templateengine.reporting.artifacts.ReportingNameHelper. */ - private ReportingNameHelper() { + protected ReportingNameHelper() { } public static Path getPath(String outputDir, String qualifiedFilename, String fileextension) { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/formatter/GMLFormatter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/formatter/GMLFormatter.java index 7a5e5a96f4..9b6d55f6b5 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/formatter/GMLFormatter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/formatter/GMLFormatter.java @@ -2,7 +2,7 @@ package de.monticore.generating.templateengine.reporting.artifacts.formatter; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -16,9 +16,9 @@ public class GMLFormatter extends AFormatter { - protected Map elementIds = new HashMap(); + protected Map elementIds = new LinkedHashMap(); - protected Map packageIds = new HashMap(); + protected Map packageIds = new LinkedHashMap(); protected int nodeIdCounter = 0; @@ -29,7 +29,7 @@ public class GMLFormatter extends AFormatter { protected double edgeSizeRange = 0; /** - * @see AFormatter.printer.APrinter#print(visualization.model.RootPkg) + * AFormatter.printer.APrinter#print(visualization.model.RootPkg) */ @Override public List getContent(RootPkg rootPkg) { @@ -144,8 +144,6 @@ protected List getPkgContent(APkg pkg) { /** * Print the dot graph representation of this element * - * @param o Open file to write to - * @param space Space for indentation */ public List getElementContent(Element element) { List lines = Lists.newArrayList(); @@ -176,7 +174,7 @@ public List getElementContent(Element element) { /** * - * @param name + * @param type * @return */ protected String getShape(ElementType type) { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/formatter/GVFormatter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/formatter/GVFormatter.java index 29e70ddb89..3f2f8bcbc8 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/formatter/GVFormatter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/formatter/GVFormatter.java @@ -2,7 +2,7 @@ package de.monticore.generating.templateengine.reporting.artifacts.formatter; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -16,7 +16,7 @@ public class GVFormatter extends AFormatter { - protected Map shapes = new HashMap(); + protected Map shapes = new LinkedHashMap(); public GVFormatter() { this.shapes.put(ElementType.HELPER, "cds"); @@ -104,7 +104,7 @@ public String getShape(ElementType type) { } /** - * @see mc.codegen.reporting.visualization.printer.AFormatter#getContent(mc.codegen.reporting.visualization.model.RootPkg) + * mc.codegen.reporting.visualization.printer.AFormatter#getContent(mc.codegen.reporting.visualization.model.RootPkg) */ @Override public List getContent(RootPkg rootPkg) { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/APkg.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/APkg.java index 5bfb12f03b..78da12e85e 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/APkg.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/APkg.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -15,12 +15,12 @@ public abstract class APkg { /** * Maps name of subpackage to subpackage */ - protected Map subPkgs = new HashMap(); + protected Map subPkgs = new LinkedHashMap(); /** * Maps fullName of Element ({@link Element#getFullName()}) to Element */ - protected Map elements = new HashMap(); + protected Map elements = new LinkedHashMap(); protected boolean containsNonFileElement = false; diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/Element.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/Element.java index 270b77fe1c..5ca8b7c4bc 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/Element.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/Element.java @@ -3,7 +3,7 @@ package de.monticore.generating.templateengine.reporting.artifacts.model; import java.util.Collection; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import de.monticore.generating.templateengine.reporting.artifacts.ReportingNameHelper; @@ -24,10 +24,10 @@ public class Element { protected APkg pkg; // List of links going from this element - protected Map links = new HashMap(); + protected Map links = new LinkedHashMap(); // Number of Link calls per Link - protected Map numberOfLinkCalls = new HashMap(); + protected Map numberOfLinkCalls = new LinkedHashMap(); protected boolean hasLinkToFile = false; diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/Pkg.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/Pkg.java index ffbbfc471b..76ee87331f 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/Pkg.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/Pkg.java @@ -32,7 +32,7 @@ public String getName() { } /** - * @see visualization.model.APkg#resolveAncestorWithElements() + * visualization.model.APkg#resolveAncestorWithElements() */ @Override public APkg resolveAncestorWithElements() { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/RootPkg.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/RootPkg.java index 5061b59165..d6c4c344c4 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/RootPkg.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/artifacts/model/RootPkg.java @@ -8,7 +8,7 @@ public class RootPkg extends APkg { /** - * @see visualization.model.APkg#getQualifiedName() + * visualization.model.APkg#getQualifiedName() */ @Override public String getQualifiedName() { @@ -29,7 +29,7 @@ public void addElementToPkgTree(String packagePath, Element e) { } /** - * @see visualization.model.APkg#resolveAncestorWithElements() + * visualization.model.APkg#resolveAncestorWithElements() */ @Override public APkg resolveAncestorWithElements() { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/IReportEventHandler.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/IReportEventHandler.java index 6b74cba23b..5db0dc8551 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/IReportEventHandler.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/IReportEventHandler.java @@ -174,7 +174,7 @@ public void reportAddAfterTemplate(String template, /** * @param template * @param ast - * @param afterHps + * @param beforeHps */ public void reportAddBeforeTemplate(String template, Optional ast, diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/Layouter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/Layouter.java index 96b429c419..5fd48acfca 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/Layouter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/Layouter.java @@ -48,7 +48,7 @@ public static String padleft(Object o, int l) { /** * Formats the source position of an ASTnode * - * @param a + * @param sp */ public static String sourcePos(SourcePosition sp) { if (sp != null) { @@ -73,7 +73,7 @@ public static String nodeName(ASTNode ast) { * Provides the Name of the Nonterminal of the AST (no qualifier, no "AST" * at the beginning) * - * @param ast + * @param s * @return Nonterminalname */ public static String unqualName(String s) { @@ -149,7 +149,8 @@ public static String valueStr(Object value) { * Provides the name of the Nonterminal of the AST (no qualifier, no "AST" * at the beginning) * - * @param ast + * @param s + * @param l * @return Nonterminalname */ public static String unqualNamePadleft(String s, int l) { diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportCreator.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportCreator.java index 0e05e51358..a35e78bc7e 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportCreator.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportCreator.java @@ -6,7 +6,7 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -27,7 +27,7 @@ public class ReportCreator { */ public ReportCreator(String outputDir) { this.outputDir = outputDir; - writers = new HashMap(); + writers = new LinkedHashMap<>(); File dir = new File(outputDir); if (!dir.isDirectory()) { dir.mkdirs(); @@ -57,7 +57,6 @@ public File createFile(String fileName, String fileextension) * Opens a file * * @param file - * @return * @throws IOException */ public void openFile(File file) throws IOException { @@ -77,7 +76,7 @@ public void openFile(File file) throws IOException { */ public void writeLineToFile(File file, String content) throws IOException { BufferedWriter writer = writers.get(file); - writer.append(content + "\n"); + writer.append(content).append("\n"); } /** @@ -107,7 +106,8 @@ public void closeAll() throws IOException { /** * Removes the file with the given name and extension * - * @param detailedFileName + * @param fileName + * @param fileextension * @return true if file has been deleted, false if file could not be deleted * or does not exists */ diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportLogHook.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportLogHook.java index bb90dff68b..875a8a173a 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportLogHook.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportLogHook.java @@ -13,7 +13,7 @@ import java.net.URL; import java.nio.file.Path; import java.util.Collection; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -69,7 +69,7 @@ public void doPrint(String msg) { /** * Map of model names to actual report managers. */ - protected Map reportManagers = new HashMap<>(); + protected Map reportManagers = new LinkedHashMap<>(); protected Map getReportManagers() { return this.reportManagers; diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportManager.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportManager.java index b29b6a6c1a..430445c66d 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportManager.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportManager.java @@ -2,6 +2,7 @@ package de.monticore.generating.templateengine.reporting.commons; +import com.google.common.base.Preconditions; import de.monticore.ast.ASTNode; import de.monticore.generating.templateengine.HookPoint; import de.monticore.generating.templateengine.reporting.artifacts.ReportingNameHelper; @@ -28,7 +29,7 @@ public String getOutputDir() { } public void addReportEventHandler(IReportEventHandler handler) { - Log.errorIfNull(handler); + Preconditions.checkNotNull(handler); this.reportEventHandlers.add(handler); } diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportingRepository.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportingRepository.java index adcb883ab2..7157bb870d 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportingRepository.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/ReportingRepository.java @@ -98,7 +98,7 @@ protected String getNameFormatted(Object obj, String out, SourcePosition sourceP * Method that converts the ASTNode into a formatted string with a source position if this is * possible. The structure of the string is * - * @nodeName!nodeType(x,y) or @nodeName!nodeType(!ID). + * @nodeName!nodeType(x,y) or @nodeName!nodeType(!ID). * @param a that should be converted into unique String * @return representation of the ASTNode that contains either the position or a unique * identification number for the object @@ -112,7 +112,7 @@ public String getASTNodeNameFormatted(ASTNode a) { * Method that converts the Symbol into a formatted string with a source position if this is * possible. The structure of the string is * - * @symbolName!symbolType(x,y) or @symbolName!symbolType(!ID). + * @symbolName!symbolType(x,y) or @symbolName!symbolType(!ID). * @param symbol The symbol that should be converted into unique String * @return representation of the ASTNode that contains either the position or a unique * identification number for the object @@ -126,7 +126,7 @@ public String getSymbolNameFormatted(ISymbol symbol) { * Method that converts the Symbol into a formatted string with a source position if this is * possible. The structure of the string is * - * @symbolName!symbolType(x,y) or @symbolName!symbolType(!ID). + * @symbolName!symbolType(x,y) or @symbolName!symbolType(!ID). * @param scope The scope that should be converted into unique String * @return representation of the ASTNode that contains either the position or a unique * identification number for the object diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/StatisticsHandler.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/StatisticsHandler.java index 21f2600bf7..8da8a609f2 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/StatisticsHandler.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/commons/StatisticsHandler.java @@ -27,7 +27,7 @@ static ExecutorService getReportSendingExecutorService() { return _reportSendingExecutorService; } - private static void sendRequest(URI url, String data, String type) throws IOException, InterruptedException { + protected static void sendRequest(URI url, String data, String type) throws IOException, InterruptedException { HttpURLConnection connection = (HttpURLConnection) url.toURL().openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("STAT_TYPE", type); diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/DetailedReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/DetailedReporter.java index ffdc9c08f3..e83b2b9083 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/DetailedReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/DetailedReporter.java @@ -245,7 +245,7 @@ protected static String calculateLine(String value) { ReportingConstants.REPORTING_ROW_LENGTH); } - private void reportTemplateAction(ASTNode astNode, String templatename, + protected void reportTemplateAction(ASTNode astNode, String templatename, String actionType) { String startString = actionType + getLineStart(astNode); String line = startString + Layouter.getSpaceString( diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/HookPointReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/HookPointReporter.java index dfa83375ff..029222a9c2 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/HookPointReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/HookPointReporter.java @@ -391,16 +391,16 @@ else if (hp instanceof StringHookPoint) { protected String getHookPointValue(HookPoint hp) { String value = null; - if (hp != null && hp instanceof TemplateHookPoint) { + if (hp instanceof TemplateHookPoint) { value = ((TemplateHookPoint) hp).getTemplateName(); value = ReportingHelper.getTemplateName(value); } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { value = ((StringHookPoint) hp).getValue(); value = ReportingHelper.formatStringToReportingString(value, ReportingConstants.REPORTING_ROW_LENGTH - ReportingConstants.FORMAT_LENGTH_2); } - else if (hp != null && hp instanceof CodeHookPoint) { + else if (hp instanceof CodeHookPoint) { value = ((CodeHookPoint) hp).getClass().getName(); value = Names.getSimpleName(value); } diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/IncGenReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/IncGenReporter.java index 62a1f1f1b0..99cb8f4bf4 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/IncGenReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/IncGenReporter.java @@ -13,7 +13,7 @@ import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Optional; @@ -36,7 +36,7 @@ public abstract class IncGenReporter extends AReporter { protected Set outputFiles = new OrderedHashSet<>(); - protected static Map modelToArtifactMap = new HashMap<>(); + protected static Map modelToArtifactMap = new LinkedHashMap<>(); protected Path inputFile; diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/InstantiationsReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/InstantiationsReporter.java index 0ed633639d..6f5a55a623 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/InstantiationsReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/InstantiationsReporter.java @@ -56,13 +56,7 @@ protected void writeFooter() { @Override public void reportInstantiate(String className, List params) { className = Names.getSimpleName(className); - if (instantiateCount.containsKey(className)) { - Integer actualCount = instantiateCount.get(className); - instantiateCount.put(className, actualCount + 1); - } - else { - instantiateCount.put(className, 1); - } + instantiateCount.merge(className, 1, Integer::sum); } @Override diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/InvolvedFilesReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/InvolvedFilesReporter.java index 44cdc7e400..5cdab52cce 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/InvolvedFilesReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/InvolvedFilesReporter.java @@ -35,7 +35,7 @@ public class InvolvedFilesReporter extends AReporter { protected Set checkedFiles = Sets.newHashSet(); - protected Map modelToArtifactMap = new HashMap<>(); + protected Map modelToArtifactMap = new LinkedHashMap<>(); protected String outputDirectory = ""; diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/NodeTreeDecoratedReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/NodeTreeDecoratedReporter.java index 432afe41c0..a490aa6a8f 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/NodeTreeDecoratedReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/NodeTreeDecoratedReporter.java @@ -185,7 +185,6 @@ public String compactStr(ASTNode ast) { * coming from * * @param ast - * @return */ protected void deriveTreeStructureAST(ASTNode ast) { @@ -250,15 +249,15 @@ protected void callHP(HookPoint hp, ASTNode ast) { protected String getHookPointValue(HookPoint hp) { String value = null; - if (hp != null && hp instanceof TemplateHookPoint) { + if (hp instanceof TemplateHookPoint) { value = ((TemplateHookPoint) hp).getTemplateName(); value = ReportingHelper.getTemplateName(value); } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { value = ((StringHookPoint) hp).getValue(); value = ReportingHelper.formatStringToReportingString(value, 50); } - else if (hp != null && hp instanceof CodeHookPoint) { + else if (hp instanceof CodeHookPoint) { value = ((CodeHookPoint) hp).getClass().getName(); value = Names.getSimpleName(value); } diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/NodeTreeReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/NodeTreeReporter.java index 4648b9819e..dfcd9585ec 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/NodeTreeReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/NodeTreeReporter.java @@ -93,7 +93,7 @@ public void reportTemplateStart(String templatename, ASTNode ast) { public void reportCallAfterHookPoint(String oldTemplate, Collection afterHPs, ASTNode ast) { for (HookPoint hp : afterHPs) { - if (hp != null && hp instanceof TemplateHookPoint) { + if (hp instanceof TemplateHookPoint) { String aident = compactStr(ast); nodeVisits.merge(aident, 1, Integer::sum); } @@ -108,7 +108,7 @@ public void reportCallAfterHookPoint(String oldTemplate, Collection a public void reportCallBeforeHookPoint(String oldTemplate, Collection beforeHPs, ASTNode ast) { for (HookPoint hp : beforeHPs) { - if (hp != null && hp instanceof TemplateHookPoint) { + if (hp instanceof TemplateHookPoint) { String aident = compactStr(ast); nodeVisits.merge(aident, 1, Integer::sum); } @@ -122,7 +122,7 @@ public void reportCallBeforeHookPoint(String oldTemplate, Collection @Override public void reportCallReplacementHookPoint(String oldTemplate, List hps, ASTNode ast) { for (HookPoint hp : hps) { - if (hp != null && hp instanceof TemplateHookPoint) { + if (hp instanceof TemplateHookPoint) { String aident = compactStr(ast); nodeVisits.merge(aident, 1, Integer::sum); } @@ -137,7 +137,7 @@ public void reportCallReplacementHookPoint(String oldTemplate, List h public void reportCallSpecificReplacementHookPoint(String oldTemplate, List hps, ASTNode ast) { for (HookPoint hp : hps) { - if (hp != null && hp instanceof TemplateHookPoint) { + if (hp instanceof TemplateHookPoint) { String aident = compactStr(ast); nodeVisits.merge(aident, 1, Integer::sum); } @@ -150,7 +150,7 @@ public void reportCallSpecificReplacementHookPoint(String oldTemplate, List getMapDiff(Map nodeTypeCount2, allKeys.addAll(nodetypeCountPos2.keySet()); allKeys.addAll(nodeTypeCount2.keySet()); for (String key : allKeys) { - int val1, val2; - if (nodeTypeCount2.containsKey(key)) { - val1 = nodeTypeCount2.get(key); - } - else { - val1 = 0; - } - if (nodetypeCountPos2.containsKey(key)) { - val2 = nodetypeCountPos2.get(key); - } - else { - val2 = 0; - } + int val1 = nodeTypeCount2.getOrDefault(key, 0); + int val2 = nodetypeCountPos2.getOrDefault(key, 0); dif.put(key, val1 - val2); } return dif; diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/StatisticsReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/StatisticsReporter.java index 427e0cbfa7..db03371373 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/StatisticsReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/StatisticsReporter.java @@ -83,7 +83,7 @@ public void flush(ASTNode ast) { closeFile(); } - private void putVersion() { + protected void putVersion() { try { Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("/buildInfo.properties")); diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/SummaryReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/SummaryReporter.java index 46c8fc3c11..2aad926ab4 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/SummaryReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/SummaryReporter.java @@ -275,13 +275,13 @@ public void reportTemplateEnd(String templatename, ASTNode ast) { public void reportCallAfterHookPoint(String oldTemplate, Collection afterHPs, ASTNode ast) { for (HookPoint hp : afterHPs) { - if (hp != null && hp instanceof CodeHookPoint) { + if (hp instanceof CodeHookPoint) { numCallCodeHookpoints++; } - else if (hp != null && hp instanceof TemplateHookPoint) { + else if (hp instanceof TemplateHookPoint) { numCallTemplateHookpoints++; } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { numCallStringHookpoints++; } } @@ -295,13 +295,13 @@ else if (hp != null && hp instanceof StringHookPoint) { public void reportCallBeforeHookPoint(String oldTemplate, Collection beforeHPs, ASTNode ast) { for (HookPoint hp : beforeHPs) { - if (hp != null && hp instanceof CodeHookPoint) { + if (hp instanceof CodeHookPoint) { numCallCodeHookpoints++; } - else if (hp != null && hp instanceof TemplateHookPoint) { + else if (hp instanceof TemplateHookPoint) { numCallTemplateHookpoints++; } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { numCallStringHookpoints++; } } @@ -314,13 +314,13 @@ else if (hp != null && hp instanceof StringHookPoint) { @Override public void reportCallReplacementHookPoint(String oldTemplate, List hps, ASTNode ast) { for (HookPoint hp : hps) { - if (hp != null && hp instanceof CodeHookPoint) { + if (hp instanceof CodeHookPoint) { numCallCodeHookpoints++; } - else if (hp != null && hp instanceof TemplateHookPoint) { + else if (hp instanceof TemplateHookPoint) { numCallTemplateHookpoints++; } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { numCallStringHookpoints++; } } @@ -475,13 +475,13 @@ protected void writeFooter() { */ @Override public void reportSetHookPoint(String hookName, HookPoint hp) { - if (hp != null && hp instanceof CodeHookPoint) { + if (hp instanceof CodeHookPoint) { numSetCodeHookpoints++; } - else if (hp != null && hp instanceof TemplateHookPoint) { + else if (hp instanceof TemplateHookPoint) { numSetTemplateHookpoints++; } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { numSetStringHookpoints++; } } @@ -492,13 +492,13 @@ else if (hp != null && hp instanceof StringHookPoint) { */ @Override public void reportCallHookPointStart(String hookName, HookPoint hp, ASTNode ast) { - if (hp != null && hp instanceof CodeHookPoint) { + if (hp instanceof CodeHookPoint) { numCallCodeHookpoints++; } - else if (hp != null && hp instanceof TemplateHookPoint) { + else if (hp instanceof TemplateHookPoint) { numCallTemplateHookpoints++; } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { numCallStringHookpoints++; } calledUnsetHookpoints.add(ReportingHelper.getHookPointName(hookName)); @@ -521,13 +521,13 @@ public void reportASTSpecificTemplateReplacement(String oldTemplate, ASTNode nod @Override public void reportSetBeforeTemplate(String template, Optional ast, List beforeHps) { for (HookPoint hp : beforeHps) { - if (hp != null && hp instanceof CodeHookPoint) { + if (hp instanceof CodeHookPoint) { numSetCodeHookpoints++; } - else if (hp != null && hp instanceof TemplateHookPoint) { + else if (hp instanceof TemplateHookPoint) { numSetTemplateHookpoints++; } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { numSetStringHookpoints++; } } @@ -540,13 +540,13 @@ else if (hp != null && hp instanceof StringHookPoint) { @Override public void reportSetAfterTemplate(String template, Optional ast, List afterHps) { for (HookPoint hp : afterHps) { - if (hp != null && hp instanceof CodeHookPoint) { + if (hp instanceof CodeHookPoint) { numSetCodeHookpoints++; } - else if (hp != null && hp instanceof TemplateHookPoint) { + else if (hp instanceof TemplateHookPoint) { numSetTemplateHookpoints++; } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { numSetStringHookpoints++; } } @@ -559,13 +559,13 @@ else if (hp != null && hp instanceof StringHookPoint) { @Override public void reportTemplateReplacement(String oldTemplate, List newHps) { for (HookPoint hp : newHps) { - if (hp != null && hp instanceof CodeHookPoint) { + if (hp instanceof CodeHookPoint) { numSetCodeHookpoints++; } - else if (hp != null && hp instanceof TemplateHookPoint) { + else if (hp instanceof TemplateHookPoint) { numSetTemplateHookpoints++; } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { numSetStringHookpoints++; } } diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/TemplateTreeReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/TemplateTreeReporter.java index fd29a46a42..30d6953c7b 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/TemplateTreeReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/TemplateTreeReporter.java @@ -223,16 +223,16 @@ protected void resetVariables() { protected String getHookPointValue(HookPoint hp) { String value = null; - if (hp != null && hp instanceof TemplateHookPoint) { + if (hp instanceof TemplateHookPoint) { value = ((TemplateHookPoint) hp).getTemplateName(); value = ReportingHelper.getTemplateName(value); } - else if (hp != null && hp instanceof StringHookPoint) { + else if (hp instanceof StringHookPoint) { value = ((StringHookPoint) hp).getValue(); value = ReportingHelper.formatStringToReportingString(value, ReportingConstants.REPORTING_ROW_LENGTH - ReportingConstants.FORMAT_LENGTH_2); } - else if (hp != null && hp instanceof CodeHookPoint) { + else if (hp instanceof CodeHookPoint) { value = ((CodeHookPoint) hp).getClass().getName(); value = Names.getSimpleName(value); } diff --git a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/TemplatesReporter.java b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/TemplatesReporter.java index b0b0f2d18f..fdf189c28a 100644 --- a/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/TemplatesReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/generating/templateengine/reporting/reporter/TemplatesReporter.java @@ -98,32 +98,17 @@ protected String getIndentAfterCount(String countString) { public void reportTemplateStart(String templatename, ASTNode ast) { Set hwTemplates = repository.getAllHWTemplateNames(); // if template is handwritten - if (hwTemplates.contains(templatename.replaceAll("\\.", "/").concat(".") - .concat(ReportingConstants.TEMPLATE_FILE_EXTENSION))) { - realHWTemplateNames.add(templatename.replaceAll("\\.", "/").concat(".") - .concat(ReportingConstants.TEMPLATE_FILE_EXTENSION)); + String templateNameSanitized = templatename.replaceAll("\\.", "/").concat(".") + .concat(ReportingConstants.TEMPLATE_FILE_EXTENSION); + if (hwTemplates.contains(templateNameSanitized)) { + realHWTemplateNames.add(templateNameSanitized); templatename = ReportingHelper.getTemplateName(templatename); - - if (hwTemplateCount.containsKey(templatename)) { - Integer actualCount = hwTemplateCount.get(templatename); - hwTemplateCount.put(templatename, actualCount + 1); - } - else { - hwTemplateCount.put(templatename, 1); - } + hwTemplateCount.merge(templatename, 1, Integer::sum); } else { - realTemplateNames.add(templatename.replaceAll("\\.", "/").concat(".") - .concat(ReportingConstants.TEMPLATE_FILE_EXTENSION)); + realTemplateNames.add(templateNameSanitized); templatename = ReportingHelper.getTemplateName(templatename); - - if (templateCount.containsKey(templatename)) { - Integer actualCount = templateCount.get(templatename); - templateCount.put(templatename, actualCount + 1); - } - else { - templateCount.put(templatename, 1); - } + templateCount.merge(templatename, 1, Integer::sum); } } diff --git a/monticore-runtime/src/main/java/de/monticore/io/FileReaderWriter.java b/monticore-runtime/src/main/java/de/monticore/io/FileReaderWriter.java index 48eaf0f227..6ba60cde2d 100644 --- a/monticore-runtime/src/main/java/de/monticore/io/FileReaderWriter.java +++ b/monticore-runtime/src/main/java/de/monticore/io/FileReaderWriter.java @@ -3,6 +3,7 @@ package de.monticore.io; import com.google.common.base.Charsets; +import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import de.monticore.AmbiguityException; import de.monticore.generating.templateengine.reporting.Reporting; @@ -127,7 +128,7 @@ protected String _readFromFile(Path sourcePath) { Log.debug("IOException while trying to read the content of " + sourcePath + ".", e, this.getClass().getName()); } - Log.errorIfNull(content); + Preconditions.checkNotNull(content); return content; } @@ -165,7 +166,7 @@ protected String _readFromFile(URL sourcePath) { Log.debug("IOException while trying to read the content of " + sourcePath + ".", e, this.getClass().getName()); } - Log.errorIfNull(content); + Preconditions.checkNotNull(content); return content; } @@ -176,7 +177,7 @@ public static String readFromFile(Reader reader) { protected String _readFromFile(Reader reader) { BufferedReader buffer = new BufferedReader(reader); String content = buffer.lines().collect(Collectors.joining()); - Log.errorIfNull(content); + Preconditions.checkNotNull(content); return content; } @@ -229,7 +230,7 @@ protected boolean _existsFile(Path sourcePath) { * Saves all {@link JarFile}s opened by {@link FileReaderWriter#getReader(URL)} if the protocol "jar:" is used. * These files must be closed at the end of programm via {@link FileReaderWriter#closeOpenedJarFiles()}. */ - protected static Set> openedJarFiles = new HashSet<>(); + protected static Set> openedJarFiles = new LinkedHashSet<>(); /** * Obtains the reader for a passed model coordinate. The resulting reader diff --git a/monticore-runtime/src/main/java/de/monticore/io/MontiCoreClassLoader.java b/monticore-runtime/src/main/java/de/monticore/io/MontiCoreClassLoader.java index c162e7b46b..a53f1c4dfe 100644 --- a/monticore-runtime/src/main/java/de/monticore/io/MontiCoreClassLoader.java +++ b/monticore-runtime/src/main/java/de/monticore/io/MontiCoreClassLoader.java @@ -8,7 +8,7 @@ public class MontiCoreClassLoader extends URLClassLoader { - private final ClassLoader parent; + protected final ClassLoader parent; public MontiCoreClassLoader(URL[] urls) { super(urls); diff --git a/monticore-runtime/src/main/java/de/monticore/io/paths/GlobExpressionEvaluator.java b/monticore-runtime/src/main/java/de/monticore/io/paths/GlobExpressionEvaluator.java index 43c6365087..be2123ce0e 100644 --- a/monticore-runtime/src/main/java/de/monticore/io/paths/GlobExpressionEvaluator.java +++ b/monticore-runtime/src/main/java/de/monticore/io/paths/GlobExpressionEvaluator.java @@ -10,7 +10,7 @@ import java.net.URI; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Pattern; @@ -36,7 +36,7 @@ public GlobExpressionEvaluator(String pathRegex, FileSystem fs, boolean isLocate pattern = Pattern.compile(pathRegex); this.fileSystem = fs; - result = new HashSet<>(); + result = new LinkedHashSet<>(); } @Override diff --git a/monticore-runtime/src/main/java/de/monticore/io/paths/MCPath.java b/monticore-runtime/src/main/java/de/monticore/io/paths/MCPath.java index cf9fd8a0b4..ff0f2241dd 100644 --- a/monticore-runtime/src/main/java/de/monticore/io/paths/MCPath.java +++ b/monticore-runtime/src/main/java/de/monticore/io/paths/MCPath.java @@ -332,7 +332,7 @@ void invalidateCaches() { } // A List of all file systems opened for jars. - private static Map openedJarFileSystems = new HashMap<>(); + static Map openedJarFileSystems = new LinkedHashMap<>(); public static FileSystem getJarFS(File jar) { if(openedJarFileSystems.containsKey(jar)){ @@ -401,7 +401,7 @@ public int hashCode() { */ static class CachedPath { // *.sym paths - final Set absolutePaths = new HashSet<>(); + final Set absolutePaths = new LinkedHashSet<>(); // path of the filesystem, which will be removed in the filter final String replacedFS; final Pattern removeFsPattern; diff --git a/monticore-runtime/src/main/java/de/monticore/prettyprint/IndentPrinter.java b/monticore-runtime/src/main/java/de/monticore/prettyprint/IndentPrinter.java index a2103d6c84..389bebc2bc 100644 --- a/monticore-runtime/src/main/java/de/monticore/prettyprint/IndentPrinter.java +++ b/monticore-runtime/src/main/java/de/monticore/prettyprint/IndentPrinter.java @@ -107,7 +107,6 @@ public int getIndentLength() { /** * Set the current indentation of the printer - * @return */ public void setIndentation(int indent) { this.indent = indent; diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/IScope.java b/monticore-runtime/src/main/java/de/monticore/symboltable/IScope.java index 7c50084b8b..b05fc1079b 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/IScope.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/IScope.java @@ -12,10 +12,9 @@ import de.se_rwth.commons.Splitters; import java.util.*; +import java.util.stream.Collectors; import static com.google.common.collect.FluentIterable.from; -import static de.se_rwth.commons.Joiners.DOT; -import static java.util.stream.Collectors.toSet; public interface IScope { @@ -117,21 +116,19 @@ default boolean checkIfContinueAsSubScope(String symbolName) { } default Optional getResolvedOrThrowException(final Collection resolved) { - Set resolvedSet = new HashSet<>(resolved); - - if (resolvedSet.size() == 1) { - return Optional.of(resolvedSet.iterator().next()); - } else if (resolvedSet.size() > 1) { - throw new ResolvedSeveralEntriesForSymbolException("0xA4095 Found " + resolvedSet.size() - + " symbols: " + resolvedSet.iterator().next().getFullName(), - resolvedSet); + if (resolved.size() == 1) { + return Optional.of(resolved.iterator().next()); + } else if (resolved.size() > 1) { + throw new ResolvedSeveralEntriesForSymbolException("0xA4095 Found " + resolved.size() + + " symbols: " + resolved.iterator().next().getFullName(), + resolved); } return Optional.empty(); } default List filterSymbolsByAccessModifier(AccessModifier modifier, Collection resolvedUnfiltered) { - return new ArrayList<>(resolvedUnfiltered.stream().filter(new IncludesAccessModifierSymbolPredicate(modifier)).collect(toSet())); + return resolvedUnfiltered.stream().filter(new IncludesAccessModifierSymbolPredicate(modifier)).distinct().collect(Collectors.toList()); } default LinkedListMultimap getUnknownSymbols() { diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindBuilder.java b/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindBuilder.java index d495771fa8..a5a78d1262 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindBuilder.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindBuilder.java @@ -6,8 +6,7 @@ import de.monticore.symboltable.stereotypes.IStereotypeReference; import de.se_rwth.commons.logging.Log; import de.monticore.ast.ASTNode; - -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; @@ -22,7 +21,7 @@ public class SymbolWithScopeOfUnknownKindBuilder { protected AccessModifier accessModifier; - protected Map> stereoinfo = new HashMap<>(); + protected Map> stereoinfo = new LinkedHashMap<>(); protected IScope enclosingScope; diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindDeSer.java b/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindDeSer.java index 8073e7a66e..62fdfca8ea 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindDeSer.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/SymbolWithScopeOfUnknownKindDeSer.java @@ -17,8 +17,8 @@ */ public class SymbolWithScopeOfUnknownKindDeSer implements ISymbolDeSer { - private final IDeSer parent; - private final Supplier scopeFactory; + protected final IDeSer parent; + protected final Supplier scopeFactory; /** * Creates a new {@code SymbolWithScopeOfUnknownKindDeSer}. diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/Symboltable.md b/monticore-runtime/src/main/java/de/monticore/symboltable/Symboltable.md index 81c82e40ca..79b5281f47 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/Symboltable.md +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/Symboltable.md @@ -257,9 +257,9 @@ adapts the foreign symbol (e.g., CDClassSymbol) to the expected symbol (e.g., St * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../../../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../../../../../../../monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](../../../../../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/modifiers/CompoundAccessModifier.java b/monticore-runtime/src/main/java/de/monticore/symboltable/modifiers/CompoundAccessModifier.java index 53d9bec99d..99f6debae7 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/modifiers/CompoundAccessModifier.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/modifiers/CompoundAccessModifier.java @@ -4,7 +4,7 @@ import de.se_rwth.commons.logging.Log; import java.util.Arrays; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -14,7 +14,7 @@ public class CompoundAccessModifier implements AccessModifier { protected Map dimensionToModifier; public CompoundAccessModifier(List modifiers) { - this.dimensionToModifier = new HashMap<>(); + this.dimensionToModifier = new LinkedHashMap<>(); for(AccessModifier modifier: modifiers){ Map modifierMap = modifier.getDimensionToModifierMap(); for(Map.Entry entry: modifierMap.entrySet()){ diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/IDeSer.java b/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/IDeSer.java index 572863f5fb..8c74b0e50b 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/IDeSer.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/IDeSer.java @@ -40,7 +40,6 @@ public interface IDeSer getKindOpt(JsonObject symbol) { * * @param deSerKind * @param serializedElement - * @return */ public static void checkCorrectDeSerForKind(String deSerKind, JsonElement serializedElement) { if (!serializedElement.isJsonObject()) { diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/JsonPrinter.java b/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/JsonPrinter.java index f878fdcc24..5a81ac3ad9 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/JsonPrinter.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/JsonPrinter.java @@ -515,7 +515,7 @@ else if (!currElements.isEmpty() && currElements.peek().isJsonObject()) { } } - private JsonObject getParentObject() { + protected JsonObject getParentObject() { if (currElements.isEmpty()) { Log.error("0xA0613 JsonPrinter detected an invalid nesting of Json. " + "Cannot add a member as the first element of a Json String!"); diff --git a/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/json/TraceableJsonObject.java b/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/json/TraceableJsonObject.java index 3e42cef66b..0e5964f9c2 100644 --- a/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/json/TraceableJsonObject.java +++ b/monticore-runtime/src/main/java/de/monticore/symboltable/serialization/json/TraceableJsonObject.java @@ -2,7 +2,7 @@ package de.monticore.symboltable.serialization.json; import java.util.Collection; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; @@ -20,7 +20,7 @@ public class TraceableJsonObject extends JsonObject { * Constructor for de.monticore.symboltable.serialization.json.TraceableJsonObject */ public TraceableJsonObject() { - visitedMembers = new HashSet<>(); + visitedMembers = new LinkedHashSet<>(); } /** @@ -28,7 +28,7 @@ public TraceableJsonObject() { */ @Override public void setMembers(Map members) { - visitedMembers = new HashSet<>(); + visitedMembers = new LinkedHashSet<>(); super.setMembers(members); } @@ -51,7 +51,7 @@ public JsonElement getMember(String name) { */ public Collection getUnvisitedMembers() { //first create a copy of the set of member names - Set keySet = new HashSet<>(this.getMemberNames()); + Set keySet = new LinkedHashSet<>(this.getMemberNames()); //and then remove all members that have been visited keySet.removeAll(visitedMembers); return keySet; diff --git a/monticore-runtime/src/main/java/de/monticore/tf/rule2od/Variable2AttributeMap.java b/monticore-runtime/src/main/java/de/monticore/tf/rule2od/Variable2AttributeMap.java index 7b96172591..1da7301c8e 100644 --- a/monticore-runtime/src/main/java/de/monticore/tf/rule2od/Variable2AttributeMap.java +++ b/monticore-runtime/src/main/java/de/monticore/tf/rule2od/Variable2AttributeMap.java @@ -5,7 +5,7 @@ import com.google.common.collect.Maps; import de.monticore.tf.ast.ITFObject; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; @@ -21,7 +21,7 @@ public void setV2a( this.v2a = v2a; } - private Map v2a = new HashMap<>(); + private Map v2a = new LinkedHashMap<>(); public void addDeclaration(String variableName, ITFObject object, String attributeName) { v2a.put(variableName, new AttributeEntry(object, attributeName)); diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/FastLookupList.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/FastLookupList.java new file mode 100644 index 0000000000..bbdac1a342 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/FastLookupList.java @@ -0,0 +1,78 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.tf.runtime; + +import java.util.AbstractList; +import java.util.ConcurrentModificationException; +import java.util.List; + +/** + * A sliding range, read-only window of list. + * Alternative to myList = new ArrayList(list); + * myList.remove(0); + * Calling {@link #remove(int)} of this class instead moves the read-window ahead. + * Does not support updates to the underlying list. + * + * @param type of the list + */ + +public class FastLookupList extends AbstractList { + + protected List list; + + public FastLookupList(List list) { + this.list = list; + this.size = list.size(); + } + + public FastLookupList(List list, int removalCounter) { + this(list); + this.removalCounter = removalCounter; + } + + protected int removalCounter = 0; + protected int size; + + public void reset() { + removalCounter = 0; + } + + @Override + public T get(int index) { + if (list.size() != size) { + throw new ConcurrentModificationException("FastLookupList size changed"); + } + return this.list.get(index + removalCounter); + } + + @Override + public T remove(int index) { + if (index != 0) { + throw new IllegalArgumentException("You may only remove index 0"); + } + removalCounter++; + return null; + } + + @Override + public int size() { + return size - removalCounter; + } + + @Override + public boolean isEmpty() { + if (list.size() != size) { + throw new ConcurrentModificationException("FastLookupList size changed"); + } + return removalCounter == size; + } + + public FastLookupList matchCopy() { + return new FastLookupList<>(this.list, this.removalCounter); + } + + @Override + public String toString() { + return "FastLookupList{" + removalCounter + "/ " + size + ": " + list.subList(removalCounter, + size) + "}"; + } +} diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/ODRule.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/ODRule.java index e49ab85434..65727856e2 100644 --- a/monticore-runtime/src/main/java/de/monticore/tf/runtime/ODRule.java +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/ODRule.java @@ -1,8 +1,6 @@ /* * (c) https://github.com/MontiCore/monticore */ - -/* (c) https://github.com/MontiCore/monticore */ package de.monticore.tf.runtime; import de.monticore.ast.ASTNode; diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/SuccessfulReporter.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/SuccessfulReporter.java index 22f39b20aa..52eab7f5b9 100644 --- a/monticore-runtime/src/main/java/de/monticore/tf/runtime/SuccessfulReporter.java +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/SuccessfulReporter.java @@ -1,9 +1,4 @@ /* (c) https://github.com/MontiCore/monticore */ -/* - * (c) https://github.com/MontiCore/monticore - */ - - package de.monticore.tf.runtime; import de.monticore.ast.ASTNode; diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/ValueComparator.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/ValueComparator.java index 5273a8cbd5..36a4a2f330 100644 --- a/monticore-runtime/src/main/java/de/monticore/tf/runtime/ValueComparator.java +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/ValueComparator.java @@ -6,7 +6,7 @@ public class ValueComparator implements Comparator { - private Map data = null; + protected Map data = null; public ValueComparator(Map data) { this.data = data; diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversal.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversal.java new file mode 100644 index 0000000000..6068f22d9f --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversal.java @@ -0,0 +1,62 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.tf.runtime.matching; + +import de.monticore.ast.ASTNode; +import de.monticore.ast.Comment; +import de.monticore.visitor.ITraverser; + +import java.util.*; + +/** + * This CommentBasedModelTraversal is a more efficient implementation of the default + * ModelTraversal. Instead of using a HashMap to store node parents, which showed unexpected + * performance issues due to the suboptimal hash function of ASTNodes, this Traversal stores + * node parents as Comment objects in the respective child nodes. + * Thereby map lookups are prevented and replaced by efficient direct lookups. + * + * @param a language traverser type + */ +public class CommentBasedModelTraversal extends ModelTraversal { + + protected CommentBasedModelTraversal(E traverser) { + super(traverser); + } + + @Override + public ASTNode getParent(ASTNode node) { + return ((WComment) node.get_PostCommentList().get(0)).getParent(); + } + + public void init() { + for (Map.Entry node : this.getParents().entrySet()) { + if (node.getKey().get_PostCommentList().isEmpty()) { + node.getKey().get_PostCommentList().add(new WComment("", node.getValue())); + } + else { + node.getKey().get_PostCommentList() + .set(0, new WComment(node.getKey().get_PostCommentList().get(0), node.getValue())); + } + } + } + + static class WComment extends Comment { + + protected ASTNode parent; + + public WComment(String text, ASTNode parent) { + super(text); + this.parent = parent; + } + + public WComment(Comment c, ASTNode parent) { + this(c.getText(), parent); + this.set_SourcePositionStart(c.get_SourcePositionStart()); + this.set_SourcePositionEnd(c.get_SourcePositionEnd()); + } + + public ASTNode getParent() { + return parent; + } + } + +} diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversalFactory.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversalFactory.java new file mode 100644 index 0000000000..49cc950bd6 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversalFactory.java @@ -0,0 +1,33 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.tf.runtime.matching; + +import de.monticore.visitor.ITraverser; + +public class CommentBasedModelTraversalFactory extends ModelTraversalFactory { + + private static CommentBasedModelTraversalFactory instance; + + public static CommentBasedModelTraversalFactory getInstance() { + if (instance == null) { + instance = new CommentBasedModelTraversalFactory(); + } + return instance; + } + + /** + * @return a {@link ModelTraversal} for the given model + */ + public ModelTraversalVisitor createVisitor(ModelTraversal modelTraversal) { + return new CommentBasedModelTraversalVisitor(modelTraversal); + } + + public ModelTraversal create(java.util.function.Supplier traverserSupplier){ + return this.create(traverserSupplier.get()); + } + + public ModelTraversal create(E traverser){ + ModelTraversal modelTraversal = new CommentBasedModelTraversal<>(traverser); + traverser.add4IVisitor(createVisitor(modelTraversal)); + return modelTraversal; + } +} diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversalVisitor.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversalVisitor.java new file mode 100644 index 0000000000..5a5f845990 --- /dev/null +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/CommentBasedModelTraversalVisitor.java @@ -0,0 +1,11 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.tf.runtime.matching; + +import de.monticore.visitor.IVisitor; + +public class CommentBasedModelTraversalVisitor extends ModelTraversalVisitor implements IVisitor { + + protected CommentBasedModelTraversalVisitor(ModelTraversal modelTraversal) { + super(modelTraversal); + } +} diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/ModelTraversal.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/ModelTraversal.java index 0a24d9c00a..b2df510bb6 100644 --- a/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/ModelTraversal.java +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/ModelTraversal.java @@ -8,12 +8,12 @@ public class ModelTraversal { - protected Map> cName2instances = new HashMap<>(); + protected Map> cName2instances = new LinkedHashMap<>(); protected List all = new ArrayList<>(); - protected Map parents= new HashMap<>(); + protected Map parents= new LinkedHashMap<>(); protected Stack currentparents = new Stack<>(); - private final E traverser; + protected final E traverser; protected ModelTraversal(E traverser) { this.traverser = traverser; diff --git a/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/ModelTraversalVisitor.java b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/ModelTraversalVisitor.java index 8a98367d8c..919cf7bea1 100644 --- a/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/ModelTraversalVisitor.java +++ b/monticore-runtime/src/main/java/de/monticore/tf/runtime/matching/ModelTraversalVisitor.java @@ -9,7 +9,7 @@ public class ModelTraversalVisitor implements IVisitor { - private final ModelTraversal modelTraversal; + protected final ModelTraversal modelTraversal; protected ModelTraversalVisitor( ModelTraversal modelTraversal) { diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ClassMatch.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ClassMatch.ftl index 5cdf2c34d2..fc0d02b098 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ClassMatch.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ClassMatch.ftl @@ -35,19 +35,19 @@ public class Match { <#if !change.isObjectWithinList()> private ${change.getType()} ${change.getObjectName()}_${change.getAttributeName()}_before; <#else> - private Map<${change.getObjectType()}, ${change.getType()?cap_first}> ${change.getObjectName()}_${change.getAttributeName()}_before = new HashMap(); + private Map<${change.getObjectType()}, ${change.getType()?cap_first}> ${change.getObjectName()}_${change.getAttributeName()}_before = new LinkedHashMap(); <#elseif change.isObjectWithinList() > <#if change.isAttributeIterated()> private int ${change.getObjectName()}_${valueName}_before_pos; - private Map<${change.getGenericType()}, Integer> ${change.getObjectName()}_${valueName}_before = new HashMap(); + private Map<${change.getGenericType()}, Integer> ${change.getObjectName()}_${valueName}_before = new LinkedHashMap(); <#else> - private Map<${change.getObjectType()}, ${change.getGenericType()}> ${change.getObjectName()}_${valueName}_before = new HashMap(); + private Map<${change.getObjectType()}, ${change.getGenericType()}> ${change.getObjectName()}_${valueName}_before = new LinkedHashMap(); <#else> <#if change.isAttributeIterated()> private int ${change.getObjectName()}_${valueName}_before_pos; - private Map<${change.getGenericType()}, Integer> ${change.getObjectName()}_${valueName}_before = new HashMap(); + private Map<${change.getGenericType()}, Integer> ${change.getObjectName()}_${valueName}_before = new LinkedHashMap(); <#else> private ${change.getGenericType()} ${change.getObjectName()}_${valueName}_before; diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ConstantCode.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ConstantCode.ftl index 72340d26dd..3f51bcb413 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ConstantCode.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ConstantCode.ftl @@ -4,10 +4,13 @@ <#assign matchObjects = hierarchyHelper.getMandatoryMatchObjects(ast.getPattern().getMatchingObjectsList())> <#assign optionalMatchObjects = hierarchyHelper.getOptionalMatchObjects(ast.getPattern().getLHSObjectsList())> + public static boolean optimizeSP = true; + private List hostGraph; private GlobalExtensionManagement glex = new GlobalExtensionManagement(); private List allMatches; private boolean doReplacementExecuted = false; + private boolean isHostGraphDirty = true; <#-- for each object creates a _candidates, _candidates_temp nodelist and an _cand object--> // Matches @@ -19,7 +22,7 @@ protected boolean ${variable.getName()}_is_fix = false; private ${variable.getType()} ${variable.getName()}; - private ModelTraversal t = ModelTraversalFactory.getInstance().create((java.util.function.Supplier)${grammarName}Mill::inheritanceTraverser); + private ModelTraversal t = CommentBasedModelTraversalFactory.getInstance().create((java.util.function.Supplier)${grammarName}Mill::inheritanceTraverser); <#list ast.getPattern().getAssocList() as association> private mc.ast.MCAssociation ${association.getName()}; @@ -67,3 +70,22 @@ doPatternMatching(); doReplacement(); } + + protected void loadIntoModelTraverser() { + for (ASTNode astNode : Log.errorIfNull(hostGraph, + "0xE1200: Hostgraph is null, check constructor arguments!")) { + astNode.accept(t.getTraverser()); + } + + if (t instanceof CommentBasedModelTraversal) { + ((CommentBasedModelTraversal) t).init(); + } + } + + /** + * Marks the original model as dirty, same as if {@link #doReplacement} was called. + * @see ${ast.getClassname()}#doReplacement() + */ + public void markDirty() { + this.isHostGraphDirty = true; + } diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatching.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatching.ftl index 70ea520ca7..d108cf4165 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatching.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatching.ftl @@ -13,11 +13,23 @@ public boolean doPatternMatching() { // (this will skip all attempts to match negative nodes) boolean isBacktracking = true; boolean isBacktrackingNegative = false; - for(ASTNode a: hostGraph){ - a.accept(t.getTraverser()); + +<#list hierarchyHelper.getOptionalMatchObjects(ast.getPattern().getLHSObjectsList()) as optional> + reset_${optional.getObjectName()}(); + + + if (isHostGraphDirty || searchPlan == null) { + this.loadIntoModelTraverser(); + isHostGraphDirty= false; } + if (searchPlan == null) { searchPlan = findSearchPlan(); + + if(optimizeSP) { + optimizeSearchplan(); + } + initializeFastLookupList(); splitSearchplan(); // for OptList structures isBacktracking = false; } @@ -29,13 +41,13 @@ public boolean doPatternMatching() { <#--creates an if statement for each object for matching the object--> <#list hierarchyHelper.getMandatoryObjectsWithoutListChilds(ast.getPattern().getLHSObjectsList()) as object> <#if object.isListObject()> - ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleListObject", object, [false])} + ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleListObject", object, [false, ""])} <#elseif object.isOptObject()> - ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleOptObject", object, [false])} + ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleOptObject", object, [false, ""])} <#elseif object.isNotObject()> - ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleNotObject", object, [false])} + ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleNotObject", object, [false, ""])} <#else> - ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleNormalObject", object, [false])} + ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleNormalObject", object, [false, ""])} <#if object_has_next>else diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatchingList.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatchingList.ftl index 3d6c3c0a6d..44c9895fc0 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatchingList.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatchingList.ftl @@ -149,7 +149,7 @@ public boolean doPatternMatching_${structure.getObjectName()}(boolean isParentBa // reset candidates list if(!isBacktracking){ if (!isBacktrackingNegative) { - ${object.getObjectName()}_candidates_temp = new ArrayList<>(${object.getObjectName()}_candidates); + ((FastLookupList)${object.getObjectName()}_candidates_temp).reset(); } //try to find a match ${object.getObjectName()}_cand = match_${object.getObjectName()}(); @@ -172,7 +172,7 @@ public boolean doPatternMatching_${structure.getObjectName()}(boolean isParentBa //put the first object of the backtracking stack searchPlan.push(backtrackingNegative.pop()); //reset candidates list - ${object.getObjectName()}_candidates_temp = new ArrayList<>(${object.getObjectName()}_candidates); + ((FastLookupList)${object.getObjectName()}_candidates_temp).reset(); } }else{ @@ -195,7 +195,7 @@ public boolean doPatternMatching_${structure.getObjectName()}(boolean isParentBa searchPlan.push(backtracking.pop()); } //reset candidates list - ${object.getObjectName()}_candidates_temp = new ArrayList<>(${object.getObjectName()}_candidates); + ((FastLookupList)${object.getObjectName()}_candidates_temp).reset(); } } @@ -211,7 +211,7 @@ public boolean doPatternMatching_${structure.getObjectName()}(boolean isParentBa clear${structure.getObjectName()}NegativeObjects(); } if (!isBacktracking) { - ${object.getObjectName()}_candidates_temp = new ArrayList<>(${object.getObjectName()}_candidates); + ((FastLookupList)${object.getObjectName()}_candidates_temp).reset(); } //try to find a match ${object.getObjectName()}_cand = match_${object.getObjectName()}(); @@ -230,7 +230,7 @@ public boolean doPatternMatching_${structure.getObjectName()}(boolean isParentBa //put the first object of the backtracking stack searchPlan.push(backtracking.pop()); //reset candidates list - ${object.getObjectName()}_candidates_temp = new ArrayList<>(${object.getObjectName()}_candidates); + ((FastLookupList)${object.getObjectName()}_candidates_temp).reset(); } }else{ // stop backtracking @@ -274,13 +274,23 @@ public boolean doPatternMatching_${structure.getObjectName()}(boolean isParentBa Match${structure.getObjectName()} match = new Match${structure.getObjectName()}(<@commaSeperatedNames/>); match.backtracking = (Stack) backtracking.clone(); <#list mandatoryObjects as o>// save context of every object and then clear it - match.${o.getObjectName()}_temp_candidates = ${o.getObjectName()}_candidates_temp; - ${o.getObjectName()}_cand = null; + match.${o.getObjectName()}_temp_candidates = ((FastLookupList)${o.getObjectName()}_candidates_temp).matchCopy(); + ${o.getObjectName()}_cand = null; ${structure.getObjectName()}_candidates.add(match); backtracking.clear(); } } + + // Reset list candidates are match + <#list structure.getInnerLinkObjectNamesList() as innerLinkObjectName> + <#if hierarchyHelper.isNoOptionalName(ast.getPattern().getLHSObjectsList(), innerLinkObjectName)> + ${innerLinkObjectName}_cand = null; + + + + // TODO: Do something similar for optionals (but somehow do not loose them?) + if(${structure.getObjectName()}_candidates.isEmpty()) { return false; } diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatchingOptional.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatchingOptional.ftl index 9d7e2a3e61..c3116eee76 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatchingOptional.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoPatternMatchingOptional.ftl @@ -12,12 +12,6 @@ protected boolean doPatternMatching_${structure.getObjectName()}(boolean isParen Stack backtrackingNegative = new Stack(); Stack searchPlan = (Stack) searchPlan_${structure.getObjectName()}.clone(); - <#list structure.getInnerLinkObjectNamesList() as elem> - <#if hierarchyHelper.isNoOptionalName(ast.getPattern().getLHSObjectsList(), elem)> - ${elem}_cand = null; - - - String nextNode = null; while(!searchPlan.isEmpty()){ nextNode = searchPlan.pop(); @@ -26,18 +20,17 @@ protected boolean doPatternMatching_${structure.getObjectName()}(boolean isParen <#-- <#list ast.getPattern().getLHSObjectsList() as object> --> <#list hierarchyHelper.getInnerLinkObjectsLHS(ast.getPattern().getLHSObjectsList(), structure) as object> <#if object.isListObject()> - ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleListObject", object, [true])} + ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleListObject", object, [true, structure])} <#elseif object.isOptObject()> - ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleOptObject", object, [true])} + ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleOptObject", object, [true, structure])} <#elseif object.isNotObject()> - ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleNotObject", object, [true])} + ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleNotObject", object, [true, structure])} <#else> - ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleNormalObject", object, [true])} + ${tc.includeArgs("de.monticore.tf.odrules.dopatternmatching.HandleNormalObject", object, [true, structure])} <#if object_has_next>else } - return true; } diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoReplacement.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoReplacement.ftl index 33ff0dc847..3bb23d0616 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoReplacement.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/DoReplacement.ftl @@ -1,6 +1,7 @@ <#-- (c) https://github.com/MontiCore/monticore --> public void doReplacement() { + isHostGraphDirty = true; for(Match m:allMatches){ diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/FastLookupList.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/FastLookupList.ftl new file mode 100644 index 0000000000..9f55fc92e2 --- /dev/null +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/FastLookupList.ftl @@ -0,0 +1,13 @@ +<#-- (c) https://github.com/MontiCore/monticore --> + + public void initializeFastLookupList() { +<#list ast.getPattern().getLHSObjectsList() as object> +<#if !object.isOptObject() && !object.isListObject()> +<#if object.isNotObject() || object.isOptObject() || object.isListObject()> + ${object.getObjectName()}_candidates_temp = new FastLookupList<>(${object.getObjectName()}_candidates); +<#else> + ${object.getObjectName()}_candidates_temp = new FastLookupList<>(${object.getObjectName()}_candidates); + + + + } \ No newline at end of file diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/FindSearchPlan.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/FindSearchPlan.ftl index 73fd806d4c..236e78d1eb 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/FindSearchPlan.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/FindSearchPlan.ftl @@ -77,7 +77,7 @@ - Map unsortedData = new HashMap<>(); + Map unsortedData = new LinkedHashMap<>(); <#list ast.getPattern().getLHSObjectsList() as object> unsortedData.put("${object.getObjectName()}<#if object.isListObject()>_$List", count_${object.getObjectName()}); diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/OptimizeSearchPlan.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/OptimizeSearchPlan.ftl new file mode 100644 index 0000000000..a4bedaf3b3 --- /dev/null +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/OptimizeSearchPlan.ftl @@ -0,0 +1,61 @@ +<#-- (c) https://github.com/MontiCore/monticore --> + + protected void optimizeSearchplan() { + + // Optimization 1: With parent->child compositions: Ensure the parent is checked first + Map> compositionDependencies = new HashMap<>(); +<#list ast.getPattern().getLHSObjectsList() as object> + compositionDependencies.put(${"\"" + object.getObjectName() + "\""}, List.of(${ast.getCompositionDependencyNames(object)?map(name -> "\""+name+"\"")?join(", ")})); + + + boolean changed = true; + while(changed) { + changed = false; + for(Map.Entry> lhsObject : compositionDependencies.entrySet()) { + String lhsObjectName = lhsObject.getKey(); + List compositionSources = lhsObject.getValue(); + if(!compositionSources.isEmpty()) { + int index = searchPlan.indexOf(lhsObjectName); + for(String compSrcOb : compositionSources) { + int indexSrc = searchPlan.indexOf(compSrcOb); + if(indexSrc > index) { + searchPlan.remove(compSrcOb); + searchPlan.add(index, compSrcOb); + changed = true; + } + } + } + } + } + + // TODO: Optimization 2: In the case of parent (large count) -> child (few occurences) + // In this case, the child should be searched for first, followed by a getParent(call) + + // We have to ensure that objects affected by a replacement are + // - LHS [more to the bottom] RHS or + // - ModifiedObject [more to the bottom] LHS <-- we try this approach here + Map replacementChangeMapping = new HashMap<>(); +<#list ast.getReplacementChangeMapping() as key, value> + replacementChangeMapping.put(${"\"" + key + "\""}, ${"\"" + value + "\""}); + + + for(Map.Entry replacementChange : replacementChangeMapping.entrySet()) { + String objectToMove = replacementChange.getKey(); + String lhsModifier = replacementChange.getValue(); + int index = searchPlan.indexOf(objectToMove); + int indexSrc = searchPlan.indexOf(lhsModifier); + if (index > indexSrc) { + searchPlan.remove(objectToMove); + searchPlan.add(indexSrc, objectToMove); + } + } + + // TODO: Improve this shuffling + /* + * state [[ $A :- $_ ]] { + * state $I; + * } + */ + + // TODO: Do we have to consider creations too? + } diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ResetOptionals.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ResetOptionals.ftl new file mode 100644 index 0000000000..341d44129f --- /dev/null +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/ResetOptionals.ftl @@ -0,0 +1,11 @@ +<#-- (c) https://github.com/MontiCore/monticore --> +<#-- We are only interested in optional structures here --> +<#list hierarchyHelper.getOptionalMatchObjects(ast.getPattern().getLHSObjectsList()) as structure> + +protected void reset_${structure.getObjectName()}() { + // TODO: correct? -> not for lists? +<#list ast.getAllInnerNonOptionalNames(ast.getPattern().getLHSObjectsList(), structure) as elem> + ${elem}_cand = null; + +} + diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/TransformationClass.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/TransformationClass.ftl index ac3a2063d1..38121dab78 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/TransformationClass.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/TransformationClass.ftl @@ -24,6 +24,8 @@ public class ${ast.getClassname()} extends ODRule { ${tc.include("de.monticore.tf.odrules.DoPatternMatchingList")} + ${tc.include("de.monticore.tf.odrules.ResetOptionals")} + ${tc.include("de.monticore.tf.odrules.CheckConstraints")} ${tc.include("de.monticore.tf.odrules.CheckSubConstraints")} @@ -34,8 +36,12 @@ public class ${ast.getClassname()} extends ODRule { ${tc.include("de.monticore.tf.odrules.FindSearchPlan")} + ${tc.include("de.monticore.tf.odrules.OptimizeSearchPlan")} + ${tc.include("de.monticore.tf.odrules.SplitSearchplan")} + ${tc.include("de.monticore.tf.odrules.FastLookupList")} + ${tc.include("de.monticore.tf.odrules.FindCandidates")} ${tc.include("de.monticore.tf.odrules.FindActualCandidates")} diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/TransformationUnit.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/TransformationUnit.ftl index 541fdf61de..02b24d7bb8 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/TransformationUnit.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/TransformationUnit.ftl @@ -5,10 +5,12 @@ import java.util.*; import java.util.Optional; import de.monticore.ast.ASTNode; +import de.monticore.tf.runtime.FastLookupList; import de.monticore.tf.runtime.ODRule; import de.monticore.tf.runtime.ValueComparator; import de.monticore.tf.runtime.matching.ModelTraversal; -import de.monticore.tf.runtime.matching.ModelTraversalFactory; +import de.monticore.tf.runtime.matching.CommentBasedModelTraversal; +import de.monticore.tf.runtime.matching.CommentBasedModelTraversalFactory; import com.google.common.collect.Lists; import static com.google.common.collect.Lists.*; import static de.se_rwth.commons.StringTransformations.*; diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleListObject.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleListObject.ftl index 40c156ec11..9e9764f379 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleListObject.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleListObject.ftl @@ -1,5 +1,5 @@ <#-- (c) https://github.com/MontiCore/monticore --> -${signature("isOptional")} +${signature("isOptional", "parentObject")} <#assign listObject = ast> if (nextNode.equals("${listObject.getObjectName()}_$List")) { @@ -16,6 +16,9 @@ if (nextNode.equals("${listObject.getObjectName()}_$List")) { if (backtracking.isEmpty()) { // no match of the pattern can be found <#if isOptional> + <#if parentObject?has_content> + reset_${parentObject.getObjectName()}(); + if (isParentBacktrackingNegative) { //Can not find a new Match, signal the parent to backtrack return false; diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleNormalObject.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleNormalObject.ftl index 8c881f21b0..6a499191e8 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleNormalObject.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleNormalObject.ftl @@ -1,5 +1,5 @@ <#-- (c) https://github.com/MontiCore/monticore --> -${signature("isOptional")} +${signature("isOptional", "parentObject")} <#assign normalObject = ast> if (nextNode.equals("${normalObject.getObjectName()}")) { @@ -9,7 +9,7 @@ if (nextNode.equals("${normalObject.getObjectName()}")) { clearNegativeObjects(); } if (!isBacktracking) { - ${normalObject.getObjectName()}_candidates_temp = new ArrayList<>(${normalObject.getObjectName()}_candidates); + ((FastLookupList)${normalObject.getObjectName()}_candidates_temp).reset(); } <#if isOptional> // exit condition for optional structures @@ -26,6 +26,8 @@ if (nextNode.equals("${normalObject.getObjectName()}")) { // no match of the pattern can be found <#if !isOptional> foundMatch = false; + <#elseif parentObject?has_content> + reset_${parentObject.getObjectName()}(); break; } else { @@ -36,7 +38,7 @@ if (nextNode.equals("${normalObject.getObjectName()}")) { // put the first object of the backtracking stack searchPlan.push(backtracking.pop()); // reset candidates list - ${normalObject.getObjectName()}_candidates_temp = new ArrayList<>(${normalObject.getObjectName()}_candidates); + ((FastLookupList)${normalObject.getObjectName()}_candidates_temp).reset(); } } else { // stop backtracking diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleNotObject.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleNotObject.ftl index 2a4455392c..5917f94deb 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleNotObject.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleNotObject.ftl @@ -1,12 +1,12 @@ <#-- (c) https://github.com/MontiCore/monticore --> -${signature("isOptional")} +${signature("isOptional", "parentObject")} <#assign notObject = ast> if (nextNode.equals("${notObject.getObjectName()}")) { // this is a negative object, reset candidates list if (!isBacktracking) { if (!isBacktrackingNegative) { - ${notObject.getObjectName()}_candidates_temp = new ArrayList<>(${notObject.getObjectName()}_candidates); + ((FastLookupList)${notObject.getObjectName()}_candidates_temp).reset(); } // try to find a match ${notObject.getObjectName()}_cand = match_${notObject.getObjectName()}(); @@ -31,9 +31,10 @@ if (nextNode.equals("${notObject.getObjectName()}")) { // put the first object of the backtracking stack searchPlan.push(backtrackingNegative.pop()); // reset candidates list - ${notObject.getObjectName()}_candidates_temp = new ArrayList<>(${notObject.getObjectName()}_candidates); + ((FastLookupList)${notObject.getObjectName()}_candidates_temp).reset(); } } else { + // TODO: We are most likely missing a reset of optionals here (when using NOT in OPT) // update candidates for next object to match if(!searchPlan.isEmpty()) { // put object on backtracking stack @@ -53,7 +54,7 @@ if (nextNode.equals("${notObject.getObjectName()}")) { searchPlan.push(backtracking.pop()); } // reset candidates list - ${notObject.getObjectName()}_candidates_temp = new ArrayList<>(${notObject.getObjectName()}_candidates); + ((FastLookupList)${notObject.getObjectName()}_candidates_temp).reset(); } } } else { diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleOptObject.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleOptObject.ftl index d42f782530..c7cb9aec6c 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleOptObject.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/dopatternmatching/HandleOptObject.ftl @@ -1,5 +1,5 @@ <#-- (c) https://github.com/MontiCore/monticore --> -${signature("isOptional")} +${signature("isOptional", "parentObject")} <#assign optObject = ast> if (nextNode.equals("${optObject.getObjectName()}")) { @@ -32,6 +32,8 @@ if (nextNode.equals("${optObject.getObjectName()}")) { // no match of the pattern can be found <#if !isOptional> foundMatch = false; + <#elseif parentObject?has_content> + reset_${parentObject.getObjectName()}(); break; } else { diff --git a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/doreplacement/CreateObjects.ftl b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/doreplacement/CreateObjects.ftl index e314350bb8..e9709421a6 100644 --- a/monticore-runtime/src/main/resources/de/monticore/tf/odrules/doreplacement/CreateObjects.ftl +++ b/monticore-runtime/src/main/resources/de/monticore/tf/odrules/doreplacement/CreateObjects.ftl @@ -28,7 +28,11 @@ if (!is_${create.getName()}_fix) { <#assign changeGetValue += ".get()"> + <#if change.isCopy()> + builder.${change.getSetter()}(${changeGetValue}.deepClone()); + <#else> builder.${change.getSetter()}(${changeGetValue}); + <#else> builder.${change.getSetter()}(); diff --git a/monticore-runtime/src/test/java/de/monticore/ast/CommentBuilderTest.java b/monticore-runtime/src/test/java/de/monticore/ast/CommentBuilderTest.java index efa290f7bf..49b2221a19 100644 --- a/monticore-runtime/src/test/java/de/monticore/ast/CommentBuilderTest.java +++ b/monticore-runtime/src/test/java/de/monticore/ast/CommentBuilderTest.java @@ -3,15 +3,14 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class CommentBuilderTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -23,11 +22,12 @@ public void positiveTest() { assertTrue(Log.getFindings().isEmpty()); } - @Test(expected=IllegalStateException.class) + @Test public void negativeTest() { final CommentBuilder commentBuilder = new CommentBuilder(); assertFalse(commentBuilder.isValid()); - commentBuilder.build(); - assertTrue(Log.getFindings().isEmpty()); + assertThrows(IllegalStateException.class, commentBuilder::build); + assertEquals(1L, Log.getFindingsCount()); + assertEquals("0xA4322 text of type String must not be null", Log.getFindings().get(0).getMsg()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/cocos/helper/Assert.java b/monticore-runtime/src/test/java/de/monticore/cocos/helper/Assert.java index 64b388e0d2..d0deeaac2d 100644 --- a/monticore-runtime/src/test/java/de/monticore/cocos/helper/Assert.java +++ b/monticore-runtime/src/test/java/de/monticore/cocos/helper/Assert.java @@ -2,15 +2,15 @@ package de.monticore.cocos.helper; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.Collection; import com.google.common.base.Joiner; import de.se_rwth.commons.logging.Finding; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Helper for testing CoCos. * @@ -30,8 +30,8 @@ public static void assertErrors(Collection expectedErrors, for (Finding expectedError : expectedErrors) { boolean found = actualErrors.stream() .filter(s -> s.buildMsg().contains(expectedError.buildMsg())).count() >= 1; - assertTrue("The following expected error was not found: " + expectedError - + actualErrorsJoined, found); + assertTrue(found, + "The following expected error was not found: " + expectedError + actualErrorsJoined); } } @@ -50,8 +50,8 @@ public static void assertErrorMsg(Collection expectedErrors, boolean found = actualErrors.stream().filter( f -> f.getMsg().equals(expectedError.getMsg()) ).count() >= 1; - assertTrue("The following expected error was not found: " + expectedError - + actualErrorsJoined, found); + assertTrue(found, + "The following expected error was not found: " + expectedError + actualErrorsJoined); } } @@ -66,10 +66,9 @@ public static void assertEqualErrorCounts(Collection expectedErrors, String actualErrorsJoined = "\nactual Errors: \n\t" + Joiner.on("\n\t").join(actualErrors); String expectedErrorsJoined = "\nexpected Errors: \n\t" + Joiner.on("\n\t").join(expectedErrors); - assertEquals( + assertEquals(expectedErrors.size(), actualErrors.size(), "Expected " + expectedErrors.size() + " errors, but found " + actualErrors.size() - + "." + expectedErrorsJoined + actualErrorsJoined, expectedErrors.size(), - actualErrors.size()); + + "." + expectedErrorsJoined + actualErrorsJoined); } } diff --git a/monticore-runtime/src/test/java/de/monticore/generating/GeneratorEngineTest.java b/monticore-runtime/src/test/java/de/monticore/generating/GeneratorEngineTest.java index c1f72a1b04..5987eee079 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/GeneratorEngineTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/GeneratorEngineTest.java @@ -12,7 +12,6 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,6 +19,7 @@ import java.nio.file.Paths; import static de.monticore.generating.GeneratorEngine.existsHandwrittenClass; +import static org.junit.jupiter.api.Assertions.*; /** * Tests for {@link de.monticore.generating.GeneratorEngine}. @@ -48,15 +48,15 @@ public void testGenerateInFile() { generatorEngine.generate("the.Template", Paths.get("a/GenerateInFile.test"), node); - Assertions.assertEquals(1, freeMarkerTemplateEngine.getProcessedTemplates().size()); + assertEquals(1, freeMarkerTemplateEngine.getProcessedTemplates().size()); FreeMarkerTemplateMock template = freeMarkerTemplateEngine.getProcessedTemplates().iterator().next(); - Assertions.assertTrue(template.isProcessed()); - Assertions.assertEquals("the.Template", template.getName()); + assertTrue(template.isProcessed()); + assertEquals("the.Template", template.getName()); - Assertions.assertEquals(1, fileHandler.getStoredFilesAndContents().size()); - Assertions.assertTrue(fileHandler.getStoredFilesAndContents().containsKey(Paths.get + assertEquals(1, fileHandler.getStoredFilesAndContents().size()); + assertTrue(fileHandler.getStoredFilesAndContents().containsKey(Paths.get (new File("target1/a/GenerateInFile.test").getAbsolutePath()))); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @AfterAll @@ -75,15 +75,15 @@ public void testGenerateStringBuilder() { GeneratorEngineMock generatorEngine = new GeneratorEngineMock(setup); StringBuilder sb = generatorEngine.generateNoA("the.Template"); - Assertions.assertTrue(sb.length()>0); + assertTrue(sb.length()>0); - Assertions.assertEquals(1, freeMarkerTemplateEngine.getProcessedTemplates().size()); + assertEquals(1, freeMarkerTemplateEngine.getProcessedTemplates().size()); FreeMarkerTemplateMock template = freeMarkerTemplateEngine.getProcessedTemplates().iterator().next(); - Assertions.assertTrue(template.isProcessed()); - Assertions.assertEquals("the.Template", template.getName()); + assertTrue(template.isProcessed()); + assertEquals("the.Template", template.getName()); - Assertions.assertEquals(0, fileHandler.getStoredFilesAndContents().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(0, fileHandler.getStoredFilesAndContents().size()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -94,8 +94,8 @@ public void testWrongPath() { setup.setAdditionalTemplatePaths(Lists.newArrayList(file)); setup.setFileHandler(fileHandler); FreeMarkerTemplateEngineMock freeMarkerTemplateEngine = new FreeMarkerTemplateEngineMock(setup.getConfig()); - Assertions.assertEquals(1, Log.getFindingsCount()); - Assertions.assertEquals("0xA1020 Unable to load templates from non-existent path doesnotexist", Log.getFindings().get(0).getMsg()); + assertEquals(1, Log.getFindingsCount()); + assertEquals("0xA1020 Unable to load templates from non-existent path doesnotexist", Log.getFindings().get(0).getMsg()); } @Test @@ -103,8 +103,8 @@ public void testExistHWC() { String classname = "test.A"; String notExistName = "test.B"; - Assertions.assertTrue(existsHandwrittenClass(new MCPath("src/test/resources/hwc"), classname)); - Assertions.assertFalse(existsHandwrittenClass(new MCPath("src/test/resources/hwc"), notExistName)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(existsHandwrittenClass(new MCPath("src/test/resources/hwc"), classname)); + assertFalse(existsHandwrittenClass(new MCPath("src/test/resources/hwc"), notExistName)); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/GlobalExtensionManagementGlobalVarsTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/GlobalExtensionManagementGlobalVarsTest.java index d3be5f9904..9dd1ade79f 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/GlobalExtensionManagementGlobalVarsTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/GlobalExtensionManagementGlobalVarsTest.java @@ -10,7 +10,6 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,8 +17,8 @@ import java.util.ArrayList; import static de.monticore.generating.templateengine.TestConstants.TEMPLATE_PACKAGE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link GlobalExtensionManagement}. @@ -47,7 +46,7 @@ public void setup() { config.setOutputDirectory(new File("dummy")); config.setTracing(false); tc = new TemplateControllerMock(config, ""); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @AfterAll @@ -61,19 +60,19 @@ public void testGlobalVars() { glex.defineGlobalVar("asd", new String("asd")); StringBuilder output = tc.include(TEMPLATE_PACKAGE + "GlobalVars"); - Assertions.assertEquals("testasd", output.toString().replaceAll("\\s+", "")); + assertEquals("testasd", output.toString().replaceAll("\\s+", "")); glex.changeGlobalVar("asd", new String("aaa")); output = tc.include(TEMPLATE_PACKAGE + "GlobalVars"); - Assertions.assertEquals("testaaa", output.toString().replaceAll("\\s+", "")); + assertEquals("testaaa", output.toString().replaceAll("\\s+", "")); glex.defineGlobalVar("liste", new ArrayList<>()); glex.addToGlobalVar("liste", new String("a")); glex.addToGlobalVar("liste", new String("b")); glex.addToGlobalVar("liste", new String("c")); output = tc.include(TEMPLATE_PACKAGE + "GlobalListVars"); - Assertions.assertEquals("abc", output.toString().replaceAll("\\s+", "")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("abc", output.toString().replaceAll("\\s+", "")); + assertTrue(Log.getFindings().isEmpty()); } @@ -87,8 +86,8 @@ public void testVariables4() { // override same variable String res = ge.generate(TEMPLATE_PACKAGE + "TestVariables4", ast).toString(); - Assertions.assertEquals("A:16B:38C:555", res.replaceAll("\\r\\n|\\r|\\n", "")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("A:16B:38C:555", res.replaceAll("\\r\\n|\\r|\\n", "")); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/ObjectFactoryTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/ObjectFactoryTest.java index 500b339b8f..d47a546f49 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/ObjectFactoryTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/ObjectFactoryTest.java @@ -7,10 +7,11 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class ObjectFactoryTest { @BeforeEach @@ -22,9 +23,9 @@ public void before() { @Test public void testInstanciationWithDefaultConstructor() { Object obj = ObjectFactory.createObject("java.lang.String"); - Assertions.assertNotNull(obj); - Assertions.assertEquals(String.class, obj.getClass()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertNotNull(obj); + assertEquals(String.class, obj.getClass()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -32,10 +33,10 @@ public void testInstanciationWithParams() { List params = new ArrayList(); params.add("myContent"); Object obj = ObjectFactory.createObject("java.lang.String", params); - Assertions.assertNotNull(obj); - Assertions.assertEquals(String.class, obj.getClass()); - Assertions.assertEquals(obj, "myContent"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertNotNull(obj); + assertEquals(String.class, obj.getClass()); + assertEquals(obj, "myContent"); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -51,10 +52,10 @@ public void testInstanciationWithTypesAndParams() { params.add(3); Object obj = ObjectFactory.createObject("java.lang.String", paramTypes, params); - Assertions.assertNotNull(obj); - Assertions.assertEquals(obj.getClass(), (new String()).getClass()); - Assertions.assertEquals(obj, "yes"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertNotNull(obj); + assertEquals(obj.getClass(), (new String()).getClass()); + assertEquals(obj, "yes"); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateAliasingTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateAliasingTest.java index 08b8793aea..1555eff0cb 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateAliasingTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateAliasingTest.java @@ -14,7 +14,6 @@ import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,6 +21,8 @@ import java.io.IOException; import java.util.*; +import static org.junit.jupiter.api.Assertions.*; + public class TemplateAliasingTest { private static final File TARGET_DIR = new File("target"); @@ -59,8 +60,8 @@ public static void resetFileReaderWriter() { public void testIncludeAlias() { StringBuilder templateOutput = tc.include(ALIASES_PACKAGE + "IncludeAlias"); - Assertions.assertEquals("Plain is included.", templateOutput.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("Plain is included.", templateOutput.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -69,14 +70,14 @@ public void testIncludeDispatching(){ StringBuilder templateOutput = tc.include(ALIASES_PACKAGE + "IncludeDispatching"); - Assertions.assertEquals("String argument\n" + + assertEquals("String argument\n" + "Plain is included.\n" + "Plain is included.\n" + "\n" + "List argument\n" + "Plain is included.Plain is included.\n" + "Plain is included.Plain is included.", templateOutput.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -84,8 +85,8 @@ public void testInclude2Alias() { String content = "Content of ast"; StringBuilder templateOutput = tc.include(ALIASES_PACKAGE + "Include2Alias", new AliasTestASTNodeMock(content)); - Assertions.assertEquals(content, templateOutput.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(content, templateOutput.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -93,8 +94,8 @@ public void testIncludeArgsAndSignatureAlias(){ StringBuilder templateOut = tc.include(ALIASES_PACKAGE + "IncludeArgsAndSignatureAlias"); - Assertions.assertEquals("Name is Charly, age is 30, city is Aachen", templateOut.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("Name is Charly, age is 30, city is Aachen", templateOut.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -102,8 +103,8 @@ public void testSignature(){ StringBuilder templateOut = tc.includeArgs(ALIASES_PACKAGE + "SignatureAliasWithThreeParameters", "Max Mustermann", "45", "Berlin"); - Assertions.assertEquals("Name is Max Mustermann, age is 45, city is Berlin", templateOut.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("Name is Max Mustermann, age is 45, city is Berlin", templateOut.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -117,7 +118,7 @@ public void testSimpleDefineHookPoint() throws IOException { StringBuilder templateOut = tc.includeArgs(templateName, ast, Collections.singletonList(alternativeAst)); - Assertions.assertEquals("/* generated by template de.monticore.generating.templateengine.templates.aliases.DefineHookPointAlias*/\n" + + assertEquals("/* generated by template de.monticore.generating.templateengine.templates.aliases.DefineHookPointAlias*/\n" + "/* Hookpoint: WithoutAst */\n" + "/* Hookpoint: WithAst */\n" + "/* Hookpoint: WithAlternativeAst */", templateOut.toString()); @@ -127,7 +128,7 @@ public void testSimpleDefineHookPoint() throws IOException { glex.bindHookPoint("WithoutAst", new StringHookPoint("a1")); templateOut = tc.includeArgs(templateName, ast, Collections.singletonList(alternativeAst)); - Assertions.assertEquals("/* generated by template de.monticore.generating.templateengine.templates.aliases.DefineHookPointAlias*/\n" + + assertEquals("/* generated by template de.monticore.generating.templateengine.templates.aliases.DefineHookPointAlias*/\n" + "a1\n" + "/* Hookpoint: WithAst */\n" + "/* Hookpoint: WithAlternativeAst */", templateOut.toString()); @@ -136,7 +137,7 @@ public void testSimpleDefineHookPoint() throws IOException { glex.bindHookPoint("WithAst", new TemplateStringHookPoint("${ast.content}")); templateOut = tc.includeArgs(templateName, ast, Collections.singletonList(alternativeAst)); - Assertions.assertEquals("/* generated by template de.monticore.generating.templateengine.templates.aliases.DefineHookPointAlias*/\n" + + assertEquals("/* generated by template de.monticore.generating.templateengine.templates.aliases.DefineHookPointAlias*/\n" + "a1\n" + "/* generated by template template*/\n" + "c1\n" + @@ -146,10 +147,10 @@ public void testSimpleDefineHookPoint() throws IOException { glex.bindHookPoint("WithAlternativeAst", new TemplateStringHookPoint("${ast.content}")); templateOut = tc.includeArgs(templateName, ast, Collections.singletonList(alternativeAst)); - Assertions.assertEquals("a1\n" + + assertEquals("a1\n" + "c1\n" + "c2", templateOut.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -161,7 +162,7 @@ public void testDefineHookPointWithDefaultAlias() throws IOException { StringBuilder templateOut = tc.includeArgs(templateName, ast, Collections.singletonList(alternativeAst)); - Assertions.assertEquals("default text 1\n" + + assertEquals("default text 1\n" + "default text 2\n" + "default text 3", templateOut.toString().replaceAll("\r", "")); @@ -170,7 +171,7 @@ public void testDefineHookPointWithDefaultAlias() throws IOException { glex.bindHookPoint("WithoutAst", new StringHookPoint("a1")); templateOut = tc.includeArgs(templateName, ast, Collections.singletonList(alternativeAst)); - Assertions.assertEquals("a1\n" + + assertEquals("a1\n" + "default text 2\n" + "default text 3", templateOut.toString().replaceAll("\r", "")); @@ -178,17 +179,17 @@ public void testDefineHookPointWithDefaultAlias() throws IOException { glex.bindHookPoint("WithAst", new TemplateStringHookPoint("${ast.content}")); templateOut = tc.includeArgs(templateName, ast, Collections.singletonList(alternativeAst)); - Assertions.assertEquals("a1\n" + + assertEquals("a1\n" + "c1\n" + "default text 3", templateOut.toString().replaceAll("\r", "")); glex.bindHookPoint("WithAlternativeAst", new TemplateStringHookPoint("${ast.content}")); templateOut = tc.includeArgs(templateName, ast, Collections.singletonList(alternativeAst)); - Assertions.assertEquals("a1\n" + + assertEquals("a1\n" + "c1\n" + "c2", templateOut.toString().replaceAll("\r", "")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -203,12 +204,12 @@ public void testBindHookPointAlias(){ StringBuilder templateOut = tc.includeArgs(templateName, ast, Arrays.asList(alternativeAst)); - Assertions.assertEquals("/* generated by template de.monticore.generating.templateengine.templates.aliases.BindHookPointAlias*/\n" + + assertEquals("/* generated by template de.monticore.generating.templateengine.templates.aliases.BindHookPointAlias*/\n" + "/* generated by template de.monticore.generating.templateengine.templates.aliases.DefineHookPointAlias*/\n" + "bound\n" + "/* Hookpoint: WithAst */\n" + "/* Hookpoint: WithAlternativeAst */", templateOut.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -222,14 +223,14 @@ public void testRequiredGlobalVarValid() { glex.getGlobalData().remove("a"); } - Assertions.assertTrue(LogStub.getPrints().isEmpty(), "Log not empty!\n" + LogStub.getPrints()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(LogStub.getPrints().isEmpty(), "Log not empty!\n" + LogStub.getPrints()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRequiredGlobalVarInvalid() { tc.include(ALIASES_PACKAGE + "RequiredGlobalVarAlias"); - Assertions.assertFalse(LogStub.getPrints().isEmpty(), "Log is empty but error was expected!"); + assertFalse(LogStub.getPrints().isEmpty(), "Log is empty but error was expected!"); } @@ -248,8 +249,8 @@ public void testRequiredGlobalVarsValid() { glex.getGlobalData().remove("c"); } - Assertions.assertTrue(LogStub.getPrints().isEmpty(), "Log not empty!\n" + LogStub.getPrints()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(LogStub.getPrints().isEmpty(), "Log not empty!\n" + LogStub.getPrints()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -257,12 +258,12 @@ public void testRequiredGlobalVarsInvalid() { StringBuilder templateOut = tc.include(ALIASES_PACKAGE + "RequiredGlobalVarsAlias"); - Assertions.assertFalse(LogStub.getPrints().isEmpty(), "Log empty, expected error"); + assertFalse(LogStub.getPrints().isEmpty(), "Log empty, expected error"); } @Test public void testLogAliases() { - Assertions.assertTrue(config.getAliases().isEmpty()); + assertTrue(config.getAliases().isEmpty()); tc.include(ALIASES_PACKAGE + "LogAliases"); assertAliases(tc, NUMBER_ALIASES); @@ -272,7 +273,7 @@ public void testLogAliases() { "Error Message" ); - Assertions.assertEquals(3, LogStub.getPrints().size()); + assertEquals(3, LogStub.getPrints().size()); assertErrors(expectedLogs, LogStub.getPrints()); } @@ -282,24 +283,24 @@ public void testLogAliases() { public void testExistsHookPoint(){ StringBuilder templateOut = tc.include(ALIASES_PACKAGE + "ExistsHookPointAlias"); - Assertions.assertEquals("false\nfalse", templateOut.toString()); + assertEquals("false\nfalse", templateOut.toString()); config.getGlex().bindHookPoint("hp1", new StringHookPoint("a")); templateOut = tc.include(ALIASES_PACKAGE + "ExistsHookPointAlias"); - Assertions.assertEquals("true\nfalse", templateOut.toString()); + assertEquals("true\nfalse", templateOut.toString()); config.getGlex().bindHookPoint("hp2", new StringHookPoint("a")); templateOut = tc.include(ALIASES_PACKAGE + "ExistsHookPointAlias"); - Assertions.assertEquals("true\ntrue", templateOut.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("true\ntrue", templateOut.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAddToGlobalVarsAliasUndefinedVariable(){ tc.include(ALIASES_PACKAGE + "AddToGlobalVarAlias"); - Assertions.assertTrue(LogStub.getPrints().stream().anyMatch(s -> s.contains("0xA8124"))); + assertTrue(LogStub.getPrints().stream().anyMatch(s -> s.contains("0xA8124"))); } @Test @@ -310,18 +311,18 @@ public void testAddToGlobalVarsAliasValid(){ tc.include(ALIASES_PACKAGE + "AddToGlobalVarAlias"); - Assertions.assertTrue(LogStub.getPrints().isEmpty()); + assertTrue(LogStub.getPrints().isEmpty()); List aList = (List) glex.getGlobalVar("a"); List bList = (List) glex.getGlobalVar("b"); - Assertions.assertEquals(2, aList.size()); - Assertions.assertEquals(1, bList.size()); + assertEquals(2, aList.size()); + assertEquals(1, bList.size()); - Assertions.assertEquals("item 1", aList.get(0)); - Assertions.assertEquals("item 2", aList.get(1)); - Assertions.assertEquals("item 3", bList.get(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("item 1", aList.get(0)); + assertEquals("item 2", aList.get(1)); + assertEquals("item 3", bList.get(0)); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -331,8 +332,8 @@ public void testChangeGlobalVarAlias(){ tc.include(ALIASES_PACKAGE + "ChangeGlobalVarAlias"); - Assertions.assertEquals("changed", glex.getGlobalVar("a")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("changed", glex.getGlobalVar("a")); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -343,8 +344,8 @@ public void testDefineGlobalVarAliasValid(){ glex.requiredGlobalVar("a"); - Assertions.assertTrue(LogStub.getPrints().isEmpty(), "Log is not empty, messages: " + LogStub.getPrints()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(LogStub.getPrints().isEmpty(), "Log is not empty, messages: " + LogStub.getPrints()); + assertTrue(Log.getFindings().isEmpty()); } @@ -354,7 +355,7 @@ public void testDefineGlobalVarAliasExistsAlready(){ glex.defineGlobalVar("a", "?"); tc.include(ALIASES_PACKAGE + "DefineGlobalVarAlias"); - Assertions.assertFalse(LogStub.getPrints().isEmpty()); + assertFalse(LogStub.getPrints().isEmpty()); } @Test @@ -364,9 +365,9 @@ public void testGetGlobalVarAliasValid(){ StringBuilder templateOut = tc.include(ALIASES_PACKAGE + "GetGlobalVarAlias"); - Assertions.assertEquals("value", templateOut.toString()); - Assertions.assertTrue(LogStub.getPrints().isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("value", templateOut.toString()); + assertTrue(LogStub.getPrints().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -374,8 +375,8 @@ public void testGetGlobalVarAliasInvalid(){ StringBuilder templateOut = tc.include(ALIASES_PACKAGE + "GetGlobalVarAlias"); - Assertions.assertEquals("unset", templateOut.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("unset", templateOut.toString()); + assertTrue(Log.getFindings().isEmpty()); } @@ -392,15 +393,15 @@ private static void assertErrors(Collection expectedErrors, String actualErrorsJoined = "\nactual Errors: \n\t" + Joiner.on("\n\t").join(actualErrors); for (String expectedError : expectedErrors) { boolean found = actualErrors.stream().filter(s -> s.contains(expectedError)).count() >= 1; - Assertions.assertTrue(found, "The following expected error was not found: " + expectedError + assertTrue(found, "The following expected error was not found: " + expectedError + actualErrorsJoined); } } private void assertAliases(TemplateController tc, int expectedNumberAliases) { List aliases = config.getAliases(); - Assertions.assertNotNull(aliases); - Assertions.assertEquals(expectedNumberAliases, aliases.size()); + assertNotNull(aliases); + assertEquals(expectedNumberAliases, aliases.size()); } public static class AliasTestASTNodeMock extends ASTCNode { diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerHookPointsTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerHookPointsTest.java index 735b737307..7d5ce22051 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerHookPointsTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerHookPointsTest.java @@ -3,6 +3,7 @@ package de.monticore.generating.templateengine; import static de.monticore.generating.templateengine.TestConstants.TEMPLATE_PACKAGE; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.io.IOException; @@ -15,7 +16,6 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -58,8 +58,8 @@ public static void resetFileReaderWriter() { @Test public void testUndefinedHook() { tc.getGeneratorSetup().setTracing(true); - Assertions.assertEquals("/* Hookpoint: hp1 */", glex.defineHookPoint(tc, "hp1")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("/* Hookpoint: hp1 */", glex.defineHookPoint(tc, "hp1")); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -67,11 +67,11 @@ public void testDefaultHook() { tc.getGeneratorSetup().setTracing(false); String hpValue; hpValue = glex.defineHookPointWithDefault(tc, "hp1", "default"); - Assertions.assertEquals("default", hpValue); + assertEquals("default", hpValue); glex.bindHookPoint("hp1", new StringHookPoint("value of hp1")); hpValue = glex.defineHookPointWithDefault(tc, "hp1", "default"); - Assertions.assertEquals("value of hp1", hpValue); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("value of hp1", hpValue); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -82,22 +82,22 @@ public void testSetStringHook() { // define new hook point hp1 glex.bindHookPoint("hp1", new StringHookPoint("value of hp1")); hpValue = glex.defineHookPoint(tc, "hp1"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("value of hp1", hpValue); + assertNotNull(hpValue); + assertEquals("value of hp1", hpValue); // overwrite value of hook point hp1 glex.bindHookPoint("hp1", new StringHookPoint("new value of hp1")); hpValue = glex.defineHookPoint(tc, "hp1"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("new value of hp1", hpValue); + assertNotNull(hpValue); + assertEquals("new value of hp1", hpValue); // define new hook point hp2 glex.bindHookPoint("hp2", new StringHookPoint("value of hp2")); hpValue = glex.defineHookPoint(tc, "hp2"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("value of hp2", hpValue); + assertNotNull(hpValue); + assertEquals("value of hp2", hpValue); // hp1 still exists - Assertions.assertEquals("new value of hp1", glex.defineHookPoint(tc, "hp1")); + assertEquals("new value of hp1", glex.defineHookPoint(tc, "hp1")); } @@ -108,22 +108,22 @@ public void testSetTemplateHook() { // define new hook point hp1 glex.bindHookPoint("hp1", new TemplateHookPoint(TEMPLATE_PACKAGE + "HelloWorld")); hpValue = glex.defineHookPoint(tc, "hp1"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("Hello World!", hpValue); + assertNotNull(hpValue); + assertEquals("Hello World!", hpValue); // overwrite value of hook point hp1 glex.bindHookPoint("hp1", new TemplateHookPoint(TEMPLATE_PACKAGE + "HowAreYou")); hpValue = glex.defineHookPoint(tc, "hp1"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("How Are You?", hpValue); + assertNotNull(hpValue); + assertEquals("How Are You?", hpValue); // define new hook point hp2 glex.bindHookPoint("hp2", new TemplateHookPoint(TEMPLATE_PACKAGE + "HelloWorld")); hpValue = glex.defineHookPoint(tc, "hp2"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("Hello World!", hpValue); + assertNotNull(hpValue); + assertEquals("Hello World!", hpValue); // hp1 still exists - Assertions.assertEquals("How Are You?", glex.defineHookPoint(tc, "hp1")); + assertEquals("How Are You?", glex.defineHookPoint(tc, "hp1")); } @Test @@ -134,24 +134,24 @@ public void testSetCodeHook() { CodeHookPointMock command = new CodeHookPointMock("command1"); glex.bindHookPoint("hp1", command); hpValue = glex.defineHookPoint(tc, "hp1"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("command1", hpValue); + assertNotNull(hpValue); + assertEquals("command1", hpValue); // overwrite value of hook point hp1 command = new CodeHookPointMock("command2"); glex.bindHookPoint("hp1", command); hpValue = glex.defineHookPoint(tc, "hp1"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("command2", hpValue); + assertNotNull(hpValue); + assertEquals("command2", hpValue); // overwrite value of hook point hp1 command = new CodeHookPointMock("command3"); glex.bindHookPoint("hp2", command); hpValue = glex.defineHookPoint(tc, "hp2"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("command3", hpValue); + assertNotNull(hpValue); + assertEquals("command3", hpValue); // hp1 still exists - Assertions.assertEquals("command2", glex.defineHookPoint(tc, "hp1")); + assertEquals("command2", glex.defineHookPoint(tc, "hp1")); } @Test @@ -159,51 +159,51 @@ public void testStringTemplateCodeHookCombinations() { final String hp = "hp"; glex.bindHookPoint(hp, new StringHookPoint("StringHook")); - Assertions.assertEquals("StringHook", glex.defineHookPoint(tc, hp)); + assertEquals("StringHook", glex.defineHookPoint(tc, hp)); glex.bindHookPoint(hp, new TemplateHookPoint(TEMPLATE_PACKAGE + "A")); - Assertions.assertEquals("A", glex.defineHookPoint(tc, hp)); + assertEquals("A", glex.defineHookPoint(tc, hp)); CodeHookPointMock command = new CodeHookPointMock("command"); glex.bindHookPoint(hp, command); - Assertions.assertEquals("command", glex.defineHookPoint(tc, hp)); + assertEquals("command", glex.defineHookPoint(tc, hp)); glex.bindHookPoint(hp, new TemplateHookPoint(TEMPLATE_PACKAGE + "A")); - Assertions.assertEquals("A", glex.defineHookPoint(tc, hp)); + assertEquals("A", glex.defineHookPoint(tc, hp)); glex.bindHookPoint(hp, new StringHookPoint("StringHook")); - Assertions.assertEquals("StringHook", glex.defineHookPoint(tc, hp)); + assertEquals("StringHook", glex.defineHookPoint(tc, hp)); } @Test public void testStringHookInSubtemplate() { - Assertions.assertEquals("TopStringHook Hello Brave New World!", tc.include(TEMPLATE_PACKAGE + "TopStringHook").toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("TopStringHook Hello Brave New World!", tc.include(TEMPLATE_PACKAGE + "TopStringHook").toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testTemplateHookInSubtemplate() { - Assertions.assertEquals("TopTemplateHook A", tc.include(TEMPLATE_PACKAGE + "TopTemplateHook").toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("TopTemplateHook A", tc.include(TEMPLATE_PACKAGE + "TopTemplateHook").toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBeforeTemplates() { - Assertions.assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A").toString()); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("BA", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("BA", tc.include(TEMPLATE_PACKAGE + "A").toString()); // previously set template is overwritten glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A").toString()); // pass a list of templates glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", Arrays.asList( new TemplateHookPoint(TEMPLATE_PACKAGE + "B"), new TemplateHookPoint(TEMPLATE_PACKAGE + "C"))); - Assertions.assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A").toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -211,21 +211,21 @@ public void testSpecificBeforeTemplates() { ASTNode ast1 = new ASTNodeMock(); ASTNode ast2 = new ASTNodeMock(); - Assertions.assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("BA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); - Assertions.assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A", ast2).toString()); + assertEquals("BA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A", ast2).toString()); // previously set template is overwritten glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); - Assertions.assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A", ast2).toString()); + assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A", ast2).toString()); // add a new template glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("CBA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); - Assertions.assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A", ast2).toString()); + assertEquals("CBA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A", ast2).toString()); } @@ -236,7 +236,7 @@ public void testOrderOfBeforeTemplates() { // Add specific template glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -245,7 +245,7 @@ public void testOrderOfBeforeTemplates() { // set specific template glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -254,7 +254,7 @@ public void testOrderOfBeforeTemplates() { // Add general template glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A").toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -263,7 +263,7 @@ public void testOrderOfBeforeTemplates() { // set general template glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A").toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -272,7 +272,7 @@ public void testOrderOfBeforeTemplates() { // Add and set specific template glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -281,7 +281,7 @@ public void testOrderOfBeforeTemplates() { // Set and add specific template glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -290,7 +290,7 @@ public void testOrderOfBeforeTemplates() { // Add and set general template glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("CA", tc.include(TEMPLATE_PACKAGE + "A").toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -299,7 +299,7 @@ public void testOrderOfBeforeTemplates() { // Set and add general template glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A").toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -308,7 +308,7 @@ public void testOrderOfBeforeTemplates() { // Add specific and general template glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -317,17 +317,17 @@ public void testOrderOfBeforeTemplates() { // Add general and specific template glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("CBA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("CBA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Set specific and general template glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("BCA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Set general and specific template glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("CBA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("CBA", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); } @Test @@ -337,7 +337,7 @@ public void testOrderOfAfterTemplates() { // Add specific template glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -346,7 +346,7 @@ public void testOrderOfAfterTemplates() { // set specific template glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -355,7 +355,7 @@ public void testOrderOfAfterTemplates() { // Add general template glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A").toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -364,7 +364,7 @@ public void testOrderOfAfterTemplates() { // set general template glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A").toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -373,7 +373,7 @@ public void testOrderOfAfterTemplates() { // Add and set specific template glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -382,7 +382,7 @@ public void testOrderOfAfterTemplates() { // Set and add specific template glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -391,7 +391,7 @@ public void testOrderOfAfterTemplates() { // Add and set general template glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A").toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -400,7 +400,7 @@ public void testOrderOfAfterTemplates() { // Set and add general template glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A").toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -409,7 +409,7 @@ public void testOrderOfAfterTemplates() { // Add specific and general template glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Reset glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, Lists.newArrayList()); @@ -418,131 +418,131 @@ public void testOrderOfAfterTemplates() { // Add general and specific template glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ACB", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("ACB", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Set specific and general template glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); // Set general and specific template glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ACB", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); + assertEquals("ACB", tc.include(TEMPLATE_PACKAGE + "A", ast1).toString()); } @Test public void testAfterTemplates() { - Assertions.assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A").toString()); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("AB", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("AB", tc.include(TEMPLATE_PACKAGE + "A").toString()); // previously set template is overwritten glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("AC", tc.include(TEMPLATE_PACKAGE + "A").toString()); // pass a list of templates glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", Arrays.asList( new TemplateHookPoint(TEMPLATE_PACKAGE + "B"), new TemplateHookPoint(TEMPLATE_PACKAGE + "C"))); - Assertions.assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A").toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAddAfterTemplates() { - Assertions.assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A").toString()); glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("AB", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("AB", tc.include(TEMPLATE_PACKAGE + "A").toString()); // previously set template is not overwritten glex.addAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("ABC", tc.include(TEMPLATE_PACKAGE + "A").toString()); } @Test public void testReplaceTemplate() { StringBuilder r = tc.include(TEMPLATE_PACKAGE + "A"); - Assertions.assertEquals("A", r.toString()); + assertEquals("A", r.toString()); // self-replacement glex.replaceTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "A")); r = tc.include(TEMPLATE_PACKAGE + "A"); - Assertions.assertEquals("A", r.toString()); + assertEquals("A", r.toString()); glex.replaceTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); r = tc.include(TEMPLATE_PACKAGE + "A"); - Assertions.assertEquals("B", r.toString()); + assertEquals("B", r.toString()); // previously set template is overwritten glex.replaceTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); r = tc.include(TEMPLATE_PACKAGE + "A"); - Assertions.assertEquals("C", r.toString()); + assertEquals("C", r.toString()); // pass a list of templates glex.replaceTemplate(TEMPLATE_PACKAGE + "A", Arrays.asList( new TemplateHookPoint(TEMPLATE_PACKAGE + "B"), new TemplateHookPoint(TEMPLATE_PACKAGE + "C"))); r = tc.include(TEMPLATE_PACKAGE + "A"); - Assertions.assertEquals("BC", r.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("BC", r.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBeforeReplaceAfterCombinations() { - Assertions.assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("A", tc.include(TEMPLATE_PACKAGE + "A").toString()); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("BA", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("BA", tc.include(TEMPLATE_PACKAGE + "A").toString()); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BAC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("BAC", tc.include(TEMPLATE_PACKAGE + "A").toString()); glex.replaceTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BCC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("BCC", tc.include(TEMPLATE_PACKAGE + "A").toString()); glex.replaceTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("BBC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertEquals("BBC", tc.include(TEMPLATE_PACKAGE + "A").toString()); // replacing B has no effect on A glex.replaceTemplate(TEMPLATE_PACKAGE + "B", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("BBC", tc.include(TEMPLATE_PACKAGE + "A").toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("BBC", tc.include(TEMPLATE_PACKAGE + "A").toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBeforeReplaceAfterInSubtemplates() { - Assertions.assertEquals("TopA A", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); + assertEquals("TopA A", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("TopA BA", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); + assertEquals("TopA BA", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); glex.replaceTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("TopA BC", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); + assertEquals("TopA BC", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("TopA BCB", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("TopA BCB", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSpecificBeforeReplaceAfterInSubtemplates() { ASTNode ast1 = new ASTNodeMock(); - Assertions.assertEquals("TopA A", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); + assertEquals("TopA A", tc.include(TEMPLATE_PACKAGE + "TopA").toString()); glex.setBeforeTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("TopA BA", tc.include(TEMPLATE_PACKAGE + "TopA", ast1).toString()); + assertEquals("TopA BA", tc.include(TEMPLATE_PACKAGE + "TopA", ast1).toString()); glex.replaceTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "C")); - Assertions.assertEquals("TopA BC", tc.include(TEMPLATE_PACKAGE + "TopA", ast1).toString()); + assertEquals("TopA BC", tc.include(TEMPLATE_PACKAGE + "TopA", ast1).toString()); glex.setAfterTemplate(TEMPLATE_PACKAGE + "A", ast1, new TemplateHookPoint(TEMPLATE_PACKAGE + "B")); - Assertions.assertEquals("TopA BCB", tc.include(TEMPLATE_PACKAGE + "TopA", ast1).toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("TopA BCB", tc.include(TEMPLATE_PACKAGE + "TopA", ast1).toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -550,20 +550,20 @@ public void testTemplateStringHook() throws IOException{ // define new hook point hp1 glex.bindHookPoint("hp1", new TemplateStringHookPoint("<#if true>true")); String hpValue = glex.defineHookPoint(tc, "hp1"); - Assertions.assertNotNull(hpValue); - Assertions.assertEquals("true", hpValue); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertNotNull(hpValue); + assertEquals("true", hpValue); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDefineHookPointWithArgs() { glex.bindHookPoint("hp1", new TemplateHookPoint(TEMPLATE_PACKAGE + "SignatureWithOneParameter")); String hpValue = glex.defineHookPoint(tc, "hp1", "A"); - Assertions.assertEquals("Name is A", hpValue); + assertEquals("Name is A", hpValue); glex.bindHookPoint("hp1", new TemplateHookPoint(TEMPLATE_PACKAGE + "SignatureWithThreeParameters")); hpValue = glex.defineHookPoint(tc, "hp1", "B", 42, "LA"); - Assertions.assertEquals("Name is B, age is 42, city is LA", hpValue); + assertEquals("Name is B, age is 42, city is LA", hpValue); } @Test @@ -572,11 +572,11 @@ public void testBeforeHookpoint() { // without binding glex.setBeforeTemplate( "hp", ast1, new StringHookPoint("Before Hookpoint")); - Assertions.assertEquals("Before Hookpoint", tc.include(TEMPLATE_PACKAGE + "HookCall", ast1).toString()); + assertEquals("Before Hookpoint", tc.include(TEMPLATE_PACKAGE + "HookCall", ast1).toString()); // with binding glex.bindHookPoint("hp", new StringHookPoint(":Bind Hookpoint")); - Assertions.assertEquals("Before Hookpoint:Bind Hookpoint", tc.include(TEMPLATE_PACKAGE + "HookCall", ast1).toString()); + assertEquals("Before Hookpoint:Bind Hookpoint", tc.include(TEMPLATE_PACKAGE + "HookCall", ast1).toString()); } @@ -585,7 +585,7 @@ public void testAfterHookpoint() { ASTNode ast1 = new ASTNodeMock(); glex.setAfterTemplate( "hp", ast1, new StringHookPoint("After Hookpoint")); - Assertions.assertEquals("After Hookpoint", tc.include(TEMPLATE_PACKAGE + "HookCall", ast1).toString()); + assertEquals("After Hookpoint", tc.include(TEMPLATE_PACKAGE + "HookCall", ast1).toString()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerSignatureUsageTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerSignatureUsageTest.java index e61a108c7f..bd23f7da18 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerSignatureUsageTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerSignatureUsageTest.java @@ -3,10 +3,7 @@ package de.monticore.generating.templateengine; import static de.monticore.generating.templateengine.TestConstants.TEMPLATE_PACKAGE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; @@ -20,7 +17,6 @@ import de.monticore.generating.templateengine.freemarker.MontiCoreFreeMarkerException; import de.monticore.io.FileReaderWriterMock; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -67,8 +63,8 @@ public static void resetFileReaderWriter() { public void testSignatureWithOneParameter() { StringBuilder output = tc.includeArgs(TEMPLATE_PACKAGE + "SignatureWithOneParameter", Lists.newArrayList("Charly")); - Assertions.assertTrue(Log.getFindings().isEmpty()); - Assertions.assertEquals("Name is Charly", output.toString()); + assertTrue(Log.getFindings().isEmpty()); + assertEquals("Name is Charly", output.toString()); } @Test @@ -76,8 +72,8 @@ public void testSignatureWithThreeParameters() { StringBuilder output = tc.includeArgs(TEMPLATE_PACKAGE + "SignatureWithThreeParameters", Lists.newArrayList("Charly", "30", "Aachen")); - Assertions.assertEquals("Name is Charly, age is 30, city is Aachen", output.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("Name is Charly, age is 30, city is Aachen", output.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -85,8 +81,8 @@ public void testSignatureWithManyParameters() { StringBuilder output = tc.includeArgs(TEMPLATE_PACKAGE + "SignatureWithManyParameters", Lists.newArrayList("Charly", "30", "Aachen", "52062", "Engineer", "No friends")); - Assertions.assertEquals("Name=Charly, age=30, city=Aachen, zip=52062, job=Engineer, friends=No friends", output.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("Name=Charly, age=30, city=Aachen, zip=52062, job=Engineer, friends=No friends", output.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -94,8 +90,8 @@ public void testNestedSignatureCalls() { StringBuilder output = tc.includeArgs(TEMPLATE_PACKAGE + "NestedSignatureCalls", Lists.newArrayList("T1")); - Assertions.assertEquals("T1 -> Name is T2", output.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("T1 -> Name is T2", output.toString()); + assertTrue(Log.getFindings().isEmpty()); } @@ -104,11 +100,11 @@ public void testWrongNumberOfArguments() { try { tc.includeArgs(TEMPLATE_PACKAGE + "SignatureWithOneParameter", Lists.newArrayList("Charly", "tooMuch")); - Assertions.fail("Argument list is too long."); + fail("Argument list is too long."); } catch (MontiCoreFreeMarkerException e) { - Assertions.assertTrue(e.getCause() instanceof IllegalArgumentException); + assertTrue(e.getCause() instanceof IllegalArgumentException); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Disabled @@ -117,8 +113,8 @@ public void testArgumentsAreOnlyVisibleInIncludedTemplate() { StringBuilder templateOutput = tc.includeArgs(TEMPLATE_PACKAGE + "ArgumentsAreOnlyVisibleInIncludedTemplate", Lists.newArrayList("Charly")); - Assertions.assertEquals("Hello Charly\nSorry, what was your name?", templateOutput.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("Hello Charly\nSorry, what was your name?", templateOutput.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -126,9 +122,9 @@ public void testArgumentsAreOnlyVisibleInIncludedTemplate() { public void testParameterizedInclusionUsage() { StringBuilder templateOutput = tc.include(TEMPLATE_PACKAGE + "ParameterizedInclusionUsage"); - Assertions.assertEquals("Name is Charly\n" + + assertEquals("Name is Charly\n" + "Name is Charly, age is 30, city is Aachen\n" + "Name=Charly, age=30, city=Aachen, zip=52062, job=Engineer, friends=No friends", templateOutput.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } \ No newline at end of file diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerTest.java index fe6b043150..751a9b1079 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateControllerTest.java @@ -13,7 +13,6 @@ import de.se_rwth.commons.logging.LogStub; import freemarker.template.Template; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -26,6 +25,7 @@ import java.util.List; import static de.monticore.generating.templateengine.TestConstants.TEMPLATE_PACKAGE; +import static org.junit.jupiter.api.Assertions.*; /** * Tests for {@link TemplateController}. @@ -73,17 +73,17 @@ public static void resetFileReaderWriter() { @Disabled @Test public void testImplicitAstPassing() { - Assertions.assertNull(tc.getAST()); + assertNull(tc.getAST()); tc.include(TEMPLATE_PACKAGE + "A"); - Assertions.assertNull(tc.getAST()); + assertNull(tc.getAST()); // pass ast explicit tc.include(TEMPLATE_PACKAGE + "A", ASTNodeMock.INSTANCE); - Assertions.assertNotNull(tc.getAST()); - Assertions.assertSame(ASTNodeMock.INSTANCE, tc.getAST()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertNotNull(tc.getAST()); + assertSame(ASTNodeMock.INSTANCE, tc.getAST()); + assertTrue(Log.getFindings().isEmpty()); } @@ -92,19 +92,19 @@ public void testWriteArgs() { String TEMPLATE_NAME = "the.Template"; tc.writeArgs(TEMPLATE_NAME, "path.to.file", ".ext", ASTNodeMock.INSTANCE, new ArrayList<>()); - Assertions.assertEquals(1, freeMarkerTemplateEngine.getProcessedTemplates().size()); + assertEquals(1, freeMarkerTemplateEngine.getProcessedTemplates().size()); FreeMarkerTemplateMock template = freeMarkerTemplateEngine.getProcessedTemplates().iterator() .next(); - Assertions.assertTrue(template.isProcessed()); - Assertions.assertEquals(TEMPLATE_NAME, template.getName()); - Assertions.assertNotNull(template.getData()); + assertTrue(template.isProcessed()); + assertEquals(TEMPLATE_NAME, template.getName()); + assertNotNull(template.getData()); - Assertions.assertEquals(1, fileHandler.getStoredFilesAndContents().size()); + assertEquals(1, fileHandler.getStoredFilesAndContents().size()); Path writtenFilePath = Paths.get(TARGET_DIR.getAbsolutePath(), "path/to/file.ext"); - Assertions.assertTrue(fileHandler.getStoredFilesAndContents().containsKey(writtenFilePath)); - Assertions.assertEquals("Content of template: " + TEMPLATE_NAME, fileHandler.getContentForFile(writtenFilePath.toString()).get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(fileHandler.getStoredFilesAndContents().containsKey(writtenFilePath)); + assertEquals("Content of template: " + TEMPLATE_NAME, fileHandler.getContentForFile(writtenFilePath.toString()).get()); + assertTrue(Log.getFindings().isEmpty()); } @@ -123,10 +123,10 @@ public void testDefaultMethods() { DefaultImpl def = new DefaultImpl(); StringBuilder result = tc .includeArgs(TEMPLATE_PACKAGE + "DefaultMethodCall", Lists.newArrayList(def)); - Assertions.assertNotNull(result); - Assertions.assertEquals("A", result.toString().trim()); + assertNotNull(result); + assertEquals("A", result.toString().trim()); FileReaderWriter.init(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -150,11 +150,11 @@ public void testBlacklisteTemplatesI() throws IOException { // configure Template Controller with black list tc.setTemplateBlackList(blackList); - Assertions.assertEquals(1, tc.getTemplateBlackList().size()); - Assertions.assertFalse(tc.isTemplateNoteGenerated(templateI)); - Assertions.assertTrue(tc.isTemplateNoteGenerated(templateII)); + assertEquals(1, tc.getTemplateBlackList().size()); + assertFalse(tc.isTemplateNoteGenerated(templateI)); + assertTrue(tc.isTemplateNoteGenerated(templateII)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -176,10 +176,10 @@ public void testBlacklistTemplatesII() throws IOException { Template templateII = new Template(templateNameII, "", null); - Assertions.assertEquals(1, tc.getTemplateBlackList().size()); - Assertions.assertFalse(tc.isTemplateNoteGenerated(templateI)); - Assertions.assertTrue(tc.isTemplateNoteGenerated(templateII)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(1, tc.getTemplateBlackList().size()); + assertFalse(tc.isTemplateNoteGenerated(templateI)); + assertTrue(tc.isTemplateNoteGenerated(templateII)); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -189,7 +189,7 @@ public void testIncludeArgsDoesNotOverrideParameters() { String result = controller.includeArgs("de.monticore.generating.templateengine.IncludeArgsDoesntOverride1", "a", "b").toString(); - Assertions.assertEquals("aba", result.strip() + assertEquals("aba", result.strip() .replaceAll("\n", "") .replaceAll(" ", "") .replaceAll("/\\*(.)*?\\*/", "")); @@ -207,7 +207,7 @@ public void testParametersOfOuterTemplateNotVisible() { "OuterParametersNotVisible1", "A"); } catch (MontiCoreFreeMarkerException e) { - Assertions.assertTrue(e.getMessage().contains( + assertTrue(e.getMessage().contains( "The following has evaluated to null or missing:\n==> A [in " + "template \"de.monticore.generating.templateengine." + "OuterParametersNotVisible2\" at line 2, column 3]")); @@ -228,7 +228,7 @@ public void testInnerParametersNotVisible() { "A"); } catch (MontiCoreFreeMarkerException e) { - Assertions.assertTrue(e.getMessage().contains("The following has evaluated to " + + assertTrue(e.getMessage().contains("The following has evaluated to " + "null or missing:\n==> B [in template \"de.monticore.generating." + "templateengine.InnerParametersNotVisible1\" at line 4, column 3]")); } diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateLoggerTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateLoggerTest.java index 68c4bb7d54..89f6861438 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateLoggerTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/TemplateLoggerTest.java @@ -3,6 +3,8 @@ package de.monticore.generating.templateengine; import static de.monticore.generating.templateengine.TestConstants.TEMPLATE_PACKAGE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; @@ -10,7 +12,6 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import de.monticore.generating.GeneratorSetup; @@ -70,8 +71,8 @@ public static void resetFileReaderWriter() { @Test public void demonstrateTemplateLogging() { StringBuilder result = tc.include(TEMPLATE_PACKAGE + "Log"); - Assertions.assertNotNull(result); - Assertions.assertEquals("A", result.toString().trim()); + assertNotNull(result); + assertEquals("A", result.toString().trim()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/reporting/commons/ReportingStringHelperTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/reporting/commons/ReportingStringHelperTest.java index 5a50816ba8..c9c2a8ba73 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/reporting/commons/ReportingStringHelperTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/reporting/commons/ReportingStringHelperTest.java @@ -3,12 +3,13 @@ package de.monticore.generating.templateengine.reporting.commons; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.*; + public class ReportingStringHelperTest { @BeforeEach @@ -19,25 +20,25 @@ public void before() { @Test public void testReportingStringHelper() { - Assertions.assertFalse(ReportingHelper + assertFalse(ReportingHelper .formatStringToReportingString( "{this.height \n\t= builder.getHeight();this.width = builder.getWidth();addAllPhotoMessages(builder.getPhotoMessages());addAllTags(builder.getTags());}", 60).contains("\t")); - Assertions.assertEquals(60, ReportingHelper + assertEquals(60, ReportingHelper .formatStringToReportingString( "{this.height \n\t= builder.getHeight();this.width = builder.getWidth();addAllPhotoMessages(builder.getPhotoMessages());addAllTags(builder.getTags());}", 60).length()); - Assertions.assertEquals(6, ReportingHelper + assertEquals(6, ReportingHelper .formatStringToReportingString( "abcd", 60).length()); - Assertions.assertEquals(7, ReportingHelper + assertEquals(7, ReportingHelper .formatStringToReportingString( "{this.height \n\t= builder.getHeight();this.width = builder.getWidth();addAllPhotoMessages(builder.getPhotoMessages());addAllTags(builder.getTags());}", 5).length()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/reporting/commons/StatisticsHandlerTest.java b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/reporting/commons/StatisticsHandlerTest.java index e4c0c2c5bd..99a78083d4 100644 --- a/monticore-runtime/src/test/java/de/monticore/generating/templateengine/reporting/commons/StatisticsHandlerTest.java +++ b/monticore-runtime/src/test/java/de/monticore/generating/templateengine/reporting/commons/StatisticsHandlerTest.java @@ -1,10 +1,9 @@ package de.monticore.generating.templateengine.reporting.commons; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class StatisticsHandlerTest { @Test @@ -12,7 +11,7 @@ public void validSHash() { String content = "SomeString with many characters? + ?+._ü1^^"; String SHASH = StatisticsHandler.getSHASH(content); - Assertions.assertTrue(StatisticsHandler.isValidSHASH(SHASH, content)); + assertTrue(StatisticsHandler.isValidSHASH(SHASH, content)); } @Test public void invalidSHash() { @@ -20,7 +19,7 @@ public void invalidSHash() { String SHASH = StatisticsHandler.getSHASH(content); String differentContent = "AnotjherString"; - Assertions.assertFalse(StatisticsHandler.isValidSHASH(SHASH, differentContent)); + assertFalse(StatisticsHandler.isValidSHASH(SHASH, differentContent)); } } \ No newline at end of file diff --git a/monticore-runtime/src/test/java/de/monticore/io/FileFinderTest.java b/monticore-runtime/src/test/java/de/monticore/io/FileFinderTest.java index 6575d7bb80..fe9df9a93e 100644 --- a/monticore-runtime/src/test/java/de/monticore/io/FileFinderTest.java +++ b/monticore-runtime/src/test/java/de/monticore/io/FileFinderTest.java @@ -6,7 +6,6 @@ import de.se_rwth.commons.Names; import de.se_rwth.commons.logging.Log; import org.apache.commons.io.filefilter.RegexFileFilter; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,8 +20,8 @@ import java.util.Optional; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class FileFinderTest { @@ -47,9 +46,9 @@ public void testGetFiles1() { entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); List files = find(mp, qualifiedModelName, fileExt); - Assertions.assertEquals(4, files.size()); + assertEquals(4, files.size()); List absolutePath = files.stream().map(f ->f.toString()).collect(Collectors.toList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -62,9 +61,9 @@ public void testGetFiles2() { entries.add(Paths.get("src", "test", "resources")); MCPath mp = new MCPath(entries); Optional file = mp.find(qualifiedModelName, fileExt); - Assertions.assertTrue(file.isPresent()); - Assertions.assertTrue(file.get().toString().endsWith("de/monticore/io/Model2.mc4")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(file.isPresent()); + assertTrue(file.get().toString().endsWith("de/monticore/io/Model2.mc4")); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -78,7 +77,7 @@ public void testGetFiles3() { MCPath mp = new MCPath(entries); Optional url = mp.find(qualifiedModelName, fileExt); assertFalse(url.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void assertFalse(boolean present) { @@ -94,11 +93,11 @@ public void testGetFiles4() { entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); List files = find(mp, qualifiedModelName, fileExt); - Assertions.assertEquals(2, files.size()); + assertEquals(2, files.size()); List absolutePath = files.stream().map(f ->f.toString()).collect(Collectors.toList()); - Assertions.assertTrue(absolutePath.get(0).endsWith("de/monticore/io/Model1.cdsym")); - Assertions.assertTrue(absolutePath.get(1).endsWith("de/monticore/io/Model1.cdsym")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(absolutePath.get(0).endsWith("de/monticore/io/Model1.cdsym")); + assertTrue(absolutePath.get(1).endsWith("de/monticore/io/Model1.cdsym")); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -112,7 +111,7 @@ public void testGetFiles5() { MCPath mp = new MCPath(entries); Optional url = mp.find(qualifiedModelName, fileExt); assertFalse(url.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -125,9 +124,9 @@ public void testGetFiles6(){ entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); List files = find(mp, qualifiedModelName, fileExt); - Assertions.assertEquals(4, files.size()); + assertEquals(4, files.size()); List absolutePath = files.stream().map(f ->f.toString()).collect(Collectors.toList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -141,7 +140,7 @@ public void testGetFiles7() { MCPath mp = new MCPath(entries); Optional url = mp.find(qualifiedModelName, fileExt); assertFalse(url.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -154,8 +153,8 @@ public void testGetFiles8() { entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); List files = find(mp, qualifiedModelName, fileExt); - Assertions.assertEquals(0, files.size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(0, files.size()); + assertTrue(Log.getFindings().isEmpty()); } @@ -169,7 +168,7 @@ public void testFindFiles1() { entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); Optional files = mp.find(qualifiedModelName, fileExt); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xA1294")); + assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xA1294")); } @@ -183,8 +182,8 @@ public void testFindFiles2() { entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); Optional files = mp.find(qualifiedModelName, fileExt); - Assertions.assertTrue(files.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(files.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -198,7 +197,7 @@ public void testFindFiles3() { MCPath mp = new MCPath(entries); Optional files = mp.find(qualifiedModelName, fileExt); assertFalse(files.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -212,7 +211,7 @@ public void testFindFiles4() { MCPath mp = new MCPath(entries); Optional files = mp.find(qualifiedModelName, fileExt); assertFalse(files.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -226,8 +225,8 @@ public void testFindFiles5() { entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); List files = find(mp, qualifiedModelName, fileExt); - Assertions.assertEquals(2, files.size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(2, files.size()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -240,7 +239,7 @@ public void testFindFile1() { entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); Optional files = mp.find(qualifiedModelName, fileExt); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xA1294")); + assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xA1294")); } @Test @@ -253,8 +252,8 @@ public void testFindFile2() { entries.add(Paths.get("src","test","resources")); MCPath mp = new MCPath(entries); Optional files = mp.find(qualifiedModelName, fileExt); - Assertions.assertTrue(files.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(files.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -268,7 +267,7 @@ public void testFindFile3() { MCPath mp = new MCPath(entries); Optional files = mp.find(qualifiedModelName, fileExt); assertFalse(files.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -282,7 +281,7 @@ public void testFindFile4() { MCPath mp = new MCPath(entries); Optional files = mp.find(qualifiedModelName, fileExt); assertFalse(files.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } public List find(MCPath mp, String qualifiedName, String fileExtRegEx) { diff --git a/monticore-runtime/src/test/java/de/monticore/io/FileReaderWriterTest.java b/monticore-runtime/src/test/java/de/monticore/io/FileReaderWriterTest.java index e5f2240e83..f796ec25f3 100644 --- a/monticore-runtime/src/test/java/de/monticore/io/FileReaderWriterTest.java +++ b/monticore-runtime/src/test/java/de/monticore/io/FileReaderWriterTest.java @@ -2,9 +2,6 @@ package de.monticore.io; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -13,10 +10,12 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class FileReaderWriterTest { Path testPath = Paths.get("target/test/FileHandlertest.txt"); @@ -46,8 +45,8 @@ public void tearDown() { public void testFileHandler() { FileReaderWriter.init(); FileReaderWriter.storeInFile(testPath, testContent); - Assertions.assertEquals(testContent, FileReaderWriter.readFromFile(testPath)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(testContent, FileReaderWriter.readFromFile(testPath)); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/io/paths/MCPathTest.java b/monticore-runtime/src/test/java/de/monticore/io/paths/MCPathTest.java index d20209787c..509e442d07 100644 --- a/monticore-runtime/src/test/java/de/monticore/io/paths/MCPathTest.java +++ b/monticore-runtime/src/test/java/de/monticore/io/paths/MCPathTest.java @@ -3,7 +3,6 @@ import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -25,6 +24,8 @@ import java.util.stream.Collectors; import java.util.zip.ZipEntry; +import static org.junit.jupiter.api.Assertions.*; + public class MCPathTest { @BeforeEach @@ -43,11 +44,11 @@ public void testFindWithOneArgument(){ mp.addEntry(Paths.get("src/test/resources/jar/Test.jar")); Optional fileInJar = mp.find("de/monticore/MCBasics.mc4"); - Assertions.assertTrue(logback.isPresent()); - Assertions.assertTrue(grammar.isPresent()); - Assertions.assertTrue(fileInJar.isPresent()); - Assertions.assertFalse(nonExistent.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(logback.isPresent()); + assertTrue(grammar.isPresent()); + assertTrue(fileInJar.isPresent()); + assertFalse(nonExistent.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -61,22 +62,22 @@ public void testFindWithTwoArguments(){ Optional grammar2 = mp.find("de.monticore.io.Model3", ".*4"); Optional nonExistent2 = mp.find("Test", "m.4"); - Assertions.assertTrue(logback.isPresent()); - Assertions.assertTrue(grammar.isPresent()); - Assertions.assertFalse(nonExistent.isPresent()); + assertTrue(logback.isPresent()); + assertTrue(grammar.isPresent()); + assertFalse(nonExistent.isPresent()); - Assertions.assertTrue(logback2.isPresent()); - Assertions.assertTrue(grammar2.isPresent()); - Assertions.assertFalse(nonExistent2.isPresent()); + assertTrue(logback2.isPresent()); + assertTrue(grammar2.isPresent()); + assertFalse(nonExistent2.isPresent()); mp.addEntry(Paths.get("src/test/resources/jar/Test.jar")); Optional fileInJar = mp.find("de.monticore.MCBasics", "mc4"); Optional fileInJar2 = mp.find("de.monticore.MCBasics", "m.4"); Optional fileNotInJar = mp.find("MCBasics", "m.4"); - Assertions.assertTrue(fileInJar.isPresent()); - Assertions.assertTrue(fileInJar2.isPresent()); - Assertions.assertFalse(fileNotInJar.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(fileInJar.isPresent()); + assertTrue(fileInJar2.isPresent()); + assertFalse(fileNotInJar.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -85,10 +86,10 @@ public void testAddEntry(){ Path resources = Paths.get("src/test/resources"); Path models = Paths.get("src/test/models"); mp.addEntry(resources); - Assertions.assertEquals(1, mp.getEntries().size()); + assertEquals(1, mp.getEntries().size()); mp.addEntry(models); - Assertions.assertEquals(2, mp.getEntries().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(2, mp.getEntries().size()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -96,10 +97,10 @@ public void testRemoveEntry(){ MCPath mp = new MCPath(); Path resources = Paths.get("src/test/resources"); mp.addEntry(resources); - Assertions.assertEquals(1, mp.getEntries().size()); + assertEquals(1, mp.getEntries().size()); mp.removeEntry(resources); - Assertions.assertTrue(mp.isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(mp.isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -112,23 +113,23 @@ public void testGetEntries(){ mp.addEntry(models); mp.addEntry(java); Collection paths = mp.getEntries(); - Assertions.assertEquals(3, paths.size()); - Assertions.assertTrue(paths.contains(resources.toAbsolutePath())); - Assertions.assertTrue(paths.contains(models.toAbsolutePath())); - Assertions.assertTrue(paths.contains(java.toAbsolutePath())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(3, paths.size()); + assertTrue(paths.contains(resources.toAbsolutePath())); + assertTrue(paths.contains(models.toAbsolutePath())); + assertTrue(paths.contains(java.toAbsolutePath())); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIsEmpty(){ MCPath mp = new MCPath(); - Assertions.assertTrue(mp.isEmpty()); + assertTrue(mp.isEmpty()); Path resources = Paths.get("src/test/resources"); mp.addEntry(resources); - Assertions.assertFalse(mp.isEmpty()); + assertFalse(mp.isEmpty()); mp.removeEntry(resources); - Assertions.assertTrue(mp.isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(mp.isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -138,9 +139,9 @@ public void testToString() throws MalformedURLException { Path models = Paths.get("src/test/models"); mp.addEntry(resources); mp.addEntry(models); - Assertions.assertEquals("[" + resources.toUri().toURL().toString() + ", " + assertEquals("[" + resources.toUri().toURL().toString() + ", " + models.toUri().toURL().toString() + "]", mp.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -148,18 +149,18 @@ public void testToPath() throws MalformedURLException { Path resources = Paths.get("src/test/resources"); URL url = resources.toUri().toURL(); Optional result = MCPath.toPath(url); - Assertions.assertTrue(result.isPresent()); - Assertions.assertEquals(result.get(), resources.toAbsolutePath()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(result.isPresent()); + assertEquals(result.get(), resources.toAbsolutePath()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testToURL() throws URISyntaxException { Path resources = Paths.get("src/test/resources"); Optional result = MCPath.toURL(resources); - Assertions.assertTrue(result.isPresent()); - Assertions.assertEquals(result.get().toURI(), resources.toUri()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(result.isPresent()); + assertEquals(result.get().toURI(), resources.toUri()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -170,8 +171,8 @@ public void testReportAmbiguity() throws MalformedURLException { urlList.add(resources); MCPath.reportAmbiguity(urlList, "src/test/resources"); List findings = Log.getFindings().stream().filter(f -> f.getMsg().startsWith("0xA1294")).collect(Collectors.toList()); - Assertions.assertEquals(1, findings.size()); - Assertions.assertEquals("0xA1294 The following entries for the file `" + "src/test/resources" + "` are ambiguous:" + assertEquals(1, findings.size()); + assertEquals("0xA1294 The following entries for the file `" + "src/test/resources" + "` are ambiguous:" + "\n" + "{" + resources.toString() + ",\n" + resources.toString() + "}", findings.get(0).getMsg()); } @Test @@ -180,22 +181,22 @@ public void testReportAmbiguity() throws MalformedURLException { public void testShouldFind(){ String jdk = System.getenv("JAVA_HOME").replaceAll("\\\\", "/") + "/jre/lib/rt.jar"; MCPath mp = new MCPath(jdk); - Assertions.assertTrue(mp.find("java/util/List.class").isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(mp.find("java/util/List.class").isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testShouldNotFind(){ MCPath mp = new MCPath(""); - Assertions.assertFalse(mp.find("java/util/List.class").isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(mp.find("java/util/List.class").isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testShouldNotFind2(){ MCPath mp = new MCPath("this/is/a/test"); - Assertions.assertFalse(mp.find("java/util/List.class").isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(mp.find("java/util/List.class").isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -204,13 +205,13 @@ public void testCachedAmbiguous() { Log.clearFindings(); MCPath path = new MCPath(); path.addEntry(Paths.get("src/test/resources/paths/1/a")); - Assertions.assertTrue(path.find("AFile", "txt").isPresent()); - Assertions.assertEquals(0, Log.getErrorCount()); + assertTrue(path.find("AFile", "txt").isPresent()); + assertEquals(0, Log.getErrorCount()); path.addEntry(Paths.get("src/test/resources/paths/2/a")); - Assertions.assertTrue(path.find("AFile", "txt").isEmpty()); + assertTrue(path.find("AFile", "txt").isEmpty()); List findings = Log.getFindings().stream().filter(f -> f.getMsg().startsWith("0xA1294")).collect(Collectors.toList()); - Assertions.assertEquals(1, findings.size()); - Assertions.assertEquals("0xA1294 The following entries for the file `" + "AFile\\.txt" + "` are ambiguous:" + assertEquals(1, findings.size()); + assertEquals("0xA1294 The following entries for the file `" + "AFile\\.txt" + "` are ambiguous:" + "\n" + "{" + Paths.get("src/test/resources/paths/1/a/AFile.txt").toUri().toString().replaceAll("///","/") + ",\n" + Paths.get("src/test/resources/paths/2/a/AFile.txt").toUri().toString().replaceAll("///","/") + "}", findings.get(0).getMsg()); } @@ -235,10 +236,10 @@ public void testCachedSym(@TempDir File tempF) throws IOException { MCPath path = new MCPath(); path.addEntry(jar.toPath()); - Assertions.assertTrue(path.find("de.mc.A", ".*sym").isPresent(), "Finding a qualified file failed"); - Assertions.assertTrue(path.find("B", ".*sym").isPresent(), "Finding an unqualified file failed"); + assertTrue(path.find("de.mc.A", ".*sym").isPresent(), "Finding a qualified file failed"); + assertTrue(path.find("B", ".*sym").isPresent(), "Finding an unqualified file failed"); path.removeEntry(jar.toPath()); - Assertions.assertFalse(path.find("de.mc.A", ".*sym").isPresent(), "removeEntry was not completed"); + assertFalse(path.find("de.mc.A", ".*sym").isPresent(), "removeEntry was not completed"); } diff --git a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonLexerTest.java b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonLexerTest.java index 739a8fffae..b08f50786d 100644 --- a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonLexerTest.java +++ b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonLexerTest.java @@ -3,13 +3,11 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static de.monticore.symboltable.serialization.JsonTokenKind.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class JsonLexerTest { @@ -22,68 +20,68 @@ public void before() { @Test public void testNumberWhitespaces() { JsonLexer lexer = new JsonLexer("12.5 3e9"); - Assertions.assertEquals("12.5", lexer.poll().getValue()); - Assertions.assertEquals(WHITESPACE, lexer.poll().getKind()); - Assertions.assertEquals("3e9", lexer.poll().getValue()); - Assertions.assertEquals(false, lexer.hasNext()); + assertEquals("12.5", lexer.poll().getValue()); + assertEquals(WHITESPACE, lexer.poll().getKind()); + assertEquals("3e9", lexer.poll().getValue()); + assertFalse(lexer.hasNext()); lexer = new JsonLexer("1\t2.5"); - Assertions.assertEquals("1", lexer.poll().getValue()); - Assertions.assertEquals(WHITESPACE, lexer.poll().getKind()); - Assertions.assertEquals("2.5", lexer.poll().getValue()); - Assertions.assertEquals(false, lexer.hasNext()); + assertEquals("1", lexer.poll().getValue()); + assertEquals(WHITESPACE, lexer.poll().getKind()); + assertEquals("2.5", lexer.poll().getValue()); + assertFalse(lexer.hasNext()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testJsonObjects() { JsonLexer lexer = new JsonLexer("{\"foo\":\"b a r\"}"); - Assertions.assertEquals(BEGIN_OBJECT, lexer.poll().getKind()); - Assertions.assertEquals(STRING, lexer.poll().getKind()); - Assertions.assertEquals(COLON, lexer.poll().getKind()); - Assertions.assertEquals(STRING, lexer.poll().getKind()); - Assertions.assertEquals(END_OBJECT, lexer.poll().getKind()); - Assertions.assertEquals(false, lexer.hasNext()); + assertEquals(BEGIN_OBJECT, lexer.poll().getKind()); + assertEquals(STRING, lexer.poll().getKind()); + assertEquals(COLON, lexer.poll().getKind()); + assertEquals(STRING, lexer.poll().getKind()); + assertEquals(END_OBJECT, lexer.poll().getKind()); + assertFalse(lexer.hasNext()); lexer = new JsonLexer("{\"a\":2,\"b\":false}"); - Assertions.assertEquals(BEGIN_OBJECT, lexer.poll().getKind()); - Assertions.assertEquals(STRING, lexer.poll().getKind()); - Assertions.assertEquals(COLON, lexer.poll().getKind()); - Assertions.assertEquals(NUMBER, lexer.poll().getKind()); - Assertions.assertEquals(COMMA, lexer.poll().getKind()); - Assertions.assertEquals(STRING, lexer.poll().getKind()); - Assertions.assertEquals(COLON, lexer.poll().getKind()); - Assertions.assertEquals(BOOLEAN, lexer.poll().getKind()); - Assertions.assertEquals(END_OBJECT, lexer.poll().getKind()); - Assertions.assertEquals(false, lexer.hasNext()); + assertEquals(BEGIN_OBJECT, lexer.poll().getKind()); + assertEquals(STRING, lexer.poll().getKind()); + assertEquals(COLON, lexer.poll().getKind()); + assertEquals(NUMBER, lexer.poll().getKind()); + assertEquals(COMMA, lexer.poll().getKind()); + assertEquals(STRING, lexer.poll().getKind()); + assertEquals(COLON, lexer.poll().getKind()); + assertEquals(BOOLEAN, lexer.poll().getKind()); + assertEquals(END_OBJECT, lexer.poll().getKind()); + assertFalse(lexer.hasNext()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testJsonArray() { JsonLexer lexer = new JsonLexer("[\"fo\\\"o\",\"\\b\\\\ar\"]"); - Assertions.assertEquals(BEGIN_ARRAY, lexer.poll().getKind()); - Assertions.assertEquals(STRING, lexer.poll().getKind()); - Assertions.assertEquals(COMMA, lexer.poll().getKind()); - Assertions.assertEquals(STRING, lexer.poll().getKind()); - Assertions.assertEquals(END_ARRAY, lexer.poll().getKind()); - Assertions.assertEquals(false, lexer.hasNext()); + assertEquals(BEGIN_ARRAY, lexer.poll().getKind()); + assertEquals(STRING, lexer.poll().getKind()); + assertEquals(COMMA, lexer.poll().getKind()); + assertEquals(STRING, lexer.poll().getKind()); + assertEquals(END_ARRAY, lexer.poll().getKind()); + assertFalse(lexer.hasNext()); lexer = new JsonLexer("[\"\\\"a\",-2.4e-5,\"b\",null]"); - Assertions.assertEquals(BEGIN_ARRAY, lexer.poll().getKind()); - Assertions.assertEquals(STRING, lexer.poll().getKind()); - Assertions.assertEquals(COMMA, lexer.poll().getKind()); - Assertions.assertEquals(NUMBER, lexer.poll().getKind()); - Assertions.assertEquals(COMMA, lexer.poll().getKind()); - Assertions.assertEquals(STRING, lexer.poll().getKind()); - Assertions.assertEquals(COMMA, lexer.poll().getKind()); - Assertions.assertEquals(NULL, lexer.poll().getKind()); - Assertions.assertEquals(END_ARRAY, lexer.poll().getKind()); - Assertions.assertEquals(false, lexer.hasNext()); + assertEquals(BEGIN_ARRAY, lexer.poll().getKind()); + assertEquals(STRING, lexer.poll().getKind()); + assertEquals(COMMA, lexer.poll().getKind()); + assertEquals(NUMBER, lexer.poll().getKind()); + assertEquals(COMMA, lexer.poll().getKind()); + assertEquals(STRING, lexer.poll().getKind()); + assertEquals(COMMA, lexer.poll().getKind()); + assertEquals(NULL, lexer.poll().getKind()); + assertEquals(END_ARRAY, lexer.poll().getKind()); + assertFalse(lexer.hasNext()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -124,18 +122,18 @@ public void testSinglelexer() { checkSingleToken("\"\\\"\"", "\"",STRING); checkSingleToken("\"foo \\b\\f\\r\\n\\t\\\" foo \"", "foo \b\f\r\n\t\" foo ", STRING); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } protected void checkSingleToken(String json, String expectedContent, JsonTokenKind expectedTokenKind){ JsonLexer lexer = new JsonLexer(json); JsonToken actual = lexer.poll(); - Assertions.assertEquals(expectedTokenKind, actual.getKind()); + assertEquals(expectedTokenKind, actual.getKind()); if (actual.getKind().hasValue()) { String value = actual.getValue(); - Assertions.assertEquals(expectedContent, value); + assertEquals(expectedContent, value); } - Assertions.assertEquals(false, lexer.hasNext()); + assertFalse(lexer.hasNext()); } protected void checkSingleToken(String json, JsonTokenKind expectedTokenKind) { diff --git a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonParserTest.java b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonParserTest.java index c2663739d8..9a6082172c 100644 --- a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonParserTest.java +++ b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonParserTest.java @@ -1,12 +1,8 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.symboltable.serialization; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -14,6 +10,8 @@ import java.util.function.Function; +import static org.junit.jupiter.api.Assertions.*; + public class JsonParserTest { @BeforeEach @@ -57,33 +55,33 @@ protected void testParseErroneousJson(Function f, String json){ catch (RuntimeException e){ //Ignore exceptions that occur because fail quick is disabled } - Assertions.assertTrue(Log.getErrorCount()>0); + assertTrue(Log.getErrorCount()>0); } @Test public void testSimpleObject() { JsonObject result = JsonParser.parseJsonObject("{\"foo\":false,\"bar\":3,\"bla\":\"yes\",\"blub\":3.4}"); - Assertions.assertTrue(result.getMember("foo").isJsonBoolean()); - Assertions.assertEquals(false, result.getMember("foo").getAsJsonBoolean().getValue()); + assertTrue(result.getMember("foo").isJsonBoolean()); + assertFalse(result.getMember("foo").getAsJsonBoolean().getValue()); - Assertions.assertTrue(result.getMember("bar").isJsonNumber()); - Assertions.assertEquals(3, result.getMember("bar").getAsJsonNumber().getNumberAsInteger()); + assertTrue(result.getMember("bar").isJsonNumber()); + assertEquals(3, result.getMember("bar").getAsJsonNumber().getNumberAsInteger()); - Assertions.assertTrue(result.getMember("bla").isJsonString()); - Assertions.assertEquals("yes", result.getMember("bla").getAsJsonString().getValue()); + assertTrue(result.getMember("bla").isJsonString()); + assertEquals("yes", result.getMember("bla").getAsJsonString().getValue()); - Assertions.assertTrue(result.getMember("blub").isJsonNumber()); - Assertions.assertEquals(3.4, result.getMember("blub").getAsJsonNumber().getNumberAsDouble(), 0.1); + assertTrue(result.getMember("blub").isJsonNumber()); + assertEquals(3.4, result.getMember("blub").getAsJsonNumber().getNumberAsDouble(), 0.1); - Assertions.assertTrue(JsonParser.parseJsonObject("{}").isJsonObject()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(JsonParser.parseJsonObject("{}").isJsonObject()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testStringEscapes(){ JsonObject result = JsonParser.parseJsonObject("{\"foo\":\"\\n\"}"); - Assertions.assertTrue(result.getMember("foo").isJsonString()); - Assertions.assertEquals("\n", result.getMember("foo").getAsJsonString().getValue()); + assertTrue(result.getMember("foo").isJsonString()); + assertEquals("\n", result.getMember("foo").getAsJsonString().getValue()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonPrinterSecurityTest.java b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonPrinterSecurityTest.java index db8173d0a4..08a576fb64 100644 --- a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonPrinterSecurityTest.java +++ b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonPrinterSecurityTest.java @@ -1,21 +1,19 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.symboltable.serialization; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.List; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import de.monticore.symboltable.serialization.json.JsonArray; import de.monticore.symboltable.serialization.json.JsonObject; +import static org.junit.jupiter.api.Assertions.*; + /** * This test checks whether injection of objects into serialization and deserialization is avoided * correctly. @@ -55,33 +53,33 @@ public void test() { String s = printFoo(bar); JsonObject o = JsonParser.parseJsonObject(s); - Assertions.assertEquals("Bar", getName(o)); - Assertions.assertEquals(2, getChildren(o).size()); + assertEquals("Bar", getName(o)); + assertEquals(2, getChildren(o).size()); JsonObject b1 = getChildren(o).get(0).getAsJsonObject(); - Assertions.assertEquals("Bar1", getName(b1)); - Assertions.assertEquals(1, getChildren(b1).size()); + assertEquals("Bar1", getName(b1)); + assertEquals(1, getChildren(b1).size()); JsonObject b11 = getChildren(b1).get(0).getAsJsonObject(); - Assertions.assertEquals("Bar1.1", getName(b11)); - Assertions.assertEquals(false, b11.hasMember("children")); + assertEquals("Bar1.1", getName(b11)); + assertFalse(b11.hasMember("children")); JsonObject b2 = getChildren(o).get(1).getAsJsonObject(); - Assertions.assertTrue(getName(b2).startsWith("Bar2")); + assertTrue(getName(b2).startsWith("Bar2")); // without escaping, Bar2 would contain the injected child Bar2.1 - Assertions.assertEquals(false, b2.hasMember("children")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(b2.hasMember("children")); + assertTrue(Log.getFindings().isEmpty()); } protected JsonArray getChildren(JsonObject foo) { - Assertions.assertEquals(true, foo.hasMember("children")); - Assertions.assertEquals(true, foo.getMember("children").isJsonArray()); + assertTrue(foo.hasMember("children")); + assertTrue(foo.getMember("children").isJsonArray()); return foo.getMember("children").getAsJsonArray(); } protected String getName(JsonObject foo) { - Assertions.assertEquals(true, foo.hasMember("name")); - Assertions.assertEquals(true, foo.getMember("name").isJsonString()); + assertTrue(foo.hasMember("name")); + assertTrue(foo.getMember("name").isJsonString()); return foo.getMember("name").getAsJsonString().getValue(); } diff --git a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonPrinterTest.java b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonPrinterTest.java index 5bb82c7b3b..1b5f1ed4a0 100644 --- a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonPrinterTest.java +++ b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonPrinterTest.java @@ -4,15 +4,14 @@ import com.google.common.collect.Lists; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests the JsonPrinter @@ -43,17 +42,17 @@ public void testOmitEmptyArray() { printer.endObject(); String serialized = printer.getContent(); - Assertions.assertTrue(null != JsonParser.parseJsonObject(serialized)); - Assertions.assertTrue(!serialized.contains("kindHierarchy")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(null != JsonParser.parseJsonObject(serialized)); + assertTrue(!serialized.contains("kindHierarchy")); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testEscapeSequences() { JsonPrinter printer = new JsonPrinter(); printer.value("\"\t\\\n'"); - Assertions.assertEquals("\"\\\"\\t\\\\\\n'\"", printer.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("\"\\\"\\t\\\\\\n'\"", printer.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -61,13 +60,13 @@ public void testEmptyObject() { JsonPrinter printer = new JsonPrinter(true); printer.beginObject(); printer.endObject(); - Assertions.assertEquals("{}", printer.toString()); + assertEquals("{}", printer.toString()); printer = new JsonPrinter(false); printer.beginObject(); printer.endObject(); - Assertions.assertEquals("", printer.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("", printer.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -76,14 +75,14 @@ public void testDefaultString() { printer.beginObject(); printer.member("s", ""); printer.endObject(); - Assertions.assertEquals("", printer.toString()); + assertEquals("", printer.toString()); printer = new JsonPrinter(true); printer.beginObject(); printer.member("s", ""); printer.endObject(); - Assertions.assertEquals("{\"s\":\"\"}", printer.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("{\"s\":\"\"}", printer.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -92,14 +91,14 @@ public void testDefaultInt() { printer.beginObject(); printer.member("i", 0); printer.endObject(); - Assertions.assertEquals("", printer.toString()); + assertEquals("", printer.toString()); printer = new JsonPrinter(true); printer.beginObject(); printer.member("i", 0); printer.endObject(); - Assertions.assertEquals("{\"i\":0}", printer.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("{\"i\":0}", printer.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -108,14 +107,14 @@ public void testDefaultBoolean() { printer.beginObject(); printer.member("b", false); printer.endObject(); - Assertions.assertEquals("", printer.toString()); + assertEquals("", printer.toString()); printer = new JsonPrinter(true); printer.beginObject(); printer.member("b", false); printer.endObject(); - Assertions.assertEquals("{\"b\":false}", printer.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("{\"b\":false}", printer.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -123,27 +122,27 @@ public void testEmptyList() { JsonPrinter printer = new JsonPrinter(true); printer.beginArray(); printer.endArray(); - Assertions.assertEquals("[]", printer.toString()); + assertEquals("[]", printer.toString()); printer = new JsonPrinter(true); printer.beginObject(); printer.beginArray("emptyList"); printer.endArray(); printer.endObject(); - Assertions.assertEquals("{\"emptyList\":[]}", printer.toString()); + assertEquals("{\"emptyList\":[]}", printer.toString()); printer = new JsonPrinter(false); printer.beginArray(); printer.endArray(); - Assertions.assertEquals("", printer.toString()); + assertEquals("", printer.toString()); printer = new JsonPrinter(false); printer.beginObject(); printer.beginArray("emptyList"); printer.endArray(); printer.endObject(); - Assertions.assertEquals("", printer.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("", printer.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -152,32 +151,32 @@ public void testBasicTypeAttributes() { printer.beginObject(); printer.member("booleanAttribute", true); printer.endObject(); - Assertions.assertEquals("{\"booleanAttribute\":true}", printer.toString()); + assertEquals("{\"booleanAttribute\":true}", printer.toString()); printer = new JsonPrinter(); printer.beginObject(); printer.member("intAttribute", -1); printer.endObject(); - Assertions.assertEquals("{\"intAttribute\":-1}", printer.toString()); + assertEquals("{\"intAttribute\":-1}", printer.toString()); printer = new JsonPrinter(); printer.beginObject(); printer.member("floatAttribute", 47.11f); printer.endObject(); - Assertions.assertEquals("{\"floatAttribute\":47.11}", printer.toString()); + assertEquals("{\"floatAttribute\":47.11}", printer.toString()); printer = new JsonPrinter(); printer.beginObject(); printer.member("doubleAttribute", 47.11); printer.endObject(); - Assertions.assertEquals("{\"doubleAttribute\":47.11}", printer.toString()); + assertEquals("{\"doubleAttribute\":47.11}", printer.toString()); printer = new JsonPrinter(); printer.beginObject(); printer.member("longAttribute", 123456789L); printer.endObject(); - Assertions.assertEquals("{\"longAttribute\":123456789}", printer.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("{\"longAttribute\":123456789}", printer.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -186,50 +185,50 @@ public void testOptionalAndList() { printer.beginObject(); printer.member("optionalAttribute", Optional.of("presentOptional")); printer.endObject(); - Assertions.assertEquals("{\"optionalAttribute\":\"presentOptional\"}", printer.toString()); + assertEquals("{\"optionalAttribute\":\"presentOptional\"}", printer.toString()); printer = new JsonPrinter(false); printer.beginObject(); printer.member("optionalAttribute", Optional.of("presentOptional")); printer.endObject(); - Assertions.assertEquals("{\"optionalAttribute\":\"presentOptional\"}", printer.toString()); + assertEquals("{\"optionalAttribute\":\"presentOptional\"}", printer.toString()); printer = new JsonPrinter(true); printer.beginObject(); printer.member("optionalAttribute", Optional.empty()); printer.endObject(); - Assertions.assertEquals("{\"optionalAttribute\":null}", printer.toString()); + assertEquals("{\"optionalAttribute\":null}", printer.toString()); printer = new JsonPrinter(false); printer.beginObject(); printer.member("optionalAttribute", Optional.empty()); printer.endObject(); - Assertions.assertEquals("", printer.toString()); + assertEquals("", printer.toString()); printer = new JsonPrinter(true); printer.beginObject(); printer.member("listAttribute", new ArrayList<>()); printer.endObject(); - Assertions.assertEquals("{\"listAttribute\":[]}", printer.toString()); + assertEquals("{\"listAttribute\":[]}", printer.toString()); printer = new JsonPrinter(false); printer.beginObject(); printer.member("listAttribute", new ArrayList<>()); printer.endObject(); - Assertions.assertEquals("", printer.toString()); + assertEquals("", printer.toString()); printer = new JsonPrinter(true); printer.beginObject(); printer.member("listAttribute", Lists.newArrayList("first", "second")); printer.endObject(); - Assertions.assertEquals("{\"listAttribute\":[\"first\",\"second\"]}", printer.toString()); + assertEquals("{\"listAttribute\":[\"first\",\"second\"]}", printer.toString()); printer = new JsonPrinter(false); printer.beginObject(); printer.member("listAttribute", Lists.newArrayList("first", "second")); printer.endObject(); - Assertions.assertEquals("{\"listAttribute\":[\"first\",\"second\"]}", printer.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("{\"listAttribute\":[\"first\",\"second\"]}", printer.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -241,7 +240,7 @@ public void testInvalidNestings() { printer.beginObject(); printer.endObject(); printer.getContent(); - Assertions.assertEquals(1, Log.getFindings().size()); + assertEquals(1, Log.getFindings().size()); Log.clearFindings(); printer = new JsonPrinter(); @@ -249,7 +248,7 @@ public void testInvalidNestings() { printer.endObject(); printer.endObject(); printer.getContent(); - Assertions.assertEquals(1, Log.getFindings().size()); + assertEquals(1, Log.getFindings().size()); Log.clearFindings(); printer = new JsonPrinter(); @@ -257,7 +256,7 @@ public void testInvalidNestings() { printer.beginArray(); printer.endArray(); printer.getContent(); - Assertions.assertEquals(1, Log.getFindings().size()); + assertEquals(1, Log.getFindings().size()); Log.clearFindings(); printer = new JsonPrinter(); @@ -265,7 +264,7 @@ public void testInvalidNestings() { printer.endArray(); printer.endArray(); printer.getContent(); - Assertions.assertEquals(1, Log.getFindings().size()); + assertEquals(1, Log.getFindings().size()); Log.clearFindings(); printer = new JsonPrinter(); @@ -275,7 +274,7 @@ public void testInvalidNestings() { printer.endArray(); printer.endObject(); printer.getContent(); - Assertions.assertEquals(3, Log.getFindings().size()); + assertEquals(3, Log.getFindings().size()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonStringEscapeTest.java b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonStringEscapeTest.java index f13b8921de..c52d76f780 100644 --- a/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonStringEscapeTest.java +++ b/monticore-runtime/src/test/java/de/monticore/symboltable/serialization/JsonStringEscapeTest.java @@ -1,11 +1,10 @@ package de.monticore.symboltable.serialization; import de.monticore.symboltable.serialization.json.JsonElement; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class JsonStringEscapeTest { @@ -15,7 +14,7 @@ public void testSingleQuoteNotEscaped(){ printer.value("'"); String content = printer.getContent(); - Assertions.assertEquals("\"'\"", content); + assertEquals("\"'\"", content); } @Test @@ -24,7 +23,7 @@ public void testUtf8Escaped(){ printer.value("✔"); String content = printer.getContent(); - Assertions.assertEquals("\"\\u2714\"", content); + assertEquals("\"\\u2714\"", content); } @Test @@ -89,9 +88,9 @@ protected void testRoundtrip(String input) { String content = printer.getContent(); JsonElement e = JsonParser.parse(content); - Assertions.assertTrue(e.isJsonString()); + assertTrue(e.isJsonString()); - Assertions.assertEquals(input, e.getAsJsonString().getValue()); + assertEquals(input, e.getAsJsonString().getValue()); } } diff --git a/monticore-runtime/src/test/java/de/monticore/templateEnginePerformance/TemplateEngineBenchmark.java b/monticore-runtime/src/test/java/de/monticore/templateEnginePerformance/TemplateEngineBenchmark.java index 51b0655555..0e9b3d29be 100644 --- a/monticore-runtime/src/test/java/de/monticore/templateEnginePerformance/TemplateEngineBenchmark.java +++ b/monticore-runtime/src/test/java/de/monticore/templateEnginePerformance/TemplateEngineBenchmark.java @@ -4,8 +4,8 @@ import de.monticore.generating.GeneratorSetup; import de.monticore.generating.templateengine.TemplateController; import de.monticore.generating.templateengine.TemplateHookPoint; -import org.junit.Test; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.concurrent.TimeUnit; diff --git a/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/AbstractMCTest.java b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/AbstractMCTest.java new file mode 100644 index 0000000000..c6fbf1629d --- /dev/null +++ b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/AbstractMCTest.java @@ -0,0 +1,49 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.runtime.junit; + +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +/** + * Common abstract super class for MontiCore language tests + * Ensures, that the correct Log is initialized + * and no findings are present after a test; + * findings are either expected to not occur at all + * or, if they occur, are checked and removed afterward, + * s.a. {@link MCAssertions}. + */ +public abstract class AbstractMCTest { + + @BeforeEach + public void initAbstract() { + defaultInitAbstract(); + } + + static void defaultInitAbstract() { + Log.clearFindings(); // clear previous findings + LogStub.init(); // replace log by a sideeffect free variant + Log.enableFailQuick(false); // do not fail quick/exit on the first error + } + + @AfterEach + public void checkLogAfterTest() { + defaultCheckLogAfterTest(); + } + + static void defaultCheckLogAfterTest() { + try { + // Ensure, no Findings are present + // the various Finding-methods of MCAssertions check for & remove + // expected findings + MCAssertions.assertNoFindings( + "After the test has run, findings were present.\n" + + "(In case they are expected: Use the MCAssertions#assertHasFinding methods to check for them first)" + ); + } finally { + Log.clearFindings(); + } + } + +} diff --git a/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java new file mode 100644 index 0000000000..d1b4a0423f --- /dev/null +++ b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCAssertions.java @@ -0,0 +1,234 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.runtime.junit; + +import com.google.common.collect.Streams; +import de.se_rwth.commons.logging.Finding; +import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.Assertions; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.fail; + +/** + * MCAssertions is a collection of utility methods that support asserting + * conditions in MontiCore tests. + * Unless otherwise noted, a failed assertion will throw an + * {@link org.opentest4j.AssertionFailedError} or a subclass thereof. + */ +@SuppressWarnings("unused") +public class MCAssertions { + + /** + * Asserts that at least one Finding starts with the expected prefix + * and removes that Finding from the Log + * + * @param expectedPrefix the expected prefix + * @param message the message to fail with iff no finding was found + * @return returns the found Finding + * @see MCAssertions#assertHasFinding(Predicate, String) + */ + public static Finding assertHasFindingStartingWith(String expectedPrefix, String message) { + return assertHasFinding(f -> f.getMsg().startsWith(expectedPrefix), message); + } + + /** + * Asserts that at least one Finding starts with the expected prefix + * and removes that Finding from the Log + * + * @param expectedPrefix the expected prefix + * @return returns the found Finding + * @see MCAssertions#assertHasFinding(Predicate) + */ + public static Finding assertHasFindingStartingWith(String expectedPrefix) { + return assertHasFindingStartingWith(expectedPrefix, + "Expected a Log-Finding with prefix " + expectedPrefix + + ", but did not find any" + ); + } + + /** + * Asserts that at least one Finding starts with the expected prefix + * and removes all matching Findings from the Log + * + * @param expectedPrefix the expected prefix + * @param message the message to fail with iff no findings were found + * @return returns the list of found Findings + * @see MCAssertions#assertHasFindings(Predicate, String) + */ + public static Collection assertHasFindingsStartingWith(String expectedPrefix, String message) { + return assertHasFindings(f -> f.getMsg().startsWith(expectedPrefix), message); + } + + /** + * Asserts that at least one Finding starts with the expected prefix + * and removes all matching Findings from the Log + * + * @param expectedPrefix the expected prefix + * @return returns the list of found Findings + * @see MCAssertions#assertHasFinding(Predicate) + */ + public static Collection assertHasFindingsStartingWith(String expectedPrefix) { + return assertHasFindingsStartingWith(expectedPrefix, + "Expected Log-Findings with prefix " + expectedPrefix + + ", but did not find any" + ); + } + + /** + * Asserts that at least one Finding matches the predicate + * and removes that Finding from the Log. + * If multiple Findings match, only the first of them will be removed. + * + * @param predicate the predicate + * @param message the message to fail with iff no finding was found + * @return returns the found Finding + */ + public static Finding assertHasFinding(Predicate predicate, String message) { + var it = Log.getFindings().iterator(); + while (it.hasNext()) { + var f = it.next(); + if (predicate.test(f)) { + it.remove(); + return f; + } + } + return failAndPrintFindings(message); + } + + /** + * Asserts that at least one Finding matches the predicate + * and removes that Finding from the Log. + * If multiple Findings match, only the first of them will be removed. + * + * @param predicate the predicate + * @return returns the found Finding + */ + public static Finding assertHasFinding(Predicate predicate) { + return assertHasFinding(predicate, + "Expected a Log-Finding matching given predicate" + + ", but did not find any" + ); + } + + /** + * Asserts that at least one Finding is present + * and removes that Finding from the Log. + * If multiple Findings match, only the first of them will be removed. + * This method should NOT be used in conjunction with CoCo-Tests. + * + * @return returns the found Finding + */ + public static Finding assertHasFinding() { + return assertHasFinding(f -> true, + "Expected any Log-Finding" + + ", but none were present" + ); + } + + /** + * Asserts that at least one Finding matches the predicate + * and removes all matching Findings from the Log + * + * @param predicate the predicate + * @param message the message to fail with iff no findings were found + * @return returns the list of found Findings + */ + public static Collection assertHasFindings(Predicate predicate, String message) { + var it = Log.getFindings().iterator(); + List matchingFindings = new ArrayList<>(); + while (it.hasNext()) { + var f = it.next(); + if (predicate.test(f)) { + it.remove(); + matchingFindings.add(f); + } + } + if (matchingFindings.isEmpty()) + return failAndPrintFindings(message); + return matchingFindings; + } + + /** + * Asserts that at least one Finding matches the predicate + * and removes all matching Findings from the Log + * + * @param predicate the predicate + * @return returns the list of found Findings + */ + public static Collection assertHasFindings(Predicate predicate) { + return assertHasFindings(predicate, + "Expected Log-Findings matching given predicate" + + ", but did not find any" + ); + } + + /** + * Asserts that no findings are present. + * + * @param message the message to fail with iff findings were found + */ + public static void assertNoFindings(String message) { + if (!Log.getFindings().isEmpty()) { + failAndPrintFindings(message); + } + } + + /** + * Asserts that no findings are present. + */ + public static void assertNoFindings() { + assertNoFindings("Encountered Log-Findings while expecting none"); + } + + /** + * Fails a test. + * Additionally, Lists the state of Log-Findings. + * See Javadoc for {@link Assertions#fail(String, Throwable)} + * for an explanation of this method's generic return type V. + * + * @return nothing + */ + public static V failAndPrintFindings() { + return failAndPrintFindings(""); + } + + + /** + * Fails a test with the given failure message. + * Additionally, Lists the state of Log-Findings. + * See Javadoc for {@link Assertions#fail(String, Throwable)} + * for an explanation of this method's generic return type V. + * + * @param message message to print + * @return nothing + */ + public static V failAndPrintFindings(String message) { + StringBuilder messageWithFindings = new StringBuilder(); + if (!message.isBlank()) { + messageWithFindings.append(message); + } + else { + messageWithFindings.append("Failed (no reason stated)"); + } + messageWithFindings.append(System.lineSeparator()); + if (Log.getFindings().isEmpty()) { + messageWithFindings.append("Got no Log-Findings."); + } + else { + messageWithFindings.append("Got Log-Findings:"); + messageWithFindings.append(System.lineSeparator()); + messageWithFindings.append(Streams.mapWithIndex( + Log.getFindings().stream().map(Finding::buildMsg), + (str, index) -> "[" + index + "]" + str) + .collect(Collectors.joining(System.lineSeparator())) + ); + } + return fail(messageWithFindings.toString()); + } + +} diff --git a/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCLanguageTestExtension.java b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCLanguageTestExtension.java new file mode 100644 index 0000000000..ec46b66cea --- /dev/null +++ b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/MCLanguageTestExtension.java @@ -0,0 +1,64 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.runtime.junit; + +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +import java.util.Optional; + +public class MCLanguageTestExtension implements BeforeEachCallback, AfterEachCallback { + + @Override + public void beforeEach(ExtensionContext extensionContext) { + if (!(AbstractMCTest.class.isAssignableFrom(extensionContext.getRequiredTestClass()))) { + // Call AbstractMCTest beforeEach hook + AbstractMCTest.defaultInitAbstract(); + } + + getAnnotation(extensionContext) + .ifPresent(a -> invokeStaticMethod(a.value(), "init")); + } + + + @Override + public void afterEach(ExtensionContext extensionContext) { + getAnnotation(extensionContext) + .ifPresent(a -> invokeStaticMethod(a.value(), "reset")); + + if (!(AbstractMCTest.class.isAssignableFrom(extensionContext.getRequiredTestClass()))) { + // Call AbstractMCTest afterEach hook + AbstractMCTest.defaultCheckLogAfterTest(); + } + } + + + /** + * Fetch the @{@link TestWithMCLanguage} annotation, + * containing a reference to the relevant Mill. + * + * @param extensionContext the test context + * @return optional of the annotation + */ + protected Optional getAnnotation(ExtensionContext extensionContext) { + return Optional.ofNullable(extensionContext.getRequiredTestClass().getAnnotation(TestWithMCLanguage.class)); + } + + /** + * invoke a public, static method (init/reset) of a mill + * + * @param millClazz class of the mill + * @param method method name + */ + protected void invokeStaticMethod(Class millClazz, String method) { + if (!millClazz.getName().endsWith("Mill")) + throw new IllegalArgumentException("@TestWithMCLanguage class " + millClazz.getSimpleName() + " is not a mill!"); + try { + // Because Mill#init and Mill#reset are static methods + // we unfortunately have to use Class#invoke to invoke init/reset + millClazz.getMethod(method).invoke(null); + } catch (Exception e) { + throw new IllegalStateException("Failed to invoke mill method", e); + } + } +} diff --git a/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/PrettyPrinterTester.java b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/PrettyPrinterTester.java new file mode 100644 index 0000000000..b1af00d40d --- /dev/null +++ b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/PrettyPrinterTester.java @@ -0,0 +1,117 @@ +package de.monticore.runtime.junit; + +import de.monticore.antlr4.MCConcreteParser; +import de.monticore.ast.ASTNode; + +import java.io.IOException; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Predicate; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Offers functions to test pretty printers + */ +public abstract class PrettyPrinterTester { + + /** + * Tests pretty printing. + * The Model is parsed, pretty printed and parsed again. + * The AST of the pretty printed model is expected + * to be comparable to the AST of the original model. + * + * @param model the model to be pretty printed + * @param parser the parser used to convert the model to an AST + * @param parseFunc the concrete parse function used, e.g., + * {@code myParser::parse_StringMyNonTerminal} + * @param prettyPrintFunc the actual pretty printing operation, e.g., + * {@code ast -> MyMill.prettyPrint(ast, true)} + * @param additionalCheck additional check on the pretty printed String + * @param the type of the ASTNode after parsing + */ + public static void testPrettyPrinter( + String model, + MCConcreteParser parser, + ParseFunction parseFunc, + Function prettyPrintFunc, + Predicate additionalCheck + ) { + // parse the model + Optional astOpt; + try { + astOpt = parseFunc.apply(model); + } + catch (IOException e) { + fail("Failed to parse input, exception occurred", e); + return; + } + MCAssertions.assertNoFindings(); + assertTrue(astOpt.isPresent(), "Failed to parse input"); + assertFalse(parser.hasErrors(), "Parser has Errors"); + N ast = astOpt.get(); + // pretty print the model + String prettyPrinted = prettyPrintFunc.apply(ast); + MCAssertions.assertNoFindings(); + // parse the pretty printed model + Optional prettyPrintedAstOpt; + try { + prettyPrintedAstOpt = parseFunc.apply(prettyPrinted); + } + catch (IOException e) { + fail( + "Failed to parse pretty printed model" + + ", exception occurred", e + ); + return; + } + MCAssertions.assertNoFindings(); + assertFalse(parser.hasErrors()); + assertTrue(prettyPrintedAstOpt.isPresent()); + // compare both ASTs + assertTrue(ast.deepEquals(prettyPrintedAstOpt.get()), + "ASTs are not deep equals" + ); + // run an additional check + if (!additionalCheck.test(prettyPrinted)) { + fail("Pretty Printer test: failed during additional check"); + } + } + + /** + * Tests pretty printing. + * The Model is parsed, pretty printed and parsed again. + * The AST of the pretty printed model is expected + * to be comparable to the AST of the original model. + * + * @param model the model to be pretty printed + * @param parser the parser used to convert the model to an AST + * @param parseFunc the concrete parse function used, e.g., + * {@code myParser::parse_StringMyNonTerminal} + * @param prettyPrintFunc the actual pretty printing operation, e.g., + * {@code ast -> MyMill.prettyPrint(ast, true)} + * @param the type of the ASTNode after parsing + */ + public static void testPrettyPrinter( + String model, + MCConcreteParser parser, + ParseFunction parseFunc, + Function prettyPrintFunc + ) { + testPrettyPrinter(model, parser, parseFunc, prettyPrintFunc, m -> true); + } + + /** + * Represents the function that parses a String. + * E.g., {@code myParser::parse_StringMyNonTerminal} + * + * @param the type of the ASTNode after Parsing. + */ + @FunctionalInterface + public interface ParseFunction { + Optional apply(String t) throws IOException; + } + +} diff --git a/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/TestWithMCLanguage.java b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/TestWithMCLanguage.java new file mode 100644 index 0000000000..e9ac01cc0a --- /dev/null +++ b/monticore-runtime/src/testFixtures/java/de/monticore/runtime/junit/TestWithMCLanguage.java @@ -0,0 +1,27 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.runtime.junit; + +import org.junit.jupiter.api.extension.ExtendWith; + +import java.lang.annotation.*; + +/** + * Performs the tests within the scope of a language. + * This means a freshly initialized mill for each test + * and a Log without Findings. + * After ech test, the language's mill is reset. + * No Findings MUST be present after a test (see {@link MCAssertions}) + * Also includes the hooks of the {@link AbstractMCTest} + */ +@Documented +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@ExtendWith(MCLanguageTestExtension.class) +public @interface TestWithMCLanguage { + /** + * The Mill of a language, + * such as {@code @TestWithMCLanguage(MyDSLMill.class)} + * @return Class of a language's mill + */ + Class value(); +} diff --git a/monticore-test/01.experiments/automaton/src/main/java/automata/AutomataTool.java b/monticore-test/01.experiments/automaton/src/main/java/automata/AutomataTool.java index 927a490c42..3bbc839778 100644 --- a/monticore-test/01.experiments/automaton/src/main/java/automata/AutomataTool.java +++ b/monticore-test/01.experiments/automaton/src/main/java/automata/AutomataTool.java @@ -29,21 +29,6 @@ */ public class AutomataTool extends AutomataToolTOP { - /** - * Main method of the Tool - * - * Arguments expected: - * * input automaton file. - * * the path to store the symbol table - * - * @param args - */ - public static void main(String[] args) { - // delegate main to instantiatable method for better integration, - // reuse, etc. - new AutomataTool().run(args); - } - /** * Run implements the main method of the Automata tool workflow: * @@ -78,6 +63,10 @@ else if (cmd.hasOption("v")) { //do not continue when help is printed return; } + //throw: simulate an internal exception occurring for testing main + else if (cmd.hasOption("throw")) { + throw new RuntimeException("This is a test exception thrown to test"); + } Log.info("Automata DSL Tool", "AutomataTool"); @@ -171,4 +160,11 @@ public void prettyPrint(ASTAutomaton ast, String file) { Log.println(pp.getResult()); } + @Override + public Options addAdditionalOptions(Options options) { + options.addOption("throw", + "used for simulating an interal exception" + ); + return options; + } } diff --git a/monticore-test/01.experiments/automaton/src/test/java/AutomataParseTest.java b/monticore-test/01.experiments/automaton/src/test/java/AutomataParseTest.java index 18ae2b6237..05cadd7859 100644 --- a/monticore-test/01.experiments/automaton/src/test/java/AutomataParseTest.java +++ b/monticore-test/01.experiments/automaton/src/test/java/AutomataParseTest.java @@ -1,42 +1,30 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; import java.util.Optional; +import automata.AutomataMill; import automata._ast.ASTAutomaton; import automata._ast.ASTState; import automata._parser.AutomataParser; -import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Main class for the some Demonstration to Parse */ +@TestWithMCLanguage(AutomataMill.class) public class AutomataParseTest { - - @Before - public void setUp() { - LogStub.init(); - Log.enableFailQuick(false); - Log.clearFindings(); - LogStub.clearPrints(); - } - - /** - * @throws IOException - * - */ - @Test + + @org.junit.jupiter.api.Test public void testParseMethods() throws IOException { String filename = "src/test/resources/example/PingPong.aut"; - AutomataParser p = new AutomataParser(); - + AutomataParser p = AutomataMill.parser(); + // parse from a file Optional at = p.parse(filename); assertTrue(at.isPresent()); @@ -55,8 +43,8 @@ public void testParseMethods() throws IOException { // parse for a sublanguage, here: a State Optional s = p.parse_StringState("state Ping;"); assertTrue(s.isPresent()); - - assertTrue(Log.getFindings().isEmpty()); + + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/automaton/src/test/java/AutomataToolTest.java b/monticore-test/01.experiments/automaton/src/test/java/AutomataToolTest.java index 3bac75ef22..939f274c7b 100644 --- a/monticore-test/01.experiments/automaton/src/test/java/AutomataToolTest.java +++ b/monticore-test/01.experiments/automaton/src/test/java/AutomataToolTest.java @@ -2,6 +2,7 @@ import automata.AutomataMill; import automata.AutomataTool; +import de.monticore.runtime.junit.MCAssertions; import org.junit.*; import de.se_rwth.commons.logging.Log; @@ -12,25 +13,26 @@ import java.util.regex.Pattern; import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; public class AutomataToolTest { - @Before + @BeforeEach public void setUp() { LogStub.init(); Log.enableFailQuick(false); Log.clearFindings(); LogStub.clearPrints(); - AutomataMill.globalScope().clear(); + AutomataMill.reset(); } @Test public void executePingPong() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/PingPong.aut", "-s", "target/PingPong.autsym" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/PingPong.aut", "-s", "target/PingPong.autsym" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); // for manual testing purpose only @@ -39,45 +41,43 @@ public void executePingPong() { assertEquals(6, p.size()); // Check some "[INFO]" outputs - assertTrue(p.get(0), p.get(0).matches(".*.INFO. AutomataTool Automata DSL Tool.*(\r)?\n")); - assertTrue(p.get(4), p.get(4).matches(".*.INFO. AutomataTool Pretty printing automaton into console.*(\r)?\n")); + assertTrue(p.get(0).matches(".*.INFO. AutomataTool Automata DSL Tool.*(\r)?\n"), p.get(0)); + assertTrue(p.get(4).matches(".*.INFO. AutomataTool Pretty printing automaton into console.*(\r)?\n"), p.get(4)); // Check resulting pretty print: String res = p.get(p.size()-1).replaceAll("[\r\n]", " "); - assertTrue(res, res.matches(".*state.*")); - assertTrue(res, res.matches(".*state NoGame <>.*")); - assertTrue(res, res.matches(".*Pong - returnBall > Ping;.*")); - assertTrue(Log.getFindings().isEmpty()); + assertTrue(res.matches(".*state.*"), res); + assertTrue(res.matches(".*state NoGame <>.*"), res); + assertTrue(res.matches(".*Pong - returnBall > Ping;.*"), res); + MCAssertions.assertNoFindings(); } @Test public void executeSimple12() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/Simple12.aut", "-s", "target/Simple12.autsym" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/Simple12.aut", "-s", "target/Simple12.autsym" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); List p = LogStub.getPrints(); assertEquals(6, p.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void executeHierarchyPingPong() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/HierarchyPingPong.aut", "-s", "target/very/very/very/deep/HierarchyPingPong.autsym" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/HierarchyPingPong.aut", "-s", "target/very/very/very/deep/HierarchyPingPong.autsym" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); List p = LogStub.getPrints(); assertEquals(6, p.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void testPrintVersion() { - - - AutomataTool.main(new String[] {"-v"}); - assertTrue(Log.getFindings().isEmpty()); + new AutomataTool().run(new String[] {"-v"}); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/automaton/src/test/java/TransitionSourceExistsTest.java b/monticore-test/01.experiments/automaton/src/test/java/TransitionSourceExistsTest.java index 85c2e44575..3acadbdc9c 100644 --- a/monticore-test/01.experiments/automaton/src/test/java/TransitionSourceExistsTest.java +++ b/monticore-test/01.experiments/automaton/src/test/java/TransitionSourceExistsTest.java @@ -4,55 +4,42 @@ import automata._ast.ASTAutomaton; import automata._ast.ASTState; import automata._cocos.AutomataCoCoChecker; -import automata._parser.AutomataParser; import automata._symboltable.*; import automata.cocos.TransitionSourceExists; import de.monticore.ast.ASTNode; import de.monticore.io.paths.MCPath; -import de.se_rwth.commons.logging.Log; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.LogStub; -import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(AutomataMill.class) public class TransitionSourceExistsTest { - // setup the parser infrastructure - AutomataParser parser = new AutomataParser() ; - - @Before - public void setUp() throws RecognitionException, IOException { - LogStub.init(); - Log.enableFailQuick(false); - Log.getFindings().clear(); - } - - // -------------------------------------------------------------------- @Test public void testBasics() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { state A; state B; A - x > A; A - y > A; }" ).get(); assertEquals("Simple", ast.getName()); List st = ast.getStateList(); assertEquals(2, st.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testRetrievalOfSymbol() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { state A; state B; A - x > A; B - y > A; }" ).get(); @@ -66,14 +53,14 @@ public void testRetrievalOfSymbol() throws IOException { assertEquals("A", aSymbol.get().getName()); ASTNode n = aSymbol.get().getAstNode(); assertEquals("A", ((ASTState)n).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testOnValidModel() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { state A; state B; A -x> A; B -y> A; }" ).get(); @@ -86,13 +73,13 @@ public void testOnValidModel() throws IOException { checker.checkAll(ast); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testOnInvalidModel() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { " + " state A; state B; A - x > A; Blubb - y > A; }" ).get(); @@ -107,9 +94,7 @@ public void testOnInvalidModel() throws IOException { checker.checkAll(ast); // we expect one error in the findings - assertEquals(1, Log.getFindings().size()); - assertEquals("0xADD31 Source state of transition missing.", - Log.getFindings().get(0).getMsg()); + MCAssertions.assertHasFindingsStartingWith("0xADD31 Source state of transition missing."); } diff --git a/monticore-test/01.experiments/build.gradle b/monticore-test/01.experiments/build.gradle index 5765c08ba2..5789ca6add 100644 --- a/monticore-test/01.experiments/build.gradle +++ b/monticore-test/01.experiments/build.gradle @@ -14,8 +14,8 @@ subprojects { dependencies { implementation "de.se_rwth.commons:se-commons-utilities:$se_commons_version" testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" } tasks.named('generateMCGrammars') { @@ -25,7 +25,7 @@ subprojects { } -configure(subprojects.findAll {it.name != 'forParser' }) { +configure(subprojects.findAll {it.name != 'forParser' && it.name != 'runtimeOnly' }) { dependencies { implementation "de.se_rwth.commons:se-commons-logging:$se_commons_version" implementation "de.se_rwth.commons:se-commons-utilities:$se_commons_version" @@ -37,10 +37,10 @@ configure(subprojects.findAll {it.name != 'forParser' }) { requireCapability("de.monticore:monticore-grammar-grammars") } } - testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation testFixtures(project(":monticore-runtime")) } + + test {useJUnitPlatform()} } clean.dependsOn(subprojects.collect{it.getTasksByName("clean", false)}) diff --git a/monticore-test/01.experiments/builderAtm/src/main/grammars/G1.mc4 b/monticore-test/01.experiments/builderAtm/src/main/grammars/G1.mc4 index 7f355d857b..72c7e21c14 100644 --- a/monticore-test/01.experiments/builderAtm/src/main/grammars/G1.mc4 +++ b/monticore-test/01.experiments/builderAtm/src/main/grammars/G1.mc4 @@ -2,4 +2,24 @@ grammar G1 extends de.monticore.MCBasics { S = "...S1" a:T; T = "T1"; + + // Next, we test that the builders do not require the operator + TestExprMandatory = l:Name operator:"&&" r:Name; + TestExprMandatoryEscaped = l:Name operator:"\"hellö" r:Name; + TestExprOpt = l:Name operator:"OPT"? r:Name; + TestExprOptGroup = l:Name (operator:"OPT_GROUP")? r:Name; + TestExprStar = l:Name operator:"STAR"* r:Name; + TestExprStarGroup = l:Name (operator:"STAR_GROUP")* r:Name; + TestExprPlus = l:Name operator:"PLUS"+ r:Name; + TestExprPlusGroup = l:Name (operator:"PLUS_GROUP")+ r:Name; + TestExprALT = l:Name (operator:"ALT1" | operator:"ALT2") r:Name; + + // Test the same with inheritance and duplicate attributes + interface TestExpression; + TestBooleanAndOpExpression implements TestExpression <120>, TestInfixExpression = + left:TestExpression operator:"&&" right:TestExpression; + interface TestInfixExpression = + left:TestExpression operator:"" right:TestExpression; + TestNameE implements TestExpression = Name; + } diff --git a/monticore-test/01.experiments/builderAtm/src/test/java/Builders4Test.java b/monticore-test/01.experiments/builderAtm/src/test/java/Builders4Test.java index 05dbce7430..25cfd7c812 100644 --- a/monticore-test/01.experiments/builderAtm/src/test/java/Builders4Test.java +++ b/monticore-test/01.experiments/builderAtm/src/test/java/Builders4Test.java @@ -1,31 +1,32 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import g1.G1Mill; import g3.G3Mill; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import g1._ast.ASTT; import g2.G2Mill; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class Builders4Test { ASTT t7,t8,t9,t10; - @Before + @BeforeEach public void setUp() throws RecognitionException, IOException { LogStub.init(); Log.enableFailQuick(false); Log.getFindings().clear(); + G2Mill.init(); t7 = G2Mill.tBuilder().build(); t8 = G2Mill.tBuilder().build(); t9 = G2Mill.tBuilder().build(); @@ -46,10 +47,10 @@ public void testG1MillS() throws IOException { .setA(t7) .setA(t8) .build(); - assertTrue(t8 == s.getA()); - assertTrue(!(t7 == s.getA())); + assertSame(t8, s.getA()); + assertNotSame(t7, s.getA()); assertEquals(g1._ast.ASTS.class, s.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests whether generated build-setters work in G2 @@ -62,12 +63,12 @@ public void testG2MillS() throws IOException { .addC(t9) .addC(t10) .build(); - assertTrue(t7 == s.getA()); - assertTrue(t8 == s.getB()); + assertSame(t7, s.getA()); + assertSame(t8, s.getB()); assertEquals(5, s.sizeC()); // 3 are predefined in the hc builder - assertTrue(t10 == s.getC(4)); + assertSame(t10, s.getC(4)); assertEquals(g2._ast.ASTS.class, s.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests: Builder from G2 derived through G1 @@ -80,7 +81,7 @@ public void testG2MillSthroughG1() throws IOException { assertEquals(g2._ast.ASTS.class, s.getClass()); // 3 are predefined in the hc builder assertEquals(3, ((g2._ast.ASTS)s).sizeC()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests: Builder from G3 derived through G1 @@ -94,7 +95,7 @@ public void testG3MillSthroughG1G2() throws IOException { // overwritten (so the result is 0) assertEquals(0, s2.sizeC()); assertEquals(g3._ast.ASTS.class, s2.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests: Builder from G3 derived through G1 @@ -108,7 +109,7 @@ public void testG3MillSthroughG1G2G3() throws IOException { // overwritten (so the result is 0) assertEquals(0, s3.sizeC()); assertEquals(g3._ast.ASTS.class, s3.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/builderAtm/src/test/java/BuildersG1G2Test.java b/monticore-test/01.experiments/builderAtm/src/test/java/BuildersG1G2Test.java index 74a352d696..1a83789a8d 100644 --- a/monticore-test/01.experiments/builderAtm/src/test/java/BuildersG1G2Test.java +++ b/monticore-test/01.experiments/builderAtm/src/test/java/BuildersG1G2Test.java @@ -1,16 +1,11 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.IOException; +import de.monticore.runtime.junit.MCAssertions; import g1.G1Mill; import g3.G3Mill; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import de.monticore.ast.Comment; import de.se_rwth.commons.logging.Log; @@ -18,12 +13,16 @@ import g1._ast.ASTT; import g1._ast.ASTTBuilder; import g2.G2Mill; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class BuildersG1G2Test { ASTT t7,t8,t9,t10; - @Before + @BeforeEach public void setUp() throws RecognitionException, IOException { LogStub.init(); Log.enableFailQuick(false); @@ -43,7 +42,7 @@ public void testG1MillTBuilder() throws IOException { .add_PreComment(new Comment("blubb2")); assertEquals(2, tb.size_PreComments()); assertEquals("blubb2", tb.get_PreComment(1).getText()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests whether inherited attributes are set through builder @@ -55,7 +54,7 @@ public void testG1MillT() throws IOException { .build(); assertEquals(2, t.size_PreComments()); assertEquals("blubb2", t.get_PreComment(1).getText()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests whether generated build-setters work @@ -66,10 +65,10 @@ public void testG1MillS() throws IOException { .setA(t7) .setA(t8) .build(); - assertTrue(t8 == s.getA()); - assertTrue(!(t7 == s.getA())); + assertSame(t8, s.getA()); + assertFalse(t7 == s.getA()); assertEquals(g1._ast.ASTS.class, s.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests whether generated build-setters work in G2 @@ -81,12 +80,12 @@ public void testG2MillS() throws IOException { .addC(t9) .addC(t10) .build(); - assertTrue(t7 == s.getA()); - assertTrue(t8 == s.getB()); + assertSame(t7, s.getA()); + assertSame(t8, s.getB()); assertEquals(5, s.sizeC()); - assertTrue(t10 == s.getC(4)); + assertSame(t10, s.getC(4)); assertEquals(g2._ast.ASTS.class, s.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests whether generated build-setters work in G2 @@ -111,9 +110,9 @@ public void testG2MillSthroughG1() throws IOException { g1._ast.ASTS s = G1Mill.sBuilder() .setA(t7) .build(); - assertTrue(t7 == s.getA()); + assertSame(t7, s.getA()); assertEquals(g2._ast.ASTS.class, s.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests: Builder from G3 derived through G1 @@ -123,21 +122,21 @@ public void testG3MillSthroughG1G2() throws IOException { g1._ast.ASTS s = G1Mill.sBuilder() .setA(t7) .build(); - assertTrue(t7 == s.getA()); + assertSame(t7, s.getA()); assertEquals(g3._ast.ASTS.class, s.getClass()); g2._ast.ASTS s2 = G2Mill.sBuilder() .setA(t7) .build(); - assertTrue(t7 == s2.getA()); + assertSame(t7, s2.getA()); assertEquals(g3._ast.ASTS.class, s2.getClass()); g3._ast.ASTS s3 = G3Mill.sBuilder() .setA(t7) .build(); - assertTrue(t7 == s3.getA()); + assertSame(t7, s3.getA()); assertEquals(g3._ast.ASTS.class, s3.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } diff --git a/monticore-test/01.experiments/builderAtm/src/test/java/BuildersTest.java b/monticore-test/01.experiments/builderAtm/src/test/java/BuildersTest.java index b00ff66ecb..18371506b5 100644 --- a/monticore-test/01.experiments/builderAtm/src/test/java/BuildersTest.java +++ b/monticore-test/01.experiments/builderAtm/src/test/java/BuildersTest.java @@ -2,26 +2,22 @@ import automata.AutomataMill; import automata._ast.*; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(AutomataMill.class) public class BuildersTest { - @Before - public void setUp() throws RecognitionException, IOException { - LogStub.init(); - Log.enableFailQuick(false); - Log.getFindings().clear(); - } // tests whether handcoded subclass of Builder is used // (which should be included upon generation) @@ -33,7 +29,7 @@ public void testMyTransitionBuilder() throws IOException { .setInput("xxxx") .setTo("setByGenBuilder").build(); assertEquals("xxxxSuf2", transition.getInput()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests whether handcoded subclass of Builder is used @@ -51,7 +47,7 @@ public void testMyTransitionBuilderInSubNT() throws IOException { ASTActTransition transition = b.build(); assertEquals("xxxx", transition.getInput()); assertEquals("Boom", transition.getAction()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -60,7 +56,7 @@ public void testHWCClassGeneratedBuilder() throws IOException { .automatonBuilder() .setName("setByGeneratedBuilder").build(); assertEquals("setByGeneratedBuilder", aut.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests whether handcoded subclass of Builder is used @@ -73,7 +69,7 @@ public void testHWCClassHWCBuilder() throws IOException { .setFinal(true) .setName("state1").build(); assertEquals(state.getName(), "state1Suf1"); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // tests whether handcoded subclass of Builder is used @@ -87,10 +83,10 @@ public void testHWCClassHWCBuilderInSubNT() throws IOException { b.setEntry("Blubb"); b.setName("state1"); ASTActState state = b.build(); - assertEquals(state.isFinal(), true); + assertTrue(state.isFinal()); assertEquals(state.getName(), "state1Suf1"); assertEquals(state.getEntry(), "Blubb"); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -100,9 +96,9 @@ public void testGetFunctions() throws IOException { .setName("x2") .setFinal(true) .setName("state1"); - assertEquals(sb.isFinal(), true); + assertTrue(sb.isFinal()); assertEquals(sb.getName(), "state1Suf1"); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/builderAtm/src/test/java/G1TerminalBuildersTest.java b/monticore-test/01.experiments/builderAtm/src/test/java/G1TerminalBuildersTest.java new file mode 100644 index 0000000000..12c2880688 --- /dev/null +++ b/monticore-test/01.experiments/builderAtm/src/test/java/G1TerminalBuildersTest.java @@ -0,0 +1,85 @@ +/* (c) https://github.com/MontiCore/monticore */ + +import de.monticore.runtime.junit.TestWithMCLanguage; +import g1.G1Mill; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * Test that we can build expressions with a terminal present within the AST + * without specifying this terminal + */ +@TestWithMCLanguage(g1.G1Mill.class) +public class G1TerminalBuildersTest { + + @Test + public void testExprMandatory() { + var elem = G1Mill.testExprMandatoryBuilder().setL("l").setR("r").build(); + Assertions.assertEquals("&&", elem.getOperator()); + } + + @Test + public void testExprMandatoryEscaped() { + var elem = G1Mill.testExprMandatoryEscapedBuilder().setL("l").setR("r").build(); + Assertions.assertEquals("\"hellö", elem.getOperator()); + } + + @Test + public void testExprOpt() { + var elem = G1Mill.testExprOptBuilder().setL("l").setR("r").build(); + Assertions.assertFalse(elem.isPresentOperator()); + } + + @Test + public void testExprOptGroup() { + var elem = G1Mill.testExprOptGroupBuilder().setL("l").setR("r").build(); + Assertions.assertFalse(elem.isPresentOperator()); + } + + @Test + public void testExprStar() { + var elem = G1Mill.testExprStarBuilder().setL("l").setR("r").build(); + Assertions.assertEquals(0, elem.getOperatorList().size()); + } + + @Test + public void testExprStarGroup() { + var elem = G1Mill.testExprStarGroupBuilder().setL("l").setR("r").build(); + Assertions.assertEquals(0, elem.getOperatorList().size()); + } + + @Test + public void testExprPlus() { + // One could consider if the correct answer here should be 1 + var elem = G1Mill.testExprPlusBuilder().setL("l").setR("r").build(); + Assertions.assertEquals(0, elem.getOperatorList().size()); + } + + @Test + public void testExprPlusGroup() { + // One could consider if the correct answer here should be 1 + var elem = G1Mill.testExprPlusGroupBuilder().setL("l").setR("r").build(); + Assertions.assertEquals(0, elem.getOperatorList().size()); + } + + @Test + public void testExprALT() { + // One could consider if this should lead to an error + var elem = G1Mill.testExprALTBuilder().setL("l").setR("r").build(); + Assertions.assertFalse(elem.isPresentOperator()); + } + + @Test + public void testBooleanAndOpExpression() { + // First, check that we can still call build() without an operator + var elem = G1Mill.testBooleanAndOpExpressionBuilder() + .setLeft(G1Mill.testNameEBuilder().setName("l").build()) + .setRight(G1Mill.testNameEBuilder().setName("r").build()) + .build(); + // With duplicate attributes: Check that the correct operator-attribute was used + Assertions.assertEquals("&&", elem.getOperator()); + // The InfixExpression's operator:"" MUST not match + // (and yes, this is a redundant check) + Assertions.assertNotEquals("", elem.getOperator()); + } +} diff --git a/monticore-test/01.experiments/ch17/src/test/java/HAutomataTest.java b/monticore-test/01.experiments/ch17/src/test/java/HAutomataTest.java index 375c45161f..d006225200 100644 --- a/monticore-test/01.experiments/ch17/src/test/java/HAutomataTest.java +++ b/monticore-test/01.experiments/ch17/src/test/java/HAutomataTest.java @@ -1,29 +1,24 @@ /* (c) https://github.com/MontiCore/monticore */ +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.*; -import hautomata._parser.HAutomataParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import hautomata.HAutomataMill; +import org.junit.jupiter.api.Test; import sautomata._ast.ASTAutomaton; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(HAutomataMill.class) public class HAutomataTest { - @Before - public void before() { - LogStub.init(); - Log.enableFailQuick(false); - } - @Test public void testPingPong() throws IOException { - Optional a = new HAutomataParser().parse("src/main/resources/hautomata/PingPong.aut"); + Optional a = HAutomataMill.parser().parse("src/main/resources/hautomata/PingPong.aut"); assertTrue(a.isPresent()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/ch17/src/test/java/IAutomataTest.java b/monticore-test/01.experiments/ch17/src/test/java/IAutomataTest.java index 9edbe384a5..47a1b875b3 100644 --- a/monticore-test/01.experiments/ch17/src/test/java/IAutomataTest.java +++ b/monticore-test/01.experiments/ch17/src/test/java/IAutomataTest.java @@ -1,29 +1,23 @@ /* (c) https://github.com/MontiCore/monticore */ -import de.se_rwth.commons.logging.*; -import iautomata._parser.IAutomataParser; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; +import iautomata.IAutomataMill; import iautomatacomp._ast.ASTAutomaton; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(IAutomataMill.class) public class IAutomataTest { - @Before - public void setup() { - LogStub.init(); // replace log by a sideffect free variant - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - } - @Test public void testPingPong() throws IOException { - Optional a = new IAutomataParser().parse("src/main/resources/iautomata/PingPong.aut"); + Optional a = IAutomataMill.parser().parse("src/main/resources/iautomata/PingPong.aut"); assertTrue(a.isPresent()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/ch17/src/test/java/SAutomataTest.java b/monticore-test/01.experiments/ch17/src/test/java/SAutomataTest.java index 4aa4d35e26..484898047b 100644 --- a/monticore-test/01.experiments/ch17/src/test/java/SAutomataTest.java +++ b/monticore-test/01.experiments/ch17/src/test/java/SAutomataTest.java @@ -1,39 +1,32 @@ /* (c) https://github.com/MontiCore/monticore */ -import de.se_rwth.commons.logging.*; +import de.monticore.runtime.junit.TestWithMCLanguage; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import sautomata.SAutomataMill; import sautomata._ast.ASTAutomaton; -import sautomata._parser.SAutomataParser; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; +@TestWithMCLanguage(SAutomataMill.class) public class SAutomataTest { - @Before - public void setup() { - LogStub.init(); // replace log by a sideffect free variant - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - } - @Test public void testPingPong() throws IOException { - Optional a = new SAutomataParser().parse("src/main/resources/PingPong.aut"); + Optional a = SAutomataMill.parser().parse("src/main/resources/PingPong.aut"); assertTrue(a.isPresent()); - assertTrue(Log.getFindings().isEmpty()); + assertNoFindings(); } @Test public void testSimple12() throws RecognitionException, IOException { - Optional a = new SAutomataParser().parse("src/main/resources/Simple12.aut"); + Optional a = SAutomataMill.parser().parse("src/main/resources/Simple12.aut"); assertTrue(a.isPresent()); - assertTrue(Log.getFindings().isEmpty()); + assertNoFindings(); } } diff --git a/monticore-test/01.experiments/composition/src/main/grammars/A.mc4 b/monticore-test/01.experiments/composition/src/main/grammars/A.mc4 index 8ab85dede1..8e6cfda1ae 100644 --- a/monticore-test/01.experiments/composition/src/main/grammars/A.mc4 +++ b/monticore-test/01.experiments/composition/src/main/grammars/A.mc4 @@ -1,3 +1,9 @@ /* (c) https://github.com/MontiCore/monticore */ -grammar A { N = "n"; } +grammar A { + N = "n"; + + // Test, that classes (from the classpath) are useable in the astextends part + MyProd implements MyInterfaceASTExtends ; // astextends composition.MyClass is prohibited by NoASTExtendsForClasses / 0xA4097 + interface MyInterfaceASTExtends astextends composition.MyInterface; // any class not specified by a grammar +} diff --git a/monticore-test/01.experiments/composition/src/main/grammars/B.mc4 b/monticore-test/01.experiments/composition/src/main/grammars/B.mc4 index faab96bacb..b4bfc4ef58 100644 --- a/monticore-test/01.experiments/composition/src/main/grammars/B.mc4 +++ b/monticore-test/01.experiments/composition/src/main/grammars/B.mc4 @@ -1,3 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ -grammar B extends A { M = "m"; } +grammar B extends A { + M = "m"; + @Override MyProd = "world"; +} diff --git a/monticore-test/01.experiments/composition/src/main/grammars/C.mc4 b/monticore-test/01.experiments/composition/src/main/grammars/C.mc4 index 1a34971bf2..7b2b420a98 100644 --- a/monticore-test/01.experiments/composition/src/main/grammars/C.mc4 +++ b/monticore-test/01.experiments/composition/src/main/grammars/C.mc4 @@ -1,3 +1,5 @@ /* (c) https://github.com/MontiCore/monticore */ -grammar C { O = "o"; } +grammar C { + O = "o"; +} diff --git a/monticore-test/01.experiments/composition/src/main/grammars/D.mc4 b/monticore-test/01.experiments/composition/src/main/grammars/D.mc4 index 49f0f0f8cb..5e22c9d3a5 100644 --- a/monticore-test/01.experiments/composition/src/main/grammars/D.mc4 +++ b/monticore-test/01.experiments/composition/src/main/grammars/D.mc4 @@ -1,3 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ -grammar D extends B,C { P = "p"; } +grammar D extends B,C { + P = "p"; + @Override MyProd = "hello_world"; +} diff --git a/monticore-test/01.experiments/composition/src/main/java/composition/MyInterface.java b/monticore-test/01.experiments/composition/src/main/java/composition/MyInterface.java new file mode 100644 index 0000000000..5ea934d52a --- /dev/null +++ b/monticore-test/01.experiments/composition/src/main/java/composition/MyInterface.java @@ -0,0 +1,6 @@ +/* (c) https://github.com/MontiCore/monticore */ +package composition; + +public interface MyInterface { + // interface referred to in astrule +} diff --git a/monticore-test/01.experiments/composition/src/test/java/Automata3ToolTest.java b/monticore-test/01.experiments/composition/src/test/java/Automata3ToolTest.java index 56a23b92bd..a2b727da51 100644 --- a/monticore-test/01.experiments/composition/src/test/java/Automata3ToolTest.java +++ b/monticore-test/01.experiments/composition/src/test/java/Automata3ToolTest.java @@ -1,21 +1,21 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.List; import automata3.Automata3Tool; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class Automata3ToolTest { - @Before + @BeforeEach public void init() { LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only @@ -26,7 +26,7 @@ public void init() { @Test public void executePingPong() throws IOException { - Automata3Tool.main(new String[] { "-i", "src/test/resources/example/PingPongInv.aut" }); + new Automata3Tool().run(new String[] { "-i", "src/test/resources/example/PingPongInv.aut" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); // for manual testing purpose only @@ -35,26 +35,26 @@ public void executePingPong() throws IOException { assertEquals(6, p.size()); // Check some "[INFO]" outputs - assertTrue(p.get(0), p.get(0).matches(".*.INFO. Automata3Tool Automata3 DSL Tool.*(\r)?\n")); + assertTrue(p.get(0).matches(".*.INFO. Automata3Tool Automata3 DSL Tool.*(\r)?\n"), p.get(0)); // Check resulting pretty print: String res = p.get(p.size()-1).replaceAll("[\r\n]", " "); - assertTrue(res, res.matches(".*print by composed Automata3PrettyPrinter.*")); + assertTrue(res.matches(".*print by composed Automata3PrettyPrinter.*"), res); // original: state NoGame /*[*/ true /*]*/ <> - assertTrue(res, res.matches(".*state NoGame /.../ true /.../ <>.*")); - assertTrue(res, res.matches(".*Pong - returnBall > Ping;.*")); - assertTrue(Log.getFindings().isEmpty()); + assertTrue(res.matches(".*state NoGame /.../ true /.../ <>.*"), res); + assertTrue(res.matches(".*Pong - returnBall > Ping;.*"), res); + MCAssertions.assertNoFindings(); } @Test public void executeSimple12() throws IOException { - Automata3Tool.main(new String[] { "-i", "src/test/resources/example/Simple12Inv.aut" }); + new Automata3Tool().run(new String[] { "-i", "src/test/resources/example/Simple12Inv.aut" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); List p = LogStub.getPrints(); assertEquals(6, p.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/composition/src/test/java/GTest.java b/monticore-test/01.experiments/composition/src/test/java/GTest.java index 961585d688..a158d60f5c 100644 --- a/monticore-test/01.experiments/composition/src/test/java/GTest.java +++ b/monticore-test/01.experiments/composition/src/test/java/GTest.java @@ -1,5 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import g.GMill; @@ -7,24 +8,17 @@ import g._ast.ASTB; import g._ast.ASTC; import g._parser.GParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(GMill.class) public class GTest { - @Before - public void init() { - LogStub.init(); // replace log by a sideffect free variant - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - } - @Test public void testG() throws IOException { GParser p = GMill.parser(); @@ -33,8 +27,6 @@ public void testG() throws IOException { Optional ast2 = p.parse_String("\"foo\": 9"); assertTrue(ast2.isPresent() && ast2.get() instanceof ASTB); - - } } diff --git a/monticore-test/01.experiments/composition/src/test/java/HierInvAutomataToolTest.java b/monticore-test/01.experiments/composition/src/test/java/HierInvAutomataToolTest.java index 5386feca71..33d7a9651b 100644 --- a/monticore-test/01.experiments/composition/src/test/java/HierInvAutomataToolTest.java +++ b/monticore-test/01.experiments/composition/src/test/java/HierInvAutomataToolTest.java @@ -1,6 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.List; @@ -8,14 +8,13 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import hierinvautomata.HierInvAutomataTool; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class HierInvAutomataToolTest { - @Before + @BeforeEach public void init() { LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only @@ -26,7 +25,7 @@ public void init() { @Test public void executePingPong() throws IOException { - HierInvAutomataTool.main(new String[] { "-i", "src/test/resources/example/PingPongInv.aut" }); + new HierInvAutomataTool().run(new String[] { "-i", "src/test/resources/example/PingPongInv.aut" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); // for manual testing purpose only @@ -36,20 +35,20 @@ public void executePingPong() throws IOException { assertEquals(59, p.size()); // many small prints ... // Check some "[INFO]" outputs - assertTrue(p.get(0), p.get(0).matches(".*.INFO. HierIAT HierInvAutomata DSL Tool.*(\r)?\n")); + assertTrue(p.get(0).matches(".*.INFO. HierIAT HierInvAutomata DSL Tool.*(\r)?\n"), p.get(0)); // Check resulting pretty print: String res = String.join("",p).replaceAll("\r\n", " ").replaceAll("\n", " "); // original: state Pung <> [[ &&[ &&[ &&[ true v1 ] ! false ] v2 ] ]] - assertTrue(res, res.matches(".*state Pung <> .. &&. &&. &&. true v1 ] ! false ] v2 ] ]].*")); - assertTrue(res, res.matches(".*Pong - returnBall > Ping;.*")); + assertTrue(res.matches(".*state Pung <> .. &&. &&. &&. true v1 ] ! false ] v2 ] ]].*"), res); + assertTrue(res.matches(".*Pong - returnBall > Ping;.*"), res); } @Test public void executeSimple12() throws IOException { - HierInvAutomataTool.main(new String[] { "-i", "src/test/resources/example/Simple12Inv.aut" }); + new HierInvAutomataTool().run(new String[] { "-i", "src/test/resources/example/Simple12Inv.aut" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); @@ -59,7 +58,7 @@ public void executeSimple12() throws IOException { @Test public void executeHierarchyPingPong() throws IOException { - HierInvAutomataTool.main(new String[] { "-i", "src/test/resources/example/Hierarchy12Inv.aut" }); + new HierInvAutomataTool().run(new String[] { "-i", "src/test/resources/example/Hierarchy12Inv.aut" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); diff --git a/monticore-test/01.experiments/demonstrator/build.gradle b/monticore-test/01.experiments/demonstrator/build.gradle index 4dbd010090..8b50c3d46a 100644 --- a/monticore-test/01.experiments/demonstrator/build.gradle +++ b/monticore-test/01.experiments/demonstrator/build.gradle @@ -1,26 +1,43 @@ /* (c) https://github.com/MontiCore/monticore */ plugins { - // provides a convenient way to have multiple test sets - id 'org.unbroken-dome.test-sets' version '4.0.0' + // provides a convenient way to have multiple test suites + id 'jvm-test-suite' } description = 'Experiments: automata' // The grammars of this subproject are built by the generateMCGrammars MCGenTask -// create an additional test set called productTest -testSets{ - productTest { extendsFrom unitTest } +// create an additional test suite called productTest +testing { + suites { + test { + useJUnitJupiter(junit_version) + } + + productTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project(":monticore-runtime")) + runtimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" + } + sources { + java.srcDirs += ["$buildDir/statepattern" , "$projectDir/src/product/java"] + } + } + } } -sourceSets { - // add output dir to the sources of productTest - productTest.java.srcDirs += ["$buildDir/statepattern" , "$projectDir/src/product/java"] +// let check depend on productTest such that it is included in the build +tasks.named('check') { + dependsOn(testing.suites.productTest) } // let productTest depend on test as test produces code for productTest -compileProductTestJava.dependsOn(test) +tasks.named("compileProductTestJava") { + dependsOn(test) +} test.configure { // The test task builds the productTest inputs @@ -29,7 +46,5 @@ test.configure { outputs.upToDateWhen {false} } -// let check depend on productTest such that it is included in the build -check.dependsOn(productTest) diff --git a/monticore-test/01.experiments/demonstrator/src/main/java/automata/AutomataTool.java b/monticore-test/01.experiments/demonstrator/src/main/java/automata/AutomataTool.java index a326a613f5..55f5c787fb 100644 --- a/monticore-test/01.experiments/demonstrator/src/main/java/automata/AutomataTool.java +++ b/monticore-test/01.experiments/demonstrator/src/main/java/automata/AutomataTool.java @@ -68,13 +68,13 @@ public class AutomataTool extends AutomataToolTOP { // the symbol table of the model (after parsing and SymTab creation) IAutomataArtifactScope modelTopScope; // Two dimensional map: SourceState x Stimulus -> Transition - Map> deltaMap = new HashMap<>(); + Map> deltaMap = new LinkedHashMap<>(); // Map: Name -> State (== State-Symbols) - Map stateMap = new HashMap<>(); + Map stateMap = new LinkedHashMap<>(); // List of stimuli - Set stimuli = new HashSet<>(); + Set stimuli = new LinkedHashSet<>(); /** * Entry method of the AutomataTool: @@ -350,7 +350,7 @@ protected void deriveStateMap_DeltaMap() { // initialize delta: transition map of maps, and state name2node for (ASTState s : ast.getStateList()) { stateMap.put(s.getName(), s); - deltaMap.put(s, new HashMap<>()); + deltaMap.put(s, new LinkedHashMap<>()); } // Add the transitions to the table diff --git a/monticore-test/01.experiments/demonstrator/src/productTest/java/PingPongTest.java b/monticore-test/01.experiments/demonstrator/src/productTest/java/PingPongTest.java index e599b60809..243a72f445 100644 --- a/monticore-test/01.experiments/demonstrator/src/productTest/java/PingPongTest.java +++ b/monticore-test/01.experiments/demonstrator/src/productTest/java/PingPongTest.java @@ -1,53 +1,51 @@ /* (c) https://github.com/MontiCore/monticore */ -import de.se_rwth.commons.logging.LogStub; -import org.junit.Test; +import de.monticore.runtime.junit.MCAssertions; -import static org.junit.Assert.*; -import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.*; public class PingPongTest { String message = "The automaton is not in state \"%s\""; - @Test + @org.junit.jupiter.api.Test public void testPingPong(){ PingPong pingpong = new PingPong(); // assert we are in the initial state - assertTrue(String.format(message,"NoGame"),pingpong.currentState instanceof NoGameState); + assertInstanceOf(NoGameState.class, pingpong.currentState, String.format(message, "NoGame")); // trigger startGame pingpong.startGame(); // assert we are in state Ping - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger returnBall pingpong.returnBall(); // assert we are in state Pong - assertTrue(String.format(message,"Pong"), pingpong.currentState instanceof PongState); + assertInstanceOf(PongState.class, pingpong.currentState, String.format(message, "Pong")); // trigger returnBall pingpong.returnBall(); // assert we are in state Ping again - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger startGame pingpong.startGame(); // assert we are still in state Ping (wrong input should be ignored) - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger stopGame pingpong.stopGame(); // assert we are in state NoGame - assertTrue(String.format(message,"NoGame"), pingpong.currentState instanceof NoGameState); + assertInstanceOf(NoGameState.class, pingpong.currentState, String.format(message, "NoGame")); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/demonstrator/src/test/java/AutomataParseTest.java b/monticore-test/01.experiments/demonstrator/src/test/java/AutomataParseTest.java index 1196583a07..61915e5577 100644 --- a/monticore-test/01.experiments/demonstrator/src/test/java/AutomataParseTest.java +++ b/monticore-test/01.experiments/demonstrator/src/test/java/AutomataParseTest.java @@ -1,33 +1,25 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; import java.util.Optional; +import automata.AutomataMill; import automata._ast.ASTAutomaton; import automata._ast.ASTState; import automata._parser.AutomataParser; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Main class for the some Demonstration to Parse */ +@TestWithMCLanguage(AutomataMill.class) public class AutomataParseTest { - @Before - public void init() { - LogStub.init(); // replace log by a sideffect free variant - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - Log.clearFindings(); - LogStub.clearPrints(); - } - /** * @throws IOException * @@ -36,7 +28,7 @@ public void init() { public void testParseMethods() throws IOException { String filename = "src/test/resources/example/PingPong.aut"; - AutomataParser p = new AutomataParser(); + AutomataParser p = AutomataMill.parser(); // parse from a file Optional at = p.parse(filename); @@ -56,7 +48,7 @@ public void testParseMethods() throws IOException { // parse for a sublanguage, here: a State Optional s = p.parse_StringState("state Ping;"); assertTrue(s.isPresent()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } diff --git a/monticore-test/01.experiments/demonstrator/src/test/java/AutomataToolTest.java b/monticore-test/01.experiments/demonstrator/src/test/java/AutomataToolTest.java index 9f87d27d70..3e30d4b2bd 100644 --- a/monticore-test/01.experiments/demonstrator/src/test/java/AutomataToolTest.java +++ b/monticore-test/01.experiments/demonstrator/src/test/java/AutomataToolTest.java @@ -2,20 +2,23 @@ import automata.AutomataMill; import automata.AutomataTool; +import de.monticore.runtime.junit.MCAssertions; import org.junit.*; import de.se_rwth.commons.logging.Log; import java.util.*; import java.util.regex.Pattern; import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; public class AutomataToolTest { - @Before + @BeforeEach public void init(){ LogStub.init();// replace log by a sideffect free variant Log.enableFailQuick(false); @@ -28,29 +31,29 @@ public void init(){ */ @Test public void testPingPong(){ - AutomataTool.main(new String[] { "-i", "src/test/resources/example/PingPong.aut", + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/PingPong.aut", "-path", "target/PingPong.autsym", "-hw", "src/product/java", "-o", "target/statepattern", "-s", "target/example/PingPong.autsym"}); assertEquals(0, Log.getErrorCount()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void testSimple12(){ - AutomataTool.main(new String[] { "-i", "src/test/resources/example/Simple12.aut", + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/Simple12.aut", "-path", "target/Simple12.autsym", "-hw", "src/product/java", "-o", "target/statepattern", "-s", "target/example/Simple12.autsym"}); assertEquals(0, Log.getErrorCount()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void testWrongArguments(){ - AutomataTool.main(new String[] { }); + new AutomataTool().run(new String[] { }); assertEquals(1, Log.getErrorCount()); assertEquals("0xA5C02 Must specify an Input file." , Log.getFindings().get(0).buildMsg()); diff --git a/monticore-test/01.experiments/demonstrator/src/test/java/TransitionSourceExistsTest.java b/monticore-test/01.experiments/demonstrator/src/test/java/TransitionSourceExistsTest.java index 6de548cc79..10790a7f73 100644 --- a/monticore-test/01.experiments/demonstrator/src/test/java/TransitionSourceExistsTest.java +++ b/monticore-test/01.experiments/demonstrator/src/test/java/TransitionSourceExistsTest.java @@ -9,57 +9,38 @@ import automata.cocos.TransitionSourceExists; import de.monticore.ast.ASTNode; import de.monticore.io.paths.MCPath; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(AutomataMill.class) public class TransitionSourceExistsTest { - - // setup the parser infrastructure - AutomataParser parser = new AutomataParser() ; - - @Before - public void init() { - // replace log by a sideffect free variant - LogStub.init(); - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - } - - - @Before - public void setUp() throws RecognitionException, IOException { - Log.getFindings().clear(); - } - - // -------------------------------------------------------------------- + @Test public void testBasics() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { state A; state B; A - x > A; A - y > A; }" ).get(); assertEquals("Simple", ast.getName()); List st = ast.getStateList(); assertEquals(2, st.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testRetrievalOfSymbol() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { state A; state B; A - x > A; B - y > A; }" ).get(); @@ -73,14 +54,14 @@ public void testRetrievalOfSymbol() throws IOException { assertEquals("A", aSymbol.get().getName()); ASTNode n = aSymbol.get().getAstNode(); assertEquals("A", ((ASTState)n).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testOnValidModel() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { state A; state B; A -x> A; B -y> A; }" ).get(); @@ -93,13 +74,13 @@ public void testOnValidModel() throws IOException { checker.checkAll(ast); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testOnInvalidModel() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { " + " state A; state B; A - x > A; Blubb - y > A; }" ).get(); @@ -114,9 +95,7 @@ public void testOnInvalidModel() throws IOException { checker.checkAll(ast); // we expect one error in the findings - assertEquals(1, Log.getFindings().size()); - assertEquals("0xDDD03 Source state of transition missing.", - Log.getFindings().get(0).getMsg()); + MCAssertions.assertHasFindingsStartingWith("0xDDD03 Source state of transition missing."); } diff --git a/monticore-test/01.experiments/forConcSt/src/test/java/minimalexample/ParserTest.java b/monticore-test/01.experiments/forConcSt/src/test/java/minimalexample/ParserTest.java index b910d4ce75..7900b98e9c 100644 --- a/monticore-test/01.experiments/forConcSt/src/test/java/minimalexample/ParserTest.java +++ b/monticore-test/01.experiments/forConcSt/src/test/java/minimalexample/ParserTest.java @@ -1,26 +1,21 @@ package minimalexample;/* (c) https://github.com/MontiCore/monticore */ +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import minimalexample._ast.ASTC; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(MinimalExampleMill.class) public class ParserTest { - @Before - public void setUp(){ - LogStub.init(); - Log.enableFailQuick(false); - } - @Test public void testCardinality() throws IOException { Optional ast = MinimalExampleMill.parser().parse_StringC("C foo 1"); diff --git a/monticore-test/01.experiments/forConcSt/src/test/java/sm2/SM2ToolTest.java b/monticore-test/01.experiments/forConcSt/src/test/java/sm2/SM2ToolTest.java index d7d936bc55..d5c81ddaef 100644 --- a/monticore-test/01.experiments/forConcSt/src/test/java/sm2/SM2ToolTest.java +++ b/monticore-test/01.experiments/forConcSt/src/test/java/sm2/SM2ToolTest.java @@ -2,49 +2,48 @@ package sm2; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SM2ToolTest { - @Before + @BeforeEach public void init() { LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only Log.enableFailQuick(false); Log.clearFindings(); LogStub.clearPrints(); - SM2Mill.globalScope().clear(); + SM2Mill.reset(); } @Test public void test() { String[] args = {"-i","src/test/resources/example/PingPong.aut"}; SM2Tool.main(args); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); List p = LogStub.getPrints(); assertEquals(9, p.size()); // Check some "[INFO]" outputs - Assert.assertTrue(p.get(0), p.get(0).matches(".*.INFO. SM2Tool SM2 DSL Tool.*(\r)?\n")); - Assert.assertTrue(p.get(3), p.get(3).matches(".*.INFO. .* StateSymbol defined for NoGame.*(\r)?\n")); - Assert.assertTrue(p.get(6), p.get(6).matches(".*.INFO. .* The model contains 3 states.*(\r)?\n")); + assertTrue(p.get(0).matches(".*.INFO. SM2Tool SM2 DSL Tool.*(\r)?\n"), p.get(0)); + assertTrue(p.get(3).matches(".*.INFO. .* StateSymbol defined for NoGame.*(\r)?\n"), p.get(3)); + assertTrue(p.get(6).matches(".*.INFO. .* The model contains 3 states.*(\r)?\n"), p.get(6)); // Check resulting pretty print: String res = p.get(p.size()-1).replaceAll("\r\n", " ").replaceAll("\n", " "); assertEquals(231, res.length()); - Assert.assertTrue(res, res.matches(".*state NoGame <>.*")); - Assert.assertTrue(res, res.matches(".*Pong - returnBall > Ping;.*")); - Assert.assertTrue(Log.getFindings().isEmpty()); + assertTrue(res.matches(".*state NoGame <>.*"), res); + assertTrue(res.matches(".*Pong - returnBall > Ping;.*"), res); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/forMill/src/test/java/MillTest.java b/monticore-test/01.experiments/forMill/src/test/java/MillTest.java index 08e94432bb..aff7262b15 100644 --- a/monticore-test/01.experiments/forMill/src/test/java/MillTest.java +++ b/monticore-test/01.experiments/forMill/src/test/java/MillTest.java @@ -1,27 +1,20 @@ /* (c) https://github.com/MontiCore/monticore */ -import de.se_rwth.commons.logging.Log; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.runtime.junit.TestWithMCLanguage; import g1.G1Mill; import g2.G2Mill; import g3.G3Mill; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -public class MillTest { - - @BeforeEach - public void before() { - G2Mill.globalScope().clear(); - G2Mill.reset(); - Log.init(); - } +@TestWithMCLanguage(G2Mill.class) +public class MillTest extends AbstractMCTest { @Test public void testCDClassMillDelegation() { - G3Mill.init(); // All Mills should return a builder of the g2.Foo (overriding the g1.Foo) assertEquals(G3Mill.fooBuilder().uncheckedBuild().getClass(), G2Mill.fooBuilder().uncheckedBuild().getClass()); diff --git a/monticore-test/01.experiments/forParser/build.gradle b/monticore-test/01.experiments/forParser/build.gradle index f0669a6036..59efeb1aa2 100644 --- a/monticore-test/01.experiments/forParser/build.gradle +++ b/monticore-test/01.experiments/forParser/build.gradle @@ -12,6 +12,10 @@ dependencies { implementation project(path: ':monticore-runtime') } +test { + useJUnitPlatform() +} + sourceSets { main.java.srcDirs = [ "$projectDir/src/main/java" ] } diff --git a/monticore-test/01.experiments/forParser/src/test/java/GenerateAutomataParserTest.java b/monticore-test/01.experiments/forParser/src/test/java/GenerateAutomataParserTest.java index e8f1a2db1d..652255789b 100644 --- a/monticore-test/01.experiments/forParser/src/test/java/GenerateAutomataParserTest.java +++ b/monticore-test/01.experiments/forParser/src/test/java/GenerateAutomataParserTest.java @@ -1,15 +1,15 @@ /* (c) https://github.com/MontiCore/monticore */ import de.se_rwth.commons.logging.*; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class GenerateAutomataParserTest { - @Before + @BeforeEach public void setup() { LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only @@ -19,7 +19,7 @@ public void setup() { // Für die Ausführung dieses Tests muss in der Pom u.U. die Versionsnummer // für monticore-grammar und monticore-grammar-grammars auf ${last.mc.release} // gesetzt werden - @Ignore + @Disabled @Test public void test() { String[] args = {"src/test/resources/Automata.mc4", "target/gen"}; diff --git a/monticore-test/01.experiments/generator/src/test/java/HierAutomataTest.java b/monticore-test/01.experiments/generator/src/test/java/HierAutomataTest.java index 17148d37fb..88d78af25b 100644 --- a/monticore-test/01.experiments/generator/src/test/java/HierAutomataTest.java +++ b/monticore-test/01.experiments/generator/src/test/java/HierAutomataTest.java @@ -2,36 +2,26 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; +import hierautomata.HierAutomataMill; import hierautomata._ast.ASTStateMachine; import hierautomata._parser.HierAutomataParser; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Main class for the HierAutomaton DSL tool. - */ +@TestWithMCLanguage(HierAutomataMill.class) public class HierAutomataTest { - @Before - public void init() { - LogStub.init(); // replace log by a sideffect free variant - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - Log.clearFindings(); - LogStub.clearPrints(); - } - @Test public void toolTest() { @@ -84,7 +74,7 @@ public void toolTest() { ge = new GeneratorEngine(s); ge.generate("tpl3/StateMachine.ftl", Paths.get("pingPong.aut"), ast); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } /** @@ -96,7 +86,7 @@ public void toolTest() { public ASTStateMachine parse(String model) { Optional optStateMachine = Optional.empty(); try { - HierAutomataParser parser = new HierAutomataParser(); + HierAutomataParser parser = HierAutomataMill.parser(); optStateMachine = parser.parse(model); if (parser.hasErrors()) { diff --git a/monticore-test/01.experiments/generator/src/test/java/SuperLexerTest.java b/monticore-test/01.experiments/generator/src/test/java/SuperLexerTest.java index b4d10aabab..15fe787718 100644 --- a/monticore-test/01.experiments/generator/src/test/java/SuperLexerTest.java +++ b/monticore-test/01.experiments/generator/src/test/java/SuperLexerTest.java @@ -1,33 +1,25 @@ /* (c) https://github.com/MontiCore/monticore */ -import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.Test; +import de.monticore.runtime.junit.TestWithMCLanguage; +import org.junit.jupiter.api.Test; import superlexer.ModifiedMCLexerBase; import superlexer.SuperLexerMill; import superlexer._parser.SuperLexerParser; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Test that the LexerSuperGrammar AntlrOption works */ +@TestWithMCLanguage(SuperLexerMill.class) public class SuperLexerTest { - - @Before - public void setup() { - LogStub.init(); // replace log by a sideffect free variant - Log.enableFailQuick(false); - } @Test public void test() throws IOException { ModifiedMCLexerBase.lexCalled = 0; - SuperLexerMill.init(); SuperLexerParser parser = SuperLexerMill.parser(); diff --git a/monticore-test/01.experiments/generator/src/test/java/SuperParserTest.java b/monticore-test/01.experiments/generator/src/test/java/SuperParserTest.java index 3b5fea954c..de4c340add 100644 --- a/monticore-test/01.experiments/generator/src/test/java/SuperParserTest.java +++ b/monticore-test/01.experiments/generator/src/test/java/SuperParserTest.java @@ -1,32 +1,28 @@ /* (c) https://github.com/MontiCore/monticore */ +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import superparser.ModifiedMCParserBase; import superparser.SuperParserMill; import superparser._parser.SuperParserParser; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Test that the ParserSuperGrammar AntlrOption works */ +@TestWithMCLanguage(SuperParserMill.class) public class SuperParserTest { - @Before - public void setup() { - LogStub.init(); // replace log by a sideffect free variant - Log.enableFailQuick(false); - } @Test public void test() throws IOException { ModifiedMCParserBase.customCalled = 0; - SuperParserMill.init(); SuperParserParser parser = SuperParserMill.parser(); diff --git a/monticore-test/01.experiments/glex/src/test/java/GlexTest.java b/monticore-test/01.experiments/glex/src/test/java/GlexTest.java index 9ec0d2a0df..93266d95c3 100644 --- a/monticore-test/01.experiments/glex/src/test/java/GlexTest.java +++ b/monticore-test/01.experiments/glex/src/test/java/GlexTest.java @@ -2,23 +2,24 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import hierautomata._ast.ASTStateMachine; import hierautomata._parser.HierAutomataParser; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -@Ignore +@Disabled public class GlexTest { // setup the language infrastructure @@ -27,7 +28,7 @@ public class GlexTest { private static final String REGEXP = "[\r\n]"; private static final String REPLACE = "#"; - @BeforeClass + @BeforeAll public static void init() throws IOException { // LogStub.initPlusLog(); // for manual testing purpose only HierAutomataParser parser = new HierAutomataParser() ; @@ -43,17 +44,17 @@ public static void init() throws IOException { } } - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - - @Before + + @BeforeEach public void setUp() throws RecognitionException { Log.getFindings().clear(); } - + // -------------------------------------------------------------------- @Test @@ -68,7 +69,7 @@ public void testSimple() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("DummyTemplate with no real content#", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -88,7 +89,7 @@ public void testTracing() { assertEquals("[]", Log.getFindings().toString()); assertEquals("AAA generated by template tpl3/TestGlexOnStateMachine1.ftl EEE#DummyTemplate with no real content#", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -105,7 +106,7 @@ public void testVariables() { // System.out.println("****RES::\n" + res + "\n****--------"); assertEquals("[]", Log.getFindings().toString()); assertEquals("#V1:17##V2:35#", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -121,7 +122,7 @@ public void testSignature() { // System.out.println("****RES::\n" + res + "\n****--------"); assertEquals("[]", Log.getFindings().toString()); assertEquals("# A:OK:PingPong# B:OK#", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -155,7 +156,7 @@ public void testVariables3() { // System.out.println("****RES::\n" + res + "\n****--------"); assertEquals("[]", Log.getFindings().toString()); assertEquals(" A:OK## B:OK# C:OK#", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -173,7 +174,7 @@ public void testVariables4() { assertEquals("[]", Log.getFindings().toString()); assertEquals("##A:16#B:38#C:555#", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -226,7 +227,7 @@ public void testVariables7() { assertEquals("[]", Log.getFindings().toString()); assertEquals("###A:16,17,###B:23,25,27,###C:34,36,#", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -245,7 +246,7 @@ public void testShowForRefMan() { assertEquals("[]", Log.getFindings().toString()); assertEquals("### Var v1 is 35## Ok.# ###### 16, 18, 19, 17,#", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/glex/src/test/java/HookTest.java b/monticore-test/01.experiments/glex/src/test/java/HookTest.java index af08baa83f..42c81e5593 100644 --- a/monticore-test/01.experiments/glex/src/test/java/HookTest.java +++ b/monticore-test/01.experiments/glex/src/test/java/HookTest.java @@ -4,21 +4,23 @@ import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.monticore.generating.templateengine.*; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; +import hierautomata.HierAutomataMill; import hierautomata._ast.ASTStateMachine; import hierautomata._parser.HierAutomataParser; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class HookTest { @@ -31,8 +33,9 @@ public class HookTest { private static final String REPLACE = " "; - @BeforeClass - public static void init() throws IOException{ + @BeforeAll + public static void init() throws IOException { + HierAutomataMill.init(); // LogStub.initPlusLog(); // for manual testing purpose only HierAutomataParser parser = new HierAutomataParser() ; String model = "src/test/resources/example/HierarchyPingPong.aut"; @@ -44,15 +47,16 @@ public static void init() throws IOException{ ast = optStateMachine.get(); } - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() throws RecognitionException { Log.getFindings().clear(); + HierAutomataMill.init(); GeneratorSetup s = new GeneratorSetup(); s.setTracing(false); glex = s.getGlex(); @@ -71,7 +75,7 @@ public void testSimple() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("TA ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -86,8 +90,8 @@ public void testDefine() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); + MCAssertions.assertNoFindings(); } @@ -103,7 +107,7 @@ public void testDefineReplace1() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A St B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -120,7 +124,7 @@ public void testDefineReplace2() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A StA StB B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -136,7 +140,7 @@ public void testDefineReplace3() throws IOException { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A St B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -152,7 +156,7 @@ public void testDefineReplace4() throws IOException { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A 38 B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -168,7 +172,7 @@ public void testDefineReplace5() throws IOException { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A PingPong B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -184,7 +188,7 @@ public void testDefineReplace6() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A R PingPong T B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -201,7 +205,7 @@ public void testDefineReplace7() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A R PingPong tpl4/Hook1.ftl T B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -229,7 +233,7 @@ public String processValue(TemplateController tc, ASTNode ast, // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A C1 C2 B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -257,7 +261,7 @@ public String processValue(TemplateController tc, ASTNode ast, // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" A PingPong1 PingPong2 B ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -293,7 +297,7 @@ public String processValue(TemplateController tc, ASTNode ast, // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" PingPong:3318 PingPong:3323 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -310,7 +314,7 @@ public void testReplaceCodeWithArgs12() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" PingPong:18 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -324,7 +328,7 @@ public void testHooksInTemplates1() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("A1 B1 C1 D1 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -340,7 +344,7 @@ public void testHooksInTemplates2() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("A1 F1 B1 C1 D1 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // Only three variants of template names work @@ -360,7 +364,7 @@ public void testHooksInTemplates2c() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("A1 F1 B1 C1 D1 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -376,7 +380,7 @@ public void testHooksInTemplates2d() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("A1 F1 B1 C1 D1 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -392,7 +396,7 @@ public void testHooksInTemplates3() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("A1 E1 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -408,7 +412,7 @@ public void testOverwriteReplace() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("A1 F1 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -428,7 +432,7 @@ public void testOverwriteAndDecorateOldB() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("A1 G1 F1 G1 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -447,7 +451,7 @@ public void testOverwriteAndDecorateOldAndNew() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals("A1 E1 F1 E1 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -466,7 +470,7 @@ public void testHookSignature1() { // Stringvergleich: -------------------- assertEquals("[]", Log.getFindings().toString()); assertEquals(" FH1:FH2:18:FH2 ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -485,7 +489,7 @@ public void testDefaults() { // System.out.println(res.toString()); assertEquals("[]", Log.getFindings().toString()); assertEquals(" HookPoint filled " + "Hook empty ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -502,7 +506,7 @@ public void testBindHookFromTemplate() { assertEquals(" // Content of (c) template" + " // Content of (c) template" + " // Developed by SE RWTH ", res.toString().replaceAll(REGEXP, REPLACE)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -516,7 +520,7 @@ public void testDefine5() { } catch (Exception e) { assertNotNull(e); } - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @@ -536,7 +540,7 @@ public void testDefine6() { assertTrue(res.contains("HookPoint1 filled")); assertTrue(res.contains("HookPoint2 filled:p2a, p2a")); assertTrue(res.contains("HookPoint3 filled:p3")); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/hooks/ReadMe.md b/monticore-test/01.experiments/hooks/ReadMe.md index 1cffa092a2..9df425c3ab 100644 --- a/monticore-test/01.experiments/hooks/ReadMe.md +++ b/monticore-test/01.experiments/hooks/ReadMe.md @@ -56,9 +56,9 @@ unit tests. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../../../monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-test/01.experiments/hooks/build.gradle b/monticore-test/01.experiments/hooks/build.gradle index 73bd846f3a..af902c2aa2 100644 --- a/monticore-test/01.experiments/hooks/build.gradle +++ b/monticore-test/01.experiments/hooks/build.gradle @@ -1,8 +1,8 @@ /* (c) https://github.com/MontiCore/monticore */ plugins { - // provides a convenient way to have multiple test sets - id 'org.unbroken-dome.test-sets' version '4.0.0' + // provides a convenient way to have multiple test suites + id 'jvm-test-suite' } dependencies { @@ -10,19 +10,35 @@ dependencies { implementation project(":monticore-test:01experiments:templates") } - -// create an additional test set called productTest -testSets{ - productTest { extendsFrom unitTest } +// create an additional test suite called productTest +testing { + suites { + test { + useJUnitJupiter(junit_version) + } + + productTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project(":monticore-runtime")) + runtimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" + } + sources { + java.srcDirs += ["$buildDir/statepattern" , "$projectDir/src/product/java"] + } + } + } } -sourceSets { - // add output dir to the sources of productTest - productTest.java.srcDirs += ["$buildDir/statepattern" , "$projectDir/src/product/java"] +// let check depend on productTest such that it is included in the build +tasks.named('check') { + dependsOn(testing.suites.productTest) } // let productTest depend on test as test produces code for productTest -compileProductTestJava.dependsOn(test) +tasks.named("compileProductTestJava") { + dependsOn(test) +} test.configure { // The test task builds the productTest inputs @@ -30,7 +46,3 @@ test.configure { outputs.cacheIf {false} outputs.upToDateWhen {false} } - -// let check depend on productTest such that it is included in the build -check.dependsOn(productTest) - diff --git a/monticore-test/01.experiments/hooks/src/productTest/java/PingPongTest.java b/monticore-test/01.experiments/hooks/src/productTest/java/PingPongTest.java index 6e75608b2d..72a5a1de66 100644 --- a/monticore-test/01.experiments/hooks/src/productTest/java/PingPongTest.java +++ b/monticore-test/01.experiments/hooks/src/productTest/java/PingPongTest.java @@ -1,10 +1,10 @@ /* (c) https://github.com/MontiCore/monticore */ -import de.se_rwth.commons.logging.LogStub; -import org.junit.Test; -import static org.junit.Assert.*; -import de.se_rwth.commons.logging.Log; +import de.monticore.runtime.junit.MCAssertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class PingPongTest { @@ -16,56 +16,56 @@ public void testPingPong(){ PingPong pingpong = new PingPong(); // assert we are in the initial state - assertTrue(String.format(message,"NoGame"),pingpong.currentState instanceof NoGameState); + assertInstanceOf(NoGameState.class, pingpong.currentState, String.format(message, "NoGame")); // trigger startGame pingpong.startGame(); // assert NoGame handled 1 event - assertEquals(String.format(messageHandle,"NoGame"),1, PingPong.getNoGameState().count); + assertEquals(1, PingPong.getNoGameState().count, String.format(messageHandle,"NoGame")); // assert we are in state Ping - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger returnBall pingpong.returnBall(); // assert Ping handled 1 event - assertEquals(String.format(messageHandle,"Ping"),1, PingPong.getPingState().count); + assertEquals(1, PingPong.getPingState().count, String.format(messageHandle,"Ping")); // assert we are in state Pong - assertTrue(String.format(message,"Pong"), pingpong.currentState instanceof PongState); + assertInstanceOf(PongState.class, pingpong.currentState, String.format(message, "Pong")); // trigger returnBall pingpong.returnBall(); // assert Pong handled 1 event - assertEquals(String.format(messageHandle,"Pong"),1, PingPong.getPongState().count); + assertEquals(1, PingPong.getPongState().count, String.format(messageHandle,"Pong")); // assert we are in state Ping again - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger startGame pingpong.startGame(); // assert stimulus was ignored - assertEquals(String.format(messageHandle,"Ping"),1, PingPong.getPingState().count); - assertEquals(String.format(messageHandle,"Pong"),1, PingPong.getPongState().count); - assertEquals(String.format(messageHandle,"NoGame"),1, PingPong.getNoGameState().count); + assertEquals(1, PingPong.getPingState().count, String.format(messageHandle,"Ping")); + assertEquals(1, PingPong.getPongState().count, String.format(messageHandle,"Pong")); + assertEquals(1, PingPong.getNoGameState().count, String.format(messageHandle,"NoGame")); // assert we are still in state Ping (wrong input should be ignored) - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger stopGame pingpong.stopGame(); // assert Ping handled 2 events - assertEquals(String.format(messageHandle,"Ping"),2, PingPong.getPingState().count); + assertEquals(2, PingPong.getPingState().count, String.format(messageHandle,"Ping")); // assert we are in state NoGame - assertTrue(String.format(message,"NoGame"), pingpong.currentState instanceof NoGameState); + assertInstanceOf(NoGameState.class, pingpong.currentState, String.format(message, "NoGame")); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/hooks/src/test/java/automata/HooksToolTest.java b/monticore-test/01.experiments/hooks/src/test/java/automata/HooksToolTest.java index bbc279a2f2..79aa1c8c7a 100644 --- a/monticore-test/01.experiments/hooks/src/test/java/automata/HooksToolTest.java +++ b/monticore-test/01.experiments/hooks/src/test/java/automata/HooksToolTest.java @@ -1,26 +1,26 @@ /* (c) https://github.com/MontiCore/monticore */ package automata; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import hooks.HooksTool; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class HooksToolTest { - @Before + @BeforeEach public void init(){ LogStub.init(); // replace log by a sideffect free variant Log.enableFailQuick(false); // LogStub.initPlusLog(); // for manual testing purpose only } - @Before + @BeforeEach public void clearFindings(){ Log.getFindings().clear(); } @@ -39,7 +39,7 @@ public void testPingPong(){ "target/statepattern", "src/main/resources"}); assertEquals(0, Log.getErrorCount()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -50,7 +50,7 @@ public void testSimple12(){ "target/statepattern", "src/main/resources"}); assertEquals(0, Log.getErrorCount()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -61,7 +61,7 @@ public void testPingPong2(){ "target/statepattern2", "src/main/templates"}); assertEquals(0, Log.getErrorCount()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/hwDeSers/src/main/java/coloredgraph/_symboltable/ColoredGraphSTCompleteTypes.java b/monticore-test/01.experiments/hwDeSers/src/main/java/coloredgraph/_symboltable/ColoredGraphSTCompleteTypes.java index 546c1d5d36..b9b5b0db4d 100644 --- a/monticore-test/01.experiments/hwDeSers/src/main/java/coloredgraph/_symboltable/ColoredGraphSTCompleteTypes.java +++ b/monticore-test/01.experiments/hwDeSers/src/main/java/coloredgraph/_symboltable/ColoredGraphSTCompleteTypes.java @@ -8,7 +8,7 @@ import coloredgraph._visitor.ColoredGraphVisitor2; import java.awt.*; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -24,7 +24,7 @@ public class ColoredGraphSTCompleteTypes implements ColoredGraphVisitor2 { protected Set allColors; public ColoredGraphSTCompleteTypes(){ - allColors = new HashSet<>(); + allColors = new LinkedHashSet<>(); } /**************************************************** diff --git a/monticore-test/01.experiments/hwDeSers/src/test/java/ColoredGraphToolTest.java b/monticore-test/01.experiments/hwDeSers/src/test/java/ColoredGraphToolTest.java index da0e790ac9..8cb87f3431 100644 --- a/monticore-test/01.experiments/hwDeSers/src/test/java/ColoredGraphToolTest.java +++ b/monticore-test/01.experiments/hwDeSers/src/test/java/ColoredGraphToolTest.java @@ -2,21 +2,20 @@ import coloredgraph.ColoredGraphTool; import coloredgraph._symboltable.*; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.awt.*; import java.io.File; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ColoredGraphToolTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -31,10 +30,10 @@ public void before() { public void testTrafficLight() { LogStub.init(); // Log.enableFailQuick(false); - ColoredGraphTool.main(new String[] { "-i", "src/test/resources/TrafficLight.cg" }); + new ColoredGraphTool().run(new String[] { "-i", "src/test/resources/TrafficLight.cg" }); File stFile = new File("target/src/test/resources/TrafficLight.cgsym"); assertTrue(stFile.exists()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test @@ -43,7 +42,7 @@ public void testBlinker() { // Log.enableFailQuick(false); // store scope and check that file exists - ColoredGraphTool.main(new String[] { "-i", "src/test/resources/Blinker.cg" }); + new ColoredGraphTool().run(new String[] { "-i", "src/test/resources/Blinker.cg" }); File stFile = new File("target/src/test/resources/Blinker.cgsym"); assertTrue(stFile.exists()); @@ -66,13 +65,13 @@ public void testBlinker() { VertexSymbol offSymbol = graphScope.getLocalVertexSymbols().get(0); assertEquals("Off", offSymbol.getName()); assertEquals(new Color(0, 0, 0), offSymbol.getColor()); - assertEquals(true, offSymbol.isInitial()); + assertTrue(offSymbol.isInitial()); VertexSymbol blinkSymbol = graphScope.getLocalVertexSymbols().get(1); assertEquals("BlinkBlue", blinkSymbol.getName()); assertEquals(new Color(0, 0, 204), blinkSymbol.getColor()); - assertEquals(false, blinkSymbol.isInitial()); - assertTrue(Log.getFindings().isEmpty()); + assertFalse(blinkSymbol.isInitial()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java new file mode 100644 index 0000000000..2d750570f6 --- /dev/null +++ b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java @@ -0,0 +1,48 @@ +/* (c) https://github.com/MontiCore/monticore */ +package simpleequations._visitor; + +import de.monticore.interpreter.Value; +import org.junit.jupiter.api.Test; +import simpleequations.SimpleEquationsMill; +import simpleequations._ast.ASTProgram; +import simpleequations._parser.SimpleEquationsParser; +import simpleequations._symboltable.SimpleEquationsScopesGenitorDelegator; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class SimpleEquationsInterpreterTest { + + @Test + public void test() throws IOException { + SimpleEquationsMill.init(); + SimpleEquationsParser parser = SimpleEquationsMill.parser(); + SimpleEquationsInterpreter interpreter = new SimpleEquationsInterpreter(); + SimpleEquationsScopesGenitorDelegator delegator = SimpleEquationsMill.scopesGenitorDelegator(); + + ASTProgram program = parser.parse_StringProgram("var a=3.5; var b=4; print(a); var c=a+b; c;").get(); + + delegator.createFromAST(program); + Value result = interpreter.interpret(program); + + assertTrue(result.isFloat()); + assertEquals(result.asFloat(), 7.5f, 0.0001f); + + SimpleEquationsMill.reset(); + SimpleEquationsMill.init(); + interpreter = new SimpleEquationsInterpreter(); + program = parser.parse_StringProgram( + "var a = 40; " + + "a = 45;" + + "a;").get(); + + delegator.createFromAST(program); + result = interpreter.interpret(program); + + assertTrue(result.isInt()); + assertEquals(result.asInt(), 45); + } + +} diff --git a/monticore-test/01.experiments/lexicalModes/src/test/java/LexicalModesParseTest.java b/monticore-test/01.experiments/lexicalModes/src/test/java/LexicalModesParseTest.java index d11c809254..8fd91f8b3c 100644 --- a/monticore-test/01.experiments/lexicalModes/src/test/java/LexicalModesParseTest.java +++ b/monticore-test/01.experiments/lexicalModes/src/test/java/LexicalModesParseTest.java @@ -1,48 +1,43 @@ /* (c) https://github.com/MontiCore/monticore */ +import automata.AutomataMill; import automata._ast.ASTAutomaton; import automata._ast.ASTState; import automata._parser.AutomataParser; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Main class for the some Demonstration to Parse */ +@TestWithMCLanguage(AutomataMill.class) public class LexicalModesParseTest { - - @Before - public void before() { - LogStub.init(); - Log.enableFailQuick(false); - Log.clearFindings(); - LogStub.clearPrints(); - } @Test public void testParse1() throws IOException { - AutomataParser p = new AutomataParser(); + AutomataParser p = AutomataMill.parser(); String aut = "automaton PingPong {" + "state Ping;" + "}"; Optional at = p.parse_String(aut); assertTrue(at.isPresent()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void testParse2() throws IOException { - AutomataParser p = new AutomataParser(); + AutomataParser p = AutomataMill.parser(); String aut = "automaton PingPong {" + "state Ping;" + "" @@ -53,7 +48,7 @@ public void testParse2() throws IOException { assertEquals(1, ast.sizeStates()); assertEquals(1, ast.sizeTags()); assertEquals("dies ist beliebiger Text mit state", ast.getTag(0).getText2()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/makeuse/src/test/java/automata/AutomataParseTest.java b/monticore-test/01.experiments/makeuse/src/test/java/automata/AutomataParseTest.java index 739c32d4cb..dc70393dd4 100644 --- a/monticore-test/01.experiments/makeuse/src/test/java/automata/AutomataParseTest.java +++ b/monticore-test/01.experiments/makeuse/src/test/java/automata/AutomataParseTest.java @@ -1,7 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package automata; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; @@ -10,25 +10,18 @@ import automata._ast.ASTAutomaton; import automata._ast.ASTState; import automata._parser.AutomataParser; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Main class for the some Demonstration to Parse */ +@TestWithMCLanguage(AutomataMill.class) public class AutomataParseTest { - @Before - public void before() { - LogStub.init(); - Log.enableFailQuick(false); - Log.clearFindings(); - LogStub.clearPrints(); - } - /** * @throws IOException * @@ -37,7 +30,7 @@ public void before() { public void testParseMethods() throws IOException { String filename = "src/test/resources/example/PingPong.aut"; - AutomataParser p = new AutomataParser(); + AutomataParser p = AutomataMill.parser(); // parse from a file Optional at = p.parse(filename); @@ -58,7 +51,7 @@ public void testParseMethods() throws IOException { Optional s = p.parse_StringState("state Ping;"); assertTrue(s.isPresent()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/makeuse/src/test/java/automata/AutomataToolTest.java b/monticore-test/01.experiments/makeuse/src/test/java/automata/AutomataToolTest.java index d4bd8a3207..2b04e82919 100644 --- a/monticore-test/01.experiments/makeuse/src/test/java/automata/AutomataToolTest.java +++ b/monticore-test/01.experiments/makeuse/src/test/java/automata/AutomataToolTest.java @@ -1,19 +1,22 @@ /* (c) https://github.com/MontiCore/monticore */ package automata; +import de.monticore.runtime.junit.MCAssertions; import org.junit.*; import de.se_rwth.commons.logging.Log; import java.util.*; import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; public class AutomataToolTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -23,7 +26,7 @@ public void before() { @Test public void executePingPong() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/PingPong.aut", "-s", "target/PingPong.autsym" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/PingPong.aut", "-s", "target/PingPong.autsym" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); // for manual testing purpose only @@ -32,38 +35,38 @@ public void executePingPong() { assertEquals(7, p.size()); // Check some "[INFO]" outputs - assertTrue(p.get(0), p.get(0).matches(".*.INFO. AutomataTool Automata DSL Tool.*(\r)?\n")); - assertTrue(p.get(5), p.get(5).matches(".*.INFO. AutomataTool Pretty printing automaton into console.*(\r)?\n")); + assertTrue(p.get(0).matches(".*.INFO. AutomataTool Automata DSL Tool.*(\r)?\n"), p.get(0)); + assertTrue(p.get(5).matches(".*.INFO. AutomataTool Pretty printing automaton into console.*(\r)?\n"), p.get(5)); // Check resulting pretty print: String res = p.get(p.size()-1).replaceAll("\r\n", " ").replaceAll("\n", " "); assertEquals(231, res.length()); - assertTrue(res, res.matches(".*state.*")); - assertTrue(res, res.matches(".*state NoGame <>.*")); - assertTrue(res, res.matches(".*Pong - returnBall > Ping;.*")); - assertTrue(Log.getFindings().isEmpty()); + assertTrue(res.matches(".*state.*"), res); + assertTrue(res.matches(".*state NoGame <>.*"), res); + assertTrue(res.matches(".*Pong - returnBall > Ping;.*"), res); + MCAssertions.assertNoFindings(); } @Test public void executeSimple12() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/Simple12.aut", "-s", "target/Simple12.autsym" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/Simple12.aut", "-s", "target/Simple12.autsym" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); List p = LogStub.getPrints(); assertEquals(7, p.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void executeHierarchyPingPong() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/HierarchyPingPong.aut", "-s", "target/HierarchyPingPong.autsym" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/HierarchyPingPong.aut", "-s", "target/HierarchyPingPong.autsym" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); List p = LogStub.getPrints(); assertEquals(7, p.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/makeuse/src/test/java/automata/TransitionSourceExistsTest.java b/monticore-test/01.experiments/makeuse/src/test/java/automata/TransitionSourceExistsTest.java index 5c13043503..e3ae840180 100644 --- a/monticore-test/01.experiments/makeuse/src/test/java/automata/TransitionSourceExistsTest.java +++ b/monticore-test/01.experiments/makeuse/src/test/java/automata/TransitionSourceExistsTest.java @@ -8,55 +8,40 @@ import automata._symboltable.*; import automata.cocos.TransitionSourceExists; import de.monticore.ast.ASTNode; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(AutomataMill.class) public class TransitionSourceExistsTest { - // setup the parser infrastructure - AutomataParser parser = new AutomataParser() ; - - @Before - public void before() { - LogStub.init(); - Log.enableFailQuick(false); - } - - - @Before - public void setUp() throws RecognitionException, IOException { - Log.getFindings().clear(); - } - - // -------------------------------------------------------------------- @Test public void testBasics() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple { state A; state B; A - x > A; A - y > A; }" ).get(); assertEquals("Simple", ast.getName()); List st = ast.getStateList(); assertEquals(2, st.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testRetrievalOfSymbol() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple1 { state A; state B; A - x > A; B - y > A; }" ).get(); @@ -70,14 +55,14 @@ public void testRetrievalOfSymbol() throws IOException { assertEquals("A", aSymbol.get().getName()); ASTNode n = aSymbol.get().getAstNode(); assertEquals("A", ((ASTState)n).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testOnValidModel() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple2 { state A; state B; A -x> A; B -y> A; }" ).get(); @@ -90,13 +75,13 @@ public void testOnValidModel() throws IOException { checker.checkAll(ast); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testOnInvalidModel() throws IOException { - ASTAutomaton ast = parser.parse_String( + ASTAutomaton ast = AutomataMill.parser().parse_String( "automaton Simple3 { " + " state A; state B; A - x > A; Blubb - y > A; }" ).get(); @@ -111,9 +96,7 @@ public void testOnInvalidModel() throws IOException { checker.checkAll(ast); // we expect one error in the findings - assertEquals(1, Log.getFindings().size()); - assertEquals("0xADD03 Source state of transition missing.", - Log.getFindings().get(0).getMsg()); + MCAssertions.assertHasFindingStartingWith("0xADD03 Source state of transition missing."); } diff --git a/monticore-test/01.experiments/prettyPrinters/src/main/grammars/de/monticore/TestPrettyPrinters.mc4 b/monticore-test/01.experiments/prettyPrinters/src/main/grammars/de/monticore/TestPrettyPrinters.mc4 index 2eb2cce4c9..0821bbb42c 100644 --- a/monticore-test/01.experiments/prettyPrinters/src/main/grammars/de/monticore/TestPrettyPrinters.mc4 +++ b/monticore-test/01.experiments/prettyPrinters/src/main/grammars/de/monticore/TestPrettyPrinters.mc4 @@ -303,4 +303,37 @@ grammar TestPrettyPrinters extends de.monticore.literals.MCCommonLiterals { TestType implements TypeInterface = "TestType" TypeInterface2?; UsingTestType = "abc" TypeInterface; TestType2 implements TypeInterface2 = "TT2"; + + // Inspired by SysMLStates#EntryAction + // Tests the condition of B | A ("t") + NestedOptFromSysML = "entry" ( ";" | + actionUsage:A | + mCQualifiedName:B + ("{" + sysMLElement:C* + "}" | ";") + ) ; + + // Test a mixture of alt ordering and optional&required + OptOrdering0 = A | ( (A | B) ) ; + OptOrdering1 = A | ( (A | B )?) ; + OptOrdering2 = A | ( (A | B) C?) ; + OptOrdering3 = A | ( (A | B)? C?) ; + OptOrdering4 = A | (( A?| B?) C?) ; + OptOrdering5 =(A | ( (A | B) C?)); + OptOrdering6 =(A | ( (A | B)? C?)); + + TFSchema = {noSpace(2)}? "$" Name; + + // real use case of OptOrdering0 + NestedFromTfIdentifier = a:Name | + ("[[" (a:Name | b:TFSchema)? ":-" (newA:Name | newB:TFSchema)? "]]") | + "Name" a:Name; + + ExhaustedAlts1 = "a" A* | A*; + ExhaustedAlts2 = "a" A | A*; // first or second alt -> non-trivial as long as no other guards exists + ExhaustedAlts3 = "a" A* | A ; // first or second alt -> non-trivial as long as no other guards exists + ExhaustedAlts4 = "a" A+ | ("hello" | A+) ; + ExhaustedAlts5 = "a" A+ | ("hello" | A ) ; // first or second alt -> non-trivial as long as no other guards exists + ExhaustedAlts6 = ("a" A* | "b" A*)*; // indistinguishable alt (in repeated block) } diff --git a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/KeywordAddingTest.java b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/KeywordAddingTest.java index 08fba0039a..d7f98392a8 100644 --- a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/KeywordAddingTest.java +++ b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/KeywordAddingTest.java @@ -4,24 +4,16 @@ import de.monticore.ast.ASTNode; import de.monticore.keywordaddingtestprettyprinters.KeywordAddingTestPrettyPrintersMill; import de.monticore.keywordaddingtestprettyprinters._ast.ASTKeywordAddingTestPrettyPrintersNode; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import org.junit.*; +import org.junit.jupiter.api.Test; import java.io.IOException; +@TestWithMCLanguage(KeywordAddingTestPrettyPrintersMill.class) public class KeywordAddingTest extends PPTestClass { - @BeforeClass - public static void init() { - KeywordAddingTestPrettyPrintersMill.init(); - Log.init(); - Log.enableFailQuick(false); - } - - @Before - public void beforeEach() { - Log.clearFindings(); - } @Test public void testSomeProdOld() throws IOException { diff --git a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/KeywordReplacingTest.java b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/KeywordReplacingTest.java index d97979c264..971671cc27 100644 --- a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/KeywordReplacingTest.java +++ b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/KeywordReplacingTest.java @@ -5,42 +5,28 @@ import de.monticore.keywordreplacingtestprettyprinters._ast.ASTKeywordReplacingTestPrettyPrintersNode; import de.monticore.keywordreplacingtestprettyprinters.KeywordReplacingTestPrettyPrintersMill; import de.monticore.keywordreplacingtestprettyprinters._ast.ASTSomeProdWhichUsesReplacing; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +@TestWithMCLanguage(KeywordReplacingTestPrettyPrintersMill.class) public class KeywordReplacingTest extends PPTestClass { - @BeforeClass - public static void init() { - KeywordReplacingTestPrettyPrintersMill.init(); - Log.init(); - Log.enableFailQuick(false); - } - - @Before - public void beforeEach() { - Log.clearFindings(); - } - @Test public void testSomeProdForException() throws IOException { Optional astOpt = KeywordReplacingTestPrettyPrintersMill.parser().parse_StringSomeProdWhichUsesReplacing("notquiteA term notquiteA"); - Assert.assertTrue(astOpt.isPresent()); + Assertions.assertTrue(astOpt.isPresent()); fullPrettyPrint(astOpt.get()); - Assert.assertEquals("Did not fail when printing", 1, Log.getErrorCount()); - Assert.assertEquals(1, Log.getErrorCount()); - Assert.assertEquals(1, Log.getFindingsCount()); - Assert.assertTrue(Log.getFindings().get(0).getMsg().endsWith("replacekeyword requires HC effort for pretty printing")); + MCAssertions.assertHasFinding(f->f.getMsg().endsWith("replacekeyword requires HC effort for pretty printing")); } @Override protected String fullPrettyPrint(ASTNode node) { - return KeywordReplacingTestPrettyPrintersMill.prettyPrint((ASTKeywordReplacingTestPrettyPrintersNode) node, true); + return KeywordReplacingTestPrettyPrintersMill.prettyPrint(node, true); } } diff --git a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/PPTestClass.java b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/PPTestClass.java index 7594a748b0..c2f1df35df 100644 --- a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/PPTestClass.java +++ b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/PPTestClass.java @@ -4,7 +4,7 @@ import de.monticore.ast.ASTNode; import de.se_rwth.commons.Joiners; import de.se_rwth.commons.logging.Log; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import java.io.IOException; import java.util.Optional; @@ -20,16 +20,16 @@ public abstract class PPTestClass { protected void testPP(String input, ParserFunction> parserFunction, Function additionalCheck) throws IOException { Optional parsedOpt = parserFunction.parse(input); - Assert.assertTrue("Failed to parse input", parsedOpt.isPresent()); + Assertions.assertTrue(parsedOpt.isPresent(), "Failed to parse input"); String prettyInput = this.fullPrettyPrint(parsedOpt.get()); Optional parsedPrettyOpt = parserFunction.parse(prettyInput); String findings = Joiners.COMMA.join(Log.getFindings()); if (parsedPrettyOpt.isEmpty()) - Assert.assertEquals("Failed to parse pretty: " + findings, input, prettyInput); + Assertions.assertEquals(input, prettyInput, "Failed to parse pretty: " + findings); if (!parsedOpt.get().deepEquals(parsedPrettyOpt.get())) - Assert.assertEquals("Not deep equals: " + findings, input, prettyInput); + Assertions.assertEquals(input, prettyInput, "Not deep equals: " + findings); if (!additionalCheck.apply(prettyInput)) - Assert.fail("Failed check, got pp-output: '" + prettyInput + "'"); + Assertions.fail("Failed check, got pp-output: '" + prettyInput + "'"); } protected void testPP(String input, ParserFunction> parserFunction) throws IOException { diff --git a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/PrettyPrinterMillTest.java b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/PrettyPrinterMillTest.java index 76dbee21f0..f7ccf9ca68 100644 --- a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/PrettyPrinterMillTest.java +++ b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/PrettyPrinterMillTest.java @@ -8,10 +8,10 @@ import de.monticore.testprettyprinters._ast.ASTTypeInterface; import de.monticore.testprettyprinters._ast.ASTUsingTestType; import de.se_rwth.commons.logging.Log; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; @@ -22,14 +22,14 @@ */ public class PrettyPrinterMillTest { - @BeforeClass + @BeforeAll public static void setup() { Log.init(); Log.enableFailQuick(false); // We initiate mills in the various test methods } - @Before + @BeforeEach public void beforeEach() { Log.clearFindings(); // Reset both mills (depending on Mill#reset even multiple times) @@ -42,7 +42,7 @@ public void testMillTestType() throws Exception { // Test-Production + TestPrettyPrinter TestPrettyPrintersMill.init(); Optional astOpt = TestPrettyPrintersMill.parser().parse_StringTypeInterface("TestType"); - Assert.assertTrue(astOpt.isPresent()); + Assertions.assertTrue(astOpt.isPresent()); ASTTestPrettyPrintersNode astNode = astOpt.get(); test(astNode, a -> TestPrettyPrintersMill.prettyPrint(a, true), TestPrettyPrintersMill.parser()::parse_StringTypeInterface); @@ -55,7 +55,7 @@ public void testSuperMill() throws Exception { SuperTestPrettyPrintersMill.init(); Optional astOpt = SuperTestPrettyPrintersMill.parser().parse_StringTypeInterface("TestType"); - Assert.assertTrue(astOpt.isPresent()); + Assertions.assertTrue(astOpt.isPresent()); ASTTestPrettyPrintersNode astNode = astOpt.get(); test(astNode, a -> TestPrettyPrintersMill.prettyPrint(a, true), SuperTestPrettyPrintersMill.parser()::parse_StringTypeInterface); @@ -66,7 +66,7 @@ public void testMillTestSuperType() throws Exception { // SuperTest-Production + TestPrettyPrinter SuperTestPrettyPrintersMill.init(); Optional astOpt = TestPrettyPrintersMill.parser().parse_StringTypeInterface("SuperTestType"); - Assert.assertTrue(astOpt.isPresent()); + Assertions.assertTrue(astOpt.isPresent()); ASTTestPrettyPrintersNode astNode = astOpt.get(); test(astNode, a -> TestPrettyPrintersMill.prettyPrint(a, true), TestPrettyPrintersMill.parser()::parse_StringTypeInterface); @@ -77,7 +77,7 @@ public void testSuperMillTestSuperType() throws Exception { // SuperTest-Production + SuperTestPrettyPrinter SuperTestPrettyPrintersMill.init(); Optional astOpt = SuperTestPrettyPrintersMill.parser().parse_StringTypeInterface("SuperTestType"); - Assert.assertTrue(astOpt.isPresent()); + Assertions.assertTrue(astOpt.isPresent()); ASTSuperTestPrettyPrintersNode astNode = (ASTSuperTestPrettyPrintersNode) astOpt.get(); test(astNode, a -> SuperTestPrettyPrintersMill.prettyPrint(a, true), SuperTestPrettyPrintersMill.parser()::parse_StringTypeInterface); @@ -87,15 +87,15 @@ protected void test(T ast, Function prettyAstOpt = parse.parse(pretty); - Assert.assertTrue("Failed to parse: " + pretty, prettyAstOpt.isPresent()); - Assert.assertTrue(ast.deepEquals(prettyAstOpt.get())); + Assertions.assertTrue(prettyAstOpt.isPresent(), "Failed to parse: " + pretty); + Assertions.assertTrue(ast.deepEquals(prettyAstOpt.get())); } @Test public void testUsingMill() throws Exception { TestPrettyPrintersMill.init(); Optional astOpt = TestPrettyPrintersMill.parser().parse_StringUsingTestType("abc TestType"); - Assert.assertTrue(astOpt.isPresent()); + Assertions.assertTrue(astOpt.isPresent()); test(astOpt.get(), a -> TestPrettyPrintersMill.prettyPrint(a, true), TestPrettyPrintersMill.parser()::parse_StringUsingTestType); } @@ -104,7 +104,7 @@ public void testUsingMill() throws Exception { public void testUsingSuperMill() throws Exception { SuperTestPrettyPrintersMill.init(); Optional astOpt = SuperTestPrettyPrintersMill.parser().parse_StringUsingTestType("abc TestType"); - Assert.assertTrue(astOpt.isPresent()); + Assertions.assertTrue(astOpt.isPresent()); test(astOpt.get(), a -> TestPrettyPrintersMill.prettyPrint(a, true), SuperTestPrettyPrintersMill.parser()::parse_StringUsingTestType); } @@ -113,7 +113,7 @@ public void testUsingSuperMill() throws Exception { public void testUsingSuperMillSuperType() throws Exception { SuperTestPrettyPrintersMill.init(); Optional astOpt = SuperTestPrettyPrintersMill.parser().parse_StringUsingTestType("abc SuperTestType"); - Assert.assertTrue(astOpt.isPresent()); + Assertions.assertTrue(astOpt.isPresent()); test(astOpt.get(), a -> SuperTestPrettyPrintersMill.prettyPrint(a, true), SuperTestPrettyPrintersMill.parser()::parse_StringUsingTestType); } diff --git a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/SuperTestPrettyPrinterTest.java b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/SuperTestPrettyPrinterTest.java index 17ae4eaeab..a527bffa60 100644 --- a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/SuperTestPrettyPrinterTest.java +++ b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/SuperTestPrettyPrinterTest.java @@ -2,30 +2,20 @@ package de.monticore.prettyprint; import de.monticore.ast.ASTNode; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.monticore.supertestprettyprinters.SuperTestPrettyPrintersMill; import de.monticore.supertestprettyprinters._prettyprint.SuperTestPrettyPrintersFullPrettyPrinter; -import de.se_rwth.commons.logging.Log; import org.junit.*; +import org.junit.jupiter.api.Test; import java.io.IOException; /** * Test the PrettyPrinter Generation when it comes to overriden productions */ +@TestWithMCLanguage(SuperTestPrettyPrintersMill.class) public class SuperTestPrettyPrinterTest extends PPTestClass { - @BeforeClass - public static void setup() { - SuperTestPrettyPrintersMill.init(); - Log.init(); - Log.enableFailQuick(false); - } - - @Before - public void beforeEach() { - Log.clearFindings(); - } - @Override protected String fullPrettyPrint(ASTNode node){ return (new SuperTestPrettyPrintersFullPrettyPrinter(new IndentPrinter())).prettyprint(node); diff --git a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/TestPrettyPrinterTest.java b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/TestPrettyPrinterTest.java index 5aab595d7e..d379544fb5 100644 --- a/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/TestPrettyPrinterTest.java +++ b/monticore-test/01.experiments/prettyPrinters/src/test/java/de/monticore/prettyprint/TestPrettyPrinterTest.java @@ -3,6 +3,8 @@ import de.monticore.ast.ASTNode; import de.monticore.keywordaddingtestprettyprinters.KeywordAddingTestPrettyPrintersMill; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.monticore.testprettyprinters.TestPrettyPrintersMill; import de.monticore.testprettyprinters._ast.ASTProdNamedTerminal; import de.monticore.testprettyprinters._ast.ASTToBeReplacedKeyword; @@ -11,6 +13,9 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.*; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; @@ -20,23 +25,12 @@ /** * Test the PrettyPrinter Generation */ +@TestWithMCLanguage(TestPrettyPrintersMill.class) public class TestPrettyPrinterTest extends PPTestClass { - @BeforeClass - public static void setup() { - TestPrettyPrintersMill.init(); - LogStub.init(); - Log.enableFailQuick(false); - } - - @Before - public void beforeEach() { - Log.clearFindings(); - } - @Override protected String fullPrettyPrint(ASTNode astNode){ - return (new TestPrettyPrintersFullPrettyPrinter(new IndentPrinter())).prettyprint(astNode); + return TestPrettyPrintersMill.prettyPrint(astNode, true); } @Test @@ -331,7 +325,7 @@ public void testDuplicateTermUsageName3() throws IOException { } @Test - @Ignore + @Disabled public void testCPAstList() throws IOException { // Currently throws "Contains a list of Alts where one is not iterator ready!" // as it generates a while ((node.isPresentA()) || (iter_b.hasNext()) || ... @@ -355,9 +349,10 @@ public void testCPCGSup() throws IOException { public void testCPCGUnsupName() throws IOException { try { testPP(".dot", TestPrettyPrintersMill.parser()::parse_StringCPCGUnsupName); - Assert.fail(); + Assertions.fail(); } catch (IllegalStateException expected) { - Assert.assertEquals("Unable to find good Constant name for getEnding and value ", expected.getMessage()); + Assertions.assertEquals("Unable to find good Constant name for getEnding and value ", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("Unable to find good Constant name for getEnding and value")); } } @@ -560,9 +555,10 @@ public void testNoSpace() throws IOException { public void testNoSpace2017() throws IOException { try { testPP(" n1.n2", TestPrettyPrintersMill.parser()::parse_StringNoWhiteSpaceA2017); - Assert.fail(); + Assertions.fail(); } catch (IllegalStateException expected) { - Assert.assertEquals("Unable to target the previous token using the noSpace control directive. You may also need to override the printing methods of productions using this NonTerminal", expected.getMessage()); + Assertions.assertEquals("Unable to target the previous token using the noSpace control directive. You may also need to override the printing methods of productions using this NonTerminal", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("Unable to target the previous token using the noSpace control directive. You may also need to override the printing methods of productions using this NonTerminal")); } } @@ -579,15 +575,18 @@ public void testNoSpaceAlts() throws IOException { public void testNoSpaceAltsOpt() throws IOException { try { testPP("-n1 +", TestPrettyPrintersMill.parser()::parse_StringNoSpaceAltsOpt); - Assert.fail(); + Assertions.fail(); } catch (IllegalStateException expected) { - Assert.assertEquals("Unable to handle noSpace control directive for block of non-default iteration", expected.getMessage()); + Assertions.assertEquals("Unable to handle noSpace control directive for block of non-default iteration", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("Unable to handle noSpace control directive for block of non-default iteration")); + MCAssertions.assertNoFindings(); } try { testPP("n1+", TestPrettyPrintersMill.parser()::parse_StringNoSpaceAltsOpt); - Assert.fail(); + Assertions.fail(); } catch (IllegalStateException expected) { - Assert.assertEquals("Unable to handle noSpace control directive for block of non-default iteration", expected.getMessage()); + Assertions.assertEquals("Unable to handle noSpace control directive for block of non-default iteration", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("Unable to handle noSpace control directive for block of non-default iteration")); } } @@ -595,9 +594,10 @@ public void testNoSpaceAltsOpt() throws IOException { public void testNoSpaceAltsOverflow() throws IOException { try { testPP("-n1.n2", TestPrettyPrintersMill.parser()::parse_StringNoSpaceAltsOverflow); - Assert.fail(); + Assertions.fail(); } catch (IllegalStateException expected) { - Assert.assertEquals("Unable to handle noSpace control directive for block with multiple alts of different length", expected.getMessage()); + Assertions.assertEquals("Unable to handle noSpace control directive for block with multiple alts of different length", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("Unable to handle noSpace control directive for block with multiple alts of different length")); } } @@ -685,16 +685,16 @@ public void testGuessSpace() throws IOException { public void testTrimRight() { IndentPrinter printer = new IndentPrinter(); printer.stripTrailing(); - Assert.assertEquals("", printer.getContent()); + Assertions.assertEquals("", printer.getContent()); printer.print("Hello world"); printer.stripTrailing(); - Assert.assertEquals("Hello world", printer.getContent()); + Assertions.assertEquals("Hello world", printer.getContent()); printer.print(" "); printer.stripTrailing(); - Assert.assertEquals("Hello world", printer.getContent()); + Assertions.assertEquals("Hello world", printer.getContent()); printer.println(); printer.stripTrailing(); - Assert.assertEquals("Hello world\n", printer.getContent()); + Assertions.assertEquals("Hello world\n", printer.getContent()); } @Test @@ -718,7 +718,8 @@ public void testReplaceKeyword() throws IOException { public void testReplaceKeywordFail() throws IOException { TestPrettyPrintersParser parser = TestPrettyPrintersMill.parser(); Optional astOpt = parser.parse_StringToBeReplacedKeyword("ReplacedKeyword"); - Assert.assertTrue(astOpt.isEmpty()); + Assertions.assertTrue(astOpt.isEmpty()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("mismatched input 'ReplacedKeyword' expecting 'ActuallyReplacedKeyword'")); } @Test @@ -738,23 +739,168 @@ public void testAddReplaceKeyword() throws IOException { @Test - @Ignore // Ignored - monticore/monticore#3328 - non-terminals with attributes do not behave with replacekeyword + @Disabled // Ignored - monticore/monticore#3328 - non-terminals with attributes do not behave with replacekeyword // We can un-ignore this test once that behaviour is settled public void testProdNamedTerminalParser() throws IOException { + KeywordAddingTestPrettyPrintersMill.init(); Optional astOpt = KeywordAddingTestPrettyPrintersMill.parser().parse_StringProdNamedTerminal("newprodNamedTerminal"); - Assert.assertTrue(astOpt.isPresent()); - Assert.assertEquals("newprodNamedTerminal", astOpt.get().getTerm()); // Parser Action does otherwise + Assertions.assertTrue(astOpt.isPresent()); + Assertions.assertEquals("newprodNamedTerminal", astOpt.get().getTerm()); // Parser Action does otherwise } @Test public void testAddingProdNamedTerminalOld() throws IOException { + KeywordAddingTestPrettyPrintersMill.init(); testPP("prodNamedTerminal", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringProdNamedTerminal); } @Test - @Ignore // Ignored - monticore/monticore#3328 - non-terminals with attributes do not behave with replacekeyword + @Disabled // Ignored - monticore/monticore#3328 - non-terminals with attributes do not behave with replacekeyword // We can un-ignore this test once that behaviour is settled public void testAddingProdNamedTerminalNew() throws IOException { + KeywordAddingTestPrettyPrintersMill.init(); testPP("newprodNamedTerminal", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringProdNamedTerminal); } + + @Test + public void testBrackets() throws IOException { + // The AND(A, OR(B, C)) expression may be printed as OR( AND(A, B), C) + // if no extra brackets/parentheses are added + testPP("entry ;", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedOptFromSysML); + testPP("entry A", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedOptFromSysML); + testPP("entry B;", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedOptFromSysML); + testPP("entry B { }", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedOptFromSysML); + testPP("entry B { C }", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedOptFromSysML); + } + + @Test + public void testOptOrdering0() throws IOException { + testPP("A", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering0); + // Test that the first altenative is only printed when no B is present + testPP("B", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering0); + } + + @Test + public void testOptOrdering1() throws IOException { + testPP("A", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering1); + testPP("B", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering1); + testPP(" ", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering1); + } + + @Test + public void testOptOrdering2() throws IOException { + testPP("A", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering2); + testPP("B", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering2); + testPP("A C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering2); + testPP("B C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering2); + } + + @Test + public void testOptOrdering3() throws IOException { + testPP("A", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering3); + testPP("B", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering3); + testPP(" ", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering3); + testPP("A C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering3); + testPP("B C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering3); + testPP(" C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering3); + } + + @Test + public void testOptOrdering4() throws IOException { + testPP("A", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering4); + testPP("B", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering4); + testPP(" ", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering4); + testPP("A C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering4); + testPP("B C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering4); + testPP(" C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering4); + } + + @Test + public void testOptOrdering5() throws IOException { + testPP("A", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering5); + testPP("B", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering5); + testPP("A C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering5); + testPP("B C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering5); + } + + @Test + public void testOptOrdering6() throws IOException { + testPP("A", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering6); + testPP("B", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering6); + testPP(" ", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering6); + testPP("A C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering6); + testPP("B C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering6); + testPP(" C", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringOptOrdering6); + } + + @Test + public void testNestedFromTfIdentifier() throws IOException { + testPP("foob", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedFromTfIdentifier); + testPP("Name foob", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedFromTfIdentifier); + testPP("[[ $a :- $b ]]", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedFromTfIdentifier); + testPP("[[ fooa :- foob]]", KeywordAddingTestPrettyPrintersMill.parser()::parse_StringNestedFromTfIdentifier); + } + + @Test + public void testExhaustedAlts1() throws IOException { + testPP("a A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts1); + testPP("a A A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts1); + testPP("A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts1); + testPP("A A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts1); + } + + @Test + public void testExhaustedAlts2() throws IOException { + // Should the first or second alt be selected? + // The case-distinction is non-trivial => we abort + try { + testPP("a A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts2); + Assertions.fail(); + } catch (IllegalStateException expected) { + Assertions.assertEquals("The NonTerminal(s) [A] caused the automatic generation to fail", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("The NonTerminal(s) [A] caused the automatic generation to fail")); + } + } + + @Test + public void testExhaustedAlts3() throws IOException { + try { + testPP("a A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts3); + Assertions.fail(); + } catch (IllegalStateException expected) { + Assertions.assertEquals("The NonTerminal(s) [A] caused the automatic generation to fail", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("The NonTerminal(s) [A] caused the automatic generation to fail")); + } + } + + + @Test + public void testExhaustedAlts4() throws IOException { + testPP("a A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts4); + testPP("a A A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts4); + testPP("hello", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts4); + testPP("A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts4); + testPP("A A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts4); + } + + @Test + public void testExhaustedAlts5() throws IOException { + try { + testPP("hello", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts5); + Assertions.fail(); + } catch (IllegalStateException expected) { + Assertions.assertEquals("The NonTerminal(s) [A] caused the automatic generation to fail", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("The NonTerminal(s) [A] caused the automatic generation to fail")); + } } + + @Test + public void testExhaustedAlts6() throws IOException { + try { + testPP("a A", TestPrettyPrintersMill.parser()::parse_StringExhaustedAlts6); + Assertions.fail(); + } catch (IllegalStateException expected) { + Assertions.assertEquals("The NonTerminal(s) [A] caused the automatic generation to fail", expected.getMessage()); + MCAssertions.assertHasFinding(f -> f.getMsg().contains("The NonTerminal(s) [A] caused the automatic generation to fail")); + } + } } diff --git a/monticore-test/01.experiments/runtimeOnly/build.gradle b/monticore-test/01.experiments/runtimeOnly/build.gradle new file mode 100644 index 0000000000..3acc2b7b8e --- /dev/null +++ b/monticore-test/01.experiments/runtimeOnly/build.gradle @@ -0,0 +1,11 @@ +/* (c) https://github.com/MontiCore/monticore */ +description = 'Experiments: runtimeOnly' + +dependencies { + implementation project(path: ':monticore-runtime') +} + +/* + * This test project builds a grammar only using the runtime. + * This ensures that the generator does not require an implicit grammar dependency + */ diff --git a/monticore-test/01.experiments/runtimeOnly/src/main/grammars/a/b/XY.mc4 b/monticore-test/01.experiments/runtimeOnly/src/main/grammars/a/b/XY.mc4 new file mode 100644 index 0000000000..bc507e1d62 --- /dev/null +++ b/monticore-test/01.experiments/runtimeOnly/src/main/grammars/a/b/XY.mc4 @@ -0,0 +1,13 @@ +/* (c) https://github.com/MontiCore/monticore */ +package a.b; + +// This grammar MUST be compiled with only the monticore-runtime present +grammar XY { + Ax = a1:Name a2:Name? ; + By = "B" i1:I* "i" i2:I i3:I?; + interface I; + symbol MySymbol = "symbol" Name; + symbol scope MyScopedSymbol implements I = "scopedsymbol" Name; + + token Name = "NAME"; +} diff --git a/monticore-test/01.experiments/scannerless/src/test/java/CheckScannerlessTest.java b/monticore-test/01.experiments/scannerless/src/test/java/CheckScannerlessTest.java index bbce235627..2e63e23caf 100644 --- a/monticore-test/01.experiments/scannerless/src/test/java/CheckScannerlessTest.java +++ b/monticore-test/01.experiments/scannerless/src/test/java/CheckScannerlessTest.java @@ -1,34 +1,19 @@ /* (c) https://github.com/MontiCore/monticore */ +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; +import de.monticore.scannerless.ScannerlessMill; import de.monticore.scannerless._ast.*; -import de.monticore.scannerless._parser.ScannerlessParser; -import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +@TestWithMCLanguage(ScannerlessMill.class) public class CheckScannerlessTest { - // setup the language infrastructure - ScannerlessParser parser = new ScannerlessParser() ; - - @Before - public void before() { - LogStub.init(); - Log.enableFailQuick(false); - } - - - @Before - public void setUp() { - Log.getFindings().clear(); - } // -------------------------------------------------------------------- // Check Types, especially ">" and "> >" @@ -37,60 +22,70 @@ public void setUp() { // -------------------------------------------------------------------- @Test public void testType1() throws IOException { - ASTType ast = parser.parse_StringType( " Theo " ).get(); + ASTType ast = ScannerlessMill.parser().parse_StringType( " Theo " ) + .orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals("Theo", ast.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType2() throws IOException { - ASTType ast = parser.parse_StringType( " List < Theo > " ).get(); + ASTType ast = ScannerlessMill.parser().parse_StringType( " List < Theo > " ) + .orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Theo", ta.getType(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType3() throws IOException { - ASTType ast = parser.parse_StringType( "List" ).get(); + ASTType ast = ScannerlessMill.parser().parse_StringType( "List" ) + .orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Theo", ta.getTypeList().get(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType4() throws IOException { - ASTType ast = parser.parse_StringType( "List>" ).get(); + ASTType ast = ScannerlessMill.parser().parse_StringType( "List>" ) + .orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Set", ta.getTypeList().get(0).getName()); ASTTypeArguments ta2 = ta.getTypeList().get(0).getTypeArguments(); assertEquals("Theo", ta2.getTypeList().get(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType5() throws IOException { - ASTExpression ast0 = parser.parse_StringExpression( - "List>" ).get(); + ASTExpression ast0 = ScannerlessMill.parser().parse_StringExpression( + "List>" ).orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals(ASTTypeAsExpression.class, ast0.getClass()); ASTType ast1 = ((ASTTypeAsExpression)ast0).getType() ; assertEquals("List", ast1.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType6() throws IOException { - ASTExpression ast0 = parser.parse_StringExpression( - "List>>>wert" ).get(); + ASTExpression ast0 = ScannerlessMill.parser().parse_StringExpression( + "List>>>wert" ).orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals(ASTShiftExpression.class, ast0.getClass()); ASTExpression ast1 = ((ASTShiftExpression)ast0).getLeftExpression() ; @@ -98,7 +93,7 @@ public void testType6() throws IOException { assertEquals(ASTTypeAsExpression.class, ast1.getClass()); ASTType ast2 = ((ASTTypeAsExpression)ast1).getType() ; assertEquals("List", ast2.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -107,8 +102,9 @@ public void testType6() throws IOException { public void testType7() throws IOException { // This will be parsed as Type >> wert, because the // type has a higher precedence - ASTExpression ast0 = parser.parse_StringExpression( - "List > >>wert" ).get(); + ASTExpression ast0 = ScannerlessMill.parser().parse_StringExpression( + "List > >>wert" ).orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals(ASTShiftExpression.class, ast0.getClass()); ASTExpression ast1 = ((ASTShiftExpression)ast0).getLeftExpression() ; @@ -116,7 +112,7 @@ public void testType7() throws IOException { assertEquals(ASTTypeAsExpression.class, ast1.getClass()); ASTType ast2 = ((ASTTypeAsExpression)ast1).getType() ; assertEquals("List", ast2.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -125,9 +121,10 @@ public void testType7() throws IOException { public void testType8() throws IOException { // This cannot be parsed as a Type >> wert // This cannot be parsed because of the illegal space in ">>" - Optional ast0 = parser.parse_StringExpression( + Optional ast0 = ScannerlessMill.parser().parse_StringExpression( "List>> >wert" ); assertFalse(ast0.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } @@ -138,52 +135,59 @@ public void testType8() throws IOException { // -------------------------------------------------------------------- @Test public void testExpr1() throws IOException { - ASTExpression ast = parser.parse_StringExpression( " theo + theo " ).get(); + ASTExpression ast = ScannerlessMill.parser().parse_StringExpression( " theo + theo " ) + .orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals(ASTAddExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr2() throws IOException { - ASTExpression ast = parser.parse_StringExpression( - " (theo < ox) > theo " ).get(); + ASTExpression ast = ScannerlessMill.parser().parse_StringExpression( + " (theo < ox) > theo " ).orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals(ASTComparisonExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr3() throws IOException { - ASTExpression ast = parser.parse_StringExpression( - " theo >> theo " ).get(); + ASTExpression ast = ScannerlessMill.parser().parse_StringExpression( + " theo >> theo " ).orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals(ASTShiftExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr4() throws IOException { - ASTExpression ast = parser.parse_StringExpression( - "theo > theo >> theo >>> theo >= theo" ).get(); + ASTExpression ast = ScannerlessMill.parser().parse_StringExpression( + "theo > theo >> theo >>> theo >= theo" ).orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals(ASTComparisonExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExprNeg1() throws IOException { - Optional ast = parser.parse_StringExpression( + Optional ast = ScannerlessMill.parser().parse_StringExpression( "theo > > theo " ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } // -------------------------------------------------------------------- @Test public void testExprNeg2() throws IOException { - Optional ast = parser.parse_StringExpression( + Optional ast = ScannerlessMill.parser().parse_StringExpression( "theo < << theo " ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } @@ -194,34 +198,41 @@ public void testExprNeg2() throws IOException { // -------------------------------------------------------------------- @Test public void testA() throws IOException { - ASTA ast = parser.parse_StringA( " Theo " ).get(); + ASTA ast = ScannerlessMill.parser().parse_StringA( " Theo " ). + orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals("Theo", ast.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testB() throws IOException { - ASTB ast = parser.parse_StringB( "Otto \n Karo " ).get(); + ASTB ast = ScannerlessMill.parser().parse_StringB( "Otto \n Karo " ). + orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals("Otto", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testC() throws IOException { - ASTC ast = parser.parse_StringC( " Otto,Karo" ).get(); + ASTC ast = ScannerlessMill.parser().parse_StringC( " Otto,Karo" ). + orElseGet(MCAssertions::failAndPrintFindings); + MCAssertions.assertNoFindings(); assertEquals("Otto", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testC2() throws IOException { - Optional ast = parser.parse_StringC( " Otto ,Karo" ); + Optional ast = ScannerlessMill.parser().parse_StringC( " Otto ,Karo" ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } } diff --git a/monticore-test/01.experiments/skeleton/src/test/java/sm2/SM2ToolTest.java b/monticore-test/01.experiments/skeleton/src/test/java/sm2/SM2ToolTest.java index 976777502c..f0f552bf15 100644 --- a/monticore-test/01.experiments/skeleton/src/test/java/sm2/SM2ToolTest.java +++ b/monticore-test/01.experiments/skeleton/src/test/java/sm2/SM2ToolTest.java @@ -2,21 +2,20 @@ package sm2; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class SM2ToolTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -29,21 +28,21 @@ public void before() { public void test() { String[] args = {"-i", "src/test/resources/example/PingPong.aut"}; SM2Tool.main(args); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); List p = LogStub.getPrints(); assertEquals(9, p.size()); // Check some "[INFO]" outputs - Assert.assertTrue(p.get(0), p.get(0).matches(".*.INFO. SM2Tool SM2 DSL Tool.*(\r)?\n")); - Assert.assertTrue(p.get(3), p.get(3).matches(".*.INFO. .* StateSymbol defined for NoGame.*(\r)?\n")); - Assert.assertTrue(p.get(6), p.get(6).matches(".*.INFO. .* The model contains 3 states.*(\r)?\n")); + assertTrue(p.get(0).matches(".*.INFO. SM2Tool SM2 DSL Tool.*(\r)?\n"), p.get(0)); + assertTrue(p.get(3).matches(".*.INFO. .* StateSymbol defined for NoGame.*(\r)?\n"), p.get(3)); + assertTrue(p.get(6).matches(".*.INFO. .* The model contains 3 states.*(\r)?\n"), p.get(6)); // Check resulting pretty print: String res = p.get(p.size()-1).replaceAll("\r\n", " ").replaceAll("\n", " "); assertEquals(231, res.length()); - Assert.assertTrue(res, res.matches(".*state NoGame <>.*")); - Assert.assertTrue(res, res.matches(".*Pong - returnBall > Ping;.*")); - Assert.assertTrue(Log.getFindings().isEmpty()); + assertTrue(res.matches(".*state NoGame <>.*"), res); + assertTrue(res.matches(".*Pong - returnBall > Ping;.*"), res); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/spaceOnOff-negative/src/test/java/CheckSpaceOnOffTest.java b/monticore-test/01.experiments/spaceOnOff-negative/src/test/java/CheckSpaceOnOffTest.java index 873ed4712e..9553cc348d 100644 --- a/monticore-test/01.experiments/spaceOnOff-negative/src/test/java/CheckSpaceOnOffTest.java +++ b/monticore-test/01.experiments/spaceOnOff-negative/src/test/java/CheckSpaceOnOffTest.java @@ -1,36 +1,19 @@ /* (c) https://github.com/MontiCore/monticore */ +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; +import de.monticore.spaceonoff.SpaceOnOffMill; import de.monticore.spaceonoff._ast.*; -import de.monticore.spaceonoff._parser.SpaceOnOffParser; import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; - +import static org.junit.jupiter.api.Assertions.*; +@TestWithMCLanguage(SpaceOnOffMill.class) public class CheckSpaceOnOffTest { - - // setup the language infrastructure - SpaceOnOffParser parser = new SpaceOnOffParser() ; - - @Before - public void init() { - LogStub.init(); // replace log by a sideffect free variant - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - } - - - @Before - public void setUp() { - Log.getFindings().clear(); - } // -------------------------------------------------------------------- // Check Types, especially ">" and "> >" @@ -39,41 +22,41 @@ public void setUp() { // -------------------------------------------------------------------- @Test public void testType1() throws IOException { - ASTType ast = parser.parse_StringType( " Theo " ).get(); + ASTType ast = SpaceOnOffMill.parser().parse_StringType( " Theo " ).get(); assertEquals("Theo", ast.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType2() throws IOException { - ASTType ast = parser.parse_StringType( " List < Theo > " ).get(); + ASTType ast = SpaceOnOffMill.parser().parse_StringType( " List < Theo > " ).get(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Theo", ta.getTypeList().get(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType3() throws IOException { - ASTType ast = parser.parse_StringType( "List" ).get(); + ASTType ast = SpaceOnOffMill.parser().parse_StringType( "List" ).get(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Theo", ta.getTypeList().get(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType4() throws IOException { - ASTType ast = parser.parse_StringType( "List>" ).get(); + ASTType ast = SpaceOnOffMill.parser().parse_StringType( "List>" ).get(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Set", ta.getTypeList().get(0).getName()); ASTTypeArguments ta2 = ta.getTypeList().get(0).getTypeArguments(); assertEquals("Theo", ta2.getTypeList().get(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -84,52 +67,54 @@ public void testType4() throws IOException { // -------------------------------------------------------------------- @Test public void testExpr1() throws IOException { - ASTExpression ast = parser.parse_StringExpression( " theo + theo " ).get(); + ASTExpression ast = SpaceOnOffMill.parser().parse_StringExpression( " theo + theo " ).get(); assertEquals(ASTAddExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr2() throws IOException { - ASTExpression ast = parser.parse_StringExpression( + ASTExpression ast = SpaceOnOffMill.parser().parse_StringExpression( " (theo < ox) > theo " ).get(); assertEquals(ASTComparisonExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr3() throws IOException { - ASTExpression ast = parser.parse_StringExpression( + ASTExpression ast = SpaceOnOffMill.parser().parse_StringExpression( " theo :!>>!: theo " ).get(); assertEquals(ASTShiftExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr4() throws IOException { - ASTExpression ast = parser.parse_StringExpression( + ASTExpression ast = SpaceOnOffMill.parser().parse_StringExpression( "theo > theo :!>>!: theo :!>>>!: theo :!>=!: theo" ).get(); assertEquals(ASTComparisonExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExprNeg1() throws IOException { - Optional ast = parser.parse_StringExpression( + Optional ast = SpaceOnOffMill.parser().parse_StringExpression( "theo > \n > theo " ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } // -------------------------------------------------------------------- @Test public void testExprNeg2() throws IOException { - Optional ast = parser.parse_StringExpression( + Optional ast = SpaceOnOffMill.parser().parse_StringExpression( "theo :!< < true); } @@ -140,34 +125,35 @@ public void testExprNeg2() throws IOException { // -------------------------------------------------------------------- @Test public void testA() throws IOException { - ASTA ast = parser.parse_StringA( " Theo " ).get(); + ASTA ast = SpaceOnOffMill.parser().parse_StringA( " Theo " ).get(); assertEquals("Theo", ast.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testB() throws IOException { - ASTB ast = parser.parse_StringB( "Otto \n Karo " ).get(); + ASTB ast = SpaceOnOffMill.parser().parse_StringB( "Otto \n Karo " ).get(); assertEquals("Otto", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testC() throws IOException { - ASTC ast = parser.parse_StringC( " :!Otto,Karo!:" ).get(); + ASTC ast = SpaceOnOffMill.parser().parse_StringC( " :!Otto,Karo!:" ).get(); assertEquals("Otto", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testC2() throws IOException { - Optional ast = parser.parse_StringC( " :!Otto ,Karo!:" ); + Optional ast = SpaceOnOffMill.parser().parse_StringC( " :!Otto ,Karo!:" ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } } diff --git a/monticore-test/01.experiments/spacesOffWithPositionCheck/src/test/java/SomeTest.java b/monticore-test/01.experiments/spacesOffWithPositionCheck/src/test/java/SomeTest.java index 0bebfb3f39..6f268ef5d5 100644 --- a/monticore-test/01.experiments/spacesOffWithPositionCheck/src/test/java/SomeTest.java +++ b/monticore-test/01.experiments/spacesOffWithPositionCheck/src/test/java/SomeTest.java @@ -3,36 +3,19 @@ import java.io.IOException; import java.util.Optional; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; +import de.monticore.spacefreechecks.SpaceFreeChecksMill; import de.monticore.spacefreechecks._ast.*; -import de.monticore.spacefreechecks._parser.SpaceFreeChecksParser; -import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +@TestWithMCLanguage(SpaceFreeChecksMill.class) public class SomeTest { - - // setup the language infrastructure - SpaceFreeChecksParser parser = new SpaceFreeChecksParser() ; - - @Before - public void init() { - LogStub.init(); // replace log by a sideffect free variant - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - } - - @Before - public void setUp() { - Log.getFindings().clear(); - } - // -------------------------------------------------------------------- // Check Types, especially ">" and "> >" // -------------------------------------------------------------------- @@ -40,59 +23,59 @@ public void setUp() { // -------------------------------------------------------------------- @Test public void testType1() throws IOException { - ASTType ast = parser.parse_StringType( " Theo " ).get(); + ASTType ast = SpaceFreeChecksMill.parser().parse_StringType( " Theo " ).get(); assertEquals("Theo", ast.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType2() throws IOException { - ASTType ast = parser.parse_StringType( " List < Theo > " ).get(); + ASTType ast = SpaceFreeChecksMill.parser().parse_StringType( " List < Theo > " ).get(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Theo", ta.getTypeList().get(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType3() throws IOException { - ASTType ast = parser.parse_StringType( "List" ).get(); + ASTType ast = SpaceFreeChecksMill.parser().parse_StringType( "List" ).get(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Theo", ta.getTypeList().get(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType4() throws IOException { - ASTType ast = parser.parse_StringType( "List>" ).get(); + ASTType ast = SpaceFreeChecksMill.parser().parse_StringType( "List>" ).get(); assertEquals("List", ast.getName()); ASTTypeArguments ta = ast.getTypeArguments(); assertEquals("Set", ta.getTypeList().get(0).getName()); ASTTypeArguments ta2 = ta.getTypeList().get(0).getTypeArguments(); assertEquals("Theo", ta2.getTypeList().get(0).getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType5() throws IOException { - ASTExpression ast0 = parser.parse_StringExpression( + ASTExpression ast0 = SpaceFreeChecksMill.parser().parse_StringExpression( "List>" ).get(); assertEquals(ASTTypeAsExpression.class, ast0.getClass()); ASTType ast1 = ((ASTTypeAsExpression)ast0).getType() ; assertEquals("List", ast1.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testType6() throws IOException { - ASTExpression ast0 = parser.parse_StringExpression( + ASTExpression ast0 = SpaceFreeChecksMill.parser().parse_StringExpression( "List>>>wert" ).get(); assertEquals(ASTShiftExpression.class, ast0.getClass()); @@ -101,7 +84,7 @@ public void testType6() throws IOException { assertEquals(ASTTypeAsExpression.class, ast1.getClass()); ASTType ast2 = ((ASTTypeAsExpression)ast1).getType() ; assertEquals("List", ast2.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -110,7 +93,7 @@ public void testType6() throws IOException { public void testType7() throws IOException { // This will be parsed as Type >> wert, because the // type has a higher precedence - ASTExpression ast0 = parser.parse_StringExpression( + ASTExpression ast0 = SpaceFreeChecksMill.parser().parse_StringExpression( "List > >>wert" ).get(); assertEquals(ASTShiftExpression.class, ast0.getClass()); @@ -119,7 +102,7 @@ public void testType7() throws IOException { assertEquals(ASTTypeAsExpression.class, ast1.getClass()); ASTType ast2 = ((ASTTypeAsExpression)ast1).getType() ; assertEquals("List", ast2.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @@ -127,9 +110,10 @@ public void testType7() throws IOException { @Test public void testType8() throws IOException { // Thois cannot be parsed as a Type >> wert - Optional ast0 = parser.parse_StringExpression( + Optional ast0 = SpaceFreeChecksMill.parser().parse_StringExpression( "List>> >wert" ); assertFalse(ast0.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } @@ -140,52 +124,54 @@ public void testType8() throws IOException { // -------------------------------------------------------------------- @Test public void testExpr1() throws IOException { - ASTExpression ast = parser.parse_StringExpression( " theo + theo " ).get(); + ASTExpression ast = SpaceFreeChecksMill.parser().parse_StringExpression( " theo + theo " ).get(); assertEquals(ASTAddExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr2() throws IOException { - ASTExpression ast = parser.parse_StringExpression( + ASTExpression ast = SpaceFreeChecksMill.parser().parse_StringExpression( " (theo < ox) > theo " ).get(); assertEquals(ASTComparisonExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr3() throws IOException { - ASTExpression ast = parser.parse_StringExpression( + ASTExpression ast = SpaceFreeChecksMill.parser().parse_StringExpression( " theo >> theo " ).get(); assertEquals(ASTShiftExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExpr4() throws IOException { - ASTExpression ast = parser.parse_StringExpression( + ASTExpression ast = SpaceFreeChecksMill.parser().parse_StringExpression( "theo > theo >> theo >>> theo >= theo" ).get(); assertEquals(ASTComparisonExpression.class, ast.getClass()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testExprNeg1() throws IOException { - Optional ast = parser.parse_StringExpression( + Optional ast = SpaceFreeChecksMill.parser().parse_StringExpression( "theo > > theo " ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } // -------------------------------------------------------------------- @Test public void testExprNeg2() throws IOException { - Optional ast = parser.parse_StringExpression( + Optional ast = SpaceFreeChecksMill.parser().parse_StringExpression( "theo < << theo " ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } @@ -196,68 +182,70 @@ public void testExprNeg2() throws IOException { // -------------------------------------------------------------------- @Test public void testA() throws IOException { - ASTA ast = parser.parse_StringA( " Theo " ).get(); + ASTA ast = SpaceFreeChecksMill.parser().parse_StringA( " Theo " ).get(); assertEquals("Theo", ast.getName()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testB() throws IOException { - ASTB ast = parser.parse_StringB( "Otto \n Karo " ).get(); + ASTB ast = SpaceFreeChecksMill.parser().parse_StringB( "Otto \n Karo " ).get(); assertEquals("Otto", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testC() throws IOException { - ASTC ast = parser.parse_StringC( " Otto.Karo" ).get(); + ASTC ast = SpaceFreeChecksMill.parser().parse_StringC( " Otto.Karo" ).get(); assertEquals("Otto", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testC1() throws IOException { - ASTC ast = parser.parse_StringC( " O.Karo" ).get(); + ASTC ast = SpaceFreeChecksMill.parser().parse_StringC( " O.Karo" ).get(); assertEquals("O", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testC2() throws IOException { - Optional ast = parser.parse_StringC( " O. Karo" ); + Optional ast = SpaceFreeChecksMill.parser().parse_StringC( " O. Karo" ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } // -------------------------------------------------------------------- @Test public void testD() throws IOException { - ASTD ast = parser.parse_StringD( " Otto.Karo" ).get(); + ASTD ast = SpaceFreeChecksMill.parser().parse_StringD( " Otto.Karo" ).get(); assertEquals("Otto", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testD1() throws IOException { - ASTD ast = parser.parse_StringD( " O.Karo" ).get(); + ASTD ast = SpaceFreeChecksMill.parser().parse_StringD( " O.Karo" ).get(); assertEquals("O", ast.getNameList().get(0)); assertEquals("Karo", ast.getNameList().get(1)); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } // -------------------------------------------------------------------- @Test public void testD2() throws IOException { - Optional ast = parser.parse_StringD( " O. Karo" ); + Optional ast = SpaceFreeChecksMill.parser().parse_StringD( " O. Karo" ); assertFalse(ast.isPresent()); + MCAssertions.assertHasFinding(finding -> true); } } diff --git a/monticore-test/01.experiments/stcomposition02/src/test/java/ParserTest.java b/monticore-test/01.experiments/stcomposition02/src/test/java/ParserTest.java index da51a9be5e..12732691f7 100644 --- a/monticore-test/01.experiments/stcomposition02/src/test/java/ParserTest.java +++ b/monticore-test/01.experiments/stcomposition02/src/test/java/ParserTest.java @@ -1,32 +1,28 @@ /* (c) https://github.com/MontiCore/monticore */ +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; +import javaaut.JavaAutMill; import javaaut._parser.JavaAutParser; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import basicjava._ast.ASTCompilationUnit; +import org.junit.jupiter.api.Test; + import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestWithMCLanguage(JavaAutMill.class) public class ParserTest { - @Before - public void setUp(){ - LogStub.init(); // replace log by a sideffect free variant - // LogStub.initPlusLog(); // for manual testing purpose only - Log.enableFailQuick(false); - } - @Test public void testPingPong(){ parse("src/test/resources/example/PingPong.javaaut"); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } /** @@ -36,7 +32,7 @@ public void testPingPong(){ * @return */ public static ASTCompilationUnit parse(String model) { - try { JavaAutParser parser = new JavaAutParser() ; + try { JavaAutParser parser = JavaAutMill.parser() ; Optional optResult = parser.parse(model); if (!parser.hasErrors() && optResult.isPresent()) { @@ -47,7 +43,6 @@ public static ASTCompilationUnit parse(String model) { catch (RecognitionException | IOException e) { Log.error("0xEE64B Failed to parse " + model, e); } - System.exit(1); return null; } } diff --git a/monticore-test/01.experiments/stcomposition02/src/test/java/SymTabTest.java b/monticore-test/01.experiments/stcomposition02/src/test/java/SymTabTest.java index bfbe1fd554..f37794c001 100644 --- a/monticore-test/01.experiments/stcomposition02/src/test/java/SymTabTest.java +++ b/monticore-test/01.experiments/stcomposition02/src/test/java/SymTabTest.java @@ -2,32 +2,23 @@ import basicjava._ast.ASTCompilationUnit; import basicjava._symboltable.MethodSymbol; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; import javaaut.JavaAutMill; import javaaut._parser.JavaAutParser; import javaaut._symboltable.*; import org.antlr.v4.runtime.RecognitionException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.*; +@TestWithMCLanguage(JavaAutMill.class) public class SymTabTest { - @Before - public void setUp(){ - LogStub.init(); // replace log by a sideffect free variant - Log.enableFailQuick(false); - JavaAutMill.init(); - // LogStub.initPlusLog(); // for manual testing purpose only - } @Test public void testPingPong() { @@ -37,8 +28,8 @@ public void testPingPong() { .resolveMethod("PingPong.simulate.Game"); //in example model, this is an automaton assertTrue(symbol.isPresent()); assertEquals("Game", symbol.get().getName()); - assertTrue(symbol.get() instanceof Automaton2MethodAdapter); //assure that an adapter was found - Assert.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(Automaton2MethodAdapter.class, symbol.get()); //assure that an adapter was found + MCAssertions.assertNoFindings(); } /** @@ -55,7 +46,7 @@ public static IJavaAutArtifactScope createSymTab(String model) { public static ASTCompilationUnit parse(String model) { try { - JavaAutParser parser = new JavaAutParser(); + JavaAutParser parser = JavaAutMill.parser(); Optional optResult = parser.parse(model); if (!parser.hasErrors() && optResult.isPresent()) { @@ -66,7 +57,6 @@ public static ASTCompilationUnit parse(String model) { catch (RecognitionException | IOException e) { Log.error("0xEE64C Failed to parse " + model, e); } - System.exit(1); return null; } } diff --git a/monticore-test/01.experiments/stcomposition03/src/test/java/BasicJavaToolTest.java b/monticore-test/01.experiments/stcomposition03/src/test/java/BasicJavaToolTest.java index 5d61acf809..43ad976072 100644 --- a/monticore-test/01.experiments/stcomposition03/src/test/java/BasicJavaToolTest.java +++ b/monticore-test/01.experiments/stcomposition03/src/test/java/BasicJavaToolTest.java @@ -1,40 +1,24 @@ /* (c) https://github.com/MontiCore/monticore */ import automata7.Automata7Mill; -import automata7._symboltable.Automata7ArtifactScope; import automata7._symboltable.IAutomata7ArtifactScope; import automata7._symboltable.StimulusSymbol; -import basiccd.BasicCDMill; import de.monticore.io.paths.MCPath; -import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import javaandaut.Class2StimulusAdapter; import javaandaut.JavaAndAutTool; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.util.Optional; import java.nio.file.Paths; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.*; +@TestWithMCLanguage(Automata7Mill.class) public class BasicJavaToolTest { - @BeforeClass - public static void setUpLogger(){ - Automata7Mill.reset(); - Automata7Mill.init(); - } - - @Before - public void before() { - LogStub.init(); - Log.enableFailQuick(false); - } - @Test public void testPingPong(){ MCPath symbolPath = new MCPath(Paths.get("src/test/resources/example")); @@ -44,8 +28,8 @@ public void testPingPong(){ Optional hit = symTab.resolveStimulus("Hit"); assertTrue(hit.isPresent()); assertEquals("Hit", hit.get().getName()); - assertTrue(hit.get() instanceof Class2StimulusAdapter); //assure that an adapter was found - Assert.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(Class2StimulusAdapter.class, hit.get()); //assure that an adapter was found + MCAssertions.assertNoFindings(); } diff --git a/monticore-test/01.experiments/stcomposition03/src/test/java/CDAndAutTest.java b/monticore-test/01.experiments/stcomposition03/src/test/java/CDAndAutTest.java index f507456c80..c75701a563 100644 --- a/monticore-test/01.experiments/stcomposition03/src/test/java/CDAndAutTest.java +++ b/monticore-test/01.experiments/stcomposition03/src/test/java/CDAndAutTest.java @@ -10,18 +10,18 @@ import basiccd._parser.BasicCDParser; import cdandaut.CDClass2StimulusAdapter; import cdandaut.CDClass2StimulusResolver; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; import java.util.Optional; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class CDAndAutTest { @@ -29,7 +29,7 @@ public class CDAndAutTest { Automata7Parser autParser = new Automata7Parser(); - @BeforeClass + @BeforeAll public static void setUpLogger() { BasicCDMill.reset(); Automata7Mill.reset(); @@ -37,7 +37,7 @@ public static void setUpLogger() { Automata7Mill.init(); } - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -66,7 +66,7 @@ public void testPingPong() throws IOException { assertTrue(s.isPresent()); assertEquals("Bla", s.get().getName()); - assertTrue(s.get() instanceof CDClass2StimulusAdapter); //assure that an adapter was found - Assert.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(CDClass2StimulusAdapter.class, s.get()); //assure that an adapter was found + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/stcomposition03/src/test/java/CDAutTest.java b/monticore-test/01.experiments/stcomposition03/src/test/java/CDAutTest.java index 93e68dee0f..85a7d5eecd 100644 --- a/monticore-test/01.experiments/stcomposition03/src/test/java/CDAutTest.java +++ b/monticore-test/01.experiments/stcomposition03/src/test/java/CDAutTest.java @@ -4,41 +4,25 @@ import cdandaut.CDClass2StimulusAdapter; import cdautomata.CDAutomataMill; import cdautomata._ast.ASTCDAutomaton; -import cdautomata._parser.CDAutomataParser; import cdautomata._symboltable.ICDAutomataArtifactScope; -import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.runtime.junit.TestWithMCLanguage; import java.io.IOException; import java.util.Optional; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; -import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.Test; -public class CDAutTest { +import static org.junit.jupiter.api.Assertions.*; - CDAutomataParser parser = new CDAutomataParser(); +@TestWithMCLanguage(CDAutomataMill.class) +public class CDAutTest { - @BeforeClass - public static void setUp() { - CDAutomataMill.init(); - } - - @Before - public void before() { - LogStub.init(); - Log.enableFailQuick(false); - } - @Test public void testResolveAdapted() throws IOException { //initialize String model = "src/test/resources/example/Foo.cdaut"; - ASTCDAutomaton ast = parser.parse(model).get(); + ASTCDAutomaton ast = CDAutomataMill.parser().parse(model).get(); ICDAutomataArtifactScope as = CDAutomataMill.scopesGenitorDelegator().createFromAST(ast); as.setName("Foo"); @@ -47,18 +31,18 @@ public void testResolveAdapted() throws IOException { .resolveStimulus("Foo.Bar.Bla"); //in example model, this is a CD class assertTrue(symbol.isPresent()); assertEquals("Bla", symbol.get().getName()); - assertTrue(symbol.get() instanceof CDClass2StimulusAdapter); //assure that an adapter was found + assertInstanceOf(CDClass2StimulusAdapter.class, symbol.get()); //assure that an adapter was found // resolve for same symbol a second time Optional symbol2 = as .resolveStimulus("Foo.Bar.Bla"); //in example model, this is a CD class assertTrue(symbol2.isPresent()); assertEquals("Bla", symbol2.get().getName()); - assertTrue(symbol2.get() instanceof CDClass2StimulusAdapter); //assure that an adapter was found + assertInstanceOf(CDClass2StimulusAdapter.class, symbol2.get()); //assure that an adapter was found //assure that the same object of the adapter was found in both calls assertEquals(symbol.get(), symbol2.get()); - Assert.assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/strules/src/test/java/STRulesToolTest.java b/monticore-test/01.experiments/strules/src/test/java/STRulesToolTest.java index 0d9b00080f..57f310650a 100644 --- a/monticore-test/01.experiments/strules/src/test/java/STRulesToolTest.java +++ b/monticore-test/01.experiments/strules/src/test/java/STRulesToolTest.java @@ -1,18 +1,18 @@ /* (c) https://github.com/MontiCore/monticore */ +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import strules.STRulesTool; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class STRulesToolTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -22,9 +22,9 @@ public void before() { public void testFooFileSystem() { LogStub.init(); // Log.enableFailQuick(false); - STRulesTool.main(new String[] { "-i", "src/test/resources/FooFileSystem.str"}); + new STRulesTool().run(new String[] { "-i", "src/test/resources/FooFileSystem.str"}); assertEquals(0, Log.getErrorCount()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/tagging/build.gradle b/monticore-test/01.experiments/tagging/build.gradle index c635a726e5..8e54409a78 100644 --- a/monticore-test/01.experiments/tagging/build.gradle +++ b/monticore-test/01.experiments/tagging/build.gradle @@ -54,8 +54,9 @@ if (("true").equals(getProperty('genTagging'))) { dependencies { withGenImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - withGenImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - withGenRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + withGenImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + withGenRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" + // monticore-grammar-tagging withGenImplementation files(project(":monticore-grammar").sourceSets.tagging.output.classesDirs) withGenImplementation project(project.path) @@ -63,6 +64,10 @@ if (("true").equals(getProperty('genTagging'))) { withGenGrammarSymbolDependencies files(project(":monticore-grammar").sourceSets.main.grammars.getSourceDirectories()) } + test { + useJUnitPlatform() + } + // Register a jUnit platform tasks.register('withGenTest', Test) { description = 'Runs tests with tagGen.' diff --git a/monticore-test/01.experiments/tagging/src/test/java/GrammarTagTest.java b/monticore-test/01.experiments/tagging/src/test/java/GrammarTagTest.java index e8513c12a0..173bb3ccbe 100644 --- a/monticore-test/01.experiments/tagging/src/test/java/GrammarTagTest.java +++ b/monticore-test/01.experiments/tagging/src/test/java/GrammarTagTest.java @@ -11,14 +11,15 @@ import de.monticore.tagging.tags._ast.ASTValuedTag; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.List; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + // Also test the SimpleSymbolTagger on a more complex language with scopes and package names public class GrammarTagTest { @@ -26,16 +27,17 @@ public class GrammarTagTest { static ISymbolTagger tagger; - @BeforeClass + @BeforeAll public static void init() throws Exception { TagRepository.clearTags(); LogStub.init(); Log.enableFailQuick(false); + TagsMill.init(); // Load all relevant models Optional opt = TagRepository.loadTagModel(new File("src/test/resources/models/SimpleGrammar.tags")); if (opt.isEmpty()) - Assert.fail("Failed to load Simple.tags"); + fail("Failed to load Simple.tags"); tagger = new SimpleSymbolTagger(TagRepository::getLoadedTagUnits); @@ -51,14 +53,14 @@ public static void init() throws Exception { @Test public void testAutomaton() { List tags = tagger.getTags(automata.getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "Grammar"); } @Test public void testAutomatonProdSymbol() { List tags = tagger.getTags(automata.getSpannedScope().resolveProd("Automaton").get()); - Assert.assertEquals(2, tags.size()); + assertEquals(2, tags.size()); assertValuedTag(tags.get(0), "SymbolProd", "within"); assertValuedTag(tags.get(1), "SymbolProd", "fqn"); } @@ -66,14 +68,14 @@ public void testAutomatonProdSymbol() { @Test public void testFQNAutomaton() { List tags = tagger.getTags(fqnAutomata.getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "FQNGrammar"); } @Test public void testFQNAutomatonProdSymbol() { List tags = tagger.getTags(fqnAutomata.getSpannedScope().resolveProd("Automaton").get()); - Assert.assertEquals(2, tags.size()); + assertEquals(2, tags.size()); assertValuedTag(tags.get(0), "SymbolProd", "within"); assertValuedTag(tags.get(1), "SymbolProd", "fqn"); } @@ -82,34 +84,34 @@ public void testFQNAutomatonProdSymbol() { @Test public void testAddRemove() { List tags = tagger.getTags(fqnAutomata.getSpannedScope().resolveProd("Automaton").get()); - Assert.assertEquals(2, tags.size()); + assertEquals(2, tags.size()); tagger.addTag(fqnAutomata.getSpannedScope().resolveProd("Automaton").get(), TagsMill.simpleTagBuilder().setName("newTag").build()); tags = tagger.getTags(fqnAutomata.getSpannedScope().resolveProd("Automaton").get()); - Assert.assertEquals("Add on FQN.Automaton", 3, tags.size()); + assertEquals(3, tags.size(), "Add on FQN.Automaton"); tagger.removeTag(fqnAutomata.getSpannedScope().resolveProd("Automaton").get(), tags.get(2)); tags = tagger.getTags(fqnAutomata.getSpannedScope().resolveProd("Automaton").get()); - Assert.assertEquals("Remove on FQN.Automaton", 2, tags.size()); + assertEquals(2, tags.size(), "Remove on FQN.Automaton"); tagger.addTag(fqnAutomata.getSpannedScope().resolveProd("State").get(), TagsMill.simpleTagBuilder().setName("newTag").build()); tags = tagger.getTags(fqnAutomata.getSpannedScope().resolveProd("State").get()); - Assert.assertEquals("Add on (freshly tagged) FQN.State", 1, tags.size()); + assertEquals(1, tags.size(), "Add on (freshly tagged) FQN.State"); } protected void assertValuedTag(ASTTag tag, String name, String value) { - Assert.assertTrue(tag instanceof ASTValuedTag); + assertInstanceOf(ASTValuedTag.class, tag); ASTValuedTag valuedTag = (ASTValuedTag) tag; - Assert.assertEquals(name, valuedTag.getName()); - Assert.assertEquals(value, valuedTag.getValue()); + assertEquals(name, valuedTag.getName()); + assertEquals(value, valuedTag.getValue()); } protected void assertSimpleTag(ASTTag tag, String name) { - Assert.assertTrue(tag instanceof ASTSimpleTag); + assertInstanceOf(ASTSimpleTag.class, tag); ASTSimpleTag simpleTag = (ASTSimpleTag) tag; - Assert.assertEquals(name, simpleTag.getName()); + assertEquals(name, simpleTag.getName()); } } diff --git a/monticore-test/01.experiments/tagging/src/test/java/TagTest.java b/monticore-test/01.experiments/tagging/src/test/java/TagTest.java index ad397d42fd..699f6c4670 100644 --- a/monticore-test/01.experiments/tagging/src/test/java/TagTest.java +++ b/monticore-test/01.experiments/tagging/src/test/java/TagTest.java @@ -16,25 +16,26 @@ import de.monticore.tagging.tags._ast.ASTValuedTag; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class TagTest { static ASTAutomaton model; static ISymbolTagger tagger; - static Map states = new HashMap<>(); + static Map states = new LinkedHashMap<>(); - @BeforeClass + @BeforeAll public static void init() throws Exception { TagRepository.clearTags(); LogStub.init(); @@ -42,11 +43,11 @@ public static void init() throws Exception { // Load all relevant models var emptyTagsOpt1 = TagRepository.loadTagModel(new File("src/test/resources/models/Empty.tags")); - Assert.assertTrue("Failed to load Empty.tags", emptyTagsOpt1.isPresent()); + assertTrue(emptyTagsOpt1.isPresent(), "Failed to load Empty.tags"); var opt = TagRepository.loadTagModel(new File("src/test/resources/models/Simple.tags")); - Assert.assertTrue("Failed to load Simple.tags", opt.isPresent()); + assertTrue(opt.isPresent(), "Failed to load Simple.tags"); var emptyTagsOpt2 = TagRepository.loadTagModel(new File("src/test/resources/models/Empty.tags")); - Assert.assertTrue("Failed to load Empty.tags", emptyTagsOpt2.isPresent()); + assertTrue(emptyTagsOpt2.isPresent(), "Failed to load Empty.tags"); tagger = new SimpleSymbolTagger(TagRepository::getLoadedTagUnits); @@ -68,7 +69,7 @@ public void visit(ASTState node) { @Test public void testAutomaton() { List tags = tagger.getTags(model.getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "Method", "App.call()"); } @@ -76,7 +77,7 @@ public void testAutomaton() { @Test public void testStateA() { List tags = tagger.getTags(states.get("A").getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "Monitored"); } @@ -84,20 +85,20 @@ public void testStateA() { @Test public void testStateBSymbol() { List tags = tagger.getTags(states.get("B").getSymbol()); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); } @Test public void testStateBASymbol() { List tags = tagger.getTags(states.get("BA").getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag1"); } @Test public void testStateBBSymbol() { List tags = tagger.getTags(states.get("BB").getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag2"); } @@ -105,44 +106,44 @@ public void testStateBBSymbol() { @Test public void testSomeScopeCSymbol() { List tags = tagger.getTags(model.getEnclosingScope().resolveScopedState("C").get()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "VerboseLog", "doLogC"); } @Test public void testStateC_CASymbol() { List tags = tagger.getTags(states.get("C.CA").getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag1"); } @Test public void testStateC_CBSymbol() { List tags = tagger.getTags(states.get("C.CB").getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag2"); } @Test public void testStateDSymbol() { List tags = tagger.getTags(states.get("D").getSymbol()); - Assert.assertEquals(2, tags.size()); + assertEquals(2, tags.size()); assertSimpleTag(tags.get(0), "WildcardedTag"); } @Test public void testDupSymbols() { Optional stateSymbolOpt = model.getEnclosingScope().resolveState("Dup"); - Assert.assertTrue(stateSymbolOpt.isPresent()); + assertTrue(stateSymbolOpt.isPresent()); Optional scopedStateSymbolOpt = model.getEnclosingScope().resolveScopedState("Dup"); - Assert.assertTrue(scopedStateSymbolOpt.isPresent()); + assertTrue(scopedStateSymbolOpt.isPresent()); // Discuss if this type-unaware duplication is desired? List tags = tagger.getTags(stateSymbolOpt.get()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "WildcardedTag"); tags = tagger.getTags(scopedStateSymbolOpt.get()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "WildcardedTag"); } @@ -150,30 +151,30 @@ public void testDupSymbols() { public void testAddStateE() { ASTState stateE = states.get("E"); List tags = tagger.getTags(stateE.getSymbol()); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); // Add new Tag ASTTag tag = TagsMill.simpleTagBuilder().setName("TestTag").build(); tagger.addTag(stateE.getSymbol(), tag); tags = tagger.getTags(stateE.getSymbol()); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "TestTag"); // Remove tag again tagger.removeTag(stateE.getSymbol(), tag); tags = tagger.getTags(stateE.getSymbol()); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); } protected void assertValuedTag(ASTTag tag, String name, String value) { - Assert.assertTrue(tag instanceof ASTValuedTag); + assertInstanceOf(ASTValuedTag.class, tag); ASTValuedTag valuedTag = (ASTValuedTag) tag; - Assert.assertEquals(name, valuedTag.getName()); - Assert.assertEquals(value, valuedTag.getValue()); + assertEquals(name, valuedTag.getName()); + assertEquals(value, valuedTag.getValue()); } protected void assertSimpleTag(ASTTag tag, String name) { - Assert.assertTrue(tag instanceof ASTSimpleTag); + assertInstanceOf(ASTSimpleTag.class, tag); ASTSimpleTag simpleTag = (ASTSimpleTag) tag; - Assert.assertEquals(name, simpleTag.getName()); + assertEquals(name, simpleTag.getName()); } } diff --git a/monticore-test/01.experiments/tagging/src/withGen/java/AutomataSchemaTest.java b/monticore-test/01.experiments/tagging/src/withGen/java/AutomataSchemaTest.java index c6571c4ec4..1b7729d1c6 100644 --- a/monticore-test/01.experiments/tagging/src/withGen/java/AutomataSchemaTest.java +++ b/monticore-test/01.experiments/tagging/src/withGen/java/AutomataSchemaTest.java @@ -8,29 +8,35 @@ import automatatagschema.AutomataTagSchemaMill; import automatatagschema._symboltable.AutomataTagSchemaSymbols2Json; import automatatagschema._symboltable.IAutomataTagSchemaArtifactScope; +import com.google.common.base.Preconditions; import com.google.common.io.Files; import de.monticore.tagging.tags._ast.ASTTagUnit; import de.monticore.tagging.tagschema._ast.ASTTagSchema; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.apache.commons.io.FileUtils; -import org.junit.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class AutomataSchemaTest { protected static ASTAutomaton model; + @TempDir static File tempDir; - @BeforeClass + @BeforeAll public static void prepare() throws Exception { - tempDir = java.nio.file.Files.createTempDirectory("AutomataSchemaTest").toFile(); - if (!tempDir.exists()) - tempDir.mkdirs(); LogStub.init(); Log.enableFailQuick(false); @@ -45,7 +51,7 @@ public static void prepare() throws Exception { // Serialize all schemas and store the .sym files (so they can be loaded later on) // Note, that the resolving using packages is not supported for tagschemas - for (File f : Objects.requireNonNull( + for (File f : Preconditions.checkNotNull( new File("src/test/resources/schema/").listFiles(x -> x.getName().endsWith(".tagschema")))) { Optional schemaOpt = AutomataTagSchemaMill.parser().parse(f.getAbsolutePath()); if (schemaOpt.isPresent()) { @@ -53,7 +59,7 @@ public static void prepare() throws Exception { IAutomataTagSchemaArtifactScope artifactScope = AutomataTagSchemaMill.scopesGenitorDelegator().createFromAST(schemaOpt.get()); String symFile = new File(new File(tempDir, "schema"), Files.getNameWithoutExtension(f.getName()) + ".sym").toString(); symbols2Json.store(artifactScope, symFile); - Assert.assertEquals("TagSchema " + f + " logged errors",0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount(), "TagSchema " + f + " logged errors"); } else { Log.clearFindings(); Log.warn("Failed to load TagSchema " + f); @@ -66,133 +72,133 @@ public static void prepare() throws Exception { // Finally, switch to the TagDef language AutomataTagDefinitionMill.init(); - Assert.assertEquals(0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount()); } - @Before + @BeforeEach public void beforeEach() { Log.clearFindings(); } @Test public void testResolve() throws IOException { - Assert.assertTrue(AutomataTagSchemaMill.globalScope().resolveTagSchema("AutomataSchema").isPresent()); - Assert.assertEquals(0, Log.getErrorCount()); + assertTrue(AutomataTagSchemaMill.globalScope().resolveTagSchema("AutomataSchema").isPresent()); + assertEquals(0, Log.getErrorCount()); } @Test public void testValidTags1() throws IOException { testTagDefCoCoChecker("src/test/resources/models/Simple.tags"); - Assert.assertEquals(0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount()); } @Test public void testSpotRootWithSimpleInsteadOfValued() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidTags1.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNWithInvalidSimpleTag() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidTags2.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNHWithInvalidSimpleTag() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidTags3.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNHWithInvalidValuedTag() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidTags4.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNWithinWithInvalidSimpleTag() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidTags5.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testComplexMissing() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidTags7.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testComplexTooMany() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidTags8.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNWithinWithInvalidPrivateTag() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidTagsPrivate.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNComplexMissingInner() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidComplexTags1.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNComplexTooManyInner() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidComplexTags2.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNComplexTypoInner() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidComplexTags3.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNComplexNotANumber() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidComplexTags4.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNComplexNotABoolean() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidComplexTags5.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNComplexUnknownInnerComplex() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidComplexTags6.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNComplexInvalidInnerComplex() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidComplexTags7.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNPattern() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidPatternTags1.tags"); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } @Test public void testFQNPatternWithin() throws IOException { testTagDefCoCoChecker("src/test/resources/models/InvalidPatternTags2.tags"); - Assert.assertEquals(2, Log.getErrorCount()); + assertEquals(2, Log.getErrorCount()); } @Test public void testFQNNonConformingTags() throws IOException { testTagDefCoCoChecker("src/test/resources/models/NonConformingTags.tags"); - Assert.assertEquals(0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount()); } protected void testTagDefCoCoChecker(String file) throws IOException { @@ -204,11 +210,4 @@ protected void testTagDefCoCoChecker(String file) throws IOException { coCoChecker.checkAll(n.get()); } - - @AfterClass - public static void cleanUp() throws IOException { - if (tempDir.exists()) { - FileUtils.deleteDirectory(tempDir); - } - } } diff --git a/monticore-test/01.experiments/tagging/src/withGen/java/CDTest.java b/monticore-test/01.experiments/tagging/src/withGen/java/CDTest.java index 253f3ff416..d7abf31b22 100644 --- a/monticore-test/01.experiments/tagging/src/withGen/java/CDTest.java +++ b/monticore-test/01.experiments/tagging/src/withGen/java/CDTest.java @@ -12,17 +12,20 @@ import de.monticore.umlstereotype.UMLStereotypeMill; import de.monticore.umlstereotype._ast.ASTStereoValue; import de.monticore.umlstereotype._ast.ASTStereoValueBuilder; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; import de.monticore.tagging.TagRepository; import de.monticore.tagtest.cdbasis4tags._tagging.CDBasis4TagsTagger; import de.monticore.tagtest.cdbasis4tags._visitor.CDBasis4TagsVisitor2; import de.monticore.tagtest.cdbasis4tags._visitor.CDBasis4TagsTraverser; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.io.File; import java.util.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * This test aims to replicate parts of CD4A to test the tagging infrastucture * in regards to interface usage (such as types) @@ -30,7 +33,7 @@ * In addition, we demonstrate the interaction between tags and stereotypes */ public class CDTest { - @BeforeClass + @BeforeAll public static void init() { CDBasis4TagsTagDefinitionMill.init(); } @@ -38,23 +41,23 @@ public static void init() { @Test public void test() throws Exception{ Optional ast = CDBasis4TagsMill.parser().parse(new File("src/test/resources/models/Door.cd").toString()); - Assert.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); CDBasis4TagsMill.scopesGenitorDelegator().createFromAST(ast.get()); Optional doorsThatAreOpenableTags = TagRepository.loadTagModel(new File("src/test/resources/models/DoorsThatAreOpenable.tags")); - Assert.assertTrue(doorsThatAreOpenableTags.isPresent()); + assertTrue(doorsThatAreOpenableTags.isPresent()); Optional theDoorSymbol = ast.get().getEnclosingScope().resolveCDType("TheDoor"); Optional aSingleDoorSymbol = ast.get().getEnclosingScope().resolveCDType("ASingleDoor"); - Assert.assertTrue(theDoorSymbol.isPresent()); - Assert.assertTrue(aSingleDoorSymbol.isPresent()); + assertTrue(theDoorSymbol.isPresent()); + assertTrue(aSingleDoorSymbol.isPresent()); List tagsForTheDoor = new ArrayList<>(CDBasis4TagsTagger.getInstance().getTags(theDoorSymbol.get())); - Assert.assertEquals(1, tagsForTheDoor.size()); + assertEquals(1, tagsForTheDoor.size()); List tagsForASingleDoor = new ArrayList<>(CDBasis4TagsTagger.getInstance().getTags(aSingleDoorSymbol.get())); - Assert.assertEquals(1, tagsForASingleDoor.size()); + assertEquals(1, tagsForASingleDoor.size()); // Turn stereos into tags @@ -62,7 +65,7 @@ public void test() throws Exception{ tagsFromStereo(ast.get(), tempTagUnit); tagsForASingleDoor.addAll(CDBasis4TagsTagger.getInstance().getTags(aSingleDoorSymbol.get())); - Assert.assertEquals(2, tagsForASingleDoor.size()); + assertEquals(2, tagsForASingleDoor.size()); stereoFromTags(ast.get(), Collections.singleton(doorsThatAreOpenableTags.get())); diff --git a/monticore-test/01.experiments/tagging/src/withGen/java/FQNEnhancedAutomataSchemaTest.java b/monticore-test/01.experiments/tagging/src/withGen/java/FQNEnhancedAutomataSchemaTest.java index 9f63b26446..562620f605 100644 --- a/monticore-test/01.experiments/tagging/src/withGen/java/FQNEnhancedAutomataSchemaTest.java +++ b/monticore-test/01.experiments/tagging/src/withGen/java/FQNEnhancedAutomataSchemaTest.java @@ -1,5 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ +import com.google.common.base.Preconditions; import de.monticore.fqn.fqnautomata._ast.ASTAutomaton; import de.monticore.fqn.fqnautomata._tagging.FQNAutomataTagConformsToSchemaCoCo; import de.monticore.fqn.fqnenhancedautomata.FQNEnhancedAutomataMill; @@ -11,20 +12,21 @@ import de.monticore.tagging.tagschema._ast.ASTTagSchema; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class FQNEnhancedAutomataSchemaTest { protected static ASTAutomaton model; - @BeforeClass + @BeforeAll public static void prepare() throws Exception { LogStub.init(); Log.enableFailQuick(false); @@ -37,7 +39,7 @@ public static void prepare() throws Exception { FQNEnhancedAutomataTagSchemaMill.init(); FQNEnhancedAutomataTagSchemaMill.globalScope().getSymbolPath().addEntry(new File("src/test/resources/").toPath()); - for (File f : Objects.requireNonNull( + for (File f : Preconditions.checkNotNull( new File("src/test/resources/schema/").listFiles(x -> x.getName().endsWith(".tagschema")))) { Optional schemaOpt = FQNEnhancedAutomataTagSchemaMill.parser().parse(f.getAbsolutePath()); if (schemaOpt.isPresent()) { @@ -50,7 +52,7 @@ public static void prepare() throws Exception { FQNEnhancedAutomataTagDefinitionMill.init(); } - @Before + @BeforeEach public void beforeEach() { Log.clearFindings(); } @@ -58,49 +60,49 @@ public void beforeEach() { @Test public void testValidTags1() throws IOException { testCoCo("src/test/resources/models/Simple.tags"); - Assert.assertEquals(0, Log.getErrorCount()); + assertEquals(0, Log.getErrorCount()); } @Test public void testSpotRootWithSimpleInsteadOfValued() throws IOException { testCoCo("src/test/resources/models/InvalidTags1.tags"); - Assert.assertEquals(2, Log.getErrorCount()); + assertEquals(2, Log.getErrorCount()); } @Test public void testFQNWithInvalidSimpleTag() throws IOException { testCoCo("src/test/resources/models/InvalidTags2.tags"); - Assert.assertEquals(2, Log.getErrorCount()); + assertEquals(2, Log.getErrorCount()); } @Test public void testFQNHWithInvalidSimpleTag() throws IOException { testCoCo("src/test/resources/models/InvalidTags3.tags"); - Assert.assertEquals(2, Log.getErrorCount()); + assertEquals(2, Log.getErrorCount()); } @Test public void testFQNHWithInvalidValuedTag() throws IOException { testCoCo("src/test/resources/models/InvalidTags4.tags"); - Assert.assertEquals(2, Log.getErrorCount()); + assertEquals(2, Log.getErrorCount()); } @Test public void testFQNWithinWithInvalidSimpleTag() throws IOException { testCoCo("src/test/resources/models/InvalidTags5.tags"); - Assert.assertEquals(2, Log.getErrorCount()); + assertEquals(2, Log.getErrorCount()); } @Test public void testFQNWithinWithInvalidPrivateTag() throws IOException { testCoCo("src/test/resources/models/InvalidTagsPrivate.tags"); - Assert.assertEquals(2, Log.getErrorCount()); + assertEquals(2, Log.getErrorCount()); } @Test public void testEnhancedFQNNonExtendedTag() throws IOException { testCoCo("src/test/resources/models/InvalidEnhancedTags1.tags"); - Assert.assertEquals(2, Log.getErrorCount()); + assertEquals(2, Log.getErrorCount()); } protected void testCoCo(String file) throws IOException { diff --git a/monticore-test/01.experiments/tagging/src/withGen/java/FQNInheritedTagTest.java b/monticore-test/01.experiments/tagging/src/withGen/java/FQNInheritedTagTest.java index e56574bc7b..016418fa04 100644 --- a/monticore-test/01.experiments/tagging/src/withGen/java/FQNInheritedTagTest.java +++ b/monticore-test/01.experiments/tagging/src/withGen/java/FQNInheritedTagTest.java @@ -22,16 +22,17 @@ import de.monticore.tagging.tags._ast.ASTValuedTag; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import util.TestUtil; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.*; + // Copy of TagTest, just with a grammar in a package // Also tests inheritance public class FQNInheritedTagTest { @@ -39,12 +40,12 @@ public class FQNInheritedTagTest { static ASTAutomaton model; static ASTTagUnit tagDefinition; - static Map states = new HashMap<>(); - static Map red_states = new HashMap<>(); + static Map states = new LinkedHashMap<>(); + static Map red_states = new LinkedHashMap<>(); protected IFQNEnhancedAutomataTagger fqnAutomataTagger = FQNEnhancedAutomataTagger.getInstance(); - @BeforeClass + @BeforeAll public static void init() throws Exception { LogStub.init(); Log.enableFailQuick(false); @@ -78,55 +79,55 @@ public void visit(ASTRedState node) { @Test public void testAutomaton() { List tags = fqnAutomataTagger.getTags(model, Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "Method", "App.call()"); } @Test public void testStateA() { List tags = fqnAutomataTagger.getTags(states.get("A"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "Monitored"); } @Test public void testStateB() { List tags = fqnAutomataTagger.getTags(states.get("B"), Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); } @Test public void testStateBA() { List tags = fqnAutomataTagger.getTags(states.get("BA"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag1"); } @Test public void testStateBB() { List tags = fqnAutomataTagger.getTags(states.get("BB"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag2"); } @Test public void testSomeScopeC() { List tags = fqnAutomataTagger.getTags(model.getEnclosingScope().resolveScopedState("C").get().getAstNode(), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "Log", "doLogC"); } @Test public void testStateC_CA() { List tags = fqnAutomataTagger.getTags(states.get("C.CA"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag1"); } @Test public void testStateC_CB() { List tags = fqnAutomataTagger.getTags(states.get("C.CB"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag2"); } @@ -134,14 +135,14 @@ public void testStateC_CB() { public void testSomeScopeC_Transition() { List tags = fqnAutomataTagger.getTags((ASTTransition) model.getEnclosingScope().resolveScopedState("C").get().getAstNode() .getScopedStateElement(2), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "Log", "timestamp"); } @Test public void testStateD() { List tags = fqnAutomataTagger.getTags(states.get("D"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "WildcardedTag"); } @@ -149,47 +150,47 @@ public void testStateD() { public void testAddStateE() { ASTState stateE = states.get("E"); List tags = fqnAutomataTagger.getTags(stateE, Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); // Add new Tag ASTTag tag = TagsMill.simpleTagBuilder().setName("TestTag").build(); fqnAutomataTagger.addTag(stateE, tagDefinition, tag); tags = fqnAutomataTagger.getTags(stateE, Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "TestTag"); // Remove tag again fqnAutomataTagger.removeTag(stateE, tagDefinition, tag); tags = fqnAutomataTagger.getTags(stateE, Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); } @Test public void testAddTransition() { ASTTransition transition = TestUtil.getTransition(model).stream().filter(e->e.getFrom().equals("E") && e.getTo().equals("E")).findAny().get(); List tags = fqnAutomataTagger.getTags(transition, Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); // Add new Tag ASTTag tag = TagsMill.simpleTagBuilder().setName("TestTag").build(); fqnAutomataTagger.addTag(transition, tagDefinition, tag); tags = fqnAutomataTagger.getTags(transition, Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "TestTag"); // Remove tag again fqnAutomataTagger.removeTag(transition, tagDefinition, tag); tags = fqnAutomataTagger.getTags(transition, Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); } @Test public void testStateRC_CA() { List tags = fqnAutomataTagger.getTags(states.get("RC.CA"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag1"); } @Test public void testStateRC_RCB() { List tags = fqnAutomataTagger.getTags(red_states.get("RC.RCB"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag2"); } @@ -198,21 +199,21 @@ public void testSomeScopeRC_Transition() { List tags = fqnAutomataTagger.getTags((ASTTransition) ((IFQNEnhancedAutomataScope) model.getEnclosingScope()) .resolveRedScopedState("RC").get().getAstNode() .getScopedStateElement(2), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "Log", "timestamp"); } protected void assertValuedTag(ASTTag tag, String name, String value) { - Assert.assertTrue(tag instanceof ASTValuedTag); + assertInstanceOf(ASTValuedTag.class, tag); ASTValuedTag valuedTag = (ASTValuedTag) tag; - Assert.assertEquals(name, valuedTag.getName()); - Assert.assertEquals(value, valuedTag.getValue()); + assertEquals(name, valuedTag.getName()); + assertEquals(value, valuedTag.getValue()); } protected void assertSimpleTag(ASTTag tag, String name) { - Assert.assertTrue(tag instanceof ASTSimpleTag); + assertInstanceOf(ASTSimpleTag.class, tag); ASTSimpleTag simpleTag = (ASTSimpleTag) tag; - Assert.assertEquals(name, simpleTag.getName()); + assertEquals(name, simpleTag.getName()); } } diff --git a/monticore-test/01.experiments/tagging/src/withGen/java/FQNTagTest.java b/monticore-test/01.experiments/tagging/src/withGen/java/FQNTagTest.java index b0f5ef120d..ef6b1d6430 100644 --- a/monticore-test/01.experiments/tagging/src/withGen/java/FQNTagTest.java +++ b/monticore-test/01.experiments/tagging/src/withGen/java/FQNTagTest.java @@ -16,28 +16,29 @@ import de.monticore.tagging.tags._ast.ASTValuedTag; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.Ignore; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import util.TestUtil; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.*; + // Copy of TagTest, just with a grammar in a package public class FQNTagTest { static ASTAutomaton model; static ASTTagUnit tagDefinition; - static Map states = new HashMap<>(); + static Map states = new LinkedHashMap<>(); protected IFQNAutomataTagger fqnAutomataTagger = FQNAutomataTagger.getInstance(); - @BeforeClass + @BeforeAll public static void init() throws Exception { LogStub.init(); Log.enableFailQuick(false); @@ -65,71 +66,71 @@ public void visit(ASTState node) { @Test public void testAutomaton() { List tags = fqnAutomataTagger.getTags(model, Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "Method", "App.call()"); } @Test public void testStateA() { List tags = fqnAutomataTagger.getTags(states.get("A"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "Monitored"); } @Test public void testStateB() { List tags = fqnAutomataTagger.getTags(states.get("B"), Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); } @Test public void testStateBA() { List tags = fqnAutomataTagger.getTags(states.get("BA"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag1"); } @Test public void testStateBB() { List tags = fqnAutomataTagger.getTags(states.get("BB"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag2"); } @Test public void testSomeScopeC() { List tags = fqnAutomataTagger.getTags(model.getEnclosingScope().resolveScopedState("C").get().getAstNode(), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "VerboseLog", "doLogC"); } @Test public void testStateC_CA() { List tags = fqnAutomataTagger.getTags(states.get("C.CA"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag1"); } @Test public void testStateC_CB() { List tags = fqnAutomataTagger.getTags(states.get("C.CB"), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "StateTag2"); } @Test - @Ignore // concrete syntax matching is WIP + @Disabled // concrete syntax matching is WIP public void testSomeScopeC_Transition() { List tags = fqnAutomataTagger.getTags((ASTTransition) model.getEnclosingScope().resolveScopedState("C").get().getAstNode() .getScopedStateElement(2), Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertValuedTag(tags.get(0), "Log", "timestamp"); } @Test public void testStateD() { List tags = fqnAutomataTagger.getTags(states.get("D"), Collections.singleton(tagDefinition)); - Assert.assertEquals(2, tags.size()); + assertEquals(2, tags.size()); assertSimpleTag(tags.get(0), "WildcardedTag"); } @@ -137,47 +138,47 @@ public void testStateD() { public void testAddStateE() { ASTState stateE = states.get("E"); List tags = fqnAutomataTagger.getTags(stateE, Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); // Add new Tag ASTTag tag = TagsMill.simpleTagBuilder().setName("TestTag").build(); fqnAutomataTagger.addTag(stateE, tagDefinition, tag); tags = fqnAutomataTagger.getTags(stateE, Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "TestTag"); // Remove tag again fqnAutomataTagger.removeTag(stateE, tagDefinition, tag); tags = fqnAutomataTagger.getTags(stateE, Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); } @Test public void testAddTransition() { ASTTransition transition = TestUtil.getTransition(model).stream().filter(e->e.getFrom().equals("E") && e.getTo().equals("E")).findAny().get(); List tags = fqnAutomataTagger.getTags(transition, Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); // Add new Tag ASTTag tag = TagsMill.simpleTagBuilder().setName("TestTag").build(); fqnAutomataTagger.addTag(transition, tagDefinition, tag); tags = fqnAutomataTagger.getTags(transition, Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), "TestTag"); // Remove tag again fqnAutomataTagger.removeTag(transition, tagDefinition, tag); tags = fqnAutomataTagger.getTags(transition, Collections.singleton(tagDefinition)); - Assert.assertEquals(0, tags.size()); + assertEquals(0, tags.size()); } protected void assertValuedTag(ASTTag tag, String name, String value) { - Assert.assertTrue(tag instanceof ASTValuedTag); + assertInstanceOf(ASTValuedTag.class, tag); ASTValuedTag valuedTag = (ASTValuedTag) tag; - Assert.assertEquals(name, valuedTag.getName()); - Assert.assertEquals(value, valuedTag.getValue()); + assertEquals(name, valuedTag.getName()); + assertEquals(value, valuedTag.getValue()); } protected void assertSimpleTag(ASTTag tag, String name) { - Assert.assertTrue(tag instanceof ASTSimpleTag); + assertInstanceOf(ASTSimpleTag.class, tag); ASTSimpleTag simpleTag = (ASTSimpleTag) tag; - Assert.assertEquals(name, simpleTag.getName()); + assertEquals(name, simpleTag.getName()); } } diff --git a/monticore-test/01.experiments/tagging/src/withGen/java/InvalidTagSchemaTest.java b/monticore-test/01.experiments/tagging/src/withGen/java/InvalidTagSchemaTest.java index 87fad7094b..d9142184cb 100644 --- a/monticore-test/01.experiments/tagging/src/withGen/java/InvalidTagSchemaTest.java +++ b/monticore-test/01.experiments/tagging/src/withGen/java/InvalidTagSchemaTest.java @@ -4,17 +4,19 @@ import de.monticore.tagging.tagschema._ast.ASTTagSchema; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class InvalidTagSchemaTest { - @BeforeClass + @BeforeAll public static void prepare() { LogStub.init(); Log.enableFailQuick(false); @@ -22,7 +24,7 @@ public static void prepare() { AutomataTagSchemaMill.init(); } - @Before + @BeforeEach public void beforeEach() { Log.clearFindings(); } @@ -30,9 +32,9 @@ public void beforeEach() { @Test public void test() throws IOException { Optional astOpt = AutomataTagSchemaMill.parser().parse("src/test/resources/schema/invalid/InvalidTagSchema.tagschema"); - Assert.assertTrue(astOpt.isPresent()); + assertTrue(astOpt.isPresent()); new de.monticore.tagging.tagschema.TagSchemaAfterParseTrafo().transform(astOpt.get()); - Assert.assertEquals(1, Log.getErrorCount()); + assertEquals(1, Log.getErrorCount()); } } diff --git a/monticore-test/01.experiments/tagging/src/withGen/java/NotQuiteAutomataTest.java b/monticore-test/01.experiments/tagging/src/withGen/java/NotQuiteAutomataTest.java index 2daf7a06fc..55bdaa779d 100644 --- a/monticore-test/01.experiments/tagging/src/withGen/java/NotQuiteAutomataTest.java +++ b/monticore-test/01.experiments/tagging/src/withGen/java/NotQuiteAutomataTest.java @@ -11,16 +11,17 @@ import de.monticore.tagging.tags._ast.ASTTagUnit; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; +import static org.junit.jupiter.api.Assertions.*; + public class NotQuiteAutomataTest { static ASTAutomaton model; @@ -30,9 +31,9 @@ public class NotQuiteAutomataTest { protected IAutomataTagger automataTagger = AutomataTagger.getInstance(); - protected static Map nodes = new HashMap<>(); + protected static Map nodes = new LinkedHashMap<>(); - @BeforeClass + @BeforeAll public static void init() throws Exception { LogStub.init(); Log.enableFailQuick(false); @@ -62,8 +63,8 @@ public static void init() throws Exception { @Test public void testParseCorrect() { - Assert.assertTrue(model.isPresentNotQuiteAutomataProductions()); - Assert.assertEquals(8, nodes.size()); + assertTrue(model.isPresentNotQuiteAutomataProductions()); + assertEquals(8, nodes.size()); } @Test @@ -123,15 +124,15 @@ public void testYetAnotherSymbolProdCS() { } protected void doTest(A ast, BiFunction, List> getTags, String name) { - Assert.assertNotNull(ast); + assertNotNull(ast); List tags = getTags.apply(ast, Collections.singleton(tagDefinition)); - Assert.assertEquals(1, tags.size()); + assertEquals(1, tags.size()); assertSimpleTag(tags.get(0), name); } protected void assertSimpleTag(ASTTag tag, String name) { - Assert.assertTrue(tag instanceof ASTSimpleTag); + assertInstanceOf(ASTSimpleTag.class, tag); ASTSimpleTag simpleTag = (ASTSimpleTag) tag; - Assert.assertEquals(name, simpleTag.getName()); + assertEquals(name, simpleTag.getName()); } } diff --git a/monticore-test/01.experiments/tagging/src/withGen/java/TagSchemaSerializationTest.java b/monticore-test/01.experiments/tagging/src/withGen/java/TagSchemaSerializationTest.java index aada37f8eb..c694952fa9 100644 --- a/monticore-test/01.experiments/tagging/src/withGen/java/TagSchemaSerializationTest.java +++ b/monticore-test/01.experiments/tagging/src/withGen/java/TagSchemaSerializationTest.java @@ -6,6 +6,7 @@ import automatatagdefinition._cocos.AutomataTagDefinitionCoCoChecker; import automatatagschema._symboltable.AutomataTagSchemaSymbols2Json; import automatatagschema._symboltable.IAutomataTagSchemaArtifactScope; +import com.google.common.base.Preconditions; import de.monticore.fqn.fqnenhancedautomata._symboltable.IFQNEnhancedAutomataArtifactScope; import de.monticore.fqn.fqnenhancedautomatatagschema.FQNEnhancedAutomataTagSchemaMill; import de.monticore.fqn.fqnenhancedautomatatagschema._symboltable.FQNEnhancedAutomataTagSchemaSymbols2Json; @@ -15,20 +16,21 @@ import de.monticore.tagging.tagschema._ast.ASTTagSchema; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class TagSchemaSerializationTest { protected static ASTAutomaton model; - @BeforeClass + @BeforeAll public static void prepare() throws Exception { LogStub.init(); Log.enableFailQuick(false); @@ -36,7 +38,7 @@ public static void prepare() throws Exception { FQNEnhancedAutomataTagSchemaMill.init(); // Load all schemas into the global scope - for (File f : Objects.requireNonNull( + for (File f : Preconditions.checkNotNull( new File("src/test/resources/schema/").listFiles(x -> x.getName().endsWith(".tagschema")))) { Optional schemaOpt = FQNEnhancedAutomataTagSchemaMill.parser().parse(f.getAbsolutePath()); if (schemaOpt.isPresent()) @@ -47,14 +49,14 @@ public static void prepare() throws Exception { } - @Before + @BeforeEach public void beforeEach() { Log.clearFindings(); } @Test public void test() throws IOException { - for (File f : Objects.requireNonNull( + for (File f : Preconditions.checkNotNull( new File("src/test/resources/schema/").listFiles(x -> x.getName().endsWith(".tagschema")))) { Optional schemaOpt = FQNEnhancedAutomataTagSchemaMill.parser().parse(f.getAbsolutePath()); if (schemaOpt.isEmpty()) { @@ -71,7 +73,7 @@ public void test() throws IOException { String serializedCopy = schemaSymbols2Json.serialize(copy); - Assert.assertEquals(serialized, serializedCopy); + assertEquals(serialized, serializedCopy); } } diff --git a/monticore-test/01.experiments/templates/ReadMe.md b/monticore-test/01.experiments/templates/ReadMe.md index 8655e10d94..a524a120cf 100644 --- a/monticore-test/01.experiments/templates/ReadMe.md +++ b/monticore-test/01.experiments/templates/ReadMe.md @@ -71,9 +71,9 @@ unit tests. * [Project root: MontiCore @github](https://github.com/MontiCore/monticore) * [MontiCore documentation](https://www.monticore.de/) -* [**List of languages**](https://github.com/MontiCore/monticore/blob/opendev/docs/Languages.md) -* [**MontiCore Core Grammar Library**](https://github.com/MontiCore/monticore/blob/opendev/monticore-grammar/src/main/grammars/de/monticore/Grammars.md) -* [Best Practices](https://github.com/MontiCore/monticore/blob/opendev/docs/BestPractices.md) +* [**List of languages**](../../../docs/Languages.md) +* [**MontiCore Core Grammar Library**](../../../monticore-grammar/src/main/grammars/de/monticore/Grammars.md) +* [Best Practices](../../../docs/BestPractices.md) * [Publications about MBSE and MontiCore](https://www.se-rwth.de/publications/) * [Licence definition](https://github.com/MontiCore/monticore/blob/master/00.org/Licenses/LICENSE-MONTICORE-3-LEVEL.md) diff --git a/monticore-test/01.experiments/templates/build.gradle b/monticore-test/01.experiments/templates/build.gradle index de99dc1ef8..09dd9e5646 100644 --- a/monticore-test/01.experiments/templates/build.gradle +++ b/monticore-test/01.experiments/templates/build.gradle @@ -1,26 +1,43 @@ /* (c) https://github.com/MontiCore/monticore */ plugins { - // provides a convenient way to have multiple test sets - id 'org.unbroken-dome.test-sets' version '4.0.0' + // provides a convenient way to have multiple test suites + id 'jvm-test-suite' } dependencies { implementation project(":monticore-test:01experiments:automaton") } -// create an additional test set called productTest -testSets{ - productTest { extendsFrom unitTest } +// create an additional test suite called productTest +testing { + suites { + test { + useJUnitJupiter(junit_version) + } + + productTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project(":monticore-runtime")) + runtimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" + } + sources { + java.srcDirs += ["$buildDir/statepattern" , "$projectDir/src/product/java"] + } + } + } } -sourceSets { - // add output dir to the sources of productTest - productTest.java.srcDirs += ["$buildDir/statepattern" , "$projectDir/src/product/java"] +// let check depend on productTest such that it is included in the build +tasks.named('check') { + dependsOn(testing.suites.productTest) } // let productTest depend on test as test produces code for productTest -compileProductTestJava.dependsOn(test) +tasks.named("compileProductTestJava") { + dependsOn(test) +} test.configure { // The test task builds the productTest inputs @@ -28,7 +45,3 @@ test.configure { outputs.cacheIf {false} outputs.upToDateWhen {false} } - -// let check depend on productTest such that it is included in the build -check.dependsOn(productTest) - diff --git a/monticore-test/01.experiments/templates/src/main/java/automata/TemplatesTool.java b/monticore-test/01.experiments/templates/src/main/java/automata/TemplatesTool.java index 3c06513374..df01095cd7 100644 --- a/monticore-test/01.experiments/templates/src/main/java/automata/TemplatesTool.java +++ b/monticore-test/01.experiments/templates/src/main/java/automata/TemplatesTool.java @@ -76,13 +76,13 @@ public class TemplatesTool { protected GlobalExtensionManagement glex; // Two dimensional map: SourceState x Stimulus -> Transition - Map> deltaMap = new HashMap<>(); + Map> deltaMap = new LinkedHashMap<>(); // Map: Name -> State (== State-Symbols) - Map stateMap = new HashMap<>(); + Map stateMap = new LinkedHashMap<>(); // List of stimuli - Set stimuli = new HashSet<>(); + Set stimuli = new LinkedHashSet<>(); /** * Use three arguments to specify the automata model, @@ -315,7 +315,7 @@ protected void deriveStateMap_DeltaMap() { // initialize delta: transition map of maps, and state name2node for(ASTState s: ast.getStateList()) { stateMap.put(s.getName(),s); - deltaMap.put(s,new HashMap<>()); + deltaMap.put(s,new LinkedHashMap<>()); } // Add the transitions to the table diff --git a/monticore-test/01.experiments/templates/src/productTest/java/PingPongTest.java b/monticore-test/01.experiments/templates/src/productTest/java/PingPongTest.java index e599b60809..1e187a5699 100644 --- a/monticore-test/01.experiments/templates/src/productTest/java/PingPongTest.java +++ b/monticore-test/01.experiments/templates/src/productTest/java/PingPongTest.java @@ -1,10 +1,9 @@ /* (c) https://github.com/MontiCore/monticore */ -import de.se_rwth.commons.logging.LogStub; -import org.junit.Test; +import de.monticore.runtime.junit.MCAssertions; -import static org.junit.Assert.*; -import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class PingPongTest { @@ -15,39 +14,39 @@ public void testPingPong(){ PingPong pingpong = new PingPong(); // assert we are in the initial state - assertTrue(String.format(message,"NoGame"),pingpong.currentState instanceof NoGameState); + assertInstanceOf(NoGameState.class, pingpong.currentState, String.format(message, "NoGame")); // trigger startGame pingpong.startGame(); // assert we are in state Ping - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger returnBall pingpong.returnBall(); // assert we are in state Pong - assertTrue(String.format(message,"Pong"), pingpong.currentState instanceof PongState); + assertInstanceOf(PongState.class, pingpong.currentState, String.format(message, "Pong")); // trigger returnBall pingpong.returnBall(); // assert we are in state Ping again - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger startGame pingpong.startGame(); // assert we are still in state Ping (wrong input should be ignored) - assertTrue(String.format(message,"Ping"), pingpong.currentState instanceof PingState); + assertInstanceOf(PingState.class, pingpong.currentState, String.format(message, "Ping")); // trigger stopGame pingpong.stopGame(); // assert we are in state NoGame - assertTrue(String.format(message,"NoGame"), pingpong.currentState instanceof NoGameState); + assertInstanceOf(NoGameState.class, pingpong.currentState, String.format(message, "NoGame")); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/01.experiments/templates/src/test/java/automata/GeneratorTest.java b/monticore-test/01.experiments/templates/src/test/java/automata/GeneratorTest.java index dc70cc2e78..37657f23bf 100644 --- a/monticore-test/01.experiments/templates/src/test/java/automata/GeneratorTest.java +++ b/monticore-test/01.experiments/templates/src/test/java/automata/GeneratorTest.java @@ -1,25 +1,25 @@ /* (c) https://github.com/MontiCore/monticore */ package automata; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class GeneratorTest { - @Before + @BeforeEach public void init(){ LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only Log.enableFailQuick(false); } - @Before + @BeforeEach public void clearFindings(){ Log.getFindings().clear(); } @@ -31,14 +31,14 @@ public void clearFindings(){ public void testPingPong(){ TemplatesTool.main(new String[] { "src/test/resources/example/PingPong.aut", "src/product/java", "target/statepattern" }); assertEquals(0, Log.getErrorCount()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void testSimple12(){ TemplatesTool.main(new String[] { "src/test/resources/example/Simple12.aut","src/product/java", "target/statepattern" }); assertEquals(0, Log.getErrorCount()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test diff --git a/monticore-test/01.experiments/textoutput/src/test/java/AutomataToolTest.java b/monticore-test/01.experiments/textoutput/src/test/java/AutomataToolTest.java index 0a65e97e05..0f6888be80 100644 --- a/monticore-test/01.experiments/textoutput/src/test/java/AutomataToolTest.java +++ b/monticore-test/01.experiments/textoutput/src/test/java/AutomataToolTest.java @@ -1,21 +1,21 @@ /* (c) https://github.com/MontiCore/monticore */ import automata.AutomataTool; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AutomataToolTest { - @Before + @BeforeEach public void init() { LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only @@ -26,7 +26,7 @@ public void init() { @Test public void executePingPong() { - AutomataTool.main(new String[]{"-i", "src/test/resources/example/PingPong.aut"}); + new AutomataTool().run(new String[]{"-i", "src/test/resources/example/PingPong.aut"}); Log.printFindings(); assertEquals(0, Log.getFindings().size()); @@ -34,44 +34,44 @@ public void executePingPong() { assertEquals(5, p.size()); // Check some "[INFO]" outputs - assertTrue(p.get(0), p.get(0).matches(".*.INFO. AutomataTool Automata DSL Tool.*(\r)?\n")); - assertTrue(p.get(3), p.get(3).matches(".*.INFO. AutomataTool Printing the parsed automaton into textual form:.*(\r)?\n")); + assertTrue(p.get(0).matches(".*.INFO. AutomataTool Automata DSL Tool.*(\r)?\n"), p.get(0)); + assertTrue(p.get(3).matches(".*.INFO. AutomataTool Printing the parsed automaton into textual form:.*(\r)?\n"), p.get(3)); // Check resulting pretty print: String res = p.get(p.size() - 1).replaceAll("\r\n", " ").replaceAll("\n", " "); // Please note: the resulting string is NONDETERMINISTIC, i.e. the text output is chosen among // three alternatives assertTrue(res.length() > 500); - assertTrue(res, res.matches(".*automaton is called 'PingPong'.*")); - assertTrue(res, - res.matches(".*State Pong changes to NoGame when receiving input stopGame.*") - || res.matches(".*With input stopGame the state of the described object changes its state from Pong to NoGame.*") - || res.matches(".*State Pong and input stopGame map to new state NoGame.*") - || res.matches(".*Processing stopGame the object transitions from state Pong to NoGame.*") - ); - assertTrue(Log.getFindings().isEmpty()); + assertTrue(res.matches(".*automaton is called 'PingPong'.*"), res); + assertTrue(res.matches(".*State Pong changes to NoGame when receiving input stopGame.*") + || res.matches(".*With input stopGame the state of the described object changes its state from Pong to NoGame.*") + || res.matches(".*State Pong and input stopGame map to new state NoGame.*") + || res.matches(".*Processing stopGame the object transitions from state Pong to NoGame.*"), + res + ); + MCAssertions.assertNoFindings(); } @Test public void executeSimple12() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/Simple12.aut" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/Simple12.aut" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); List p = LogStub.getPrints(); assertEquals(5, p.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } @Test public void executeHierarchyPingPong() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/HierarchyPingPong.aut" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/HierarchyPingPong.aut" }); Log.printFindings(); assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); List p = LogStub.getPrints(); assertEquals(5, p.size()); - assertTrue(Log.getFindings().isEmpty()); + MCAssertions.assertNoFindings(); } } diff --git a/monticore-test/02.experiments/build.gradle b/monticore-test/02.experiments/build.gradle index e59fa1dcfe..730996f504 100644 --- a/monticore-test/02.experiments/build.gradle +++ b/monticore-test/02.experiments/build.gradle @@ -23,8 +23,12 @@ subprojects { } } testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" + } + + test { + useJUnitPlatform() } } diff --git a/monticore-test/02.experiments/configTemplate/build.gradle b/monticore-test/02.experiments/configTemplate/build.gradle index e916b99424..43126cc8ec 100644 --- a/monticore-test/02.experiments/configTemplate/build.gradle +++ b/monticore-test/02.experiments/configTemplate/build.gradle @@ -5,5 +5,5 @@ description = 'Experiments: configTemplate' tasks.named('generateMCGrammars') { configTemplate = "ct.ftl" // Note: Incremental building will not work. Any change to a file within the templatePath will require a full rebuild - templatePath "$projectDir/src/main/tpl" + templatePath = "$projectDir/src/main/tpl" } diff --git a/monticore-test/02.experiments/configTemplate/src/test/java/CustomTemplateTest.java b/monticore-test/02.experiments/configTemplate/src/test/java/CustomTemplateTest.java index 5f5318ae50..8aef893340 100644 --- a/monticore-test/02.experiments/configTemplate/src/test/java/CustomTemplateTest.java +++ b/monticore-test/02.experiments/configTemplate/src/test/java/CustomTemplateTest.java @@ -1,8 +1,5 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.util.List; @@ -11,10 +8,11 @@ import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Main class for the some Demonstration to Parse */ @@ -44,18 +42,18 @@ public void testParseMethods() throws IOException { // expecting two warnings of the same type, once for instantiating the mill // and once for instantiating the ASTAutomaton node List findings = Log.getFindings(); - Assertions.assertEquals(2, findings.size()); - Assertions.assertEquals(MSG, findings.get(0).getMsg()); - Assertions.assertEquals(MSG, findings.get(1).getMsg()); + assertEquals(2, findings.size()); + assertEquals(MSG, findings.get(0).getMsg()); + assertEquals(MSG, findings.get(1).getMsg()); // the config template additionally configures overriding the specific // "sizeStates" method of the automaton to always return 10. // Thus, we expect the corresponding method to return 10, while the // actual state list is empty - Assertions.assertEquals(0, aut.getStateList().size()); // actual state list size - Assertions.assertEquals(10, aut.sizeStates()); // modified state list size + assertEquals(0, aut.getStateList().size()); // actual state list size + assertEquals(10, aut.sizeStates()); // modified state list size - Assertions.assertEquals(0, aut.count()); + assertEquals(0, aut.count()); } } diff --git a/monticore-test/02.experiments/dispatcher/src/test/java/GetDispatcherFromMillTest.java b/monticore-test/02.experiments/dispatcher/src/test/java/GetDispatcherFromMillTest.java index 31f35e0bfa..3d7793f962 100644 --- a/monticore-test/02.experiments/dispatcher/src/test/java/GetDispatcherFromMillTest.java +++ b/monticore-test/02.experiments/dispatcher/src/test/java/GetDispatcherFromMillTest.java @@ -1,11 +1,10 @@ /* (c) https://github.com/MontiCore/monticore */ -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import simpleinterfaces.SimpleInterfacesMill; import simpleinterfaces._util.ISimpleInterfacesTypeDispatcher; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; public class GetDispatcherFromMillTest { @@ -13,7 +12,7 @@ public class GetDispatcherFromMillTest { public void testGetterInMill() { ISimpleInterfacesTypeDispatcher dispatcher1 = SimpleInterfacesMill.typeDispatcher(); ISimpleInterfacesTypeDispatcher dispatcher2 = SimpleInterfacesMill.typeDispatcher(); - Assertions.assertSame(dispatcher1, dispatcher2); + assertSame(dispatcher1, dispatcher2); } } diff --git a/monticore-test/02.experiments/forGrammarOps/src/test/java/AutomataParseTest.java b/monticore-test/02.experiments/forGrammarOps/src/test/java/AutomataParseTest.java index 91e3c90b42..71aa3ca7e5 100644 --- a/monticore-test/02.experiments/forGrammarOps/src/test/java/AutomataParseTest.java +++ b/monticore-test/02.experiments/forGrammarOps/src/test/java/AutomataParseTest.java @@ -1,5 +1,4 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.StringReader; @@ -10,10 +9,11 @@ import automata._parser.AutomataParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Main class for the some Demonstration to Parse */ @@ -37,24 +37,24 @@ public void testParseMethods() throws IOException { // parse from a file Optional at = p.parse(filename); - Assertions.assertTrue(at.isPresent()); + assertTrue(at.isPresent()); // parse from a Reader object String aut = "automaton PingPong {" + "state Ping;" + "}"; at = p.parse(new StringReader(aut)); - Assertions.assertTrue(at.isPresent()); + assertTrue(at.isPresent()); // another parse from a String at = p.parse_String(aut); - Assertions.assertTrue(at.isPresent()); + assertTrue(at.isPresent()); // parse for a sublanguage, here: a State Optional s = p.parse_StringState("state Ping;"); - Assertions.assertTrue(s.isPresent()); + assertTrue(s.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/02.experiments/forGrammarOps/src/test/java/AutomataToolTest.java b/monticore-test/02.experiments/forGrammarOps/src/test/java/AutomataToolTest.java index 44de5bd800..25d7471ca4 100644 --- a/monticore-test/02.experiments/forGrammarOps/src/test/java/AutomataToolTest.java +++ b/monticore-test/02.experiments/forGrammarOps/src/test/java/AutomataToolTest.java @@ -5,12 +5,11 @@ import java.util.*; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AutomataToolTest { @@ -25,13 +24,13 @@ public void init() { @Test public void executeSimple12() { - AutomataTool.main(new String[] { "-i", "src/test/resources/example/Simple12.aut" }); + new AutomataTool().run(new String[] { "-i", "src/test/resources/example/Simple12.aut" }); Log.printFindings(); - Assertions.assertEquals(0, Log.getFindings().size()); + assertEquals(0, Log.getFindings().size()); // LogStub.printPrints(); List p = LogStub.getPrints(); - Assertions.assertEquals(6, p.size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(6, p.size()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/02.experiments/parser/src/main/grammars/QuoteTest.mc4 b/monticore-test/02.experiments/parser/src/main/grammars/QuoteTest.mc4 new file mode 100644 index 0000000000..ced27cfb0e --- /dev/null +++ b/monticore-test/02.experiments/parser/src/main/grammars/QuoteTest.mc4 @@ -0,0 +1,12 @@ +/* (c) https://github.com/MontiCore/monticore */ + +/** + * This grammar is used to test that single quotes ' and double quotes " can be used in implicit tokens. + */ +grammar QuoteTest extends de.monticore.MCBasics { + + EscapedNameSingleQuote = "n'" Name "'"; + + EscapedNameDoubleQuote = "n\"" Name "\""; + +} \ No newline at end of file diff --git a/monticore-test/02.experiments/parser/src/test/java/ParseErrorTest.java b/monticore-test/02.experiments/parser/src/test/java/ParseErrorTest.java index 323160277b..0d72dfef19 100644 --- a/monticore-test/02.experiments/parser/src/test/java/ParseErrorTest.java +++ b/monticore-test/02.experiments/parser/src/test/java/ParseErrorTest.java @@ -236,7 +236,7 @@ public void testUnknownAlts() throws IOException { // An incorrect input is used in an alt-context parser.parse_StringUnknownAlts("X"); Assertions.assertTrue(parser.hasErrors()); - Assertions.assertEquals("no viable alternative at input 'X', expecting 'UnknownAltsKey', 'UnknownAltsT' or Name (with additional constraints from unknownAlts) in rule stack: [UnknownAlts]\u00A0\n" + + Assertions.assertEquals("no viable alternative at input 'X', expecting 'UnknownAltsT', 'UnknownAltsKey' or Name (with additional constraints from unknownAlts) in rule stack: [UnknownAlts]\u00A0\n" + "X\n" + "^", Log.getFindings().get(0).getMsg()); } @@ -276,7 +276,7 @@ public void testCDClass() throws IOException { // No input was provided parser.parse_StringCDLike("cd cl"); Assertions.assertTrue(parser.hasErrors()); - Assertions.assertEquals("no viable alternative at input 'cl', expecting 'private', 'class', 'composition', '<<', '+', 'public', 'package' or 'association' in rule stack: [CDLike]\u00A0\n" + + Assertions.assertEquals("no viable alternative at input 'cl', expecting '<<', 'public', '+', 'private', 'class', 'package', 'association' or 'composition' in rule stack: [CDLike]\u00A0\n" + "cd cl\n" + " ^", Log.getFindings().get(0).getMsg()); } @@ -286,7 +286,7 @@ public void testCDPub() throws IOException { // No input was provided parser.parse_StringCDLike("cd publ"); Assertions.assertTrue(parser.hasErrors()); - Assertions.assertEquals("no viable alternative at input 'publ', expecting 'private', 'class', 'composition', '<<', '+', 'public', 'package' or 'association' in rule stack: [CDLike]\u00A0\n" + + Assertions.assertEquals("no viable alternative at input 'publ', expecting '<<', 'public', '+', 'private', 'class', 'package', 'association' or 'composition' in rule stack: [CDLike]\u00A0\n" + "cd publ\n" + " ^", Log.getFindings().get(0).getMsg()); } @@ -306,7 +306,7 @@ public void testCDAssoc() throws IOException { // No input was provided parser.parse_StringCDLike("cd \n class C1{}\n xxx\n association A1;"); Assertions.assertTrue(parser.hasErrors()); - Assertions.assertEquals("no viable alternative at input 'xxx', expecting 'private', 'class', 'composition', '<<', '+', 'public', 'package' or 'association' in rule stack: [CDLike]\u00A0\n" + + Assertions.assertEquals("no viable alternative at input 'xxx', expecting '<<', 'public', '+', 'private', 'class', 'package', 'association' or 'composition' in rule stack: [CDLike]\u00A0\n" + " xxx\n" + " ^", Log.getFindings().get(0).getMsg()); } diff --git a/monticore-test/02.experiments/parser/src/test/java/QuoteTest.java b/monticore-test/02.experiments/parser/src/test/java/QuoteTest.java new file mode 100644 index 0000000000..9156eca5fa --- /dev/null +++ b/monticore-test/02.experiments/parser/src/test/java/QuoteTest.java @@ -0,0 +1,64 @@ +import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import quotetest.QuoteTestMill; +import quotetest._ast.ASTEscapedNameDoubleQuote; +import quotetest._ast.ASTEscapedNameSingleQuote; +import quotetest._parser.QuoteTestParser; + +import java.util.Optional; + +public class QuoteTest { + QuoteTestParser parser; + + @BeforeEach + public void setUp() { + QuoteTestMill.init(); + parser = QuoteTestMill.parser(); + Log.enableFailQuick(false); + } + + @AfterEach + public void tearDown() { + QuoteTestMill.reset(); + Log.clearFindings(); + } + + @Test + public void testSingleQuoteValid() { + ASTEscapedNameSingleQuote ast = Assertions.assertDoesNotThrow(() -> parser.parse_StringEscapedNameSingleQuote( + "n'thisWorks'" + ).orElseThrow()); + Assertions.assertEquals("thisWorks", ast.getName()); + Assertions.assertEquals(0, Log.getFindingsCount()); + } + + @Test + public void testSingleQuoteInvalid() { + Optional ast = Assertions.assertDoesNotThrow(() -> parser.parse_StringEscapedNameSingleQuote( + "nthisDoesNotWork" + )); + Assertions.assertFalse(ast.isPresent()); + Assertions.assertTrue(Log.getFindingsCount() > 0); + } + + @Test + public void testDoubleQuoteValid() { + ASTEscapedNameDoubleQuote ast = Assertions.assertDoesNotThrow(() -> parser.parse_StringEscapedNameDoubleQuote( + "n\"thisWorks\"" + ).orElseThrow()); + Assertions.assertEquals("thisWorks", ast.getName()); + Assertions.assertEquals(0, Log.getFindingsCount()); + } + + @Test + public void testDoubleQuoteInvalid() { + Optional ast = Assertions.assertDoesNotThrow(() -> parser.parse_StringEscapedNameDoubleQuote( + "n\\\"thisDoesNotWork\\\"" + )); + Assertions.assertFalse(ast.isPresent()); + Assertions.assertTrue(Log.getFindingsCount() > 0); + } +} diff --git a/monticore-test/02.experiments/resolving/src/main/java/de/monticore/simplecd/CoCoHelper.java b/monticore-test/02.experiments/resolving/src/main/java/de/monticore/simplecd/CoCoHelper.java index c40091482b..8980982541 100644 --- a/monticore-test/02.experiments/resolving/src/main/java/de/monticore/simplecd/CoCoHelper.java +++ b/monticore-test/02.experiments/resolving/src/main/java/de/monticore/simplecd/CoCoHelper.java @@ -9,14 +9,14 @@ public class CoCoHelper { public static List findDuplicates(Collection list) { - Set uniques = new HashSet<>(); + Set uniques = new LinkedHashSet<>(); return list.stream().filter(e -> !uniques.add(e)).collect(Collectors.toList()); } public static List findDuplicatesBy( Collection list, java.util.function.Function function) { - Set existingElements = new HashSet<>(); + Set existingElements = new LinkedHashSet<>(); List duplicates = new ArrayList<>(); for (T elem : list) { diff --git a/monticore-test/02.experiments/resolving/src/test/java/de/monticore/simplecd/ResolvingTest.java b/monticore-test/02.experiments/resolving/src/test/java/de/monticore/simplecd/ResolvingTest.java index 5ef3232821..93af938bd3 100644 --- a/monticore-test/02.experiments/resolving/src/test/java/de/monticore/simplecd/ResolvingTest.java +++ b/monticore-test/02.experiments/resolving/src/test/java/de/monticore/simplecd/ResolvingTest.java @@ -12,15 +12,14 @@ import de.monticore.symboltable.resolving.ResolvedSeveralEntriesForSymbolException; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ResolvingTest { @@ -60,38 +59,38 @@ public void testValidExample(){ Optional a = parseAndTransform("src/test/resources/de/monticore/simplecd/valid/A.cd"); Optional b = parseAndTransform("src/test/resources/de/monticore/simplecd/valid/B.cd"); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ISimpleCDArtifactScope asB = buildSymbolTable(b.get()); ISimpleCDArtifactScope asA = buildSymbolTable(a.get()); Optional fooSymbol = asA.resolveCDClass("Foo"); - Assertions.assertTrue(fooSymbol.isPresent()); + assertTrue(fooSymbol.isPresent()); ISimpleCDScope fooScope = fooSymbol.get().getSpannedScope(); Optional type = fooScope.resolveCDClass("B.Bar"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); } @Test public void testSimpleInvalid(){ Optional c = parseAndTransform("src/test/resources/de/monticore/simplecd/invalid/C.cd"); - Assertions.assertTrue(c.isPresent()); + assertTrue(c.isPresent()); ISimpleCDArtifactScope asC = buildSymbolTable(c.get()); Optional fooSymbol = asC.resolveCDClass("Foo"); - Assertions.assertTrue(fooSymbol.isPresent()); + assertTrue(fooSymbol.isPresent()); ISimpleCDScope fooScope = fooSymbol.get().getSpannedScope(); try { Optional type = fooScope.resolveCDClass("Bar"); //if a type could be resolved: Test fails because Bar should be ambiguous - Assertions.assertFalse(type.isPresent()); + assertFalse(type.isPresent()); } catch(ResolvedSeveralEntriesForSymbolException e) { - Assertions.assertTrue(e.getMessage().startsWith("0xA4095")); + assertTrue(e.getMessage().startsWith("0xA4095")); } } @@ -100,22 +99,22 @@ public void testInterModelInvalid(){ Optional a = parseAndTransform("src/test/resources/de/monticore/simplecd/invalid/A.cd"); Optional b = parseAndTransform("src/test/resources/de/monticore/simplecd/invalid/B.cd"); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ISimpleCDArtifactScope asB = buildSymbolTable(b.get()); ISimpleCDArtifactScope asA = buildSymbolTable(a.get()); Optional fooSymbol = asA.resolveCDClass("Foo"); - Assertions.assertTrue(fooSymbol.isPresent()); + assertTrue(fooSymbol.isPresent()); ISimpleCDScope fooScope = fooSymbol.get().getSpannedScope(); try { Optional type = fooScope.resolveCDClass("B.Bar"); //if a type could be resolved: Test fails because B.Bar should be ambiguous - Assertions.assertFalse(type.isPresent()); + assertFalse(type.isPresent()); } catch(ResolvedSeveralEntriesForSymbolException e) { - Assertions.assertTrue(e.getMessage().startsWith("0xA4095")); + assertTrue(e.getMessage().startsWith("0xA4095")); } } diff --git a/monticore-test/02.experiments/scopes/src/test/java/GlobalScopeTest.java b/monticore-test/02.experiments/scopes/src/test/java/GlobalScopeTest.java index 4092d2178e..9e845557d0 100644 --- a/monticore-test/02.experiments/scopes/src/test/java/GlobalScopeTest.java +++ b/monticore-test/02.experiments/scopes/src/test/java/GlobalScopeTest.java @@ -6,13 +6,12 @@ import de.monticore.io.paths.MCPath; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Paths; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class GlobalScopeTest { @@ -33,6 +32,6 @@ public void testGS() { gs.putSymbolDeSer("automata._symboltable.StateSymbol", new MyStateDeSer()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/02.experiments/traverser/src/test/java/TreesTest.java b/monticore-test/02.experiments/traverser/src/test/java/TreesTest.java index b9341ed356..40fde3e6ea 100644 --- a/monticore-test/02.experiments/traverser/src/test/java/TreesTest.java +++ b/monticore-test/02.experiments/traverser/src/test/java/TreesTest.java @@ -1,15 +1,10 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,6 +16,8 @@ import trees._parser.TreesParser; import trees._visitor.TreesTraverser; +import static org.junit.jupiter.api.Assertions.*; + public class TreesTest { @BeforeEach @@ -36,12 +33,12 @@ public void testTrees() throws IOException { TreesParser parser = new TreesParser(); Optional tree = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(tree.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(tree.isPresent()); // compute and check result - Assertions.assertEquals(3, leafCount(tree.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(3, leafCount(tree.get())); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -51,12 +48,12 @@ public void testBranches() throws IOException { SubTreesParser parser = new SubTreesParser(); Optional tree = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(tree.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(tree.isPresent()); // compute and check result - Assertions.assertEquals(6, leafCount(tree.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(6, leafCount(tree.get())); + assertTrue(Log.getFindings().isEmpty()); } /** diff --git a/monticore-test/02.experiments/typecheck/src/test/java/MyLangTest.java b/monticore-test/02.experiments/typecheck/src/test/java/MyLangTest.java index 6421992022..1efe9f686c 100644 --- a/monticore-test/02.experiments/typecheck/src/test/java/MyLangTest.java +++ b/monticore-test/02.experiments/typecheck/src/test/java/MyLangTest.java @@ -1,9 +1,5 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.util.Optional; @@ -20,10 +16,10 @@ import mylang.FullSynthesizeFromMyLang; import mylang._ast.ASTMyVar; import mylang._parser.MyLangParser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; public class MyLangTest { @@ -40,8 +36,8 @@ public void testMyLang() throws IOException { MyLangParser parser = MyLangMill.parser(); Optional varOpt = parser.parse_String("boolean x = 3 > 4"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(varOpt.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(varOpt.isPresent()); MyLangMill.scopesGenitorDelegator().createFromAST(varOpt.get()); @@ -60,20 +56,20 @@ public void testMyLang() throws IOException { SymTypeExpression symType2 = tc.typeOf(exp); // check whether the type is boolean - Assertions.assertEquals("boolean", symType1.getTypeInfo().getName()); - Assertions.assertTrue(TypeCheck.isBoolean(symType1)); + assertEquals("boolean", symType1.getTypeInfo().getName()); + assertTrue(TypeCheck.isBoolean(symType1)); - Assertions.assertEquals("boolean", symType2.getTypeInfo().getName()); + assertEquals("boolean", symType2.getTypeInfo().getName()); - Assertions.assertTrue(TypeCheck.isBoolean(symType2)); + assertTrue(TypeCheck.isBoolean(symType2)); // check whether both types are compatible - Assertions.assertTrue(TypeCheck.compatible(symType1,symType2)); + assertTrue(TypeCheck.compatible(symType1,symType2)); // check whether the expression is of assignable type - Assertions.assertTrue(tc.isOfTypeForAssign(symType1,exp)); + assertTrue(tc.isOfTypeForAssign(symType1,exp)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-test/02.experiments/unknownScopes/src/test/java/UnknownScopeDeSerTests.java b/monticore-test/02.experiments/unknownScopes/src/test/java/UnknownScopeDeSerTests.java index 73495dab43..c44867d3b9 100644 --- a/monticore-test/02.experiments/unknownScopes/src/test/java/UnknownScopeDeSerTests.java +++ b/monticore-test/02.experiments/unknownScopes/src/test/java/UnknownScopeDeSerTests.java @@ -1,8 +1,5 @@ /* (c) https://github.com/MontiCore/monticore */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import bar.BarMill; import bar._symboltable.BarArtifactScope; import bar._symboltable.IBarGlobalScope; @@ -15,7 +12,6 @@ import foo._parser.FooParser; import foo._symboltable.FooSymbols2Json; import foo._symboltable.IFooArtifactScope; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import java.io.IOException; @@ -24,6 +20,9 @@ import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class UnknownScopeDeSerTests { @BeforeEach @@ -42,7 +41,7 @@ public void test() throws IOException { "}\n" ); - Assertions.assertTrue(parsedFooArtifact.isPresent()); + assertTrue(parsedFooArtifact.isPresent()); ASTFooArtifact fooArtifact = parsedFooArtifact.get(); @@ -55,14 +54,14 @@ public void test() throws IOException { IBarGlobalScope barGlobalScope = BarMill.globalScope(); BarArtifactScope scope = (BarArtifactScope) barGlobalScope.getDeSer().deserializeArtifactScope(jsonFoo); - Assertions.assertTrue(scope.getUnknownSymbols().containsKey("TestNest")); - Assertions.assertEquals(1, scope.getUnknownSymbols().get("TestNest").size()); + assertTrue(scope.getUnknownSymbols().containsKey("TestNest")); + assertEquals(1, scope.getUnknownSymbols().get("TestNest").size()); IBarScope unknownNestScope = (IBarScope) scope.getUnknownSymbols().get("TestNest").get(0).getSpannedScope(); - Assertions.assertEquals(2, unknownNestScope.getSubScopes().size()); + assertEquals(2, unknownNestScope.getSubScopes().size()); - Assertions.assertTrue(unknownNestScope.getSubScopes().stream().anyMatch(it -> Objects.equals(it.getName(), "testFunction"))); - Assertions.assertTrue(unknownNestScope.getSubScopes().stream().anyMatch(it -> Objects.equals(it.getName(), "testFunction2"))); + assertTrue(unknownNestScope.getSubScopes().stream().anyMatch(it -> Objects.equals(it.getName(), "testFunction"))); + assertTrue(unknownNestScope.getSubScopes().stream().anyMatch(it -> Objects.equals(it.getName(), "testFunction2"))); } } diff --git a/monticore-test/example/src/test/java/automata/AutomatonToolTest.java b/monticore-test/example/src/test/java/automata/AutomatonToolTest.java index c761c6dd11..33e810cbf3 100644 --- a/monticore-test/example/src/test/java/automata/AutomatonToolTest.java +++ b/monticore-test/example/src/test/java/automata/AutomatonToolTest.java @@ -16,7 +16,7 @@ public void setup(){ @Test public void executeMain() { - AutomataTool.main(new String[] { "src/main/resources/example/PingPong.aut" }); + new AutomataTool().run(new String[] { "src/main/resources/example/PingPong.aut" }); assertTrue(!false); } diff --git a/monticore-test/it/build.gradle b/monticore-test/it/build.gradle index 65766d516a..3f6e97adde 100644 --- a/monticore-test/it/build.gradle +++ b/monticore-test/it/build.gradle @@ -7,7 +7,6 @@ plugins { description = 'MontiCore Generator Main Integration Test' ext.grammarDir = 'src/main/grammars' -ext.junit_version = '5.10.3' configurations {grammar} @@ -20,9 +19,11 @@ dependencies { implementation project(':monticore-grammar') implementation "de.se_rwth.commons:se-commons-utilities:$se_commons_version" // implementation project (':monticore-generator') + testImplementation testFixtures(project(':monticore-runtime')) testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" grammar (project(path: ':monticore-grammar')){ capabilities { requireCapability("de.monticore:monticore-grammar-grammars") @@ -53,6 +54,7 @@ java { } test { + useJUnitPlatform() testLogging { showStandardStreams = true } diff --git a/monticore-test/it/src/main/grammars/mc/feature/scopes/ScopeInheritance.mc4 b/monticore-test/it/src/main/grammars/mc/feature/scopes/ScopeInheritance.mc4 new file mode 100644 index 0000000000..7c731e30ca --- /dev/null +++ b/monticore-test/it/src/main/grammars/mc/feature/scopes/ScopeInheritance.mc4 @@ -0,0 +1,43 @@ +/* (c) https://github.com/MontiCore/monticore */ +package mc.feature.scopes; + + +grammar ScopeInheritance extends mc.common.Basics { + + StartProd = (A | B | C | D | E | F | G | H | EA)*; + + interface scope (shadowing non_exporting ordered) + symbol ShadowingNonExportingOrdered = Name; + + interface scope (shadowing non_exporting) + symbol ShadowingNonExporting = Name; + + interface scope (shadowing ordered) + symbol ShadowingOrdered = Name; + + interface scope (non_exporting ordered) + symbol NonExportingOrdered = Name; + + interface scope (shadowing) + symbol Shadowing = Name; + + interface scope (non_exporting) + symbol NonExporting = Name; + + interface scope (ordered) + symbol Ordered = Name; + + interface scope + symbol DefaultScope = Name; + + symbol scope A implements ShadowingNonExportingOrdered = "A" Name; + symbol scope B implements ShadowingNonExporting = "B" Name; + symbol scope C implements ShadowingOrdered = "C" Name; + symbol scope D implements NonExportingOrdered = "D" Name; + symbol scope E implements Shadowing = "E" Name; + symbol scope F implements NonExporting = "F" Name; + symbol scope G implements Ordered = "G" Name; + symbol scope H implements DefaultScope = "H" Name; + + symbol scope EA extends A = "EA" Name; +} \ No newline at end of file diff --git a/monticore-test/it/src/test/java/mc/examples/automaton/TestAutomaton.java b/monticore-test/it/src/test/java/mc/examples/automaton/TestAutomaton.java index 73525af124..073a00b598 100644 --- a/monticore-test/it/src/test/java/mc/examples/automaton/TestAutomaton.java +++ b/monticore-test/it/src/test/java/mc/examples/automaton/TestAutomaton.java @@ -13,7 +13,6 @@ import mc.examples.automaton.automaton._od.Automaton2OD; import mc.examples.automaton.automaton._parser.AutomatonParser; import mc.examples.automaton.automaton._visitor.AutomatonTraverser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,8 +23,8 @@ import java.nio.file.Paths; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestAutomaton extends GeneratorIntegrationsTest { @@ -39,8 +38,8 @@ private ASTAutomaton parse() throws IOException { AutomatonParser parser = new AutomatonParser(); Optional optAutomaton; optAutomaton = parser.parseAutomaton("src/test/resources/examples/automaton/Testautomat.aut"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(optAutomaton.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(optAutomaton.isPresent()); AutomatonMill.globalScope().clear(); AutomatonMill.scopesGenitorDelegator().createFromAST(optAutomaton.get()); return optAutomaton.get(); @@ -55,15 +54,15 @@ private void printOD(ASTAutomaton ast, String symbolName) throws IOException { traverser.add4Automaton(odCreator); traverser.setAutomatonHandler(odCreator); odCreator.printObjectDiagram(symbolName, ast); - Assertions.assertTrue(printer.getContent().length()>0); - Assertions.assertTrue(readFile("src/test/resources/examples/automaton/Output.od", StandardCharsets.UTF_8).endsWith(printer.getContent())); + assertTrue(printer.getContent().length()>0); + assertTrue(readFile("src/test/resources/examples/automaton/Output.od", StandardCharsets.UTF_8).endsWith(printer.getContent())); } @Test public void test() throws IOException { ASTAutomaton ast = parse(); printOD(ast, "Testautomat"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } protected String readFile(String path, Charset encoding) diff --git a/monticore-test/it/src/test/java/mc/examples/coord/TestCoordinates.java b/monticore-test/it/src/test/java/mc/examples/coord/TestCoordinates.java index 8e252286eb..f51404673a 100644 --- a/monticore-test/it/src/test/java/mc/examples/coord/TestCoordinates.java +++ b/monticore-test/it/src/test/java/mc/examples/coord/TestCoordinates.java @@ -2,17 +2,12 @@ package mc.examples.coord; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,6 +25,8 @@ import mc.examples.polar.coordpolar._parser.CoordpolarParser; import mc.examples.polar.coordpolar._visitor.CoordpolarTraverser; +import static org.junit.jupiter.api.Assertions.*; + public class TestCoordinates extends GeneratorIntegrationsTest { private static final double DELTA = 1e-5; @@ -47,21 +44,21 @@ public void testCoordcartesianParser() throws IOException { .parseCoordinateFile("src/test/resources/examples/coord/coordinates.cart"); // (2,4) // (5,2) // (1,7) - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astCartesian.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astCartesian.isPresent()); - Assertions.assertEquals(astCartesian.get().getCoordinateList().size(), 3); + assertEquals(3, astCartesian.get().getCoordinateList().size()); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(0).getX(), 2); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(0).getY(), 4); + assertEquals(2, astCartesian.get().getCoordinateList().get(0).getX()); + assertEquals(4, astCartesian.get().getCoordinateList().get(0).getY()); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(1).getX(), 5); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(1).getY(), 2); + assertEquals(5, astCartesian.get().getCoordinateList().get(1).getX()); + assertEquals(2, astCartesian.get().getCoordinateList().get(1).getY()); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(2).getX(), 1); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(2).getY(), 7); + assertEquals(1, astCartesian.get().getCoordinateList().get(2).getX()); + assertEquals(7, astCartesian.get().getCoordinateList().get(2).getY()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -72,22 +69,22 @@ public void testCoordpolarParser() throws IOException { // [1,0;0,5] // [2,5;1,3] // [47,11;0,815] - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astPolar.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astPolar.isPresent()); - Assertions.assertEquals(astPolar.get().getCoordinateList().size(), 3); + assertEquals(3, astPolar.get().getCoordinateList().size()); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(0).getD(), 1.0, DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(0).getPhi(), 0.5, DELTA); + assertEquals(1.0, astPolar.get().getCoordinateList().get(0).getD(), DELTA); + assertEquals(0.5, astPolar.get().getCoordinateList().get(0).getPhi(), DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(1).getD(), 2.5, DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(1).getPhi(), 1.3, DELTA); + assertEquals(2.5, astPolar.get().getCoordinateList().get(1).getD(), DELTA); + assertEquals(1.3, astPolar.get().getCoordinateList().get(1).getPhi(), DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(2).getD(), 47.11, DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(2).getPhi(), 0.815, DELTA); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(47.11, astPolar.get().getCoordinateList().get(2).getD(), DELTA); + assertEquals(0.815, astPolar.get().getCoordinateList().get(2).getPhi(), DELTA); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -95,8 +92,8 @@ public void cartesian2Polar() throws IOException { CoordcartesianParser parser = new CoordcartesianParser(); Optional astCartesian = parser .parseCoordinateFile("src/test/resources/examples/coord/coordinates.cart"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astCartesian.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astCartesian.isPresent()); // Transform cartesian to polar coordinates CoordcartesianTraverser t1 = CoordcartesianMill.traverser(); @@ -116,21 +113,21 @@ public void cartesian2Polar() throws IOException { mc.examples.polar.coordpolar._parser.CoordpolarParser polarParser = new CoordpolarParser(); Optional astPolar = polarParser .parseCoordinateFile(new StringReader(ip.getContent())); - Assertions.assertFalse(polarParser.hasErrors()); - Assertions.assertTrue(astPolar.isPresent()); + assertFalse(polarParser.hasErrors()); + assertTrue(astPolar.isPresent()); - Assertions.assertEquals(astPolar.get().getCoordinateList().size(), 3); + assertEquals(3, astPolar.get().getCoordinateList().size()); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(0).getD(), 4.47213, DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(0).getPhi(), 1.10714, DELTA); + assertEquals(4.47213, astPolar.get().getCoordinateList().get(0).getD(), DELTA); + assertEquals(1.10714, astPolar.get().getCoordinateList().get(0).getPhi(), DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(1).getD(), 5.38516, DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(1).getPhi(), 0.380506, DELTA); + assertEquals(5.38516, astPolar.get().getCoordinateList().get(1).getD(), DELTA); + assertEquals(0.380506, astPolar.get().getCoordinateList().get(1).getPhi(), DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(2).getD(), 7.07106, DELTA); - Assertions.assertEquals(astPolar.get().getCoordinateList().get(2).getPhi(), 1.428899, DELTA); + assertEquals(7.07106, astPolar.get().getCoordinateList().get(2).getD(), DELTA); + assertEquals(1.428899, astPolar.get().getCoordinateList().get(2).getPhi(), DELTA); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -138,19 +135,19 @@ public void mirrorTransformation() throws IOException { CoordcartesianParser parser = new CoordcartesianParser(); Optional astCartesian = parser .parseCoordinateFile("src/test/resources/examples/coord/coordinates.cart"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astCartesian.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astCartesian.isPresent()); - Assertions.assertEquals(astCartesian.get().getCoordinateList().size(), 3); + assertEquals(3, astCartesian.get().getCoordinateList().size()); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(0).getX(), 2); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(0).getY(), 4); + assertEquals(2, astCartesian.get().getCoordinateList().get(0).getX()); + assertEquals(4, astCartesian.get().getCoordinateList().get(0).getY()); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(1).getX(), 5); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(1).getY(), 2); + assertEquals(5, astCartesian.get().getCoordinateList().get(1).getX()); + assertEquals(2, astCartesian.get().getCoordinateList().get(1).getY()); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(2).getX(), 1); - Assertions.assertEquals(astCartesian.get().getCoordinateList().get(2).getY(), 7); + assertEquals(1, astCartesian.get().getCoordinateList().get(2).getX()); + assertEquals(7, astCartesian.get().getCoordinateList().get(2).getY()); // Transform cartesian to polar coordinates CoordcartesianTraverser t1 = CoordcartesianMill.traverser(); @@ -168,21 +165,21 @@ public void mirrorTransformation() throws IOException { astCartesian.get().accept(t2); Optional astTransformed = parser.parseCoordinateFile(new StringReader(ip.getContent())); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astTransformed.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astTransformed.isPresent()); - Assertions.assertEquals(astTransformed.get().getCoordinateList().size(), 3); + assertEquals(3, astTransformed.get().getCoordinateList().size()); - Assertions.assertEquals(astTransformed.get().getCoordinateList().get(0).getX(), 4); - Assertions.assertEquals(astTransformed.get().getCoordinateList().get(0).getY(), 2); + assertEquals(4, astTransformed.get().getCoordinateList().get(0).getX()); + assertEquals(2, astTransformed.get().getCoordinateList().get(0).getY()); - Assertions.assertEquals(astTransformed.get().getCoordinateList().get(1).getX(), 2); - Assertions.assertEquals(astTransformed.get().getCoordinateList().get(1).getY(), 5); + assertEquals(2, astTransformed.get().getCoordinateList().get(1).getX()); + assertEquals(5, astTransformed.get().getCoordinateList().get(1).getY()); - Assertions.assertEquals(astTransformed.get().getCoordinateList().get(2).getX(), 7); - Assertions.assertEquals(astTransformed.get().getCoordinateList().get(2).getY(), 1); + assertEquals(7, astTransformed.get().getCoordinateList().get(2).getX()); + assertEquals(1, astTransformed.get().getCoordinateList().get(2).getY()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/examples/lwc/TestEDL.java b/monticore-test/it/src/test/java/mc/examples/lwc/TestEDL.java index cc0e34dde4..287de6b182 100644 --- a/monticore-test/it/src/test/java/mc/examples/lwc/TestEDL.java +++ b/monticore-test/it/src/test/java/mc/examples/lwc/TestEDL.java @@ -2,18 +2,12 @@ package mc.examples.lwc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import mc.examples.lwc.edl.edl.EDLMill; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import com.google.common.collect.Lists; @@ -24,6 +18,8 @@ import mc.examples.lwc.edl.edl._parser.EDLParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class TestEDL extends GeneratorIntegrationsTest { @BeforeEach @@ -37,37 +33,37 @@ public void testParser() throws IOException { EDLParser parser = new EDLParser(); Optional ast = parser .parseEDLCompilationUnit("src/test/resources/examples/lwc/edl/Car.edl"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertNotNull(ast.get().getEntity()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertNotNull(ast.get().getEntity()); ASTEntity entity = ast.get().getEntity(); - Assertions.assertEquals(entity.getName(), "Car"); - Assertions.assertEquals(entity.getPropertyList().size(), 7); + assertEquals("Car", entity.getName()); + assertEquals(7, entity.getPropertyList().size()); - Assertions.assertEquals(entity.getPropertyList().get(0).getName(), "brand"); - Assertions.assertTrue(entity.getPropertyList().get(0).getType() + assertEquals("brand", entity.getPropertyList().get(0).getName()); + assertTrue(entity.getPropertyList().get(0).getType() .deepEquals(EDLMill.stringLiteralBuilder().build())); - Assertions.assertEquals(entity.getPropertyList().get(1).getName(), "model"); - Assertions.assertTrue(entity.getPropertyList().get(1).getType() + assertEquals("model", entity.getPropertyList().get(1).getName()); + assertTrue(entity.getPropertyList().get(1).getType() .deepEquals(EDLMill.stringLiteralBuilder().build())); - Assertions.assertEquals(entity.getPropertyList().get(2).getName(), "price"); - Assertions.assertTrue(entity.getPropertyList().get(2).getType() + assertEquals("price", entity.getPropertyList().get(2).getName()); + assertTrue(entity.getPropertyList().get(2).getType() .deepEquals(EDLMill.intLiteralBuilder().build())); - Assertions.assertEquals(entity.getPropertyList().get(3).getName(), "age"); - Assertions.assertTrue(entity.getPropertyList().get(3).getType() + assertEquals("age", entity.getPropertyList().get(3).getName()); + assertTrue(entity.getPropertyList().get(3).getType() .deepEquals(EDLMill.intLiteralBuilder().build())); - Assertions.assertEquals(entity.getPropertyList().get(4).getName(), "doors"); - Assertions.assertTrue(entity.getPropertyList().get(4).getType() + assertEquals("doors", entity.getPropertyList().get(4).getName()); + assertTrue(entity.getPropertyList().get(4).getType() .deepEquals(EDLMill.intLiteralBuilder().build())); - Assertions.assertEquals(entity.getPropertyList().get(5).getName(), "myself"); - Assertions.assertTrue(entity + assertEquals("myself", entity.getPropertyList().get(5).getName()); + assertTrue(entity .getPropertyList() .get(5) .getType() @@ -76,8 +72,8 @@ public void testParser() throws IOException { .setQualifiedName( EDLMill.qualifiedNameBuilder().setNamesList(Lists.newArrayList("Car")).build()).build())); - Assertions.assertEquals(entity.getPropertyList().get(6).getName(), "owner"); - Assertions.assertTrue(entity + assertEquals("owner", entity.getPropertyList().get(6).getName()); + assertTrue(entity .getPropertyList() .get(6) .getType() @@ -87,7 +83,7 @@ public void testParser() throws IOException { EDLMill.qualifiedNameBuilder().setNamesList(Lists.newArrayList("lwc", "edl", "Person")) .build()).build())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/examples/lwc/TestODL.java b/monticore-test/it/src/test/java/mc/examples/lwc/TestODL.java index 8ed33d47a4..22e5e6163e 100644 --- a/monticore-test/it/src/test/java/mc/examples/lwc/TestODL.java +++ b/monticore-test/it/src/test/java/mc/examples/lwc/TestODL.java @@ -2,18 +2,12 @@ package mc.examples.lwc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import mc.examples.lwc.odl.odl.ODLMill; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import com.google.common.collect.Lists; @@ -24,6 +18,8 @@ import mc.examples.lwc.odl.odl._parser.ODLParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class TestODL extends GeneratorIntegrationsTest { @BeforeEach @@ -37,22 +33,22 @@ public void testParser() throws IOException { ODLParser parser = new ODLParser(); Optional ast = parser .parseODLCompilationUnit("src/test/resources/examples/lwc/odl/MyWorld.odl"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTInstances instances = ast.get().getInstances(); - Assertions.assertNotNull(instances); + assertNotNull(instances); - Assertions.assertEquals(instances.getName(), "MyWorld"); - Assertions.assertEquals(instances.getObjectList().size(), 2); + assertEquals("MyWorld", instances.getName()); + assertEquals(2, instances.getObjectList().size()); - Assertions.assertEquals(instances.getObjectList().get(0).getName(), "person"); - Assertions.assertTrue(instances.getObjectList().get(0).getType().deepEquals( + assertEquals("person", instances.getObjectList().get(0).getName()); + assertTrue(instances.getObjectList().get(0).getType().deepEquals( ODLMill.qualifiedNameBuilder().setNamesList(Lists.newArrayList("Person")).build())); - Assertions.assertEquals(instances.getObjectList().get(0).getAssignmentList().size(), 4); - Assertions.assertEquals(instances.getObjectList().get(0).getAssignmentList().get(0).getName(), "birthday"); - Assertions.assertTrue(instances + assertEquals(4, instances.getObjectList().get(0).getAssignmentList().size()); + assertEquals("birthday", instances.getObjectList().get(0).getAssignmentList().get(0).getName()); + assertTrue(instances .getObjectList() .get(0) .getAssignmentList() @@ -62,8 +58,8 @@ public void testParser() throws IOException { ODLMill.dateValueBuilder() .setDate(ODLMill.dateBuilder().setDay("01").setMonth("01").setYear("1999").build()).build())); - Assertions.assertEquals(instances.getObjectList().get(0).getAssignmentList().get(1).getName(), "name"); - Assertions.assertTrue(instances + assertEquals("name", instances.getObjectList().get(0).getAssignmentList().get(1).getName()); + assertTrue(instances .getObjectList() .get(0) .getAssignmentList() @@ -73,8 +69,8 @@ public void testParser() throws IOException { ODLMill.stringValueBuilder() .setSTRING("alice").build())); - Assertions.assertEquals(instances.getObjectList().get(0).getAssignmentList().get(2).getName(), "id"); - Assertions.assertTrue(instances + assertEquals("id", instances.getObjectList().get(0).getAssignmentList().get(2).getName()); + assertTrue(instances .getObjectList() .get(0) .getAssignmentList() @@ -84,8 +80,8 @@ public void testParser() throws IOException { ODLMill.intValueBuilder() .setINT("1").build())); - Assertions.assertEquals(instances.getObjectList().get(0).getAssignmentList().get(3).getName(), "car"); - Assertions.assertTrue(instances + assertEquals("car", instances.getObjectList().get(0).getAssignmentList().get(3).getName()); + assertTrue(instances .getObjectList() .get(0) .getAssignmentList() @@ -95,10 +91,10 @@ public void testParser() throws IOException { ODLMill.referenceValueBuilder() .setName("car").build())); - Assertions.assertEquals(instances.getObjectList().get(1).getName(), "car"); - Assertions.assertTrue(instances.getObjectList().get(1).getType().deepEquals( + assertEquals("car", instances.getObjectList().get(1).getName()); + assertTrue(instances.getObjectList().get(1).getType().deepEquals( ODLMill.qualifiedNameBuilder().setNamesList(Lists.newArrayList("lwc", "edl", "Car")).build())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/abc/EmbedTest.java b/monticore-test/it/src/test/java/mc/feature/abc/EmbedTest.java index d72543cdcb..1bdefbfca4 100644 --- a/monticore-test/it/src/test/java/mc/feature/abc/EmbedTest.java +++ b/monticore-test/it/src/test/java/mc/feature/abc/EmbedTest.java @@ -2,21 +2,19 @@ package mc.feature.abc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import mc.GeneratorIntegrationsTest; import mc.feature.abc.realabc._parser.RealABCParser; +import static org.junit.jupiter.api.Assertions.*; + public class EmbedTest extends GeneratorIntegrationsTest { @BeforeEach @@ -30,8 +28,8 @@ public void test() throws IOException { RealABCParser p = parse("a b c"); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -39,8 +37,8 @@ public void testb() throws IOException { RealABCParser p = parse("a b"); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -48,8 +46,8 @@ public void testc() throws IOException { RealABCParser p = parse("a a a b b b c c c"); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -57,8 +55,8 @@ public void testd() throws IOException { RealABCParser p = parse("a b c c"); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } private RealABCParser parse(String in) throws IOException { diff --git a/monticore-test/it/src/test/java/mc/feature/abstractgrammar/AbstractGrammarTest.java b/monticore-test/it/src/test/java/mc/feature/abstractgrammar/AbstractGrammarTest.java index 15f97c74ec..7370b19bb3 100644 --- a/monticore-test/it/src/test/java/mc/feature/abstractgrammar/AbstractGrammarTest.java +++ b/monticore-test/it/src/test/java/mc/feature/abstractgrammar/AbstractGrammarTest.java @@ -2,15 +2,11 @@ package mc.feature.abstractgrammar; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -21,6 +17,8 @@ import mc.feature.abstractgrammar.implementation._parser.ImplementationParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class AbstractGrammarTest extends GeneratorIntegrationsTest { @BeforeEach @@ -35,10 +33,10 @@ public void testRefInterface() throws IOException { ImplementationParser p = new ImplementationParser(); java.util.Optional ast = p.parseUseUnterface(new StringReader("use impl myimplinterface")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(p.hasErrors()); - Assertions.assertTrue(ast.get().getII() instanceof ASTB); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(ast.isPresent()); + assertFalse(p.hasErrors()); + assertInstanceOf(ASTB.class, ast.get().getII()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -47,9 +45,9 @@ public void testRefAbstractRule() throws IOException { ImplementationParser p = new ImplementationParser(); java.util.Optional ast = p.parseUseAbstract(new StringReader("use ext myextabstract")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(p.hasErrors()); - Assertions.assertTrue(ast.get().getAA() instanceof ASTC); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(ast.isPresent()); + assertFalse(p.hasErrors()); + assertInstanceOf(ASTC.class, ast.get().getAA()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/abstractprod/AbstractProdTest.java b/monticore-test/it/src/test/java/mc/feature/abstractprod/AbstractProdTest.java index 5044c0ac81..f3367a3f6e 100644 --- a/monticore-test/it/src/test/java/mc/feature/abstractprod/AbstractProdTest.java +++ b/monticore-test/it/src/test/java/mc/feature/abstractprod/AbstractProdTest.java @@ -2,15 +2,11 @@ package mc.feature.abstractprod; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -20,6 +16,8 @@ import mc.feature.abstractprod.abstractprod._parser.AbstractProdParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class AbstractProdTest extends GeneratorIntegrationsTest { @BeforeEach @@ -34,11 +32,11 @@ public void testb() throws IOException { AbstractProdParser p = new AbstractProdParser(); java.util.Optional ast = p.parseA(new StringReader("b")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get() instanceof ASTB); - Assertions.assertFalse(p.hasErrors()); + assertTrue(ast.isPresent()); + assertInstanceOf(ASTB.class, ast.get()); + assertFalse(p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -47,10 +45,10 @@ public void testc() throws IOException { AbstractProdParser p = new AbstractProdParser(); java.util.Optional ast = p.parseA(new StringReader("c")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get() instanceof ASTC); - Assertions.assertFalse(p.hasErrors()); + assertTrue(ast.isPresent()); + assertInstanceOf(ASTC.class, ast.get()); + assertFalse(p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/addkeywords/AddKeywordsTest.java b/monticore-test/it/src/test/java/mc/feature/addkeywords/AddKeywordsTest.java index 239c9cab3c..07bf7eca5c 100644 --- a/monticore-test/it/src/test/java/mc/feature/addkeywords/AddKeywordsTest.java +++ b/monticore-test/it/src/test/java/mc/feature/addkeywords/AddKeywordsTest.java @@ -2,17 +2,12 @@ package mc.feature.addkeywords; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,6 +16,8 @@ import mc.feature.addkeywords.addkeywords._ast.ASTE; import mc.feature.addkeywords.addkeywords._parser.AddKeywordsParser; +import static org.junit.jupiter.api.Assertions.*; + public class AddKeywordsTest extends GeneratorIntegrationsTest { @BeforeEach @@ -36,15 +33,15 @@ public void testB() throws IOException { helperb("keyword"); helperb("key2"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void helperb(String in) throws IOException { AddKeywordsParser b = new AddKeywordsParser(); b.parseB(new StringReader(in)); - Assertions.assertFalse(b.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(b.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -54,13 +51,13 @@ public void testC() throws IOException { helperc("keyword"); helperc("key2"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void helperc(String in) throws IOException { AddKeywordsParser b = new AddKeywordsParser(); b.parseC(new StringReader(in)); - Assertions.assertFalse(b.hasErrors()); + assertFalse(b.hasErrors()); } @Test @@ -70,18 +67,18 @@ public void testD() throws IOException { helperd("keyword"); helperd("key2"); - Assertions.assertEquals(3, helperd("10 keyword 2").getNameList().size()); - Assertions.assertEquals(3, helperd("2 2 3").getNameList().size()); - Assertions.assertEquals(3, helperd("48 keyword key2").getNameList().size()); + assertEquals(3, helperd("10 keyword 2").getNameList().size()); + assertEquals(3, helperd("2 2 3").getNameList().size()); + assertEquals(3, helperd("48 keyword key2").getNameList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private ASTD helperd(String in) throws IOException { AddKeywordsParser createSimpleParser = new AddKeywordsParser(); Optional parse = createSimpleParser.parseD(new StringReader(in)); - Assertions.assertTrue(parse.isPresent()); - Assertions.assertFalse(createSimpleParser.hasErrors()); + assertTrue(parse.isPresent()); + assertFalse(createSimpleParser.hasErrors()); return parse.get(); } @@ -93,18 +90,18 @@ public void testE() throws IOException { helpere("keyword"); helpere("key2"); - Assertions.assertEquals(3, helpere("10 keyword 2").getINTList().size()); - Assertions.assertEquals(3, helpere("2 2 3").getINTList().size()); - Assertions.assertEquals(3, helpere("48 keyword key2").getINTList().size()); + assertEquals(3, helpere("10 keyword 2").getINTList().size()); + assertEquals(3, helpere("2 2 3").getINTList().size()); + assertEquals(3, helpere("48 keyword key2").getINTList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private ASTE helpere(String in) throws IOException { AddKeywordsParser createSimpleParser = new AddKeywordsParser(); Optional parse = createSimpleParser.parseE(new StringReader(in)); - Assertions.assertTrue(parse.isPresent()); - Assertions.assertFalse(createSimpleParser.hasErrors()); + assertTrue(parse.isPresent()); + assertFalse(createSimpleParser.hasErrors()); return parse.get(); } diff --git a/monticore-test/it/src/test/java/mc/feature/ast/ASTTest.java b/monticore-test/it/src/test/java/mc/feature/ast/ASTTest.java index 6e506a77cf..0d10568dd2 100644 --- a/monticore-test/it/src/test/java/mc/feature/ast/ASTTest.java +++ b/monticore-test/it/src/test/java/mc/feature/ast/ASTTest.java @@ -2,37 +2,19 @@ package mc.feature.ast; -import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import de.se_rwth.commons.logging.Slf4jLog; +import de.monticore.runtime.junit.AbstractMCTest; import mc.feature.delete.deletetest.DeleteTestMill; import mc.feature.delete.deletetest._ast.ASTChild; import mc.feature.delete.deletetest._ast.ASTParent; import mc.feature.featuredsl.FeatureDSLMill; import mc.feature.featuredsl._ast.ASTA; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class ASTTest { - - @BeforeAll - public static void setup() { - Slf4jLog.init(); - } - - @BeforeEach - public void before() { - LogStub.init(); - Log.enableFailQuick(false); - } +public class ASTTest extends AbstractMCTest { @Test public void testGet_ChildNodes1() { @@ -41,7 +23,6 @@ public void testGet_ChildNodes1() { Assertions.assertEquals(0, aList.size()); aList.add(a); Assertions.assertEquals(1, aList.size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); } @Test @@ -52,7 +33,6 @@ public void testGet_ChildNodes2() { p.setSon(s); Assertions.assertEquals(1, p.getChildList().size()); Assertions.assertTrue(p.containsChild(s)); - Assertions.assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/ast/ParserForInterfaceTest.java b/monticore-test/it/src/test/java/mc/feature/ast/ParserForInterfaceTest.java index 17de12e6c1..6a65d13895 100644 --- a/monticore-test/it/src/test/java/mc/feature/ast/ParserForInterfaceTest.java +++ b/monticore-test/it/src/test/java/mc/feature/ast/ParserForInterfaceTest.java @@ -2,21 +2,19 @@ package mc.feature.ast; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; import mc.feature.featuredsl._parser.FeatureDSLParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class ParserForInterfaceTest extends GeneratorIntegrationsTest { @BeforeEach @@ -32,9 +30,9 @@ public void testExtraComponent() throws IOException { FeatureDSLParser p = new FeatureDSLParser(); p.parseExtraComponent(s); - Assertions.assertEquals(false, p.hasErrors()); + assertFalse(p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/ast/ParserTest.java b/monticore-test/it/src/test/java/mc/feature/ast/ParserTest.java index ad07fa49a0..06ff5b4966 100644 --- a/monticore-test/it/src/test/java/mc/feature/ast/ParserTest.java +++ b/monticore-test/it/src/test/java/mc/feature/ast/ParserTest.java @@ -2,10 +2,6 @@ package mc.feature.ast; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; @@ -31,6 +27,8 @@ import mc.feature.featuredsl._ast.ASTSpices2; import mc.feature.featuredsl._parser.FeatureDSLParser; +import static org.junit.jupiter.api.Assertions.*; + public class ParserTest extends GeneratorIntegrationsTest { @BeforeEach @@ -46,27 +44,27 @@ public void testConstants() throws IOException { FeatureDSLParser p = new FeatureDSLParser(); Optional opt = p.parseAutomaton(s); - Assertions.assertTrue(opt.isPresent()); + assertTrue(opt.isPresent()); ASTAutomaton ast = opt.get(); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertEquals("a", ast.getName()); + assertFalse(p.hasErrors()); + assertEquals("a", ast.getName()); - Assertions.assertEquals(true, ((ASTConstants) ast.getWiredList().get(0)).isPubblic()); - Assertions.assertEquals(false, ((ASTConstants) ast.getWiredList().get(0)).isPrivate()); + assertTrue(((ASTConstants) ast.getWiredList().get(0)).isPubblic()); + assertFalse(((ASTConstants) ast.getWiredList().get(0)).isPrivate()); - Assertions.assertEquals(true, ((ASTConstants) ast.getWiredList().get(1)).isPubblic()); - Assertions.assertEquals(false, ((ASTConstants) ast.getWiredList().get(1)).isPrivate()); + assertTrue(((ASTConstants) ast.getWiredList().get(1)).isPubblic()); + assertFalse(((ASTConstants) ast.getWiredList().get(1)).isPrivate()); - Assertions.assertEquals(false, ((ASTConstants) ast.getWiredList().get(2)).isPubblic()); - Assertions.assertEquals(true, ((ASTConstants) ast.getWiredList().get(2)).isPrivate()); + assertFalse(((ASTConstants) ast.getWiredList().get(2)).isPubblic()); + assertTrue(((ASTConstants) ast.getWiredList().get(2)).isPrivate()); - Assertions.assertEquals(true, ((ASTSpices1) ast.getWiredList().get(3)).isCarlique()); - Assertions.assertEquals(true, ((ASTSpices1) ast.getWiredList().get(3)).isPepper()); + assertTrue(((ASTSpices1) ast.getWiredList().get(3)).isCarlique()); + assertTrue(((ASTSpices1) ast.getWiredList().get(3)).isPepper()); - Assertions.assertEquals(ASTConstantsFeatureDSL.NONE, ((ASTSpices2) ((ASTAutomaton) ast).getWiredList().get(4)).getSpicelevel()); + assertEquals(ASTConstantsFeatureDSL.NONE, ((ASTSpices2) ((ASTAutomaton) ast).getWiredList().get(4)).getSpicelevel()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -80,7 +78,7 @@ public void testConstantsParseError() throws IOException { FeatureDSLParser p = new FeatureDSLParser(); p.parseAutomaton(s); - Assertions.assertEquals(true, p.hasErrors()); + assertTrue(p.hasErrors()); } /* Grammar: B: A:A (B:A)*; @@ -99,12 +97,12 @@ public void testListError() throws IOException { FeatureDSLParser p = new FeatureDSLParser(); Optional ast = p.parseB(s); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals(true, ast.get().getA() instanceof ASTA); - Assertions.assertEquals(true, ast.get().getBList() instanceof List); + assertFalse(p.hasErrors()); + assertTrue(ast.isPresent()); + assertInstanceOf(ASTA.class, ast.get().getA()); + assertInstanceOf(List.class, ast.get().getBList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /* Grammar: B: A:A (A:A)*; @@ -123,11 +121,11 @@ public void testListError2() throws IOException { FeatureDSLParser p = new FeatureDSLParser(); Optional ast = p.parseC(s); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertEquals(true, ast.get().getAList() instanceof List); + assertTrue(ast.isPresent()); + assertFalse(p.hasErrors()); + assertInstanceOf(List.class, ast.get().getAList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /* Grammar: @@ -146,7 +144,7 @@ public void testListError3() throws IOException { FeatureDSLParser p = new FeatureDSLParser(); Optional ast = p.parseComplexname(s); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/astident/TestASTIdent.java b/monticore-test/it/src/test/java/mc/feature/astident/TestASTIdent.java index bf59b7e9cc..7b775665f2 100644 --- a/monticore-test/it/src/test/java/mc/feature/astident/TestASTIdent.java +++ b/monticore-test/it/src/test/java/mc/feature/astident/TestASTIdent.java @@ -2,15 +2,11 @@ package mc.feature.astident; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -18,6 +14,8 @@ import mc.feature.astident.astident._parser.AstIdentParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class TestASTIdent extends GeneratorIntegrationsTest { @BeforeEach @@ -34,13 +32,13 @@ public void testParser() throws IOException { AstIdentParser p = new AstIdentParser(); java.util.Optional ast = p.parseA(s); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals(false, p.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(p.hasErrors()); // Test parsing - Assertions.assertEquals("Otto", ast.get().getName()); + assertEquals("Otto", ast.get().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/astlist/CollectionTest.java b/monticore-test/it/src/test/java/mc/feature/astlist/CollectionTest.java index 50e57e1e6b..f991e232fe 100644 --- a/monticore-test/it/src/test/java/mc/feature/astlist/CollectionTest.java +++ b/monticore-test/it/src/test/java/mc/feature/astlist/CollectionTest.java @@ -8,12 +8,11 @@ import mc.feature.list.lists.ListsMill; import mc.feature.list.lists._ast.ASTParent; import mc.feature.list.lists._ast.ASTSon; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CollectionTest { @@ -38,16 +37,16 @@ public void testDeepEquals1() { p2.getSonsList().add(s3); p2.getSonsList().add(s4); - Assertions.assertTrue(p1.deepEquals(p1, true)); - Assertions.assertTrue(p2.deepEquals(p2, true)); - Assertions.assertTrue(p1.deepEquals(p2, true)); - Assertions.assertTrue(p2.deepEquals(p1, true)); + assertTrue(p1.deepEquals(p1, true)); + assertTrue(p2.deepEquals(p2, true)); + assertTrue(p1.deepEquals(p2, true)); + assertTrue(p2.deepEquals(p1, true)); p1.getSonsList().remove(s1); - Assertions.assertFalse(p1.deepEquals(p2, true)); - Assertions.assertFalse(p2.deepEquals(p1, true)); + assertFalse(p1.deepEquals(p2, true)); + assertFalse(p2.deepEquals(p1, true)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -69,14 +68,14 @@ public void testDeepEquals2() { p2.getSonsList().add(s3); p2.getSonsList().add(s4); - Assertions.assertTrue(p1.deepEquals(p1)); - Assertions.assertFalse(p1.deepEquals(p2)); - Assertions.assertTrue(p1.deepEquals(p2, false)); - Assertions.assertTrue(p2.deepEquals(p1, false)); - Assertions.assertFalse(p1.deepEquals(p2, true)); - Assertions.assertFalse(p2.deepEquals(p1, true)); + assertTrue(p1.deepEquals(p1)); + assertFalse(p1.deepEquals(p2)); + assertTrue(p1.deepEquals(p2, false)); + assertTrue(p2.deepEquals(p1, false)); + assertFalse(p1.deepEquals(p2, true)); + assertFalse(p2.deepEquals(p1, true)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -94,16 +93,16 @@ public void testDeepEqualsWithComments1() { p2.getSonsList().add(s3); p2.getSonsList().add(s4); - Assertions.assertTrue(p1.deepEqualsWithComments(p1)); - Assertions.assertTrue(p2.deepEqualsWithComments(p2)); - Assertions.assertTrue(p1.deepEqualsWithComments(p2)); - Assertions.assertTrue(p2.deepEqualsWithComments(p1)); + assertTrue(p1.deepEqualsWithComments(p1)); + assertTrue(p2.deepEqualsWithComments(p2)); + assertTrue(p1.deepEqualsWithComments(p2)); + assertTrue(p2.deepEqualsWithComments(p1)); p1.getSonsList().remove(s1); - Assertions.assertFalse(p1.deepEqualsWithComments(p2)); - Assertions.assertFalse(p2.deepEqualsWithComments(p1)); + assertFalse(p1.deepEqualsWithComments(p2)); + assertFalse(p2.deepEqualsWithComments(p1)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -125,10 +124,10 @@ public void testDeepEqualsWithComments2() { p2.getSonsList().add(s3); p2.getSonsList().add(s4); - Assertions.assertFalse(p1.deepEqualsWithComments(p2)); - Assertions.assertFalse(p2.deepEqualsWithComments(p1)); + assertFalse(p1.deepEqualsWithComments(p2)); + assertFalse(p2.deepEqualsWithComments(p1)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -152,15 +151,15 @@ public void deepEqualsWithComments3() { p2.getSonsList().add(s3); p2.getSonsList().add(s4); - Assertions.assertTrue(p1.deepEqualsWithComments(p2)); - Assertions.assertTrue(p2.deepEqualsWithComments(p1)); + assertTrue(p1.deepEqualsWithComments(p2)); + assertTrue(p2.deepEqualsWithComments(p1)); c1.setText("different comment"); - Assertions.assertFalse(p1.deepEqualsWithComments(p2)); - Assertions.assertFalse(p2.deepEqualsWithComments(p1)); + assertFalse(p1.deepEqualsWithComments(p2)); + assertFalse(p2.deepEqualsWithComments(p1)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -180,9 +179,9 @@ public void testDeepClone() { ASTParent p2 = p1.deepClone(); - Assertions.assertTrue(p1.deepEqualsWithComments(p2)); + assertTrue(p1.deepEqualsWithComments(p2)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -203,9 +202,9 @@ public void testClone() { ASTParent p2 = p1.deepClone(); - Assertions.assertTrue(p1.deepEquals(p2)); + assertTrue(p1.deepEquals(p2)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/astlist/TestLists.java b/monticore-test/it/src/test/java/mc/feature/astlist/TestLists.java index 92b161c596..13ad7c9c42 100644 --- a/monticore-test/it/src/test/java/mc/feature/astlist/TestLists.java +++ b/monticore-test/it/src/test/java/mc/feature/astlist/TestLists.java @@ -13,8 +13,8 @@ import java.util.ArrayList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestLists extends GeneratorIntegrationsTest { @@ -45,10 +45,10 @@ public void testLists() { list.add(f); list.add(g); - Assertions.assertEquals(6, list.indexOf(g)); + assertEquals(6, list.indexOf(g)); list.remove(g); - Assertions.assertEquals(-1, list.indexOf(g)); + assertEquals(-1, list.indexOf(g)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/aststring/ASTStringParserTest.java b/monticore-test/it/src/test/java/mc/feature/aststring/ASTStringParserTest.java index 633acac71d..d861398f3f 100644 --- a/monticore-test/it/src/test/java/mc/feature/aststring/ASTStringParserTest.java +++ b/monticore-test/it/src/test/java/mc/feature/aststring/ASTStringParserTest.java @@ -1,8 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ package mc.feature.aststring; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.StringReader; @@ -12,7 +10,6 @@ import de.se_rwth.commons.logging.LogStub; import mc.feature.aststring.aststring.AststringMill; import mc.feature.aststring.aststring._ast.ASTTestSingleQuote; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -20,6 +17,8 @@ import mc.feature.aststring.aststring._parser.AststringParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class ASTStringParserTest extends GeneratorIntegrationsTest { @BeforeEach @@ -36,34 +35,34 @@ public void testParser() throws IOException { AststringParser p = new AststringParser(); java.util.Optional opt = p.parseStart(s); - Assertions.assertTrue(opt.isPresent()); + assertTrue(opt.isPresent()); ASTStart ast = opt.get(); - Assertions.assertEquals(false, p.hasErrors()); + assertFalse(p.hasErrors()); // Test parsing - Assertions.assertEquals("ah", ast.getAList().get(0)); - Assertions.assertEquals("be", ast.getAList().get(1)); - Assertions.assertEquals("ce", ast.getAList().get(2)); - Assertions.assertEquals("oh", ast.getBList().get(0)); - Assertions.assertEquals("pe", ast.getBList().get(1)); - Assertions.assertEquals("qu", ast.getBList().get(2)); - Assertions.assertEquals("x", ast.getCList().get(0)); - Assertions.assertEquals("y", ast.getCList().get(1)); - Assertions.assertEquals("z", ast.getCList().get(2)); - Assertions.assertEquals("de", ast.getDList().get(0)); - Assertions.assertEquals("eh", ast.getDList().get(1)); + assertEquals("ah", ast.getAList().get(0)); + assertEquals("be", ast.getAList().get(1)); + assertEquals("ce", ast.getAList().get(2)); + assertEquals("oh", ast.getBList().get(0)); + assertEquals("pe", ast.getBList().get(1)); + assertEquals("qu", ast.getBList().get(2)); + assertEquals("x", ast.getCList().get(0)); + assertEquals("y", ast.getCList().get(1)); + assertEquals("z", ast.getCList().get(2)); + assertEquals("de", ast.getDList().get(0)); + assertEquals("eh", ast.getDList().get(1)); // Test toString method - Assertions.assertEquals("ef", ast.getDList().get(2).toString()); + assertEquals("ef", ast.getDList().get(2).toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSingleQuote() throws IOException { Optional ast = AststringMill.parser().parse_StringTestSingleQuote("Alex's Parser probleme"); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/automaton/SubclassParsingTest.java b/monticore-test/it/src/test/java/mc/feature/automaton/SubclassParsingTest.java index 565c1e1d2b..3cf61e47c9 100644 --- a/monticore-test/it/src/test/java/mc/feature/automaton/SubclassParsingTest.java +++ b/monticore-test/it/src/test/java/mc/feature/automaton/SubclassParsingTest.java @@ -2,15 +2,12 @@ package mc.feature.automaton; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -19,6 +16,9 @@ import mc.feature.automaton.automaton._ast.ASTTransition; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class SubclassParsingTest extends GeneratorIntegrationsTest { @BeforeEach @@ -33,9 +33,9 @@ public void testSubtypeParsing() throws IOException { AutomatonParser parser = new AutomatonParser(); Optional ast = parser.parseTransition(new StringReader("sub a -x> b;")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get() instanceof ASTSubTransition); + assertTrue(ast.isPresent()); + assertInstanceOf(ASTSubTransition.class, ast.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/classgenwithingrammar/ParserTest.java b/monticore-test/it/src/test/java/mc/feature/classgenwithingrammar/ParserTest.java index a7461e5293..dcbc981511 100644 --- a/monticore-test/it/src/test/java/mc/feature/classgenwithingrammar/ParserTest.java +++ b/monticore-test/it/src/test/java/mc/feature/classgenwithingrammar/ParserTest.java @@ -2,21 +2,20 @@ package mc.feature.classgenwithingrammar; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import mc.GeneratorIntegrationsTest; import mc.feature.classgenwithingrammar.type._parser.TypeParser; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ParserTest extends GeneratorIntegrationsTest { @BeforeEach @@ -30,7 +29,7 @@ public void before() { public void test() throws IOException { boolean hasError = parse("Hallo Hallo Hallo Welt "); - Assertions.assertTrue(hasError); + assertTrue(hasError); } // Test that the last Hallo is too much @@ -38,7 +37,7 @@ public void test() throws IOException { public void test2() throws IOException { boolean hasError = parse("Hallo Hallo Hallo Hallo "); - Assertions.assertTrue(hasError); + assertTrue(hasError); } // Tests that String is ok @@ -47,9 +46,9 @@ public void test3() throws IOException { boolean hasError = parse("Hallo Hallo Hallo "); - Assertions.assertFalse(hasError); + assertFalse(hasError); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // Tests that one hallo is issing @@ -58,7 +57,7 @@ public void test4() throws IOException { boolean hasError = parse("Hallo "); - Assertions.assertTrue(hasError); + assertTrue(hasError); } // Test that one Welt is too much @@ -67,7 +66,7 @@ public void testl() throws IOException { boolean hasError = parse2("Hall Hall Hall \"Wel\" "); - Assertions.assertTrue(hasError); + assertTrue(hasError); } // Test that too many Hallo and Welt are detected in one go @@ -76,7 +75,7 @@ public void testl2() throws IOException { boolean hasError = parse2("Hall Hall Hall Hall \"Wel\" "); - Assertions.assertTrue(hasError); + assertTrue(hasError); } // Tests that String is ok @@ -85,9 +84,9 @@ public void testl3() throws IOException { boolean hasError = parse2("Hall Hall Hall "); - Assertions.assertFalse(hasError); + assertFalse(hasError); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private boolean parse( String input) throws IOException { diff --git a/monticore-test/it/src/test/java/mc/feature/cocochecker/CoCoCheckerTest.java b/monticore-test/it/src/test/java/mc/feature/cocochecker/CoCoCheckerTest.java index 0bd9f4f18b..f3c0bbf6f5 100644 --- a/monticore-test/it/src/test/java/mc/feature/cocochecker/CoCoCheckerTest.java +++ b/monticore-test/it/src/test/java/mc/feature/cocochecker/CoCoCheckerTest.java @@ -2,17 +2,12 @@ package mc.feature.cocochecker; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,6 +24,8 @@ import mc.feature.cocochecker.c._cocos.CASTZCoCo; import mc.feature.cocochecker.c._cocos.CCoCoChecker; +import static org.junit.jupiter.api.Assertions.*; + /** * Tests adding cocos of super languages to a checker of a sublanguage.
*
@@ -97,9 +94,9 @@ public void setUp() { } catch (IOException e) { e.printStackTrace(); - Assertions.fail("Parser Error."); + fail("Parser Error."); } - Assertions.assertTrue(astOpt.isPresent()); + assertTrue(astOpt.isPresent()); ast = astOpt.get(); checked.setLength(0); } @@ -114,8 +111,8 @@ public void testCoCoComposition() { checker.addCoCo(cocoZ); checker.checkAll(ast); - Assertions.assertEquals("BAYZ", checked.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("BAYZ", checked.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -137,8 +134,8 @@ public void testCheckerComposition() { checkerA.addChecker(checkerC); checkerA.checkAll(ast); - Assertions.assertEquals("BAYZ", checked.toString()); + assertEquals("BAYZ", checked.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/comments/CommentTest.java b/monticore-test/it/src/test/java/mc/feature/comments/CommentTest.java index b0e1c20396..8bfea3fced 100644 --- a/monticore-test/it/src/test/java/mc/feature/comments/CommentTest.java +++ b/monticore-test/it/src/test/java/mc/feature/comments/CommentTest.java @@ -2,15 +2,11 @@ package mc.feature.comments; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -22,6 +18,8 @@ import mc.feature.featuredsl._parser.FeatureDSLParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class CommentTest extends GeneratorIntegrationsTest { @BeforeEach @@ -41,30 +39,30 @@ public void testConstants() throws IOException { ASTAutomaton ast = optAst.get(); // Parsing - Assertions.assertEquals(false, cp.hasErrors()); - Assertions.assertEquals("a", ast.getName()); + assertFalse(cp.hasErrors()); + assertEquals("a", ast.getName()); - Assertions.assertEquals(true, ((ASTConstants) ast.getWiredList().get(0)).isPubblic()); - Assertions.assertEquals(false, ((ASTConstants) ast.getWiredList().get(0)).isPrivate()); + assertTrue(((ASTConstants) ast.getWiredList().get(0)).isPubblic()); + assertFalse(((ASTConstants) ast.getWiredList().get(0)).isPrivate()); - Assertions.assertEquals(true, ((ASTConstants) ast.getWiredList().get(1)).isPubblic()); - Assertions.assertEquals(false, ((ASTConstants) ast.getWiredList().get(1)).isPrivate()); + assertTrue(((ASTConstants) ast.getWiredList().get(1)).isPubblic()); + assertFalse(((ASTConstants) ast.getWiredList().get(1)).isPrivate()); - Assertions.assertEquals(false, ((ASTConstants) ast.getWiredList().get(2)).isPubblic()); - Assertions.assertEquals(true, ((ASTConstants) ast.getWiredList().get(2)).isPrivate()); + assertFalse(((ASTConstants) ast.getWiredList().get(2)).isPubblic()); + assertTrue(((ASTConstants) ast.getWiredList().get(2)).isPrivate()); - Assertions.assertEquals(true, ((ASTSpices1) ast.getWiredList().get(3)).isCarlique()); - Assertions.assertEquals(true, ((ASTSpices1) ast.getWiredList().get(3)).isPepper()); + assertTrue(((ASTSpices1) ast.getWiredList().get(3)).isCarlique()); + assertTrue(((ASTSpices1) ast.getWiredList().get(3)).isPepper()); - Assertions.assertEquals(ASTConstantsFeatureDSL.NONE, ((ASTSpices2) ((ASTAutomaton) ast).getWiredList().get(4)).getSpicelevel()); + assertEquals(ASTConstantsFeatureDSL.NONE, ((ASTSpices2) ((ASTAutomaton) ast).getWiredList().get(4)).getSpicelevel()); - Assertions.assertEquals("// Test ", ast.get_PreCommentList().get(0).getText()); - Assertions.assertEquals("/*Second*/", ast.get_PreCommentList().get(1).getText()); - Assertions.assertEquals("// First Constant 1", ast.getWiredList().get(0).get_PreCommentList().get(0).getText()); - Assertions.assertEquals("// First Constant 2", ast.getWiredList().get(0).get_PostCommentList().get(0).getText()); - Assertions.assertEquals("/*Second Constant*/", ast.getWiredList().get(1).get_PreCommentList().get(0).getText()); + assertEquals("// Test ", ast.get_PreCommentList().get(0).getText()); + assertEquals("/*Second*/", ast.get_PreCommentList().get(1).getText()); + assertEquals("// First Constant 1", ast.getWiredList().get(0).get_PreCommentList().get(0).getText()); + assertEquals("// First Constant 2", ast.getWiredList().get(0).get_PostCommentList().get(0).getText()); + assertEquals("/*Second Constant*/", ast.getWiredList().get(1).get_PreCommentList().get(0).getText()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/comments/CommentTypesTest.java b/monticore-test/it/src/test/java/mc/feature/comments/CommentTypesTest.java index cb65e9f2d3..87bbcc68fa 100644 --- a/monticore-test/it/src/test/java/mc/feature/comments/CommentTypesTest.java +++ b/monticore-test/it/src/test/java/mc/feature/comments/CommentTypesTest.java @@ -2,21 +2,19 @@ package mc.feature.comments; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import mc.GeneratorIntegrationsTest; import mc.feature.comments.commenttypestest._parser.CommentTypesTestParser; +import static org.junit.jupiter.api.Assertions.*; + public class CommentTypesTest extends GeneratorIntegrationsTest { @BeforeEach @@ -37,8 +35,8 @@ public void testXMLComment() throws IOException { CommentTypesTestParser p = new CommentTypesTestParser(); p.parseCStart(r); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -52,8 +50,8 @@ public void testCComment_With__() throws IOException { CommentTypesTestParser p = new CommentTypesTestParser(); p.parseCStart(r); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -67,8 +65,8 @@ public void testTexComment() throws IOException { CommentTypesTestParser p = new CommentTypesTestParser(); p.parseCStart(r); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -82,8 +80,8 @@ public void testFreeMarkerComment() throws IOException { CommentTypesTestParser p = new CommentTypesTestParser(); p.parseCStart(r); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -97,8 +95,8 @@ public void testHashComment() throws IOException { CommentTypesTestParser p = new CommentTypesTestParser(); p.parseCStart(r); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/comments/CommentsTest.java b/monticore-test/it/src/test/java/mc/feature/comments/CommentsTest.java index ba30faaf90..d32579a524 100644 --- a/monticore-test/it/src/test/java/mc/feature/comments/CommentsTest.java +++ b/monticore-test/it/src/test/java/mc/feature/comments/CommentsTest.java @@ -2,15 +2,11 @@ package mc.feature.comments; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import de.monticore.ast.ASTNode; @@ -19,6 +15,8 @@ import mc.feature.comments.commenttest._parser.CommentTestParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class CommentsTest extends GeneratorIntegrationsTest { @BeforeEach @@ -38,14 +36,14 @@ public void testComment() throws IOException { CommentTestParser p = new CommentTestParser(); java.util.Optional optAst = p.parseStart(r); - Assertions.assertTrue(optAst.isPresent()); + assertTrue(optAst.isPresent()); ASTStart ast = optAst.get(); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertEquals(1, ast.getAList().size()); - Assertions.assertEquals(1, ast.getBList().size()); - Assertions.assertEquals(1, ((ASTNode) ast.getAList().get(0)).get_PreCommentList().size()); - Assertions.assertEquals(1, ((ASTNode) ast.getAList().get(0)).get_PostCommentList().size()); - Assertions.assertEquals(0, ((ASTNode) ast.getBList().get(0)).get_PreCommentList().size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertEquals(1, ast.getAList().size()); + assertEquals(1, ast.getBList().size()); + assertEquals(1, ((ASTNode) ast.getAList().get(0)).get_PreCommentList().size()); + assertEquals(1, ((ASTNode) ast.getAList().get(0)).get_PostCommentList().size()); + assertEquals(0, ((ASTNode) ast.getBList().get(0)).get_PreCommentList().size()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/compilationunit/ParserTest.java b/monticore-test/it/src/test/java/mc/feature/compilationunit/ParserTest.java index 85c8acc647..560d1acadf 100644 --- a/monticore-test/it/src/test/java/mc/feature/compilationunit/ParserTest.java +++ b/monticore-test/it/src/test/java/mc/feature/compilationunit/ParserTest.java @@ -2,16 +2,12 @@ package mc.feature.compilationunit; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,6 +17,8 @@ import mc.feature.compilationunit.compunit._ast.ASTCuFoo; import mc.feature.compilationunit.compunit._parser.CompunitParser; +import static org.junit.jupiter.api.Assertions.*; + public class ParserTest extends GeneratorIntegrationsTest { @BeforeEach @@ -34,10 +32,10 @@ public void testFoo() throws IOException { CompunitParser p = new CompunitParser(); Optional cUnit = p.parseCu(new StringReader("foo a")); - Assertions.assertFalse(p.hasErrors()); - Assertions.assertTrue(cUnit.isPresent()); - Assertions.assertTrue(cUnit.get() instanceof ASTCuFoo); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(cUnit.isPresent()); + assertInstanceOf(ASTCuFoo.class, cUnit.get()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -45,10 +43,10 @@ public void testBar() throws IOException { CompunitParser p = new CompunitParser(); Optional cUnit = p.parseCu(new StringReader("bar a")); - Assertions.assertFalse(p.hasErrors()); - Assertions.assertTrue(cUnit.isPresent()); - Assertions.assertTrue(cUnit.get() instanceof ASTCuBar); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(cUnit.isPresent()); + assertInstanceOf(ASTCuBar.class, cUnit.get()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/constantsshortform/ConstantsShortFormTest.java b/monticore-test/it/src/test/java/mc/feature/constantsshortform/ConstantsShortFormTest.java index 3c728f2b0a..c0b43f2886 100644 --- a/monticore-test/it/src/test/java/mc/feature/constantsshortform/ConstantsShortFormTest.java +++ b/monticore-test/it/src/test/java/mc/feature/constantsshortform/ConstantsShortFormTest.java @@ -8,12 +8,10 @@ import mc.feature.constantsshortform.constantsshortform.ConstantsShortFormMill; import mc.feature.constantsshortform.constantsshortform._ast.ASTA; import mc.feature.constantsshortform.constantsshortform._ast.ASTB; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ConstantsShortFormTest extends GeneratorIntegrationsTest { @@ -26,15 +24,15 @@ public void before() { @Test public void test() { ASTA a = ConstantsShortFormMill.aBuilder().build(); - Assertions.assertEquals(a.isMyConst(), false); + assertFalse(a.isMyConst()); a.setMyConst(true); - Assertions.assertEquals(a.isMyConst(), true); + assertTrue(a.isMyConst()); ASTB b = ConstantsShortFormMill.bBuilder().build(); - Assertions.assertEquals(b.isConst(), false); + assertFalse(b.isConst()); b.setConst(true); - Assertions.assertEquals(b.isConst(), true); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(b.isConst()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/deepclone/DeepCloneNotEqualTest.java b/monticore-test/it/src/test/java/mc/feature/deepclone/DeepCloneNotEqualTest.java index 0128e67ce0..de357fa050 100644 --- a/monticore-test/it/src/test/java/mc/feature/deepclone/DeepCloneNotEqualTest.java +++ b/monticore-test/it/src/test/java/mc/feature/deepclone/DeepCloneNotEqualTest.java @@ -8,15 +8,14 @@ import mc.feature.deepclone.deepclone._parser.DeepCloneParser; import mc.grammar.literals.ittestliterals._ast.ASTStringLiteral; import mc.grammar.literals.ittestliterals._ast.ASTIntLiteral; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DeepCloneNotEqualTest { @@ -30,64 +29,64 @@ public void before() { public void TestName() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneName("Name"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneName astClone = ast.get().deepClone(); astClone.setName("NewName"); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestNameList() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneNameList("Name1 Name2 Name3"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneNameList astClone = ast.get().deepClone(); astClone.setName(1, "NewName"); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestNameOptionalPresent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneNameOptional("opt Name"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get().isPresentName()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(ast.get().isPresentName()); ASTCloneNameOptional astClone = ast.get().deepClone(); astClone.setNameAbsent(); - Assertions.assertFalse(astClone.isPresentName()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(astClone.isPresentName()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestNameOptionalAbsent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneNameOptional("opt"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(ast.get().isPresentName()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(ast.get().isPresentName()); ASTCloneNameOptional astClone = ast.get().deepClone(); astClone.setName("NewName"); - Assertions.assertTrue(astClone.isPresentName()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(astClone.isPresentName()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestAST() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneAST("clone Name1 Name2 Name3"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneAST astClone = ast.get().deepClone(); astClone.getCloneNameList().setName(1, "NewName"); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -95,12 +94,12 @@ public void TestASTList() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser .parse_StringCloneASTList("clone Name1 Name2 clone Name3 Name4 Name5"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneASTList astClone = ast.get().deepClone(); astClone.getCloneAST(1).getCloneNameList().setName(1, "NewName"); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -108,244 +107,244 @@ public void TestASTOptionalPresent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser .parse_StringCloneASTOptional("opt clone Name1 Name2 Name3"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get().isPresentCloneAST()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(ast.get().isPresentCloneAST()); ASTCloneASTOptional astClone = ast.get().deepClone(); astClone.setCloneASTAbsent(); - Assertions.assertFalse(astClone.isPresentCloneAST()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(astClone.isPresentCloneAST()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestASTOptionalAbsent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneASTOptional("opt"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(ast.get().isPresentCloneAST()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(ast.get().isPresentCloneAST()); ASTCloneASTOptional astClone = ast.get().deepClone(); ASTCloneAST newast = parser.parse_StringCloneAST("clone Name1 Name2").get(); astClone.setCloneAST(newast); - Assertions.assertTrue(astClone.isPresentCloneAST()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(astClone.isPresentCloneAST()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestString() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneString("\"String\""); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneString astClone = ast.get().deepClone(); ASTStringLiteral string = parser.parse_StringCloneString("\"NewString\"").get().getStringLiteral(); astClone.setStringLiteral(string); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestStringList() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneStringList("\"String1\" \"String2\" \"String3\""); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneStringList astClone = ast.get().deepClone(); ASTStringLiteral string = parser.parse_StringCloneString("\"NewString\"").get().getStringLiteral(); astClone.getStringLiteralList().set(1, string); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestStringOptionalPresent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneStringOptional("opt \"String\""); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get().isPresentStringLiteral()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(ast.get().isPresentStringLiteral()); ASTCloneStringOptional astClone = ast.get().deepClone(); astClone.setStringLiteralAbsent(); - Assertions.assertFalse(astClone.isPresentStringLiteral()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(astClone.isPresentStringLiteral()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestStringOptionalAbsent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneStringOptional("opt"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(ast.get().isPresentStringLiteral()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(ast.get().isPresentStringLiteral()); ASTCloneStringOptional astClone = ast.get().deepClone(); ASTStringLiteral string = parser.parse_StringCloneString("\"NewString\"").get().getStringLiteral(); astClone.setStringLiteral(string); - Assertions.assertTrue(astClone.isPresentStringLiteral()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(astClone.isPresentStringLiteral()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestInt() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneInt("1234"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneInt astClone = ast.get().deepClone(); ASTIntLiteral i= parser.parse_StringCloneInt("4567").get().getIntLiteral(); astClone.setIntLiteral(i); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestIntList() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneIntList("12 34 56"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneIntList astClone = ast.get().deepClone(); ASTIntLiteral i= parser.parse_StringCloneInt("4567").get().getIntLiteral(); astClone.setIntLiteral(1, i); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestIntOptionalPresent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneIntOptional("opt 234"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get().isPresentIntLiteral()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(ast.get().isPresentIntLiteral()); ASTCloneIntOptional astClone = ast.get().deepClone(); astClone.setIntLiteralAbsent(); - Assertions.assertFalse(astClone.isPresentIntLiteral()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(astClone.isPresentIntLiteral()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestIntOptionalAbsent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneIntOptional("opt"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(ast.get().isPresentIntLiteral()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(ast.get().isPresentIntLiteral()); ASTCloneIntOptional astClone = ast.get().deepClone(); ASTIntLiteral i= parser.parse_StringCloneInt("4567").get().getIntLiteral(); astClone.setIntLiteral(i); - Assertions.assertTrue(astClone.isPresentIntLiteral()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(astClone.isPresentIntLiteral()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestString2() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneString2("\"String\""); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneString2 astClone = ast.get().deepClone(); astClone.setString("NewString"); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestStringList2() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneStringList2("\"String1\" \"String2\" \"String3\""); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneStringList2 astClone = ast.get().deepClone(); astClone.setString(1,"NewString"); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestStringOptionalPresent2() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneStringOptional2("opt \"String\""); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get().isPresentString()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(ast.get().isPresentString()); ASTCloneStringOptional2 astClone = ast.get().deepClone(); astClone.setStringAbsent(); - Assertions.assertFalse(astClone.isPresentString()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(astClone.isPresentString()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestStringOptionalAbsent2() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneStringOptional2("opt"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(ast.get().isPresentString()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(ast.get().isPresentString()); ASTCloneStringOptional2 astClone = ast.get().deepClone(); astClone.setString("NewString"); - Assertions.assertTrue(astClone.isPresentString()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(astClone.isPresentString()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestInt2() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneInt2("1234"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneInt2 astClone = ast.get().deepClone(); astClone.setNum_Int("4567"); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestIntList2() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneIntList2("12 34 56"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); ASTCloneIntList2 astClone = ast.get().deepClone(); astClone.setNum_Int(1, "2345"); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestIntOptionalPresent2() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneIntOptional2("opt 234"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get().isPresentNum_Int()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(ast.get().isPresentNum_Int()); ASTCloneIntOptional2 astClone = ast.get().deepClone(); astClone.setNum_IntAbsent(); - Assertions.assertFalse(astClone.isPresentNum_Int()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(astClone.isPresentNum_Int()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } @Test public void TestIntOptionalAbsent2() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneIntOptional2("opt"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(ast.get().isPresentNum_Int()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(ast.get().isPresentNum_Int()); ASTCloneIntOptional2 astClone = ast.get().deepClone(); astClone.setNum_Int("1234"); - Assertions.assertTrue(astClone.isPresentNum_Int()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(astClone.isPresentNum_Int()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } /* @Test @@ -362,14 +361,14 @@ public void TestEnumList() throws IOException { public void TestEnumOptionalPresent() throws IOException { DeepCloneParser parser = new DeepCloneParser(); Optional ast = parser.parse_StringCloneEnumOptional("opt enum"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(ast.get().isPresentCloneEnum()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(ast.get().isPresentCloneEnum()); ASTCloneEnumOptional astClone = ast.get().deepClone(); astClone.setCloneEnumAbsent(); - Assertions.assertFalse(astClone.isPresentCloneEnum()); - Assertions.assertFalse(ast.get().deepEquals(astClone)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(astClone.isPresentCloneEnum()); + assertFalse(ast.get().deepEquals(astClone)); + assertTrue(Log.getFindings().isEmpty()); } /* @Test diff --git a/monticore-test/it/src/test/java/mc/feature/deepclone/NoDoubleAddingTest.java b/monticore-test/it/src/test/java/mc/feature/deepclone/NoDoubleAddingTest.java index 11bba20458..360a345f13 100644 --- a/monticore-test/it/src/test/java/mc/feature/deepclone/NoDoubleAddingTest.java +++ b/monticore-test/it/src/test/java/mc/feature/deepclone/NoDoubleAddingTest.java @@ -5,15 +5,14 @@ import de.se_rwth.commons.logging.LogStub; import mc.feature.deepclone.nodoubleadding._ast.ASTSupProd; import mc.feature.deepclone.nodoubleadding._parser.NoDoubleAddingParser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class NoDoubleAddingTest { @@ -28,14 +27,14 @@ public void testNoDoubleListElements() throws IOException { //test that deepClone does not copy list elements twice NoDoubleAddingParser parser = new NoDoubleAddingParser(); Optional astSupProd = parser.parse_StringSupProd("Foo foo Name1 Name2 Name3"); - Assertions.assertTrue(astSupProd.isPresent()); + assertTrue(astSupProd.isPresent()); ASTSupProd clonedProd = astSupProd.get().deepClone(); - Assertions.assertEquals(3, clonedProd.sizeNames()); - Assertions.assertEquals("Name1", clonedProd.getName(0)); - Assertions.assertEquals("Name2", clonedProd.getName(1)); - Assertions.assertEquals("Name3", clonedProd.getName(2)); + assertEquals(3, clonedProd.sizeNames()); + assertEquals("Name1", clonedProd.getName(0)); + assertEquals("Name2", clonedProd.getName(1)); + assertEquals("Name3", clonedProd.getName(2)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/embedding/EmbedTest.java b/monticore-test/it/src/test/java/mc/feature/embedding/EmbedTest.java index 3950de6227..b1dca0ad4b 100644 --- a/monticore-test/it/src/test/java/mc/feature/embedding/EmbedTest.java +++ b/monticore-test/it/src/test/java/mc/feature/embedding/EmbedTest.java @@ -2,21 +2,19 @@ package mc.feature.embedding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import mc.GeneratorIntegrationsTest; import mc.feature.embedding.outer.embedded._parser.EmbeddedParser; +import static org.junit.jupiter.api.Assertions.*; + public class EmbedTest extends GeneratorIntegrationsTest { @BeforeEach @@ -32,8 +30,8 @@ public void test() throws IOException { EmbeddedParser parser = new EmbeddedParser(); parser.parseStart(new StringReader("a a a")); - Assertions.assertEquals(false, parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(false, parser.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -42,8 +40,8 @@ public void test2_a() throws IOException { EmbeddedParser parser = new EmbeddedParser(); parser.parseStart(new StringReader("a x a")); - Assertions.assertEquals(false, parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(parser.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -52,8 +50,8 @@ public void test2_b() throws IOException { EmbeddedParser parser = new EmbeddedParser(); parser.parseStart2(new StringReader("a x a")); - Assertions.assertEquals(false, parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(parser.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -62,7 +60,7 @@ public void test3() throws IOException { EmbeddedParser parser = new EmbeddedParser(); parser.parseStart2(new StringReader("a a x a a")); - Assertions.assertEquals(true, parser.hasErrors()); + assertTrue(parser.hasErrors()); } @Test @@ -71,8 +69,8 @@ public void test4() throws IOException { EmbeddedParser parser = new EmbeddedParser(); parser.parseStart3(new StringReader("b x")); - Assertions.assertEquals(false, parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(parser.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/embedding/EmbeddingTest.java b/monticore-test/it/src/test/java/mc/feature/embedding/EmbeddingTest.java index 13564562da..a3d1df9e74 100644 --- a/monticore-test/it/src/test/java/mc/feature/embedding/EmbeddingTest.java +++ b/monticore-test/it/src/test/java/mc/feature/embedding/EmbeddingTest.java @@ -2,9 +2,6 @@ package mc.feature.embedding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.Reader; import java.io.StringReader; @@ -12,7 +9,6 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,6 +18,9 @@ import mc.feature.embedding.outer.featureouterdsl._ast.ASTOuter; import mc.feature.embedding.outer.featureouterdsl._ast.ASTOuter3; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class EmbeddingTest extends GeneratorIntegrationsTest { @BeforeEach @@ -59,9 +58,9 @@ public void testEmbedding() throws IOException { ASTOuter ast = createAST("hihi", s); - Assertions.assertEquals("test", ((ASTExt) ast.getInner()).getInner().getName()); + assertEquals("test", ((ASTExt) ast.getInner()).getInner().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -71,7 +70,7 @@ public void testEmbedding3() throws IOException { createAST3("Embedded - optional taken", s); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -81,7 +80,7 @@ public void testEmbedding4() throws IOException { createAST3("Embedded - optional not taken", s); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/expression/Expression3Test.java b/monticore-test/it/src/test/java/mc/feature/expression/Expression3Test.java index d84bc7425d..c7235a368d 100644 --- a/monticore-test/it/src/test/java/mc/feature/expression/Expression3Test.java +++ b/monticore-test/it/src/test/java/mc/feature/expression/Expression3Test.java @@ -2,16 +2,11 @@ package mc.feature.expression; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -25,6 +20,8 @@ import mc.feature.expression.expression3._ast.ASTPrimaryExpr; import mc.feature.expression.expression3._parser.Expression3Parser; +import static org.junit.jupiter.api.Assertions.*; + public class Expression3Test extends GeneratorIntegrationsTest { @BeforeEach @@ -43,113 +40,113 @@ public Optional parse(String input) throws IOException { public void testPlus() { try { Optional res = parse("1+2"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTAddExpr); + assertInstanceOf(ASTAddExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLiteral() { try { Optional res = parse("1"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTPrimaryExpr); + assertInstanceOf(ASTPrimaryExpr.class, ast); - Assertions.assertEquals("1", ((ASTPrimaryExpr) ast).getNumericLiteral()); + assertEquals("1", ((ASTPrimaryExpr) ast).getNumericLiteral()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testStar() { try { Optional res = parse("1*2"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTMultExpr); + assertInstanceOf(ASTMultExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBracket() { try { Optional res = parse("(1*2)"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTBracketExpr); + assertInstanceOf(ASTBracketExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr1() { try { Optional res = parse("1*2+3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTAddExpr); + assertInstanceOf(ASTAddExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr2() { try { Optional res = parse("1+2*3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTAddExpr); + assertInstanceOf(ASTAddExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr3() { try { Optional res = parse("1-2-3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTAddExpr); + assertInstanceOf(ASTAddExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPowerWithRightAssoc() { try { Optional res = parse("2^3^4"); - Assertions.assertTrue(res.isPresent()); - Assertions.assertTrue(res.get()instanceof ASTPowerExpr); + assertTrue(res.isPresent()); + assertInstanceOf(ASTPowerExpr.class, res.get()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/expression/Expression4Test.java b/monticore-test/it/src/test/java/mc/feature/expression/Expression4Test.java index e763a2850e..df40446cee 100644 --- a/monticore-test/it/src/test/java/mc/feature/expression/Expression4Test.java +++ b/monticore-test/it/src/test/java/mc/feature/expression/Expression4Test.java @@ -2,16 +2,11 @@ package mc.feature.expression; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -25,6 +20,8 @@ import mc.feature.expression.expression4._ast.ASTPrimaryExpr; import mc.feature.expression.expression4._parser.Expression4Parser; +import static org.junit.jupiter.api.Assertions.*; + public class Expression4Test extends GeneratorIntegrationsTest { @BeforeEach @@ -43,113 +40,113 @@ public Optional parse(String input) throws IOException { public void testPlus() { try { Optional res = parse("1+2"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTAddExpr); + assertInstanceOf(ASTAddExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLiteral() { try { Optional res = parse("1"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTPrimaryExpr); + assertInstanceOf(ASTPrimaryExpr.class, ast); - Assertions.assertEquals("1", ((ASTPrimaryExpr) ast).getNumericLiteral()); + assertEquals("1", ((ASTPrimaryExpr) ast).getNumericLiteral()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testStar() { try { Optional res = parse("1*2"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTMultExpr); + assertInstanceOf(ASTMultExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBracket() { try { Optional res = parse("(1*2)"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTBracketExpr); + assertInstanceOf(ASTBracketExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr1() { try { Optional res = parse("1*2+3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTAddExpr); + assertInstanceOf(ASTAddExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr2() { try { Optional res = parse("1+2*3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTAddExpr); + assertInstanceOf(ASTAddExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr3() { try { Optional res = parse("1-2-3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTAddExpr); + assertInstanceOf(ASTAddExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPowerWithRightAssoc() { try { Optional res = parse("2^3^4"); - Assertions.assertTrue(res.isPresent()); - Assertions.assertTrue(res.get()instanceof ASTPowerExpr); + assertTrue(res.isPresent()); + assertInstanceOf(ASTPowerExpr.class, res.get()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/expression/Expression5Test.java b/monticore-test/it/src/test/java/mc/feature/expression/Expression5Test.java index e0a2a8a2ec..0cdf75e4bc 100644 --- a/monticore-test/it/src/test/java/mc/feature/expression/Expression5Test.java +++ b/monticore-test/it/src/test/java/mc/feature/expression/Expression5Test.java @@ -2,16 +2,11 @@ package mc.feature.expression; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,6 +16,8 @@ import mc.feature.expression.expression5._ast.ASTMultExpr; import mc.feature.expression.expression5._parser.Expression5Parser; +import static org.junit.jupiter.api.Assertions.*; + public class Expression5Test extends GeneratorIntegrationsTest { @BeforeEach @@ -40,42 +37,42 @@ public Optional parse(String input) throws IOException { public void testExpr1() { try { Optional res = parse("1*2+3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTMultExpr); + assertInstanceOf(ASTMultExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr2() { try { Optional res = parse("1+2*3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTMultExpr); + assertInstanceOf(ASTMultExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr3() { try { Optional res = parse("1*2*3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast instanceof ASTMultExpr); + assertInstanceOf(ASTMultExpr.class, ast); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-test/it/src/test/java/mc/feature/expression/ExpressionTest.java b/monticore-test/it/src/test/java/mc/feature/expression/ExpressionTest.java index b545783fec..116ff811e1 100644 --- a/monticore-test/it/src/test/java/mc/feature/expression/ExpressionTest.java +++ b/monticore-test/it/src/test/java/mc/feature/expression/ExpressionTest.java @@ -2,16 +2,11 @@ package mc.feature.expression; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import de.se_rwth.commons.logging.Log; @@ -21,6 +16,8 @@ import mc.feature.expression.expression._parser.ExpressionParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class ExpressionTest extends GeneratorIntegrationsTest { @BeforeEach @@ -39,113 +36,113 @@ public Optional parse(String input) throws IOException { public void testPlus() { try { Optional res = parse("1+2"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertEquals(ASTConstantsExpression.PLUS, ast.getOp()); + assertEquals(ASTConstantsExpression.PLUS, ast.getOp()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLiteral() { try { Optional res = parse("1"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast.isPresentNumericLiteral()); - Assertions.assertEquals("1", ast.getNumericLiteral()); + assertTrue(ast.isPresentNumericLiteral()); + assertEquals("1", ast.getNumericLiteral()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testStar() { try { Optional res = parse("1*2"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertEquals(ASTConstantsExpression.STAR, ast.getOp()); + assertEquals(ASTConstantsExpression.STAR, ast.getOp()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBracket() { try { Optional res = parse("(1*2)"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertTrue(ast.isPresentExpr()); + assertTrue(ast.isPresentExpr()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr1() { try { Optional res = parse("1*2+3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertEquals(ASTConstantsExpression.PLUS, ast.getOp()); + assertEquals(ASTConstantsExpression.PLUS, ast.getOp()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr2() { try { Optional res = parse("1+2*3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertEquals(ASTConstantsExpression.PLUS, ast.getOp()); + assertEquals(ASTConstantsExpression.PLUS, ast.getOp()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpr3() { try { Optional res = parse("1-2-3"); - Assertions.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); ASTExpr ast = res.get(); - Assertions.assertEquals(ASTConstantsExpression.MINUS, ast.getOp()); + assertEquals(ASTConstantsExpression.MINUS, ast.getOp()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPowerWithRightAssoc() { try { Optional res = parse("2^3^4"); - Assertions.assertTrue(res.isPresent()); - Assertions.assertTrue(res.get().isPresentLeft()); - Assertions.assertTrue(res.get().getLeft().isPresentNumericLiteral()); + assertTrue(res.isPresent()); + assertTrue(res.get().isPresentLeft()); + assertTrue(res.get().getLeft().isPresentNumericLiteral()); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/filefindertest/FileFinderTest.java b/monticore-test/it/src/test/java/mc/feature/filefindertest/FileFinderTest.java index c6e91fdbc2..3094da8b41 100644 --- a/monticore-test/it/src/test/java/mc/feature/filefindertest/FileFinderTest.java +++ b/monticore-test/it/src/test/java/mc/feature/filefindertest/FileFinderTest.java @@ -9,7 +9,6 @@ import mc.feature.filefindertest.filefindertest._ast.ASTSCArtifact; import mc.feature.filefindertest.filefindertest._parser.FileFinderTestParser; import mc.feature.filefindertest.filefindertest._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,8 +16,8 @@ import java.nio.file.Paths; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class FileFinderTest { @@ -37,8 +36,8 @@ public void setUp() throws IOException { Optional artifactII = parser.parse("src/test/resources/mc/feature/filefindertest/Model2.sc"); FileFinderTestScopesGenitorDelegator delegator = FileFinderTestMill.scopesGenitorDelegator(); FileFinderTestScopesGenitorDelegator delegatorII = FileFinderTestMill.scopesGenitorDelegator(); - Assertions.assertTrue(artifact.isPresent()); - Assertions.assertTrue(artifactII.isPresent()); + assertTrue(artifact.isPresent()); + assertTrue(artifactII.isPresent()); IFileFinderTestArtifactScope scope = delegator.createFromAST(artifact.get()); scope.setPackageName("mc.feature.filefindertest"); IFileFinderTestArtifactScope scopeII = delegatorII.createFromAST(artifactII.get()); @@ -58,8 +57,8 @@ public void testFileFinder1() { gs.clear(); gs.setSymbolPath(new MCPath(Paths.get(SYMBOL_PATH))); Optional statechartSymbol = gs.resolveStatechart("mc.feature.filefindertest.Model1"); - Assertions.assertTrue(statechartSymbol.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(statechartSymbol.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -70,8 +69,8 @@ public void testFileFinder2() { gs.setFileExt("scsym"); gs.setSymbolPath(new MCPath(Paths.get(SYMBOL_PATH))); Optional statechartSymbol = gs.resolveStatechart("mc.feature.filefindertest.Model1"); - Assertions.assertTrue(statechartSymbol.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(statechartSymbol.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -82,8 +81,8 @@ public void testFileFinder3() { gs.setFileExt("ym"); gs.setSymbolPath(new MCPath(Paths.get(SYMBOL_PATH))); Optional statechartSymbol = gs.resolveStatechart("mc.feature.filefindertest.Model1"); - Assertions.assertFalse(statechartSymbol.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(statechartSymbol.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -93,8 +92,8 @@ public void testFileFinder4() { gs.clear(); gs.setSymbolPath(new MCPath(Paths.get("src/test"))); Optional statechartSymbol = gs.resolveStatechart("mc.feature.filefindertest.Model1"); - Assertions.assertFalse(statechartSymbol.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(statechartSymbol.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -104,8 +103,8 @@ public void testFileFinder5() { gs.clear(); gs.setSymbolPath(new MCPath()); Optional statechartSymbol = gs.resolveStatechart("mc.feature.filefindertest.Model1"); - Assertions.assertFalse(statechartSymbol.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(statechartSymbol.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -116,7 +115,7 @@ public void testFileFinder6() { gs.setFileExt("json"); gs.setSymbolPath(new MCPath(Paths.get(SYMBOL_PATH))); Optional statechartSymbol = gs.resolveStatechart("mc.feature.filefindertest.Model1"); - Assertions.assertTrue(statechartSymbol.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(statechartSymbol.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/followoption/FollowOptionTest.java b/monticore-test/it/src/test/java/mc/feature/followoption/FollowOptionTest.java index 630187d1a6..6c84fea9fa 100644 --- a/monticore-test/it/src/test/java/mc/feature/followoption/FollowOptionTest.java +++ b/monticore-test/it/src/test/java/mc/feature/followoption/FollowOptionTest.java @@ -2,21 +2,19 @@ package mc.feature.followoption; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; import mc.feature.followoption.followoption._parser.FollowOptionParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class FollowOptionTest extends GeneratorIntegrationsTest { @BeforeEach @@ -31,9 +29,9 @@ public void test1() throws IOException { //-- extractfile gen/FollowOptionTest.x FollowOptionParser simpleAParser = new FollowOptionParser(); simpleAParser.parseA(new StringReader("test ,")); - Assertions.assertEquals(false, simpleAParser.hasErrors()); + assertFalse(simpleAParser.hasErrors()); //-- endfile gen/FollowOptionTest.x - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -42,7 +40,7 @@ public void test2() throws IOException { FollowOptionParser simpleBParser = new FollowOptionParser(); simpleBParser.parseB(new StringReader("test ,")); - Assertions.assertEquals(true, simpleBParser.hasErrors()); + assertTrue(simpleBParser.hasErrors()); //-- endfile gen/FollowOptionTest.x } @@ -57,7 +55,7 @@ public void test3() throws IOException { FollowOptionParser simpleParser = new FollowOptionParser(); simpleParser.parseB(new StringReader(",")); - Assertions.assertEquals(true, simpleParser.hasErrors()); + assertTrue(simpleParser.hasErrors()); } @Test @@ -65,7 +63,7 @@ public void test4() throws IOException { FollowOptionParser simpleAParser = new FollowOptionParser(); simpleAParser.parseA(new StringReader("test .")); - - Assertions.assertEquals(true, simpleAParser.hasErrors()); + + assertTrue(simpleAParser.hasErrors()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/grammarinherit/TestGrammarInherit.java b/monticore-test/it/src/test/java/mc/feature/grammarinherit/TestGrammarInherit.java index 976254c95d..ba298f0e44 100644 --- a/monticore-test/it/src/test/java/mc/feature/grammarinherit/TestGrammarInherit.java +++ b/monticore-test/it/src/test/java/mc/feature/grammarinherit/TestGrammarInherit.java @@ -6,15 +6,13 @@ import de.se_rwth.commons.logging.LogStub; import mc.GeneratorIntegrationsTest; import mc.feature.grammarinherit.sub.subfeaturedslgrammarinherit._parser.SubFeatureDSLgrammarinheritParser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.StringReader; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class TestGrammarInherit extends GeneratorIntegrationsTest { @@ -32,9 +30,10 @@ public void test1() throws IOException { SubFeatureDSLgrammarinheritParser p = new SubFeatureDSLgrammarinheritParser(); p.parseFile(s); - Assertions.assertEquals(false, p.hasErrors()); + assertFalse(p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/hwc/BuildersTest.java b/monticore-test/it/src/test/java/mc/feature/hwc/BuildersTest.java index 98351c3191..fabed90a74 100644 --- a/monticore-test/it/src/test/java/mc/feature/hwc/BuildersTest.java +++ b/monticore-test/it/src/test/java/mc/feature/hwc/BuildersTest.java @@ -1,14 +1,10 @@ /* (c) https://github.com/MontiCore/monticore */ package mc.feature.hwc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import de.se_rwth.commons.logging.LogStub; import org.antlr.v4.runtime.RecognitionException; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +14,9 @@ import mc.feature.hwc.statechartdsl._ast.ASTTransition; import mc.feature.hwc.statechartdsl.StatechartDSLMill; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class BuildersTest { @BeforeEach @@ -34,22 +33,22 @@ public void setUp() throws RecognitionException, IOException { @Test public void testMyTransitionBuilder() throws IOException { ASTTransition transition = StatechartDSLMill.transitionBuilder().setFrom("setByGenBuilder").setFrom("xxxx").setTo("setByGenBuilder").build(); - Assertions.assertEquals("xxxxSuf2", transition.getFrom()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("xxxxSuf2", transition.getFrom()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testHWCClassGeneratedBuilder() throws IOException { ASTStatechart aut = StatechartDSLMill.statechartBuilder().setName("setByGeneratedBuilder").build(); - Assertions.assertEquals("setByGeneratedBuilder", aut.getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("setByGeneratedBuilder", aut.getName()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testHWCClassHWCBuilder() throws IOException { ASTState state = StatechartDSLMill.stateBuilder().setName("x2").setFinal(true).setName("state1").build(); - Assertions.assertEquals(state.getName(), "state1Suf1"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("state1Suf1", state.getName()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/inheritedbuilder/TestInheritedBuilder.java b/monticore-test/it/src/test/java/mc/feature/inheritedbuilder/TestInheritedBuilder.java index 2fcd9707bf..5aedf7c1fc 100644 --- a/monticore-test/it/src/test/java/mc/feature/inheritedbuilder/TestInheritedBuilder.java +++ b/monticore-test/it/src/test/java/mc/feature/inheritedbuilder/TestInheritedBuilder.java @@ -5,11 +5,11 @@ import de.se_rwth.commons.logging.LogStub; import mc.feature.inheritedbuilder.buildertest.BuilderTestMill; import mc.feature.inheritedbuilder.buildertest._ast.ASTSubBuilder; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestInheritedBuilder { @@ -22,8 +22,8 @@ public void before() { @Test public void test(){ //test if the return type of the builder for the inherited attribute name of Sub is correct - Assertions.assertTrue(BuilderTestMill.subBuilder().setName("Foo") instanceof ASTSubBuilder); + assertInstanceOf(ASTSubBuilder.class, BuilderTestMill.subBuilder().setName("Foo")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/inheritence/CloneInheritenceTest.java b/monticore-test/it/src/test/java/mc/feature/inheritence/CloneInheritenceTest.java index 7906584d97..645ff85df4 100644 --- a/monticore-test/it/src/test/java/mc/feature/inheritence/CloneInheritenceTest.java +++ b/monticore-test/it/src/test/java/mc/feature/inheritence/CloneInheritenceTest.java @@ -8,11 +8,10 @@ import mc.feature.inheritence.inheritence._ast.ASTSub; import mc.feature.inheritence.inheritence._ast.ASTSuper; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CloneInheritenceTest extends GeneratorIntegrationsTest { @@ -41,7 +40,7 @@ public void test() { .uncheckedBuild(); t.deepClone(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/inheritence/InheritenceTest.java b/monticore-test/it/src/test/java/mc/feature/inheritence/InheritenceTest.java index 17280d5181..8a700c7f76 100644 --- a/monticore-test/it/src/test/java/mc/feature/inheritence/InheritenceTest.java +++ b/monticore-test/it/src/test/java/mc/feature/inheritence/InheritenceTest.java @@ -2,16 +2,12 @@ package mc.feature.inheritence; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,6 +27,8 @@ import mc.feature.inheritence.inheritence._ast.ASTXP; import mc.feature.inheritence.inheritence._parser.InheritenceParser; +import static org.junit.jupiter.api.Assertions.*; + public class InheritenceTest extends GeneratorIntegrationsTest { @BeforeEach @@ -53,8 +51,8 @@ public void test1a() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseIG(new StringReader("a")); - Assertions.assertTrue(ast.get() instanceof ASTA); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTA.class, ast.get()); + assertTrue(Log.getFindings().isEmpty()); } @@ -64,8 +62,8 @@ public void test1b() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseIG(new StringReader("b")); - Assertions.assertTrue(ast.get() instanceof ASTB); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTB.class, ast.get()); + assertTrue(Log.getFindings().isEmpty()); } @@ -75,8 +73,8 @@ public void test1c() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseIG(new StringReader("c")); - Assertions.assertTrue(ast.get() instanceof ASTC); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTC.class, ast.get()); + assertTrue(Log.getFindings().isEmpty()); } @@ -90,8 +88,8 @@ public void test2() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseIH(new StringReader("d")); - Assertions.assertTrue(ast.get() instanceof ASTD); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTD.class, ast.get()); + assertTrue(Log.getFindings().isEmpty()); } @@ -106,8 +104,8 @@ public void test3a() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseIM(new StringReader("aa")); - Assertions.assertTrue(ast.get() instanceof ASTK); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTK.class, ast.get()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -115,8 +113,8 @@ public void test3b() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseIM(new StringReader("bb")); - Assertions.assertTrue(ast.get() instanceof ASTK); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTK.class, ast.get()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -124,8 +122,8 @@ public void test3c() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseIM(new StringReader("ab")); - Assertions.assertTrue(ast.get() instanceof ASTL); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTL.class, ast.get()); + assertTrue(Log.getFindings().isEmpty()); } @@ -136,8 +134,8 @@ public void test4a() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseXAE(new StringReader("f")); - Assertions.assertTrue(ast.get() instanceof ASTXF); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTXF.class, ast.get()); + assertTrue(Log.getFindings().isEmpty()); } // Test 5 : XAO should parse "p" but not "q" and return an XP @@ -147,9 +145,9 @@ public void test5a() throws IOException { InheritenceParser parser = new InheritenceParser(); Optional ast = parser.parseXAO(new StringReader("p")); - Assertions.assertTrue(ast.get() instanceof ASTXP); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertInstanceOf(ASTXP.class, ast.get()); + assertFalse(parser.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @@ -158,7 +156,7 @@ public void test5b() throws IOException { InheritenceParser parser = new InheritenceParser(); parser.parseXAO(new StringReader("q")); - Assertions.assertTrue(parser.hasErrors()); + assertTrue(parser.hasErrors()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/interfaces/InterfacesTest.java b/monticore-test/it/src/test/java/mc/feature/interfaces/InterfacesTest.java index c27bb0a84c..d868b160d7 100644 --- a/monticore-test/it/src/test/java/mc/feature/interfaces/InterfacesTest.java +++ b/monticore-test/it/src/test/java/mc/feature/interfaces/InterfacesTest.java @@ -2,16 +2,12 @@ package mc.feature.interfaces; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -19,6 +15,8 @@ import mc.feature.interfaces.sub._parser.SubParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class InterfacesTest extends GeneratorIntegrationsTest { @BeforeEach @@ -33,10 +31,10 @@ public void test1a() throws IOException { SubParser parser = new SubParser(); Optional ast = parser.parseA(new StringReader("Hello Otto Mustermann")); - Assertions.assertTrue(ast.get() instanceof ASTA); + assertInstanceOf(ASTA.class, ast.get()); ASTA astA = ast.get(); - Assertions.assertNotNull(astA.getB()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertNotNull(astA.getB()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/interfaces/ListInterfaceTest.java b/monticore-test/it/src/test/java/mc/feature/interfaces/ListInterfaceTest.java index 56eba2edeb..1d149435b3 100644 --- a/monticore-test/it/src/test/java/mc/feature/interfaces/ListInterfaceTest.java +++ b/monticore-test/it/src/test/java/mc/feature/interfaces/ListInterfaceTest.java @@ -5,16 +5,13 @@ import de.se_rwth.commons.logging.LogStub; import mc.feature.interfaces.listgeneration._ast.*; import mc.feature.interfaces.listgeneration._parser.ListGenerationParser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ListInterfaceTest { @@ -28,49 +25,49 @@ public void before() { public void testMethodExistenceTokenPlus() throws IOException{ ListGenerationParser parser = new ListGenerationParser(); Optional ast = parser.parse_StringTokenPlus("+ Name, name"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals(2, ast.get().getNameList().size()); - Assertions.assertFalse(ast.get().isEmptyNames()); - Assertions.assertEquals(0, ast.get().indexOfName("Name")); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals(2, ast.get().getNameList().size()); + assertFalse(ast.get().isEmptyNames()); + assertEquals(0, ast.get().indexOfName("Name")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMethodExistenceTokenStar() throws IOException{ ListGenerationParser parser = new ListGenerationParser(); Optional ast = parser.parse_StringTokenStar("something * Name name"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals(2, ast.get().getNameList().size()); - Assertions.assertFalse(ast.get().isEmptyNames()); - Assertions.assertEquals(0, ast.get().indexOfName("Name")); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals(2, ast.get().getNameList().size()); + assertFalse(ast.get().isEmptyNames()); + assertEquals(0, ast.get().indexOfName("Name")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMethodExistenceListPlus() throws IOException{ ListGenerationParser parser = new ListGenerationParser(); Optional ast = parser.parse_StringListPlus("something Abc Dec"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals(2, ast.get().getTestList().size()); - Assertions.assertFalse(ast.get().isEmptyTest()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals(2, ast.get().getTestList().size()); + assertFalse(ast.get().isEmptyTest()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMethodExistenceListStar() throws IOException{ ListGenerationParser parser = new ListGenerationParser(); Optional ast = parser.parse_StringListStar("Abc Dec Abc word"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals(3, ast.get().getTestList().size()); - Assertions.assertFalse(ast.get().isEmptyTest()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals(3, ast.get().getTestList().size()); + assertFalse(ast.get().isEmptyTest()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/interfaces/MethodInterfaceTest.java b/monticore-test/it/src/test/java/mc/feature/interfaces/MethodInterfaceTest.java index 42758c298f..a53e72e9d3 100644 --- a/monticore-test/it/src/test/java/mc/feature/interfaces/MethodInterfaceTest.java +++ b/monticore-test/it/src/test/java/mc/feature/interfaces/MethodInterfaceTest.java @@ -6,16 +6,13 @@ import de.se_rwth.commons.logging.LogStub; import mc.feature.interfaces.methodinterface._ast.*; import mc.feature.interfaces.methodinterface._parser.MethodInterfaceParser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MethodInterfaceTest { @@ -29,65 +26,65 @@ public void before() { public void testInterfaceDefaultA() throws IOException { MethodInterfaceParser parser = new MethodInterfaceParser(); Optional ast = parser.parse_StringInterfaceDefault("Hello3"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("test", ast.get().getTest()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals("test", ast.get().getTest()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInterfaceDefaultA1() throws IOException { MethodInterfaceParser parser = new MethodInterfaceParser(); Optional ast = parser.parse_StringInterfaceDefaultA("Hello"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("A", ast.get().getTest()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals("A", ast.get().getTest()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInterfaceDefaultA2() throws IOException { MethodInterfaceParser parser = new MethodInterfaceParser(); Optional ast = parser.parse_StringA("Hello"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("A", ast.get().getTest()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals("A", ast.get().getTest()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInterfaceAbstract() throws IOException { MethodInterfaceParser parser = new MethodInterfaceParser(); Optional ast = parser.parse_StringInterfaceAbstract("Hello2"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("B", ast.get().getTest2()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals("B", ast.get().getTest2()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInterfaceAbstractB() throws IOException { MethodInterfaceParser parser = new MethodInterfaceParser(); Optional ast = parser.parse_StringB("Hello2"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("B", ast.get().getTest2()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals("B", ast.get().getTest2()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testClassMethod() throws IOException { MethodInterfaceParser parser = new MethodInterfaceParser(); Optional ast = parser.parse_StringClassMethod("Name C"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("ABC", ast.get().getTest3()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals("ABC", ast.get().getTest3()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/interfaces/OptionalInterfacesTest.java b/monticore-test/it/src/test/java/mc/feature/interfaces/OptionalInterfacesTest.java index 7b777d4a2a..7a75fa8ead 100644 --- a/monticore-test/it/src/test/java/mc/feature/interfaces/OptionalInterfacesTest.java +++ b/monticore-test/it/src/test/java/mc/feature/interfaces/OptionalInterfacesTest.java @@ -5,16 +5,13 @@ import de.se_rwth.commons.logging.LogStub; import mc.feature.interfaces.optionalgeneration._ast.*; import mc.feature.interfaces.optionalgeneration._parser.OptionalGenerationParser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class OptionalInterfacesTest { @@ -28,48 +25,48 @@ public void before() { public void testMethodExistenceTest1() throws IOException{ OptionalGenerationParser parser = new OptionalGenerationParser(); Optional astOpt1 = parser.parse_StringOpt1("abc Name"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astOpt1.isPresent()); - Assertions.assertTrue(astOpt1.get().isPresentName()); - Assertions.assertEquals("Name", astOpt1.get().getName()); + assertFalse(parser.hasErrors()); + assertTrue(astOpt1.isPresent()); + assertTrue(astOpt1.get().isPresentName()); + assertEquals("Name", astOpt1.get().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMethodExistenceTest2() throws IOException{ OptionalGenerationParser parser = new OptionalGenerationParser(); Optional astTest2 = parser.parse_StringTest2("abc someName"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astTest2.isPresent()); - Assertions.assertTrue(astTest2.get().isPresentName()); - Assertions.assertEquals("someName", astTest2.get().getName()); + assertFalse(parser.hasErrors()); + assertTrue(astTest2.isPresent()); + assertTrue(astTest2.get().isPresentName()); + assertEquals("someName", astTest2.get().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMethodExistenceTest3() throws IOException{ OptionalGenerationParser parser = new OptionalGenerationParser(); Optional astOpt2 = parser.parse_StringOpt2("def Name"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astOpt2.isPresent()); - Assertions.assertTrue(astOpt2.get().isPresentName()); - Assertions.assertEquals("Name", astOpt2.get().getName()); + assertFalse(parser.hasErrors()); + assertTrue(astOpt2.isPresent()); + assertTrue(astOpt2.get().isPresentName()); + assertEquals("Name", astOpt2.get().getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMethodExistenceTest4() throws IOException{ OptionalGenerationParser parser = new OptionalGenerationParser(); Optional astTest4 = parser.parse_StringTest4("def someName"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astTest4.isPresent()); - Assertions.assertEquals("someName", astTest4.get().getName()); - Assertions.assertTrue(astTest4.get().isPresentName()); + assertFalse(parser.hasErrors()); + assertTrue(astTest4.isPresent()); + assertEquals("someName", astTest4.get().getName()); + assertTrue(astTest4.get().isPresentName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/javasql/JavaSQLTest.java b/monticore-test/it/src/test/java/mc/feature/javasql/JavaSQLTest.java index 4477b943dc..eb2c0e4c67 100644 --- a/monticore-test/it/src/test/java/mc/feature/javasql/JavaSQLTest.java +++ b/monticore-test/it/src/test/java/mc/feature/javasql/JavaSQLTest.java @@ -2,21 +2,20 @@ package mc.feature.javasql; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; import mc.feature.javasql.javasql.javasql._parser.JavaSQLParser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class JavaSQLTest extends GeneratorIntegrationsTest { @BeforeEach @@ -31,8 +30,8 @@ public void test1() throws IOException { JavaSQLParser p = new JavaSQLParser(); p.parseStart(new StringReader("a++,a=SELECT a FROM x ,i++")); - Assertions.assertEquals(false, p.hasErrors()); + assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/keyrule/KeyRuleTest.java b/monticore-test/it/src/test/java/mc/feature/keyrule/KeyRuleTest.java index 40a31cea07..862903c354 100644 --- a/monticore-test/it/src/test/java/mc/feature/keyrule/KeyRuleTest.java +++ b/monticore-test/it/src/test/java/mc/feature/keyrule/KeyRuleTest.java @@ -8,16 +8,13 @@ import mc.feature.keyrule.keyrule._ast.ASTB; import mc.feature.keyrule.keyrule._ast.ASTJ; import mc.feature.keyrule.keyrule._parser.KeyRuleParser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class KeyRuleTest extends GeneratorIntegrationsTest { @@ -31,24 +28,24 @@ public void before() { public void test() throws IOException { KeyRuleParser parser = new KeyRuleParser(); parser.parse_StringA("bla1 Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); parser.parse_StringA("bla2 Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); parser.parse_StringA("bla3 Foo"); - Assertions.assertTrue(parser.hasErrors()); + assertTrue(parser.hasErrors()); Optional ast = parser.parse_StringB("bla1 Foo"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("bla1", ast.get().getBla()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals("bla1", ast.get().getBla()); ast = parser.parse_StringB("bla2 Foo"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("bla2", ast.get().getBla()); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertEquals("bla2", ast.get().getBla()); Optional astj = parser.parse_StringJ("blaj"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astj.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astj.isPresent()); astj = parser.parse_StringJ("blax"); - Assertions.assertTrue(parser.hasErrors()); + assertTrue(parser.hasErrors()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/lexerformat/KleenePlusTest.java b/monticore-test/it/src/test/java/mc/feature/lexerformat/KleenePlusTest.java index 79d22d5858..9e230c3ce8 100644 --- a/monticore-test/it/src/test/java/mc/feature/lexerformat/KleenePlusTest.java +++ b/monticore-test/it/src/test/java/mc/feature/lexerformat/KleenePlusTest.java @@ -2,17 +2,12 @@ package mc.feature.lexerformat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,6 +15,8 @@ import mc.feature.lexerformat.kleeneplus._ast.ASTKPStart; import mc.feature.lexerformat.kleeneplus._parser.KleenePlusParser; +import static org.junit.jupiter.api.Assertions.*; + public class KleenePlusTest extends GeneratorIntegrationsTest { @BeforeEach @@ -38,23 +35,23 @@ public void testKleeneStar() throws IOException { Optional ast; ast = p.parseKPStart(new StringReader("a")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("a", ast.get().getKleene()); + assertTrue(ast.isPresent()); + assertEquals("a", ast.get().getKleene()); ast = p.parseKPStart(new StringReader("ab")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("ab", ast.get().getKleene()); + assertTrue(ast.isPresent()); + assertEquals("ab", ast.get().getKleene()); ast = p.parseKPStart(new StringReader("abb")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("abb", ast.get().getKleene()); + assertTrue(ast.isPresent()); + assertEquals("abb", ast.get().getKleene()); ast = p.parseKPStart(new StringReader("abbbb")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("abbbb", ast.get().getKleene()); + assertTrue(ast.isPresent()); + assertEquals("abbbb", ast.get().getKleene()); ast = p.parseKPStart(new StringReader("b")); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); } /** @@ -67,23 +64,23 @@ public void testSimpleKleene() throws IOException { Optional ast; ast = p.parseKPStart(new StringReader("c")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("c", ast.get().getSimpleKleene()); + assertTrue(ast.isPresent()); + assertEquals("c", ast.get().getSimpleKleene()); ast = p.parseKPStart(new StringReader("cd")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("cd", ast.get().getSimpleKleene()); + assertTrue(ast.isPresent()); + assertEquals("cd", ast.get().getSimpleKleene()); ast = p.parseKPStart(new StringReader("cdd")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("cdd", ast.get().getSimpleKleene()); + assertTrue(ast.isPresent()); + assertEquals("cdd", ast.get().getSimpleKleene()); ast = p.parseKPStart(new StringReader("cdddd")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("cdddd", ast.get().getSimpleKleene()); + assertTrue(ast.isPresent()); + assertEquals("cdddd", ast.get().getSimpleKleene()); ast = p.parseKPStart(new StringReader("d")); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); } /** @@ -96,23 +93,23 @@ public void testSimpleKleeneString() throws IOException { Optional ast; ast = p.parseKPStart(new StringReader("ee")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("ee", ast.get().getSimpleKleeneString()); + assertTrue(ast.isPresent()); + assertEquals("ee", ast.get().getSimpleKleeneString()); ast = p.parseKPStart(new StringReader("eefg")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("eefg", ast.get().getSimpleKleeneString()); + assertTrue(ast.isPresent()); + assertEquals("eefg", ast.get().getSimpleKleeneString()); ast = p.parseKPStart(new StringReader("eefgfg")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("eefgfg", ast.get().getSimpleKleeneString()); + assertTrue(ast.isPresent()); + assertEquals("eefgfg", ast.get().getSimpleKleeneString()); ast = p.parseKPStart(new StringReader("eefgfgfgfg")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("eefgfgfgfg", ast.get().getSimpleKleeneString()); + assertTrue(ast.isPresent()); + assertEquals("eefgfgfgfg", ast.get().getSimpleKleeneString()); ast = p.parseKPStart(new StringReader("fg")); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); } /** @@ -125,22 +122,22 @@ public void testPlus() throws IOException { Optional ast; ast = p.parseKPStart(new StringReader("g")); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); ast = p.parseKPStart(new StringReader("gh")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("gh", ast.get().getPlus()); + assertTrue(ast.isPresent()); + assertEquals("gh", ast.get().getPlus()); ast = p.parseKPStart(new StringReader("ghh")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("ghh", ast.get().getPlus()); + assertTrue(ast.isPresent()); + assertEquals("ghh", ast.get().getPlus()); ast = p.parseKPStart(new StringReader("ghhhh")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("ghhhh", ast.get().getPlus()); + assertTrue(ast.isPresent()); + assertEquals("ghhhh", ast.get().getPlus()); ast = p.parseKPStart(new StringReader("h")); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); } /** @@ -153,22 +150,22 @@ public void testSimplePlus() throws IOException { Optional ast; ast = p.parseKPStart(new StringReader("i")); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); ast = p.parseKPStart(new StringReader("ij")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("ij", ast.get().getSimplePlus()); + assertTrue(ast.isPresent()); + assertEquals("ij", ast.get().getSimplePlus()); ast = p.parseKPStart(new StringReader("ijj")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("ijj", ast.get().getSimplePlus()); + assertTrue(ast.isPresent()); + assertEquals("ijj", ast.get().getSimplePlus()); ast = p.parseKPStart(new StringReader("ijjjj")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("ijjjj", ast.get().getSimplePlus()); + assertTrue(ast.isPresent()); + assertEquals("ijjjj", ast.get().getSimplePlus()); ast = p.parseKPStart(new StringReader("j")); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); } /** @@ -183,22 +180,22 @@ public void testSimplePlusString() throws IOException { ast = p.parseKPStart(new StringReader("kk")); ast = null; - Assertions.assertTrue(p.hasErrors()); + assertTrue(p.hasErrors()); ast = p.parseKPStart(new StringReader("kklm")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("kklm", ast.get().getSimplePlusString()); + assertTrue(ast.isPresent()); + assertEquals("kklm", ast.get().getSimplePlusString()); ast = p.parseKPStart(new StringReader("kklmlm")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("kklmlm", ast.get().getSimplePlusString()); + assertTrue(ast.isPresent()); + assertEquals("kklmlm", ast.get().getSimplePlusString()); ast = p.parseKPStart(new StringReader("kklmlmlmlm")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals("kklmlmlmlm", ast.get().getSimplePlusString()); + assertTrue(ast.isPresent()); + assertEquals("kklmlmlmlm", ast.get().getSimplePlusString()); ast = p.parseKPStart(new StringReader("lm")); - Assertions.assertFalse(ast.isPresent()); + assertFalse(ast.isPresent()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/lexerformat/LexRulesOrderTest.java b/monticore-test/it/src/test/java/mc/feature/lexerformat/LexRulesOrderTest.java index 6ef945325b..6655e2e0ea 100644 --- a/monticore-test/it/src/test/java/mc/feature/lexerformat/LexRulesOrderTest.java +++ b/monticore-test/it/src/test/java/mc/feature/lexerformat/LexRulesOrderTest.java @@ -2,21 +2,20 @@ package mc.feature.lexerformat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import mc.GeneratorIntegrationsTest; import mc.feature.featuredsl._parser.FeatureDSLParser; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class LexRulesOrderTest extends GeneratorIntegrationsTest { @BeforeEach @@ -29,8 +28,8 @@ public void before() { public void testOrder() throws IOException { FeatureDSLParser parser = new FeatureDSLParser(); parser.parseClassProd(new StringReader("aString")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(parser.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/lexerformat/LexerTest.java b/monticore-test/it/src/test/java/mc/feature/lexerformat/LexerTest.java index 72d10fb5e7..e7290f2b34 100644 --- a/monticore-test/it/src/test/java/mc/feature/lexerformat/LexerTest.java +++ b/monticore-test/it/src/test/java/mc/feature/lexerformat/LexerTest.java @@ -2,16 +2,12 @@ package mc.feature.lexerformat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,6 +16,8 @@ import mc.feature.lexerformat.lexerformat._ast.ASTTest2; import mc.feature.lexerformat.lexerformat._parser.LexerFormatParser; +import static org.junit.jupiter.api.Assertions.*; + public class LexerTest extends GeneratorIntegrationsTest { @BeforeEach @@ -33,11 +31,11 @@ public void test0() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("007")); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); int r = ast.get().getA(); - Assertions.assertEquals(7, r); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(7, r); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -45,55 +43,55 @@ public void test1() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("on")); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); boolean r = ast.get().isB(); - Assertions.assertEquals(true, r); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(r); + assertTrue(Log.getFindings().isEmpty()); } @Test public void test1a() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("start")); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); boolean r = ast.get().isB(); - Assertions.assertEquals(true, r); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(r); + assertTrue(Log.getFindings().isEmpty()); } @Test public void test1b() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("stop")); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); boolean r = ast.get().isB(); - Assertions.assertEquals(false, r); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(r); + assertTrue(Log.getFindings().isEmpty()); } @Test public void test1c() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("off")); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); boolean r = ast.get().isB(); - Assertions.assertEquals(false, r); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(r); + assertTrue(Log.getFindings().isEmpty()); } @Test public void test2() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("a")); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); char r = ast.get().getC(); - Assertions.assertEquals('a', r); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals('a', r); + assertTrue(Log.getFindings().isEmpty()); } @@ -101,44 +99,44 @@ public void test2() throws IOException { public void test3() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("99.5")); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); float r = ast.get().getD(); - Assertions.assertEquals(99.5f, r, 0); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(99.5f, r, 0); + assertTrue(Log.getFindings().isEmpty()); } @Test public void test4() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("*")); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); int r = ast.get().getE(); - Assertions.assertEquals(-1, r); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(-1, r); + assertTrue(Log.getFindings().isEmpty()); } @Test public void test5() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest2(new StringReader("1;1")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(ast.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void test6() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("<>")); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(ast.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void test7() throws IOException { LexerFormatParser p = new LexerFormatParser(); Optional ast = p.parseTest(new StringReader("<>fd>>")); - Assertions.assertTrue(p.hasErrors()); + assertTrue(p.hasErrors()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/linepreprocess/embedding/AutomatonOverallParserTest.java b/monticore-test/it/src/test/java/mc/feature/linepreprocess/embedding/AutomatonOverallParserTest.java index ee7d7c87d0..2b8b1dcb65 100644 --- a/monticore-test/it/src/test/java/mc/feature/linepreprocess/embedding/AutomatonOverallParserTest.java +++ b/monticore-test/it/src/test/java/mc/feature/linepreprocess/embedding/AutomatonOverallParserTest.java @@ -2,15 +2,11 @@ package mc.feature.linepreprocess.embedding; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +14,9 @@ import mc.feature.linepreprocess.embedding.automaton._ast.ASTAutomaton; import mc.feature.linepreprocess.embedding.automatonwithaction._parser.AutomatonWithActionParser; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class AutomatonOverallParserTest extends GeneratorIntegrationsTest { @BeforeEach @@ -31,9 +30,9 @@ public void testRun() throws IOException { StringReader s = new StringReader("automaton foo { a-e>b / { DUMMY_ACTION } ; } "); AutomatonWithActionParser p = new AutomatonWithActionParser(); java.util.Optional ast = p.parseAutomaton(s); - Assertions.assertFalse(p.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(p.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/listrule/ListRuleTest.java b/monticore-test/it/src/test/java/mc/feature/listrule/ListRuleTest.java index f94f77ffc2..75b1149b13 100644 --- a/monticore-test/it/src/test/java/mc/feature/listrule/ListRuleTest.java +++ b/monticore-test/it/src/test/java/mc/feature/listrule/ListRuleTest.java @@ -2,21 +2,19 @@ package mc.feature.listrule; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import mc.GeneratorIntegrationsTest; import mc.feature.listrule.listrule._parser.ListRuleParser; +import static org.junit.jupiter.api.Assertions.*; + public class ListRuleTest extends GeneratorIntegrationsTest { @BeforeEach @@ -31,14 +29,14 @@ public void testParent1() throws IOException { "P1 a, P1 b"); ListRuleParser p = new ListRuleParser(); p.parseParent(s); - - Assertions.assertEquals(false, p.hasErrors()); + + assertFalse(p.hasErrors()); // Empty lists are NOT allowed s = new StringReader(""); p.parse(s); - - Assertions.assertEquals(true, p.hasErrors()); + + assertTrue(p.hasErrors()); } @Test @@ -47,9 +45,9 @@ public void testParent2() throws IOException { "Parent2 P2 a, P2 b Parent2"); ListRuleParser p = new ListRuleParser(); p.parseParent2(s); - - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -58,9 +56,9 @@ public void testParent3() throws IOException { "P3 a, P3 b"); ListRuleParser p = new ListRuleParser(); p.parseParent3(s); - - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -69,15 +67,15 @@ public void testParent4() throws IOException { "P4 a, P4 b"); ListRuleParser p = new ListRuleParser(); p.parseParent4(s); - - Assertions.assertEquals(false, p.hasErrors()); + + assertFalse(p.hasErrors()); // Empty lists are allowed s = new StringReader(""); p.parseParent4(s); - - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); } @@ -87,7 +85,7 @@ public void testParent6() throws IOException { "a, P"); ListRuleParser p = new ListRuleParser(); p.parseParent6(s); - - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + + assertFalse(p.hasErrors()); + assertTrue(Log.getFindings().isEmpty()); }} diff --git a/monticore-test/it/src/test/java/mc/feature/mcenum/EnumTest.java b/monticore-test/it/src/test/java/mc/feature/mcenum/EnumTest.java index e02284c6a6..e85e025c1f 100644 --- a/monticore-test/it/src/test/java/mc/feature/mcenum/EnumTest.java +++ b/monticore-test/it/src/test/java/mc/feature/mcenum/EnumTest.java @@ -5,10 +5,8 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import mc.GeneratorIntegrationsTest; - import mc.feature.mcenum.enums._ast.*; import mc.feature.mcenum.enums._parser.EnumsParser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +14,7 @@ import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class EnumTest extends GeneratorIntegrationsTest { @@ -29,76 +26,76 @@ public void before() { @Test public void testa() throws IOException { - + EnumsParser p = new EnumsParser(); Optional optAst = p.parse(new StringReader("++++WORD")); - Assertions.assertTrue(optAst.isPresent()); + assertTrue(optAst.isPresent()); ASTA ast = optAst.get(); - Assertions.assertEquals(true, ast.isA()); - Assertions.assertEquals(true, ast.getE() == ASTE.PLUS); - Assertions.assertEquals(true, ast.getG() == ASTG.PLUS); - Assertions.assertEquals(true, ast.getF() == ASTF.PLUS); - Assertions.assertEquals(true, ast.getF().getIntValue() == ASTConstantsEnums.PLUS); - Assertions.assertEquals(true, ast.getF().ordinal() == 0); - Assertions.assertEquals(true, ast.getF().name() == "PLUS"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(true, ast.isA()); + assertEquals(true, ast.getE() == ASTE.PLUS); + assertEquals(true, ast.getG() == ASTG.PLUS); + assertEquals(true, ast.getF() == ASTF.PLUS); + assertEquals(true, ast.getF().getIntValue() == ASTConstantsEnums.PLUS); + assertEquals(true, ast.getF().ordinal() == 0); + assertEquals(true, ast.getF().name() == "PLUS"); + assertTrue(Log.getFindings().isEmpty()); } - @Test + @Test public void testB() throws IOException { - - EnumsParser p = new EnumsParser(); + + EnumsParser p = new EnumsParser(); Optional optAst = p.parseB(new StringReader("++,++")); - Assertions.assertTrue(optAst.isPresent()); + assertTrue(optAst.isPresent()); ASTB ast = optAst.get(); - Assertions.assertEquals(true, ast.getE(0) == ASTE.PLUS); - Assertions.assertEquals(true, ast.getE(0).getIntValue() == ASTConstantsEnums.PLUS); - Assertions.assertEquals(2, ast.sizeEs()); - Assertions.assertEquals(true, ast.getF(0) == ASTF.PLUS); - Assertions.assertEquals(true, ast.getF(0).getIntValue() == ASTConstantsEnums.PLUS); - Assertions.assertEquals(2, ast.sizeFs()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(true, ast.getE(0) == ASTE.PLUS); + assertEquals(true, ast.getE(0).getIntValue() == ASTConstantsEnums.PLUS); + assertEquals(2, ast.sizeEs()); + assertEquals(true, ast.getF(0) == ASTF.PLUS); + assertEquals(true, ast.getF(0).getIntValue() == ASTConstantsEnums.PLUS); + assertEquals(2, ast.sizeFs()); + + assertTrue(Log.getFindings().isEmpty()); } - @Test + @Test public void testB2() throws IOException { - - EnumsParser p = new EnumsParser(); + + EnumsParser p = new EnumsParser(); Optional optAst = p.parseB(new StringReader("++,#+")); - Assertions.assertTrue(optAst.isPresent()); + assertTrue(optAst.isPresent()); ASTB ast = optAst.get(); - Assertions.assertEquals(true, ast.getE(0) == ASTE.PLUS); - Assertions.assertEquals(2, ast.sizeEs()); - Assertions.assertEquals(true, ast.getF(0).ordinal() == 0); - Assertions.assertEquals(2, ast.sizeFs()); - Assertions.assertEquals(ast.getF(0), ast.getF(1)); - Assertions.assertEquals(true, ast.getF(0) == ASTF.PLUS); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertSame(ASTE.PLUS, ast.getE(0)); + assertEquals(2, ast.sizeEs()); + assertEquals(0, ast.getF(0).ordinal()); + assertEquals(2, ast.sizeFs()); + assertEquals(ast.getF(0), ast.getF(1)); + assertSame(ASTF.PLUS, ast.getF(0)); + + assertTrue(Log.getFindings().isEmpty()); } - @Test + @Test public void testB3() throws IOException { - - EnumsParser p = new EnumsParser(); + + EnumsParser p = new EnumsParser(); Optional optAst = p.parseB(new StringReader("++,#-")); - Assertions.assertTrue(optAst.isPresent()); + assertTrue(optAst.isPresent()); ASTB ast = optAst.get(); - - Assertions.assertEquals(2, ast.sizeEs()); - Assertions.assertEquals(true, ast.getE(0) == ASTE.PLUS); - Assertions.assertEquals(true, ast.getE(1) == ASTE.PLUS); - Assertions.assertEquals(2, ast.sizeFs()); - Assertions.assertEquals(true, ast.getF(0) == ASTF.PLUS); - Assertions.assertEquals(true, ast.getF(1) == ASTF.MINUS); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(2, ast.sizeEs()); + assertSame(ASTE.PLUS, ast.getE(0)); + assertSame(ASTE.PLUS, ast.getE(1)); + + assertEquals(2, ast.sizeFs()); + assertSame(ASTF.PLUS, ast.getF(0)); + assertSame(ASTF.MINUS, ast.getF(1)); + + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/multipletopsymbols/StatechartResolvingTest.java b/monticore-test/it/src/test/java/mc/feature/multipletopsymbols/StatechartResolvingTest.java index 61fa3b822e..cbfb6cc04c 100644 --- a/monticore-test/it/src/test/java/mc/feature/multipletopsymbols/StatechartResolvingTest.java +++ b/monticore-test/it/src/test/java/mc/feature/multipletopsymbols/StatechartResolvingTest.java @@ -11,7 +11,6 @@ import mc.feature.multipletopsymbols.statechart._symboltable.IStatechartGlobalScope; import mc.feature.multipletopsymbols.statechart._symboltable.StateSymbol; import mc.feature.multipletopsymbols.statechart._symboltable.StatechartSymbol; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -20,8 +19,8 @@ import java.nio.file.Paths; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class StatechartResolvingTest { @@ -44,8 +43,8 @@ public void before() { public void testResolving() throws IOException { StatechartParser parser = StatechartMill.parser(); Optional artifact = parser.parse("src/test/resources/mc/feature/multipletopsymbols/MyStatechart.sc"); - Assertions.assertTrue(artifact.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(artifact.isPresent()); + assertFalse(parser.hasErrors()); IStatechartArtifactScope as = StatechartMill.scopesGenitorDelegator().createFromAST(artifact.get()); String packageName = String.join(".", artifact.get().getPackageDeclaration().getQualifiedName().getPartList()); @@ -60,14 +59,14 @@ public void testResolving() throws IOException { Optional t = gs.resolveState("mc.feature.multipletopsymbols.MyStatechart.s.t"); Optional s2 = gs.resolveState("mc.feature.multipletopsymbols.MyStatechart.MySC.s"); Optional u = gs.resolveState("mc.feature.multipletopsymbols.MyStatechart.MySC.u"); - Assertions.assertTrue(myStatechart.isPresent()); - Assertions.assertTrue(mySC.isPresent()); - Assertions.assertTrue(s.isPresent()); - Assertions.assertTrue(t.isPresent()); - Assertions.assertTrue(s2.isPresent()); - Assertions.assertTrue(u.isPresent()); + assertTrue(myStatechart.isPresent()); + assertTrue(mySC.isPresent()); + assertTrue(s.isPresent()); + assertTrue(t.isPresent()); + assertTrue(s2.isPresent()); + assertTrue(u.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-test/it/src/test/java/mc/feature/options/MultipleOptionTest.java b/monticore-test/it/src/test/java/mc/feature/options/MultipleOptionTest.java index d1d1595015..c17cf5be58 100644 --- a/monticore-test/it/src/test/java/mc/feature/options/MultipleOptionTest.java +++ b/monticore-test/it/src/test/java/mc/feature/options/MultipleOptionTest.java @@ -2,15 +2,11 @@ package mc.feature.options; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -19,6 +15,8 @@ import mc.feature.featuredsl._parser.FeatureDSLParser; import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.*; + public class MultipleOptionTest extends GeneratorIntegrationsTest { @BeforeEach @@ -36,10 +34,10 @@ public void test() throws IOException { Optional ast = p.parseTestOptions(r); - Assertions.assertEquals(false, p.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertEquals(false, ast.get().isA()); + assertFalse(p.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(ast.get().isA()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/parserinfo/ComponentGrammarParserInfoTest.java b/monticore-test/it/src/test/java/mc/feature/parserinfo/ComponentGrammarParserInfoTest.java index 958a6cb207..95282ac3fa 100644 --- a/monticore-test/it/src/test/java/mc/feature/parserinfo/ComponentGrammarParserInfoTest.java +++ b/monticore-test/it/src/test/java/mc/feature/parserinfo/ComponentGrammarParserInfoTest.java @@ -3,7 +3,7 @@ import mc.feature.parserinfo.parserinfocomponentgrammartest._parser.ParserInfoComponentGrammarTestParserInfo; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; public class ComponentGrammarParserInfoTest { diff --git a/monticore-test/it/src/test/java/mc/feature/parserinfo/ParserInfoTest.java b/monticore-test/it/src/test/java/mc/feature/parserinfo/ParserInfoTest.java index a21a41818d..4c66aed6fa 100644 --- a/monticore-test/it/src/test/java/mc/feature/parserinfo/ParserInfoTest.java +++ b/monticore-test/it/src/test/java/mc/feature/parserinfo/ParserInfoTest.java @@ -4,43 +4,35 @@ import de.se_rwth.commons.logging.LogStub; import mc.feature.parserinfo.parserinfosimpleinheritancetest._parser._auxiliary.ParserInfoSimpleInheritanceTestParserInfoForParserInfoTest; import mc.feature.parserinfo.parserinfotest._parser.ParserInfoTestParserInfo; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.Arrays; -import java.util.Collection; + import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; -import static org.junit.Assert.*; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; /** * Test the generated ParserInfo classes. * Since the concrete antlr state numbers are not stable, we must always check a range of state numbers. */ -@RunWith(Parameterized.class) +@ParameterizedClass +@ValueSource(booleans = {true, false}) public class ParserInfoTest { + @Parameter private boolean useSimpleInheritance; - @Parameterized.Parameters - public static Collection data(){ - return Arrays.asList(new Boolean[]{false}, new Boolean[]{true}); - } - - public ParserInfoTest(boolean useSimpleInheritance){ - this.useSimpleInheritance = useSimpleInheritance; - } - // The generated parser has around 125 states // => add some safety margin private final int MAX_STATE_NUMBER = 250; - @Before + @BeforeEach public void init(){ if(useSimpleInheritance){ ParserInfoTestParserInfo.initMe(new ParserInfoSimpleInheritanceTestParserInfoForParserInfoTest()); @@ -49,7 +41,7 @@ public void init(){ } } - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/it/src/test/java/mc/feature/replacekeyword/ReplaceRuleTest.java b/monticore-test/it/src/test/java/mc/feature/replacekeyword/ReplaceRuleTest.java index 1180d2b7b5..a65b90709f 100644 --- a/monticore-test/it/src/test/java/mc/feature/replacekeyword/ReplaceRuleTest.java +++ b/monticore-test/it/src/test/java/mc/feature/replacekeyword/ReplaceRuleTest.java @@ -7,14 +7,13 @@ import mc.GeneratorIntegrationsTest; import mc.feature.replacerule.replacerule2.ReplaceRule2Mill; import mc.feature.replacerule.replacerule2._parser.ReplaceRule2Parser; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ReplaceRuleTest extends GeneratorIntegrationsTest { @@ -30,38 +29,38 @@ public void test() throws IOException { // Replace keyword parser.parse_StringA("a1 Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); parser.parse_StringA("A Foo"); - Assertions.assertTrue(parser.hasErrors()); + assertTrue(parser.hasErrors()); // Add keyword in combination with nokeyword parser.parse_StringB("BLA Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); parser.parse_StringB("bla Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); // Replace keyword in combination with key parser.parse_StringC("bla_c Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); parser.parse_StringC("BLA_C Foo"); - Assertions.assertTrue(parser.hasErrors()); + assertTrue(parser.hasErrors()); // Replace keyword in combination with splittoken parser.parse_StringD("}} Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); parser.parse_StringD(">> Foo"); - Assertions.assertTrue(parser.hasErrors()); + assertTrue(parser.hasErrors()); // Add keyword in combination with token parser.parse_StringE("{{ Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); parser.parse_StringE("<< Foo"); - Assertions.assertFalse(parser.hasErrors()); + assertFalse(parser.hasErrors()); } diff --git a/monticore-test/it/src/test/java/mc/feature/scoperules/ScoperuleTest.java b/monticore-test/it/src/test/java/mc/feature/scoperules/ScoperuleTest.java index 560381c96d..04fefba05a 100644 --- a/monticore-test/it/src/test/java/mc/feature/scoperules/ScoperuleTest.java +++ b/monticore-test/it/src/test/java/mc/feature/scoperules/ScoperuleTest.java @@ -9,17 +9,16 @@ import mc.feature.scoperules.scoperuletest._parser.ScoperuleTestParser; import mc.feature.scoperules.scoperuletest._symboltable.*; import mc.feature.scoperules.scoperuletest._ast.ASTFoo; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class ScoperuleTest { @BeforeEach @@ -39,7 +38,7 @@ public void setup(){ public void testModel() throws IOException { ScoperuleTestParser parser = ScoperuleTestMill.parser(); Optional optModel = parser.parse("src/test/resources/mc/feature/symbolrules/SymbolruleTest.rule"); - Assertions.assertTrue(optModel.isPresent()); + assertTrue(optModel.isPresent()); ScoperuleTestScopesGenitorDelegator scopesGenitorDelegator = ScoperuleTestMill.scopesGenitorDelegator(); IScoperuleTestArtifactScope scope = scopesGenitorDelegator.createFromAST(optModel.get()); @@ -52,26 +51,26 @@ public void testModel() throws IOException { scope.accept(symbols2Json.getTraverser()); String serialized = symbols2Json.getSerializedString(); IScoperuleTestScope as = symbols2Json.deserialize(serialized); - Assertions.assertTrue(as.isBar()); - Assertions.assertEquals(17, as.getNumber()); - Assertions.assertEquals(3, as.getModifiedNameList().size()); - Assertions.assertEquals("foo", as.getModifiedName(0)); - Assertions.assertEquals("bar", as.getModifiedName(1)); - Assertions.assertEquals("test", as.getModifiedName(2)); - Assertions.assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(as.getSymType())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(as.isBar()); + assertEquals(17, as.getNumber()); + assertEquals(3, as.getModifiedNameList().size()); + assertEquals("foo", as.getModifiedName(0)); + assertEquals("bar", as.getModifiedName(1)); + assertEquals("test", as.getModifiedName(2)); + assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(as.getSymType())); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExtendsAndImplements(){ IScoperuleTestScope scope = ScoperuleTestMill.scope(); - - Assertions.assertTrue(scope instanceof ScoperuleTestScope); + + assertInstanceOf(ScoperuleTestScope.class, scope); Dummy dummy = (ScoperuleTestScope) scope; - - Assertions.assertTrue(scope instanceof IDummy); + + assertInstanceOf(IDummy.class, scope); IDummy dummyI = (IDummy) scope; - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/scopes/ScopeInheritanceTest.java b/monticore-test/it/src/test/java/mc/feature/scopes/ScopeInheritanceTest.java new file mode 100644 index 0000000000..f5a1e1ae5f --- /dev/null +++ b/monticore-test/it/src/test/java/mc/feature/scopes/ScopeInheritanceTest.java @@ -0,0 +1,147 @@ +/* (c) https://github.com/MontiCore/monticore */ +package mc.feature.scopes; + +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; +import mc.feature.scopes.scopeinheritance.ScopeInheritanceMill; +import mc.feature.scopes.scopeinheritance._ast.ASTStartProd; +import mc.feature.scopes.scopeinheritance._parser.ScopeInheritanceParser; +import mc.feature.scopes.scopeinheritance._symboltable.IScopeInheritanceArtifactScope; +import mc.feature.scopes.scopeinheritance._symboltable.IScopeInheritanceGlobalScope; +import mc.feature.scopes.scopeinheritance._symboltable.IScopeInheritanceScope; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.Optional; +import com.google.common.base.Preconditions; + +/** + * test that the attributes of scope in the grammar like shadowing, exporting, ordering are inherited correctly + * NOTE: there can be no conflicts as default values can not be set explicitly. + * only the attributes shadowing non_exporting and ordered are inherited + */ +public class ScopeInheritanceTest { + + private ASTStartProd startProd; + private IScopeInheritanceArtifactScope scope; + + @BeforeEach + public void before() { + LogStub.init(); + Log.enableFailQuick(false); + ScopeInheritanceMill.reset(); + ScopeInheritanceMill.init(); + } + + @BeforeEach + public void Setup() throws IOException { + ScopeInheritanceParser scopeInheritanceParser = ScopeInheritanceMill.parser(); + Optional astInheritance = scopeInheritanceParser.parse("src/test/resources/mc/feature/scopes/ScopeInheritanceModel.st"); + Assertions.assertFalse(scopeInheritanceParser.hasErrors()); + Assertions.assertTrue(astInheritance.isPresent()); + startProd = astInheritance.get(); + + IScopeInheritanceGlobalScope globalScope = ScopeInheritanceMill.globalScope(); + scope = ScopeInheritanceMill.scopesGenitorDelegator().createFromAST(astInheritance.get()); + } + + /** + * test all combinations of inherited scope attributes + */ + @Test + public void testScopeInheritanceA() { + Assertions.assertEquals(2, startProd.getAList().size()); + IScopeInheritanceScope scopeShadowingNonExportingOrdered = startProd.getAList().get(0).getSpannedScope(); + Preconditions.checkNotNull(scopeShadowingNonExportingOrdered); + Assertions.assertFalse(scopeShadowingNonExportingOrdered.isExportingSymbols()); + Assertions.assertTrue(scopeShadowingNonExportingOrdered.isShadowing()); + Assertions.assertTrue(scopeShadowingNonExportingOrdered.isOrdered()); + + scopeShadowingNonExportingOrdered = startProd.getAList().get(1).getSpannedScope(); + Preconditions.checkNotNull(scopeShadowingNonExportingOrdered); + Assertions.assertFalse(scopeShadowingNonExportingOrdered.isExportingSymbols()); + Assertions.assertTrue(scopeShadowingNonExportingOrdered.isShadowing()); + Assertions.assertTrue(scopeShadowingNonExportingOrdered.isOrdered()); + + Assertions.assertTrue(Log.getFindings().isEmpty()); + } + + @Test + public void testScopeInheritanceB() { + Assertions.assertEquals(1, startProd.getBList().size()); + IScopeInheritanceScope scopeShadowingNonExporting = startProd.getBList().get(0).getSpannedScope(); + Preconditions.checkNotNull(scopeShadowingNonExporting); + Assertions.assertFalse(scopeShadowingNonExporting.isExportingSymbols()); + Assertions.assertTrue(scopeShadowingNonExporting.isShadowing()); + Assertions.assertFalse(scopeShadowingNonExporting.isOrdered()); + Assertions.assertTrue(Log.getFindings().isEmpty()); + } + + @Test + public void testScopeInheritanceC() { + Assertions.assertEquals(1, startProd.getCList().size()); + IScopeInheritanceScope scopeShadowingOrdered = startProd.getCList().get(0).getSpannedScope(); + Preconditions.checkNotNull(scopeShadowingOrdered); + Assertions.assertTrue(scopeShadowingOrdered.isExportingSymbols()); + Assertions.assertTrue(scopeShadowingOrdered.isShadowing()); + Assertions.assertTrue(scopeShadowingOrdered.isOrdered()); + Assertions.assertTrue(Log.getFindings().isEmpty()); + } + + @Test + public void testScopeInheritanceD() { + Assertions.assertEquals(1, startProd.getDList().size()); + IScopeInheritanceScope scopeNonExportingOrdered = startProd.getDList().get(0).getSpannedScope(); + Preconditions.checkNotNull(scopeNonExportingOrdered); + Assertions.assertFalse(scopeNonExportingOrdered.isExportingSymbols()); + Assertions.assertFalse(scopeNonExportingOrdered.isShadowing()); + Assertions.assertTrue(scopeNonExportingOrdered.isOrdered()); + Assertions.assertTrue(Log.getFindings().isEmpty()); + } + + @Test + public void testScopeInheritanceE() { + Assertions.assertEquals(1, startProd.getEList().size()); + IScopeInheritanceScope scopeShadowing = startProd.getEList().get(0).getSpannedScope(); + Preconditions.checkNotNull(scopeShadowing); + Assertions.assertTrue(scopeShadowing.isExportingSymbols()); + Assertions.assertTrue(scopeShadowing.isShadowing()); + Assertions.assertFalse(scopeShadowing.isOrdered()); + Assertions.assertTrue(Log.getFindings().isEmpty()); + } + + @Test + public void testScopeInheritanceF() { + Assertions.assertEquals(1, startProd.getFList().size()); + IScopeInheritanceScope scopeNonExporting = startProd.getFList().get(0).getSpannedScope(); + Preconditions.checkNotNull(scopeNonExporting); + Assertions.assertFalse(scopeNonExporting.isExportingSymbols()); + Assertions.assertFalse(scopeNonExporting.isShadowing()); + Assertions.assertFalse(scopeNonExporting.isOrdered()); + Assertions.assertTrue(Log.getFindings().isEmpty()); + } + + @Test + public void testScopeInheritanceG() { + Assertions.assertEquals(1, startProd.getGList().size()); + IScopeInheritanceScope scopeOrdered = startProd.getGList().get(0).getSpannedScope(); + Preconditions.checkNotNull(scopeOrdered); + Assertions.assertTrue(scopeOrdered.isExportingSymbols()); + Assertions.assertFalse(scopeOrdered.isShadowing()); + Assertions.assertTrue(scopeOrdered.isOrdered()); + Assertions.assertTrue(Log.getFindings().isEmpty()); + } + + @Test + public void testScopeInheritanceH() { + Assertions.assertEquals(1, startProd.getHList().size()); + IScopeInheritanceScope scopeDefault = startProd.getHList().get(0).getSpannedScope(); + Preconditions.checkNotNull(scopeDefault); + Assertions.assertTrue(scopeDefault.isExportingSymbols()); + Assertions.assertFalse(scopeDefault.isShadowing()); + Assertions.assertFalse(scopeDefault.isOrdered()); + Assertions.assertTrue(Log.getFindings().isEmpty()); + } +} \ No newline at end of file diff --git a/monticore-test/it/src/test/java/mc/feature/scopes/ScopesTest.java b/monticore-test/it/src/test/java/mc/feature/scopes/ScopesTest.java index b3e28caf5f..1aa31f1f03 100644 --- a/monticore-test/it/src/test/java/mc/feature/scopes/ScopesTest.java +++ b/monticore-test/it/src/test/java/mc/feature/scopes/ScopesTest.java @@ -19,8 +19,8 @@ import java.nio.file.Paths; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ScopesTest { @@ -40,8 +40,8 @@ public void setUp() throws IOException { SupAutomatonMill.init(); SupAutomatonParser supAutomatonParser = new SupAutomatonParser(); Optional astSup = supAutomatonParser.parse("src/test/resources/mc/feature/scopes/SupAutomatonModel.aut"); - Assertions.assertFalse(supAutomatonParser.hasErrors()); - Assertions.assertTrue(astSup.isPresent()); + assertFalse(supAutomatonParser.hasErrors()); + assertTrue(astSup.isPresent()); ISupAutomatonGlobalScope globalScope = SupAutomatonMill.globalScope(); globalScope.setFileExt("aut"); @@ -71,13 +71,13 @@ public void testResolvingFromGrammarScope(){ //findet also voll qualifiziert auch vom global aus Optional pingStateSymbolGlobal = globalScope.resolveState("TopPingPong.PingPong.Ping"); - Assertions.assertTrue(pingPongAutomatonSymbolLokal.isPresent()); - Assertions.assertTrue(pingPongAutomatonSymbolGlobal.isPresent()); - Assertions.assertTrue(pingStateSymbol.isPresent()); - Assertions.assertTrue(pongStateSymbol.isPresent()); - Assertions.assertTrue(noGameStateSymbol.isPresent()); - Assertions.assertTrue(pingStateSymbolGlobal.isPresent()); + assertTrue(pingPongAutomatonSymbolLokal.isPresent()); + assertTrue(pingPongAutomatonSymbolGlobal.isPresent()); + assertTrue(pingStateSymbol.isPresent()); + assertTrue(pongStateSymbol.isPresent()); + assertTrue(noGameStateSymbol.isPresent()); + assertTrue(pingStateSymbolGlobal.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/semanticpredicate/SemPredWithInterfaceParserTest.java b/monticore-test/it/src/test/java/mc/feature/semanticpredicate/SemPredWithInterfaceParserTest.java index 1ec00b4104..9579a750bc 100644 --- a/monticore-test/it/src/test/java/mc/feature/semanticpredicate/SemPredWithInterfaceParserTest.java +++ b/monticore-test/it/src/test/java/mc/feature/semanticpredicate/SemPredWithInterfaceParserTest.java @@ -2,16 +2,10 @@ package mc.feature.semanticpredicate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -20,6 +14,8 @@ import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class SemPredWithInterfaceParserTest extends GeneratorIntegrationsTest { @BeforeEach @@ -36,15 +32,15 @@ public void testParse() { try { ast = p.parseISequence(new StringReader(input)); } catch (IOException e) { - Assertions.fail(); + fail(); } - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); ASTISequence seq = ast.get(); - Assertions.assertEquals(2, seq.getIList().size()); + assertEquals(2, seq.getIList().size()); - Assertions.assertTrue(seq.getIList().get(0).isFirst()); - Assertions.assertFalse(seq.getIList().get(1).isFirst()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(seq.getIList().get(0).isFirst()); + assertFalse(seq.getIList().get(1).isFirst()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/sourcepositions/ExpressionSourcePositionsTest.java b/monticore-test/it/src/test/java/mc/feature/sourcepositions/ExpressionSourcePositionsTest.java index 5e8b3bc5fe..c292d8f093 100644 --- a/monticore-test/it/src/test/java/mc/feature/sourcepositions/ExpressionSourcePositionsTest.java +++ b/monticore-test/it/src/test/java/mc/feature/sourcepositions/ExpressionSourcePositionsTest.java @@ -2,14 +2,11 @@ package mc.feature.sourcepositions; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -18,6 +15,9 @@ import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Tests the source position's computing for the AST nodes * Defined grammar: mc.feature.expression.Expression.mc @@ -53,30 +53,33 @@ private void doTestPExpSourcePositions(ASTExpr node) { ASTExpr leftChild = null; if (node.isPresentLeft()) { leftChild = node.getLeft(); - Assertions.assertTrue(node.get_SourcePositionStart().compareTo(leftChild.get_SourcePositionStart()) == 0); + assertEquals(0, + node.get_SourcePositionStart().compareTo(leftChild.get_SourcePositionStart())); if (node.isPresentRight()) { ASTExpr rightChild = node.getRight(); // End position of expression node coincides with the end position of // the right child - Assertions.assertTrue(node.get_SourcePositionEnd().compareTo(rightChild.get_SourcePositionEnd()) == 0); + assertEquals(0, + node.get_SourcePositionEnd().compareTo(rightChild.get_SourcePositionEnd())); // Start position of the right child is the next to the end position of // the left child - Assertions.assertTrue(rightChild.get_SourcePositionStart().getColumn() - - leftChild.get_SourcePositionEnd().getColumn() == 1); + assertEquals(1, + rightChild.get_SourcePositionStart().getColumn() - leftChild.get_SourcePositionEnd() + .getColumn()); } } node = leftChild; } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private ASTExpr parse(String input) throws IOException { ExpressionParser parser = new ExpressionParser(); Optional ast = parser.parseExpr(new StringReader(input)); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); return ast.get(); } diff --git a/monticore-test/it/src/test/java/mc/feature/symbolrules/SymbolruleTest.java b/monticore-test/it/src/test/java/mc/feature/symbolrules/SymbolruleTest.java index 2faecb6ba2..23d17bf9b9 100644 --- a/monticore-test/it/src/test/java/mc/feature/symbolrules/SymbolruleTest.java +++ b/monticore-test/it/src/test/java/mc/feature/symbolrules/SymbolruleTest.java @@ -14,17 +14,16 @@ import mc.feature.symbolrules.symbolruletest._ast.ASTFoo; import mc.feature.symbolrules.symbolruletest._parser.SymbolruleTestParser; import mc.feature.symbolrules.symbolruletest._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.*; + public class SymbolruleTest { @BeforeEach @@ -48,8 +47,8 @@ public void testSymbols(){ FooSymbolDeSer fooSymbolDeSer = new FooSymbolDeSer(); String serializedFoo = fooSymbolDeSer.serialize(fooSymbol, new SymbolruleTestSymbols2Json()); FooSymbol deserializedFoo = fooSymbolDeSer.deserialize(serializedFoo); - Assertions.assertEquals(fooSymbol.getName(), deserializedFoo.getName()); - Assertions.assertEquals(fooSymbol.getBarName(), deserializedFoo.getBarName()); + assertEquals(fooSymbol.getName(), deserializedFoo.getName()); + assertEquals(fooSymbol.getBarName(), deserializedFoo.getBarName()); ITestSymbol itest = SymbolruleTestMill.iTestSymbolBuilder().setName("itest").build(); @@ -57,10 +56,10 @@ public void testSymbols(){ ITestSymbolDeSer iTestSymbolDeSer = new ITestSymbolDeSer(); String serializedITest = iTestSymbolDeSer.serialize(itest, new SymbolruleTestSymbols2Json()); ITestSymbol deserializedITest = iTestSymbolDeSer.deserialize(serializedITest); - Assertions.assertEquals(itest.getName(), deserializedITest.getName()); - Assertions.assertEquals(1, deserializedITest.sizeSuperTypes()); - Assertions.assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedITest.getSuperTypes(0))); - Assertions.assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedITest.getByName("int"))); + assertEquals(itest.getName(), deserializedITest.getName()); + assertEquals(1, deserializedITest.sizeSuperTypes()); + assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedITest.getSuperTypes(0))); + assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedITest.getByName("int"))); Test1Symbol test1 = SymbolruleTestMill.test1SymbolBuilder().setName("test11").build(); test1.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createPrimitive("int"))); @@ -68,12 +67,12 @@ public void testSymbols(){ Test1SymbolDeSer test1SymbolDeSer = new Test1SymbolDeSer(); String serializedTest1 = test1SymbolDeSer.serialize(test1, new SymbolruleTestSymbols2Json()); Test1Symbol deserializedTest1 = test1SymbolDeSer.deserialize(serializedTest1); - Assertions.assertEquals(test1.getName(), deserializedTest1.getName()); - Assertions.assertEquals(1, deserializedTest1.sizeSuperTypes()); - Assertions.assertTrue(deserializedTest1.isIsPrivate()); - Assertions.assertEquals(deserializedTest1, deserializedTest1.getIfPrivate()); - Assertions.assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedTest1.getSuperTypes(0))); - Assertions.assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedTest1.getByName("int"))); + assertEquals(test1.getName(), deserializedTest1.getName()); + assertEquals(1, deserializedTest1.sizeSuperTypes()); + assertTrue(deserializedTest1.isIsPrivate()); + assertEquals(deserializedTest1, deserializedTest1.getIfPrivate()); + assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedTest1.getSuperTypes(0))); + assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedTest1.getByName("int"))); Test2Symbol test2 = SymbolruleTestMill.test2SymbolBuilder().setName("test22").build(); test2.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createPrimitive("int"))); @@ -81,20 +80,20 @@ public void testSymbols(){ Test2SymbolDeSer test2SymbolDeSer = new Test2SymbolDeSer(); String serializedTest2 = test2SymbolDeSer.serialize(test2, new SymbolruleTestSymbols2Json()); Test2Symbol deserializedTest2 = test2SymbolDeSer.deserialize(serializedTest2); - Assertions.assertEquals(test2.getName(), deserializedTest2.getName()); - Assertions.assertEquals(1, deserializedTest2.sizeSuperTypes()); - Assertions.assertTrue(deserializedTest2.isIsPublic()); - Assertions.assertEquals(deserializedTest2, deserializedTest2.getIfPublic()); - Assertions.assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedTest2.getSuperTypes(0))); - Assertions.assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedTest2.getByName("int"))); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(test2.getName(), deserializedTest2.getName()); + assertEquals(1, deserializedTest2.sizeSuperTypes()); + assertTrue(deserializedTest2.isIsPublic()); + assertEquals(deserializedTest2, deserializedTest2.getIfPublic()); + assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedTest2.getSuperTypes(0))); + assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(deserializedTest2.getByName("int"))); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testModel() throws IOException { SymbolruleTestParser parser = SymbolruleTestMill.parser(); Optional model = parser.parse("src/test/resources/mc/feature/symbolrules/SymbolruleTest.rule"); - Assertions.assertTrue(model.isPresent()); + assertTrue(model.isPresent()); SymbolruleTestScopesGenitorDelegator scopesGenitor = SymbolruleTestMill.scopesGenitorDelegator(); ISymbolruleTestArtifactScope as = scopesGenitor.createFromAST(model.get()); @@ -109,50 +108,50 @@ public void testModel() throws IOException { String serialized = symbols2Json.getSerializedString(); ISymbolruleTestArtifactScope as2 = symbols2Json.deserialize(serialized); - Assertions.assertEquals(as.getName(), as2.getName()); - Assertions.assertEquals(as.getSymbolsSize(), as2.getSymbolsSize()); - Assertions.assertTrue(as2.isBar()); - Assertions.assertEquals(17, as2.getNumber()); - Assertions.assertEquals(3, as.getModifiedNameList().size()); - Assertions.assertEquals("foo", as.getModifiedName(0)); - Assertions.assertEquals("bar", as.getModifiedName(1)); - Assertions.assertEquals("test", as.getModifiedName(2)); - Assertions.assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(as2.getSymType())); - Assertions.assertEquals(1, as2.getLocalFooSymbols().size()); + assertEquals(as.getName(), as2.getName()); + assertEquals(as.getSymbolsSize(), as2.getSymbolsSize()); + assertTrue(as2.isBar()); + assertEquals(17, as2.getNumber()); + assertEquals(3, as.getModifiedNameList().size()); + assertEquals("foo", as.getModifiedName(0)); + assertEquals("bar", as.getModifiedName(1)); + assertEquals("test", as.getModifiedName(2)); + assertTrue(SymTypeExpressionFactory.createPrimitive("int").deepEquals(as2.getSymType())); + assertEquals(1, as2.getLocalFooSymbols().size()); ISymbolruleTestScope fooSpannedScope = as2.getLocalFooSymbols().get(0).getSpannedScope(); - Assertions.assertEquals(2, fooSpannedScope.getLocalBarSymbols().size()); - Assertions.assertEquals("Test1", fooSpannedScope.getLocalBarSymbols().get(0).getName()); - Assertions.assertEquals("Test2", fooSpannedScope.getLocalBarSymbols().get(1).getName()); + assertEquals(2, fooSpannedScope.getLocalBarSymbols().size()); + assertEquals("Test1", fooSpannedScope.getLocalBarSymbols().get(0).getName()); + assertEquals("Test2", fooSpannedScope.getLocalBarSymbols().get(1).getName()); ISymbolruleTestScope bar1SpannedScope = fooSpannedScope.getLocalBarSymbols().get(0).getSpannedScope(); - Assertions.assertEquals(2, bar1SpannedScope.getLocalTest1Symbols().size()); - Assertions.assertEquals("symbol1", bar1SpannedScope.getLocalTest1Symbols().get(0).getName()); - Assertions.assertEquals("symbol11", bar1SpannedScope.getLocalTest1Symbols().get(1).getName()); - Assertions.assertEquals(1, bar1SpannedScope.getLocalTest2Symbols().size()); - Assertions.assertEquals("symbol2", bar1SpannedScope.getLocalTest2Symbols().get(0).getName()); + assertEquals(2, bar1SpannedScope.getLocalTest1Symbols().size()); + assertEquals("symbol1", bar1SpannedScope.getLocalTest1Symbols().get(0).getName()); + assertEquals("symbol11", bar1SpannedScope.getLocalTest1Symbols().get(1).getName()); + assertEquals(1, bar1SpannedScope.getLocalTest2Symbols().size()); + assertEquals("symbol2", bar1SpannedScope.getLocalTest2Symbols().get(0).getName()); ISymbolruleTestScope bar2SpannedScope = fooSpannedScope.getLocalBarSymbols().get(1).getSpannedScope(); - Assertions.assertEquals(2, bar2SpannedScope.getLocalTest1Symbols().size()); - Assertions.assertEquals("symbol3", bar2SpannedScope.getLocalTest1Symbols().get(0).getName()); - Assertions.assertEquals("symbol4", bar2SpannedScope.getLocalTest1Symbols().get(1).getName()); - Assertions.assertEquals(1, bar2SpannedScope.getLocalTest2Symbols().size()); - Assertions.assertEquals("symbol22", bar2SpannedScope.getLocalTest2Symbols().get(0).getName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(2, bar2SpannedScope.getLocalTest1Symbols().size()); + assertEquals("symbol3", bar2SpannedScope.getLocalTest1Symbols().get(0).getName()); + assertEquals("symbol4", bar2SpannedScope.getLocalTest1Symbols().get(1).getName()); + assertEquals(1, bar2SpannedScope.getLocalTest2Symbols().size()); + assertEquals("symbol22", bar2SpannedScope.getLocalTest2Symbols().get(0).getName()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExtendsAndImplements(){ IBarSymbol symbol = SymbolruleTestMill.barSymbolBuilder().setName("lala").build(); - Assertions.assertTrue(symbol instanceof Dummy); + assertInstanceOf(Dummy.class, symbol); Dummy dummy = (Dummy) symbol; - Assertions.assertTrue(symbol instanceof IDummy); + assertInstanceOf(IDummy.class, symbol); IDummy iDummy = (IDummy) symbol; - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSymbolruleListAttributes() throws IOException{ SymbolruleListTestParser parser = SymbolruleListTestMill.parser(); Optional opt = parser.parse("src/test/resources/mc/feature/symbolrules/SymbolruleTest.rule"); - Assertions.assertTrue(opt.isPresent()); + assertTrue(opt.isPresent()); SymbolruleListTestScopesGenitorDelegator scopesGenitor = SymbolruleListTestMill.scopesGenitorDelegator(); ISymbolruleListTestArtifactScope as = scopesGenitor.createFromAST(opt.get()); as.setName("SymbolruleTest"); @@ -169,34 +168,34 @@ public void testSymbolruleListAttributes() throws IOException{ String serialized = symbols2Json.getSerializedString(); ISymbolruleListTestArtifactScope as2 = symbols2Json.deserialize(serialized); - Assertions.assertEquals(as.getName(), as2.getName()); - Assertions.assertEquals(as.sizeNumbers(), as2.sizeNumbers()); - Assertions.assertEquals(as.getNumbers(0), as2.getNumbers(0)); - Assertions.assertEquals(as.getNumbers(1), as2.getNumbers(1)); - Assertions.assertEquals(as.getNumbers(2), as2.getNumbers(2)); - Assertions.assertEquals(as.sizeNames(), as2.sizeNames()); - Assertions.assertEquals(as.getNames(0), as2.getNames(0)); - Assertions.assertEquals(as.getNames(1), as2.getNames(1)); - Assertions.assertEquals(as.getNames(2), as2.getNames(2)); - Assertions.assertEquals(as.sizeSymTypes(), as2.sizeSymTypes()); - Assertions.assertTrue(as.getSymTypes(0).deepEquals(as2.getSymTypes(0))); - Assertions.assertTrue(as.getSymTypes(1).deepEquals(as2.getSymTypes(1))); - Assertions.assertEquals(as.sizeArePresent(), as2.sizeArePresent()); - Assertions.assertEquals(as.getArePresent(0), as2.getArePresent(0)); - Assertions.assertEquals(as.getArePresent(1), as2.getArePresent(1)); - Assertions.assertEquals(as.getArePresent(2), as2.getArePresent(2)); - Assertions.assertEquals(as.getArePresent(3), as2.getArePresent(3)); - Assertions.assertEquals(as.sizeBigNumbers(), as2.sizeBigNumbers()); - Assertions.assertEquals(as.getBigNumbers(0), as2.getBigNumbers(0)); - Assertions.assertEquals(as.sizeDoubleFloatingPoints(), as2.sizeDoubleFloatingPoints()); - Assertions.assertEquals(as.getDoubleFloatingPoints(0), as2.getDoubleFloatingPoints(0)); - Assertions.assertEquals(as.getDoubleFloatingPoints(1), as2.getDoubleFloatingPoints(1)); - Assertions.assertEquals(as.getDoubleFloatingPoints(2), as2.getDoubleFloatingPoints(2)); - Assertions.assertEquals(as.sizeFloatingPoints(), as2.sizeFloatingPoints()); - Assertions.assertEquals(as.getFloatingPoints(0), as2.getFloatingPoints(0)); - Assertions.assertEquals(as.getFloatingPoints(1), as2.getFloatingPoints(1)); - Assertions.assertEquals(as.getFloatingPoints(2), as2.getFloatingPoints(2)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(as.getName(), as2.getName()); + assertEquals(as.sizeNumbers(), as2.sizeNumbers()); + assertEquals(as.getNumbers(0), as2.getNumbers(0)); + assertEquals(as.getNumbers(1), as2.getNumbers(1)); + assertEquals(as.getNumbers(2), as2.getNumbers(2)); + assertEquals(as.sizeNames(), as2.sizeNames()); + assertEquals(as.getNames(0), as2.getNames(0)); + assertEquals(as.getNames(1), as2.getNames(1)); + assertEquals(as.getNames(2), as2.getNames(2)); + assertEquals(as.sizeSymTypes(), as2.sizeSymTypes()); + assertTrue(as.getSymTypes(0).deepEquals(as2.getSymTypes(0))); + assertTrue(as.getSymTypes(1).deepEquals(as2.getSymTypes(1))); + assertEquals(as.sizeArePresent(), as2.sizeArePresent()); + assertEquals(as.getArePresent(0), as2.getArePresent(0)); + assertEquals(as.getArePresent(1), as2.getArePresent(1)); + assertEquals(as.getArePresent(2), as2.getArePresent(2)); + assertEquals(as.getArePresent(3), as2.getArePresent(3)); + assertEquals(as.sizeBigNumbers(), as2.sizeBigNumbers()); + assertEquals(as.getBigNumbers(0), as2.getBigNumbers(0)); + assertEquals(as.sizeDoubleFloatingPoints(), as2.sizeDoubleFloatingPoints()); + assertEquals(as.getDoubleFloatingPoints(0), as2.getDoubleFloatingPoints(0)); + assertEquals(as.getDoubleFloatingPoints(1), as2.getDoubleFloatingPoints(1)); + assertEquals(as.getDoubleFloatingPoints(2), as2.getDoubleFloatingPoints(2)); + assertEquals(as.sizeFloatingPoints(), as2.sizeFloatingPoints()); + assertEquals(as.getFloatingPoints(0), as2.getFloatingPoints(0)); + assertEquals(as.getFloatingPoints(1), as2.getFloatingPoints(1)); + assertEquals(as.getFloatingPoints(2), as2.getFloatingPoints(2)); + assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo1Test.java b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo1Test.java index 4f5c025cb4..915c09b56d 100644 --- a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo1Test.java +++ b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo1Test.java @@ -5,13 +5,14 @@ import de.se_rwth.commons.logging.LogStub; import mc.GeneratorIntegrationsTest; import mc.feature.symboltable.automatonwithstinfo1._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class AutomatonWithSTInfo1Test extends GeneratorIntegrationsTest { @BeforeEach @@ -32,11 +33,11 @@ public void test() { AutomatonSymbolSurrogate automatonSymbolSurrogate; AutomatonWithSTInfo1ScopesGenitorDelegator automatonWithSTInfo1SymbolTableCreator; StateSymbol stateSymbol = new StateSymbol("S"); - Assertions.assertTrue(stateSymbol instanceof StateSymbol); + assertInstanceOf(StateSymbol.class, stateSymbol); // Collection stateSymbols2 = stateSymbol.getStates(); StateSymbolSurrogate stateSymbolReference; - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo2Test.java b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo2Test.java index 175b9e73f1..47909b1f12 100644 --- a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo2Test.java +++ b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo2Test.java @@ -6,14 +6,13 @@ import de.se_rwth.commons.logging.LogStub; import mc.GeneratorIntegrationsTest; import mc.feature.symboltable.automatonwithstinfo2._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.*; + public class AutomatonWithSTInfo2Test extends GeneratorIntegrationsTest { @BeforeEach @@ -29,14 +28,14 @@ public void before() { @Test public void test() { AutomatonElementSymbol automatonElementSymbol = new AutomatonElementSymbol("A"); - Assertions.assertFalse(automatonElementSymbol instanceof IScopeSpanningSymbol); + assertFalse(automatonElementSymbol instanceof IScopeSpanningSymbol); AutomatonWithSTInfo2Scope automatonScope; AutomatonSymbol automatonSymbol = new AutomatonSymbol("A"); - Assertions.assertTrue(automatonSymbol instanceof IScopeSpanningSymbol); + assertInstanceOf(IScopeSpanningSymbol.class, automatonSymbol); // Collection automatonElementSymbols = automatonSymbol.getAutomatonElements(); AutomatonSymbolSurrogate automatonSymbolSurrogate; AutomatonWithSTInfo2ScopesGenitorDelegator automatonWithSTInfo2SymbolTableCreator; - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo3Test.java b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo3Test.java index 66d6b41307..a37267138b 100644 --- a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo3Test.java +++ b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo3Test.java @@ -7,14 +7,14 @@ import mc.GeneratorIntegrationsTest; import mc.feature.symboltable.automatonwithstinfo3.AutomatonWithSTInfo3Mill; import mc.feature.symboltable.automatonwithstinfo3._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class AutomatonWithSTInfo3Test extends GeneratorIntegrationsTest { @BeforeEach @@ -30,7 +30,7 @@ public void before() { @Test public void test() { AutomatonSymbol automatonSymbol = new AutomatonSymbol("A"); - Assertions.assertFalse(automatonSymbol instanceof IScopeSpanningSymbol); + assertFalse(automatonSymbol instanceof IScopeSpanningSymbol); AutomatonSymbolSurrogate automatonSymbolSurrogate; AutomatonWithSTInfo3ScopesGenitor automatonWithSTInfo3SymbolTableCreator; AutomatonWithSTInfo3ScopesGenitorDelegator automatonWithSTInfo3SymbolTableCreatorDelegator; @@ -41,9 +41,9 @@ public void test() { IAutomatonWithSTInfo3Scope iAutomatonWithSTInfo3Scope; ICommonAutomatonWithSTInfo3Symbol iCommonAutomatonWithSTInfo3Symbol; StateSymbol stateSymbol = new StateSymbol("S"); - Assertions.assertFalse(stateSymbol instanceof IScopeSpanningSymbol); + assertFalse(stateSymbol instanceof IScopeSpanningSymbol); StateSymbolSurrogate stateSymbolSurrogate; - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo4Test.java b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo4Test.java index 2c0a13048b..5646b1b90e 100644 --- a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo4Test.java +++ b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo4Test.java @@ -8,14 +8,13 @@ import mc.feature.symboltable.automatonwithstinfo4.AutomatonWithSTInfo4Mill; import mc.feature.symboltable.automatonwithstinfo4._ast.ASTState; import mc.feature.symboltable.automatonwithstinfo4._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.*; + public class AutomatonWithSTInfo4Test extends GeneratorIntegrationsTest { @BeforeEach @@ -31,11 +30,11 @@ public void before() { @Test public void test() { AutomatonElementSymbol automatonElementSymbol = new AutomatonElementSymbol("A"); - Assertions.assertFalse(automatonElementSymbol instanceof IScopeSpanningSymbol); + assertFalse(automatonElementSymbol instanceof IScopeSpanningSymbol); AutomatonElementSymbolSurrogate automatonElementSymbolSurrogate; AutomatonWithSTInfo4Scope automatonScope; AutomatonSymbol automatonSymbol= new AutomatonSymbol("A"); - Assertions.assertTrue(automatonSymbol instanceof IScopeSpanningSymbol); + assertInstanceOf(IScopeSpanningSymbol.class, automatonSymbol); AutomatonSymbolSurrogate automatonSymbolSurrogate; AutomatonWithSTInfo4ScopesGenitor automatonWithSTInfo4SymbolTableCreator; ASTState s = AutomatonWithSTInfo4Mill.stateBuilder().setName("S").build(); @@ -43,7 +42,7 @@ public void test() { AutomatonElementSymbol aESymbol = s.getSymbol(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo5Test.java b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo5Test.java index 18dd714ddf..c33a26ba7c 100644 --- a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo5Test.java +++ b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo5Test.java @@ -6,14 +6,13 @@ import de.se_rwth.commons.logging.LogStub; import mc.GeneratorIntegrationsTest; import mc.feature.symboltable.automatonwithstinfo5._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class AutomatonWithSTInfo5Test extends GeneratorIntegrationsTest { @BeforeEach @@ -30,14 +29,14 @@ public void before() { public void test() { AutomatonWithSTInfo5Scope automatonScope; AutomatonSymbol automatonSymbol = new AutomatonSymbol("A"); - Assertions.assertTrue(automatonSymbol instanceof IScopeSpanningSymbol); + assertInstanceOf(IScopeSpanningSymbol.class, automatonSymbol); AutomatonSymbolSurrogate automatonSymbolSurrogate; AutomatonWithSTInfo5ScopesGenitor automatonWithSTInfo5SymbolTableCreator; StateSymbol stateSymbol = new StateSymbol("A"); - Assertions.assertFalse(stateSymbol instanceof IScopeSpanningSymbol); + assertFalse(stateSymbol instanceof IScopeSpanningSymbol); StateSymbolSurrogate stateSymbolSurrogate; TransitionSymbol transitionSymbol = new TransitionSymbol("T"); - Assertions.assertFalse(transitionSymbol instanceof IScopeSpanningSymbol); + assertFalse(transitionSymbol instanceof IScopeSpanningSymbol); TransitionSymbolSurrogate transitionSymbolReference; // Collection stateSymbols = automatonSymbol.getStates(); @@ -46,7 +45,7 @@ public void test() { // StateSymbol from = transitionSymbol.getFrom(); // StateSymbol to = transitionSymbol.getTo(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo6Test.java b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo6Test.java index 7e049316d6..e6bf973a4d 100644 --- a/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo6Test.java +++ b/monticore-test/it/src/test/java/mc/feature/symboltable/AutomatonWithSTInfo6Test.java @@ -6,14 +6,13 @@ import de.se_rwth.commons.logging.LogStub; import mc.GeneratorIntegrationsTest; import mc.feature.symboltable.automatonwithstinfo6._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class AutomatonWithSTInfo6Test extends GeneratorIntegrationsTest { @BeforeEach @@ -30,16 +29,16 @@ public void before() { public void test() { AutomatonWithSTInfo6Scope automatonScope; AutomatonSymbol automatonSymbol = new AutomatonSymbol("A"); - Assertions.assertTrue(automatonSymbol instanceof IScopeSpanningSymbol); + assertInstanceOf(IScopeSpanningSymbol.class, automatonSymbol); AutomatonSymbolSurrogate automatonSymbolSurrogate; AutomatonWithSTInfo6ScopesGenitor automatonwithstinfo6SymbolTableCreator; StateSymbol stateSymbol = new StateSymbol("A"); - Assertions.assertFalse(stateSymbol instanceof IScopeSpanningSymbol); + assertFalse(stateSymbol instanceof IScopeSpanningSymbol); StateSymbolSurrogate stateSymbolSurrogate; TransitionSymbol transitionSymbol = new TransitionSymbol("T"); - Assertions.assertFalse(transitionSymbol instanceof IScopeSpanningSymbol); + assertFalse(transitionSymbol instanceof IScopeSpanningSymbol); TransitionSymbolSurrogate transitionSymbolSurrogate; - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/visitor/VisitorTest.java b/monticore-test/it/src/test/java/mc/feature/visitor/VisitorTest.java index a08235bdb4..cf3620bcaf 100644 --- a/monticore-test/it/src/test/java/mc/feature/visitor/VisitorTest.java +++ b/monticore-test/it/src/test/java/mc/feature/visitor/VisitorTest.java @@ -2,17 +2,11 @@ package mc.feature.visitor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import de.se_rwth.commons.logging.Log; @@ -25,6 +19,8 @@ import mc.feature.visitor.sup._visitor.SupVisitor2; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class VisitorTest extends GeneratorIntegrationsTest { @BeforeEach @@ -38,8 +34,8 @@ public void testConcreteVisitor() throws IOException { // Create AST SubParser p = new SubParser(); Optional node = p.parseA(new StringReader("test1 test2")); - Assertions.assertFalse(p.hasErrors()); - Assertions.assertTrue(node.isPresent()); + assertFalse(p.hasErrors()); + assertTrue(node.isPresent()); // Running Visitor SubTraverser t1 = SubMill.traverser(); @@ -47,7 +43,7 @@ public void testConcreteVisitor() throws IOException { t1.add4Sub(v); t1.handle(node.get()); - Assertions.assertTrue(v.hasVisited()); + assertTrue(v.hasVisited()); SubTraverser t2 = SubMill.traverser(); SupVisitor2 vSup = new SupVisitor2() {}; @@ -55,8 +51,8 @@ public void testConcreteVisitor() throws IOException { long errorCount = Log.getErrorCount(); // no expected error, as super visitor should run on sub language t2.handle(node.get()); - Assertions.assertEquals(errorCount, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(errorCount, Log.getErrorCount()); + assertTrue(Log.getFindings().isEmpty()); } @@ -64,8 +60,8 @@ public void testConcreteVisitor() throws IOException { public void testInheritanceTraversal() throws IOException { SubParser p = new SubParser(); Optional node = p.parse_String("test2 NodeOverride"); - Assertions.assertFalse(p.hasErrors()); - Assertions.assertTrue(node.isPresent()); + assertFalse(p.hasErrors()); + assertTrue(node.isPresent()); // init with plain traverser SubTraverser t1 = SubMill.traverser(); @@ -74,7 +70,7 @@ public void testInheritanceTraversal() throws IOException { // plain traverser should not reach the interface implementation node.get().accept(t1); - Assertions.assertEquals(0, c1.getNum()); + assertEquals(0, c1.getNum()); // init with inheritance traverser @@ -84,7 +80,7 @@ public void testInheritanceTraversal() throws IOException { // inheritance traverser should reach the interface implementation precisely once node.get().accept(t2); - Assertions.assertEquals(1, c2.getNum()); + assertEquals(1, c2.getNum()); } diff --git a/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/InheritanceVisitorTest.java b/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/InheritanceVisitorTest.java index 3bc0c72aee..e733ffaaca 100644 --- a/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/InheritanceVisitorTest.java +++ b/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/InheritanceVisitorTest.java @@ -16,10 +16,9 @@ import mc.feature.visitors.c._visitor.CInheritanceHandler; import mc.feature.visitors.c._visitor.CTraverser; import mc.feature.visitors.c._visitor.CVisitor2; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class InheritanceVisitorTest { @@ -39,21 +38,21 @@ public void testInheritanceHandler() { ICScope scope = CMill.scope(); scope.accept(traverser); - Assertions.assertEquals("ASBSCS", sb.toString()); + assertEquals("ASBSCS", sb.toString()); sb = new StringBuilder(); ICGlobalScope globalScope = CMill.globalScope(); globalScope.accept(traverser); - Assertions.assertEquals("AGSASBGSBSCSCGS", sb.toString()); + assertEquals("AGSASBGSBSCSCGS", sb.toString()); sb = new StringBuilder(); ICArtifactScope artifactScope = CMill.artifactScope(); artifactScope.accept(traverser); - Assertions.assertEquals("AASASBASBSCSCAS", sb.toString()); + assertEquals("AASASBASBSCSCAS", sb.toString()); } diff --git a/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/VisitorTest.java b/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/VisitorTest.java index f20220b373..d39e053fb7 100644 --- a/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/VisitorTest.java +++ b/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/VisitorTest.java @@ -2,14 +2,10 @@ package mc.feature.visitor.inheritance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import de.se_rwth.commons.logging.LogStub; import mc.feature.visitor.inheritance.a.AMill; import mc.feature.visitor.inheritance.b.BMill; import mc.feature.visitor.inheritance.c.CMill; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -17,6 +13,9 @@ import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Tests that for grammar C extends B extends A the CVisitor also visits rules * from B and A. Furthermore, we test that rules extending rules from a super @@ -40,14 +39,14 @@ public void testSimple() { traverser.add4C(v); traverser.handle(AMill.xABuilder().build()); - Assertions.assertEquals("A", v.getRun()); + assertEquals("A", v.getRun()); v.clear(); traverser.handle(BMill.xBBuilder().build()); - Assertions.assertEquals("B", v.getRun()); + assertEquals("B", v.getRun()); v.clear(); traverser.handle(CMill.xCBuilder().build()); - Assertions.assertEquals("C", v.getRun()); + assertEquals("C", v.getRun()); v.clear(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/delegator/ComposeSimpleTest.java b/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/delegator/ComposeSimpleTest.java index 34881a54e5..1226f47e44 100644 --- a/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/delegator/ComposeSimpleTest.java +++ b/monticore-test/it/src/test/java/mc/feature/visitor/inheritance/delegator/ComposeSimpleTest.java @@ -2,11 +2,7 @@ package mc.feature.visitor.inheritance.delegator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,6 +22,9 @@ import mc.feature.visitor.inheritance.c._visitor.CVisitor2; import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Tests composing simple visiors using the traverser visitor. The * SimpleXVisitors append "[NameOfVisitor].[h|t|v|e][ASTNode]" when a method of @@ -70,22 +69,22 @@ public void setUp() { @Test public void testSimpleComposed() { traverser.handle(AMill.xABuilder().build()); - Assertions.assertEquals("SimpleAVisitor.hXASimpleAVisitor.vXASimpleAVisitor.tXASimpleAVisitor.eXA", run.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("SimpleAVisitor.hXASimpleAVisitor.vXASimpleAVisitor.tXASimpleAVisitor.eXA", run.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSimpleComposed2() { traverser.handle(BMill.xBBuilder().build()); - Assertions.assertEquals("SimpleBVisitor.hXBSimpleBVisitor.vXBSimpleBVisitor.tXBSimpleBVisitor.eXB", run.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("SimpleBVisitor.hXBSimpleBVisitor.vXBSimpleBVisitor.tXBSimpleBVisitor.eXB", run.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSimpleComposed3() { traverser.handle(mc.feature.visitor.inheritance.c.CMill.xCBuilder().build()); - Assertions.assertEquals("SimpleCVisitor.hXCSimpleCVisitor.vXCSimpleCVisitor.tXCSimpleCVisitor.eXC", run.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals("SimpleCVisitor.hXCSimpleCVisitor.vXCSimpleCVisitor.tXCSimpleCVisitor.eXC", run.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -101,8 +100,8 @@ public void testSimpleComposed4() { expectedRun.append("SimpleBVisitor.hYBSimpleBVisitor.vYBSimpleBVisitor.tYBSimpleBVisitor.eYB"); // rest of yc expectedRun.append("SimpleCVisitor.eYC"); - Assertions.assertEquals(expectedRun.toString(), run.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(expectedRun.toString(), run.toString()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -123,8 +122,8 @@ public void testSimpleComposed5() { expectedRun.append("SimpleBVisitor.hYBSimpleBVisitor.vYBSimpleBVisitor.tYBSimpleBVisitor.eYB"); // rest of zb expectedRun.append("SimpleBVisitor.eZB"); - Assertions.assertEquals(expectedRun.toString(), run.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(expectedRun.toString(), run.toString()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/feature/wiki/WikiTest.java b/monticore-test/it/src/test/java/mc/feature/wiki/WikiTest.java index 716c875d36..ba03429f1a 100644 --- a/monticore-test/it/src/test/java/mc/feature/wiki/WikiTest.java +++ b/monticore-test/it/src/test/java/mc/feature/wiki/WikiTest.java @@ -2,14 +2,10 @@ package mc.feature.wiki; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import mc.GeneratorIntegrationsTest; @@ -17,6 +13,8 @@ import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class WikiTest extends GeneratorIntegrationsTest { @BeforeEach @@ -31,9 +29,9 @@ public void test() throws IOException { WikiParser p = new WikiParser(); p.parseWikiArtikel(new StringReader("==Test==\n==Test== ==\n== test ==\n")); - Assertions.assertEquals(false, p.hasErrors()); + assertFalse(p.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/grammar/MCParserTest.java b/monticore-test/it/src/test/java/mc/grammar/MCParserTest.java index 0d99b6edcb..0d6ff6cc6f 100644 --- a/monticore-test/it/src/test/java/mc/grammar/MCParserTest.java +++ b/monticore-test/it/src/test/java/mc/grammar/MCParserTest.java @@ -2,13 +2,10 @@ package mc.grammar; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.util.Optional; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,6 +14,8 @@ import mc.grammar.ittestgrammar_withconcepts._parser.ItTestGrammar_WithConceptsParser; import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class MCParserTest extends GeneratorIntegrationsTest { @BeforeEach @@ -32,9 +31,9 @@ public void test1() throws IOException { Optional ast = parser.parseMCGrammar("src/test/resources/mc/grammar/SimpleGrammarWithConcept.mc4"); - Assertions.assertTrue(ast.isPresent()); + assertTrue(ast.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-test/it/src/test/java/mc/tfcs/ast/TestVisitor.java b/monticore-test/it/src/test/java/mc/tfcs/ast/TestVisitor.java index d7af885fa8..9b37225fad 100644 --- a/monticore-test/it/src/test/java/mc/tfcs/ast/TestVisitor.java +++ b/monticore-test/it/src/test/java/mc/tfcs/ast/TestVisitor.java @@ -4,12 +4,13 @@ import mc.feature.featuredsl._ast.ASTState; import mc.feature.featuredsl._visitor.FeatureDSLVisitor2; -import org.junit.Assert; + +import static org.junit.jupiter.api.Assertions.fail; public class TestVisitor implements FeatureDSLVisitor2 { public void visit(ASTState a) { - Assert.fail("Should be ignored by overriding the traverse method of automaton"); + fail("Should be ignored by overriding the traverse method of automaton"); } } diff --git a/monticore-test/it/src/test/resources/mc/feature/scopes/ScopeInheritanceModel.st b/monticore-test/it/src/test/resources/mc/feature/scopes/ScopeInheritanceModel.st new file mode 100644 index 0000000000..f1aa8860b9 --- /dev/null +++ b/monticore-test/it/src/test/resources/mc/feature/scopes/ScopeInheritanceModel.st @@ -0,0 +1,10 @@ +/* (c) https://github.com/MontiCore/monticore */ +A ShadowingNonExportingOrdered +B ShadowingNonExporting +C ShadowingOrdered +D NonExportingOrdered +E Shadowing +F NonExporting +G Ordered +H Default +EA ShadowingNonExportingOrdered diff --git a/monticore-test/it/src/test_emf/java/mc/emf/east/GeneratedAstClassesTest.java b/monticore-test/it/src/test_emf/java/mc/emf/east/GeneratedAstClassesTest.java index 8f32b56ee5..e8a15b1181 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/east/GeneratedAstClassesTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/east/GeneratedAstClassesTest.java @@ -5,22 +5,18 @@ import mc.GeneratorIntegrationsTest; import mc.feature.hwc.statechartdsl._ast.ASTState; import mc.feature.hwc.statechartdsl.StatechartDSLMill; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class GeneratedAstClassesTest extends GeneratorIntegrationsTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testErrorsIfNullByAstNodes() { ASTState b = StatechartDSLMill.stateBuilder().uncheckedBuild(); - thrown.expect(NullPointerException.class); - // Log.errorIfNull is not generated - // thrown.expectMessage("must not be null."); - b.setTransitionsList(null); + // Preconditions.checkNotNull is not generated + // NullPointerException is thrown + assertThrows(NullPointerException.class, () -> b.setTransitionsList(null)); } } diff --git a/monticore-test/it/src/test_emf/java/mc/emf/emethods/EGeterSeterTest.java b/monticore-test/it/src/test_emf/java/mc/emf/emethods/EGeterSeterTest.java index 00427c7749..d30242fb17 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/emethods/EGeterSeterTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/emethods/EGeterSeterTest.java @@ -8,12 +8,12 @@ import mc.feature.fautomaton.action.expression._ast.ExpressionPackage; import mc.feature.fautomaton.automaton.flatautomaton._ast.*; import mc.feature.fautomaton.automaton.flatautomaton.*; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class EGeterSeterTest extends GeneratorIntegrationsTest { @@ -21,7 +21,7 @@ public class EGeterSeterTest extends GeneratorIntegrationsTest { private ASTTransition transition; private ASTAssignment assign; - @Before + @BeforeEach public void setUp() { aut = FlatAutomatonMill.automatonBuilder().uncheckedBuild(); aut.setName("aut1"); diff --git a/monticore-test/it/src/test_emf/java/mc/emf/emethods/FeatureIDConversionTest.java b/monticore-test/it/src/test_emf/java/mc/emf/emethods/FeatureIDConversionTest.java index cd99eb88fa..fc573710d9 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/emethods/FeatureIDConversionTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/emethods/FeatureIDConversionTest.java @@ -2,23 +2,23 @@ package mc.emf.emethods; -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - import mc.GeneratorIntegrationsTest; import mc.feature.fautomaton.action.expression._ast.ASTComplexAssigment; import mc.feature.fautomaton.action.expression._ast.ASTValue; import mc.feature.fautomaton.action.expression.ExpressionMill; import mc.feature.fautomaton.action.expression._ast.ExpressionPackage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +@Disabled public class FeatureIDConversionTest extends GeneratorIntegrationsTest { ASTComplexAssigment ast; - @Before + @BeforeEach public void setUp() throws Exception { ast = ExpressionMill.complexAssigmentBuilder().uncheckedBuild(); } @@ -30,6 +30,7 @@ public void testDerivedFeatureID() { assertEquals(expectedDerivedID, derivedID); } + @Test public void testBaseFeatureID() { int baseID = ast.eBaseStructuralFeatureID( ExpressionPackage.ASTComplexAssigment_A, ASTValue.class); diff --git a/monticore-test/it/src/test_emf/java/mc/emf/eobjects/CreateEObjectsTest.java b/monticore-test/it/src/test_emf/java/mc/emf/eobjects/CreateEObjectsTest.java index 273fe82b34..5fa030f94f 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/eobjects/CreateEObjectsTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/eobjects/CreateEObjectsTest.java @@ -8,25 +8,24 @@ import mc.feature.fautomaton.automaton.flatautomaton._ast.ASTAutomaton; import mc.feature.fautomaton.automaton.flatautomaton._ast.ASTState; import mc.feature.fautomaton.automaton.flatautomaton._ast.ASTTransition; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class CreateEObjectsTest extends GeneratorIntegrationsTest { @Test public void builderTest() { ASTENode ast = FlatAutomatonMill.automatonBuilder().setName(("A")).build(); assertNotNull(ast); - assertTrue(ast instanceof ASTAutomaton); + assertInstanceOf(ASTAutomaton.class, ast); ast = FlatAutomatonMill.stateBuilder().setName("s").build(); assertNotNull(ast); - assertTrue(ast instanceof ASTState); + assertInstanceOf(ASTState.class, ast); ast = FlatAutomatonMill.transitionBuilder().setActivate("t").setFrom("a").setTo("b").build(); assertNotNull(ast); - assertTrue(ast instanceof ASTTransition); + assertInstanceOf(ASTTransition.class, ast); } } diff --git a/monticore-test/it/src/test_emf/java/mc/emf/epackage/IDTest.java b/monticore-test/it/src/test_emf/java/mc/emf/epackage/IDTest.java index 7c144e4782..b14b98e0b9 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/epackage/IDTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/epackage/IDTest.java @@ -6,9 +6,9 @@ import mc.feature.fautomaton.action.expression._ast.ExpressionPackage; import mc.feature.fautomaton.automaton.flatautomaton._ast.FlatAutomatonPackage; import mc.feature.fautomaton.automaton.flatautomaton._ast.FlatAutomatonPackageImpl; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class IDTest extends GeneratorIntegrationsTest { diff --git a/monticore-test/it/src/test_emf/java/mc/emf/epackage/MetaObjectTest.java b/monticore-test/it/src/test_emf/java/mc/emf/epackage/MetaObjectTest.java index ef6b8c301b..b8a62cf0a6 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/epackage/MetaObjectTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/epackage/MetaObjectTest.java @@ -9,12 +9,10 @@ import mc.feature.fautomaton.automaton.flatautomaton._ast.FlatAutomatonPackage; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.*; -import org.junit.Test; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MetaObjectTest extends GeneratorIntegrationsTest { @@ -22,7 +20,7 @@ public void setup() { } @Test - @Ignore + @Disabled public void testSuperTypes() { EClass compAssig = ExpressionPackage.eINSTANCE.getASTComplexAssigment(); diff --git a/monticore-test/it/src/test_emf/java/mc/emf/etools/EcoreUtilTest.java b/monticore-test/it/src/test_emf/java/mc/emf/etools/EcoreUtilTest.java index efc6f0b840..e0cce084d0 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/etools/EcoreUtilTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/etools/EcoreUtilTest.java @@ -9,9 +9,6 @@ import org.antlr.v4.runtime.RecognitionException; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EcoreUtil; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; import de.monticore.emf.util.AST2ModelFiles; import mc.GeneratorIntegrationsTest; @@ -21,10 +18,12 @@ import mc.feature.fautomaton.automaton.flatautomaton.FlatAutomatonMill; import mc.feature.fautomaton.automaton.flatautomaton._ast.FlatAutomatonPackage; import mc.feature.fautomaton.automaton.flatautomaton._parser.FlatAutomatonParser; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -@Ignore +@Disabled public class EcoreUtilTest extends GeneratorIntegrationsTest { @Test @@ -48,14 +47,14 @@ public void testSerializeAndDeserializeParseInstance() { EObject deserAstTransC = AST2ModelFiles.get().deserializeASTInstance("ASTAutomaton_C", FlatAutomatonPackage.eINSTANCE); assertNotNull(deserAstTransC); - assertTrue(deserAstTransC instanceof ASTAutomaton); + assertInstanceOf(ASTAutomaton.class, deserAstTransC); EObject deserAstTransA = AST2ModelFiles.get().deserializeASTInstance("ASTAutomaton_A", FlatAutomatonPackage.eINSTANCE); assertNotNull(deserAstTransA); - assertTrue(deserAstTransA instanceof ASTAutomaton); + assertInstanceOf(ASTAutomaton.class, deserAstTransA); assertNotEquals(deserAstTransA.toString(),deserAstTransC.toString()); assertFalse(EcoreUtil.equals(deserAstTransA, deserAstTransC)); @@ -94,12 +93,12 @@ public void testSerializeAndDeserializeParseInstance2() { EObject deserAstTransC = AST2ModelFiles.get().deserializeASTInstance("ASTAutomaton_C2", FlatAutomatonPackage.eINSTANCE); assertNotNull(deserAstTransC); - assertTrue(deserAstTransC instanceof ASTAutomaton); + assertInstanceOf(ASTAutomaton.class, deserAstTransC); EObject deserAstTransB = AST2ModelFiles.get().deserializeASTInstance("ASTAutomaton_B2", FlatAutomatonPackage.eINSTANCE); assertNotNull(deserAstTransB); - assertTrue(deserAstTransB instanceof ASTAutomaton); + assertInstanceOf(ASTAutomaton.class, deserAstTransB); assertEquals(deserAstTransB.toString(),deserAstTransC.toString()); diff --git a/monticore-test/it/src/test_emf/java/mc/emf/etools/EmfDiffTest.java b/monticore-test/it/src/test_emf/java/mc/emf/etools/EmfDiffTest.java index c97103be3a..05b6190c72 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/etools/EmfDiffTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/etools/EmfDiffTest.java @@ -7,19 +7,19 @@ import mc.feature.fautomaton.automaton.flatautomaton._parser.FlatAutomatonParser; import org.antlr.v4.runtime.RecognitionException; import org.eclipse.emf.compare.diff.metamodel.DiffElement; -import org.junit.Test; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class EmfDiffTest extends GeneratorIntegrationsTest { - @Ignore + @Disabled @Test public void testDiffAutomaton() { try { @@ -63,10 +63,7 @@ public void testDiffAutomaton() { fail("Parse errors"); } } - catch (RecognitionException | IOException e) { - fail("Should not reach this, but: " + e); - } - catch (InterruptedException e) { + catch (RecognitionException | IOException | InterruptedException e) { fail("Should not reach this, but: " + e); } } diff --git a/monticore-test/it/src/test_emf/java/mc/emf/generator/ASTNodeTest.java b/monticore-test/it/src/test_emf/java/mc/emf/generator/ASTNodeTest.java index b9807cd2a2..7ea73d5f9c 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/generator/ASTNodeTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/generator/ASTNodeTest.java @@ -6,16 +6,16 @@ import de.monticore.emf.util.AST2ModelFiles; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; public class ASTNodeTest { - @BeforeClass + @BeforeAll public static void setup() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/it/src/test_emf/java/mc/emf/generator/GrammarDiffsTest.java b/monticore-test/it/src/test_emf/java/mc/emf/generator/GrammarDiffsTest.java index e7ad706076..ce18bcd909 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/generator/GrammarDiffsTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/generator/GrammarDiffsTest.java @@ -9,26 +9,24 @@ import mc.grammar.ittestgrammar_withconcepts._parser.ItTestGrammar_WithConceptsParser; import org.antlr.v4.runtime.RecognitionException; import org.eclipse.emf.compare.diff.metamodel.DiffElement; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class GrammarDiffsTest { - @BeforeClass + @BeforeAll public static void setup() { LogStub.init(); Log.enableFailQuick(false); } - @Ignore // TODO + @Disabled // TODO @Test public void testAstGrammarDiffs() throws IOException { try { @@ -59,10 +57,7 @@ public void testAstGrammarDiffs() throws IOException { fail("Parse errors"); } } - catch (RecognitionException | IOException e) { - fail("Should not reach this, but: " + e); - } - catch (InterruptedException e) { + catch (RecognitionException | IOException | InterruptedException e) { fail("Should not reach this, but: " + e); } } diff --git a/monticore-test/it/src/test_emf/java/mc/emf/generator/GrammarSerDeserTest.java b/monticore-test/it/src/test_emf/java/mc/emf/generator/GrammarSerDeserTest.java index ae770102c8..524c549025 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/generator/GrammarSerDeserTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/generator/GrammarSerDeserTest.java @@ -12,28 +12,25 @@ import org.antlr.v4.runtime.RecognitionException; import org.eclipse.emf.compare.diff.metamodel.DiffElement; import org.eclipse.emf.ecore.EObject; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class GrammarSerDeserTest { - @BeforeClass + @BeforeAll public static void setup() { LogStub.init(); Log.enableFailQuick(false); } - @Ignore // TODO + @Disabled // TODO @Test public void testSerializeDesirializeASTMCGrammarInstance() { try { @@ -47,7 +44,7 @@ public void testSerializeDesirializeASTMCGrammarInstance() { EObject deserAutomatonGrammar = AST2ModelFiles.get().deserializeASTInstance("ASTMCGrammar_Automaton", ItTestGrammarPackage.eINSTANCE); assertNotNull(deserAutomatonGrammar); - assertTrue(deserAutomatonGrammar instanceof ASTMCGrammar); + assertInstanceOf(ASTMCGrammar.class, deserAutomatonGrammar); assertTrue(automatonGrammar.get().deepEquals(deserAutomatonGrammar)); assertEquals("Automaton", ((ASTMCGrammar) deserAutomatonGrammar).getName()); @@ -56,10 +53,7 @@ public void testSerializeDesirializeASTMCGrammarInstance() { (ASTMCGrammar) deserAutomatonGrammar); assertTrue(diffs.isEmpty()); } - catch (RecognitionException | IOException e) { - fail("Should not reach this, but: " + e); - } - catch (InterruptedException e) { + catch (RecognitionException | IOException | InterruptedException e) { fail("Should not reach this, but: " + e); } } diff --git a/monticore-test/it/src/test_emf/java/mc/emf/modularity/ExternalTest.java b/monticore-test/it/src/test_emf/java/mc/emf/modularity/ExternalTest.java index ab98b08dd5..02e4747bae 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/modularity/ExternalTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/modularity/ExternalTest.java @@ -10,17 +10,17 @@ import mc.feature.fautomaton.automatonwithaction.actionautomaton.ActionAutomatonMill; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EReference; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ExternalTest extends GeneratorIntegrationsTest { private ASTAutomaton aut; - @Before + @BeforeEach public void setUp() throws Exception { aut = ActionAutomatonMill.automatonBuilder().uncheckedBuild(); } diff --git a/monticore-test/it/src/test_emf/java/mc/emf/serialization/ASTInstanceSerialDeserialTest.java b/monticore-test/it/src/test_emf/java/mc/emf/serialization/ASTInstanceSerialDeserialTest.java index 061a5454e1..03971a86f9 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/serialization/ASTInstanceSerialDeserialTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/serialization/ASTInstanceSerialDeserialTest.java @@ -1,12 +1,6 @@ /* (c) https://github.com/MontiCore/monticore */ package mc.emf.serialization; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.util.List; import java.util.Optional; @@ -15,8 +9,6 @@ import org.eclipse.emf.compare.diff.metamodel.DiffElement; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EcoreUtil; -import org.junit.Ignore; -import org.junit.Test; //import de.monticore.emf.fautomaton.automatonwithaction.actionautomaton._ast.ActionAutomatonPackage; import de.monticore.emf.util.AST2ModelFiles; @@ -28,8 +20,12 @@ import mc.feature.fautomaton.automaton.flatautomaton.FlatAutomatonMill; import mc.feature.fautomaton.automaton.flatautomaton._ast.FlatAutomatonPackage; import mc.feature.fautomaton.automaton.flatautomaton._parser.FlatAutomatonParser; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; -@Ignore +@Disabled public class ASTInstanceSerialDeserialTest extends GeneratorIntegrationsTest { @Test @@ -49,7 +45,7 @@ public void testSerializeAndDeserializeParseInstance() { EObject deserAstTransB = AST2ModelFiles.get().deserializeASTInstance("ASTAutomaton_B1", FlatAutomatonPackage.eINSTANCE); assertNotNull(deserAstTransB); - assertTrue(deserAstTransB instanceof ASTAutomaton); + assertInstanceOf(ASTAutomaton.class, deserAstTransB); assertTrue(transB.get().deepEquals(deserAstTransB)); assertFalse(transC.get().deepEquals(deserAstTransB)); assertEquals("Testautomat", ((ASTAutomaton) deserAstTransB).getName()); @@ -63,10 +59,7 @@ public void testSerializeAndDeserializeParseInstance() { } } - catch (RecognitionException | IOException e) { - fail("Should not reach this, but: " + e); - } - catch (InterruptedException e) { + catch (RecognitionException | IOException | InterruptedException e) { fail("Should not reach this, but: " + e); } } @@ -96,7 +89,7 @@ public void testSerializeAndDeserializeCreatedInstance() { EObject deserObject = AST2ModelFiles.get().deserializeASTInstance("ASTAutomaton_Aut1", FlatAutomatonPackage.eINSTANCE); assertNotNull(deserObject); - assertTrue(deserObject instanceof ASTAutomaton); + assertInstanceOf(ASTAutomaton.class, deserObject); ASTAutomaton serializedAut = (ASTAutomaton) deserObject; assertTrue(EcoreUtil.equals(aut, serializedAut)); diff --git a/monticore-test/it/src/test_emf/java/mc/emf/serialization/ASTModelSerialDeserialTest.java b/monticore-test/it/src/test_emf/java/mc/emf/serialization/ASTModelSerialDeserialTest.java index c5b6482e24..1010d60148 100644 --- a/monticore-test/it/src/test_emf/java/mc/emf/serialization/ASTModelSerialDeserialTest.java +++ b/monticore-test/it/src/test_emf/java/mc/emf/serialization/ASTModelSerialDeserialTest.java @@ -15,14 +15,18 @@ import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +@Disabled public class ASTModelSerialDeserialTest extends GeneratorIntegrationsTest { + @Test public void testECoreFileOFSuperGrammar() { ASTAutomaton aut = FlatAutomatonMill.automatonBuilder().uncheckedBuild(); @@ -53,6 +57,7 @@ public void testECoreFileOFSuperGrammar() { } } + @Test public void testECoreFileOFGrammar() { ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put( @@ -76,6 +81,7 @@ public void testECoreFileOFGrammar() { serializedTransitionWithAction.getEAllStructuralFeatures().get(ActionAutomatonPackage.ASTCounter_Names).getName()); } + @Test public void testECoreFileOFASTENode() { ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put( diff --git a/monticore-test/monticore-grammar-it/build.gradle b/monticore-test/monticore-grammar-it/build.gradle index 53bf8c8191..90931b8677 100644 --- a/monticore-test/monticore-grammar-it/build.gradle +++ b/monticore-test/monticore-grammar-it/build.gradle @@ -17,8 +17,8 @@ dependencies { implementation project(':monticore-grammar') implementation "de.se_rwth.commons:se-commons-utilities:$se_commons_version" testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" grammar (project(path: ':monticore-grammar')){ capabilities { requireCapability("de.monticore:monticore-grammar-grammars") @@ -26,6 +26,10 @@ dependencies { } } +test { + useJUnitPlatform() +} + buildDir = file("$projectDir/target") // The grammars of this subproject are built by the generateMCGrammars MCGenTask @@ -40,16 +44,16 @@ java { } } -tasks.withType(JavaCompile) { +tasks.withType(JavaCompile).configureEach { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 options.encoding = 'UTF-8' - options.deprecation false + options.deprecation = false options.warnings = false } -task testReport(type: TestReport) { +tasks.register('testReport', TestReport) { destinationDirectory = file("$buildDir/reports/allTests") // Include the results from the 'test' task - testResults.from(tasks.withType(Test).each({it.getBinaryResultsDirectory()})) + testResults.from(tasks.withType(Test).each({ it.getBinaryResultsDirectory() })) } \ No newline at end of file diff --git a/monticore-test/monticore-grammar-it/src/test/java/mc/typechecktest/CoCoTests.java b/monticore-test/monticore-grammar-it/src/test/java/mc/typechecktest/CoCoTests.java index 265508c461..61d641044f 100644 --- a/monticore-test/monticore-grammar-it/src/test/java/mc/typechecktest/CoCoTests.java +++ b/monticore-test/monticore-grammar-it/src/test/java/mc/typechecktest/CoCoTests.java @@ -13,7 +13,6 @@ import mc.typechecktest._cocos.VariableDeclarationIsCorrect; import mc.typechecktest._parser.TypeCheckTestParser; import mc.typechecktest._symboltable.TypeCheckTestPhasedSTC; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -22,8 +21,8 @@ import java.nio.file.Paths; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CoCoTests { @@ -61,28 +60,28 @@ public void setup() throws IOException { TypeCheckTestParser parser = TypeCheckTestMill.parser(); Optional bar = parser .parse("src/test/resources/mc/typescalculator/valid/Bar.tc"); - Assertions.assertTrue(bar.isPresent()); + assertTrue(bar.isPresent()); TypeCheckTestPhasedSTC stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(bar.get()); this.bar = bar.get(); Optional inheritanceBar = parser .parse("src/test/resources/mc/typescalculator/valid/InheritanceBar.tc"); - Assertions.assertTrue(inheritanceBar.isPresent()); + assertTrue(inheritanceBar.isPresent()); stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(inheritanceBar.get()); this.inheritanceBar = inheritanceBar.get(); Optional staticAbstractOOMethods = parser .parse("src/test/resources/mc/typescalculator/inbetween/StaticAbstractOOMethods.tc"); - Assertions.assertTrue(staticAbstractOOMethods.isPresent()); + assertTrue(staticAbstractOOMethods.isPresent()); stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(staticAbstractOOMethods.get()); this.staticAbstractOOMethods = staticAbstractOOMethods.get(); Optional staticAbstractOOFields = parser .parse("src/test/resources/mc/typescalculator/inbetween/StaticAbstractOOFields.tc"); - Assertions.assertTrue(staticAbstractOOFields.isPresent()); + assertTrue(staticAbstractOOFields.isPresent()); stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(staticAbstractOOFields.get()); this.staticAbstractOOFields = staticAbstractOOFields.get(); @@ -90,35 +89,35 @@ public void setup() throws IOException { Optional check = parser .parse("src/test/resources/mc/typescalculator/valid/Check.tc"); - Assertions.assertTrue(check.isPresent()); + assertTrue(check.isPresent()); this.check = check.get(); stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(check.get()); Optional wrongAssignment = parser .parse("src/test/resources/mc/typescalculator/invalid/WrongAssignment.tc"); - Assertions.assertTrue(wrongAssignment.isPresent()); + assertTrue(wrongAssignment.isPresent()); this.wrongAssignment = wrongAssignment.get(); stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(wrongAssignment.get()); Optional complicatedWrongAssignment = parser .parse("src/test/resources/mc/typescalculator/invalid/ComplicatedWrongAssignment.tc"); - Assertions.assertTrue(complicatedWrongAssignment.isPresent()); + assertTrue(complicatedWrongAssignment.isPresent()); this.complicatedWrongAssignment = complicatedWrongAssignment.get(); stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(complicatedWrongAssignment.get()); Optional complicatedCorrectAssignment = parser .parse("src/test/resources/mc/typescalculator/valid/ComplicatedCorrectAssignment.tc"); - Assertions.assertTrue(complicatedCorrectAssignment.isPresent()); + assertTrue(complicatedCorrectAssignment.isPresent()); this.complicatedCorrectAssignment = complicatedCorrectAssignment.get(); stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(complicatedCorrectAssignment.get()); Optional inheritedCannotUseStaticFromSuper = parser .parse("src/test/resources/mc/typescalculator/inbetween/InheritedCannotUseStaticFromSuper.tc"); - Assertions.assertTrue(inheritedCannotUseStaticFromSuper.isPresent()); + assertTrue(inheritedCannotUseStaticFromSuper.isPresent()); this.inheritedCannotUseStaticFromSuper = inheritedCannotUseStaticFromSuper.get(); stc = new TypeCheckTestPhasedSTC(); stc.createFromAST(inheritedCannotUseStaticFromSuper.get()); @@ -186,8 +185,8 @@ protected void testInvalidAbstract(String errorCode, ASTTCCompilationUnit comp){ }catch(Exception e){ //do nothing here, just catch the exception for further testing } - Assertions.assertTrue(Log.getFindingsCount()>=1); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(errorCode)); + assertTrue(Log.getFindingsCount()>=1); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(errorCode)); } protected void testInvalidOO(String errorCode, ASTTCCompilationUnit comp){ @@ -198,22 +197,22 @@ protected void testInvalidOO(String errorCode, ASTTCCompilationUnit comp){ }catch(Exception e){ //do nothing here, just catch the exception for further testing } - Assertions.assertTrue(Log.getFindingsCount()>=1); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(errorCode)); + assertTrue(Log.getFindingsCount()>=1); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(errorCode)); } protected void testValidAbstract(ASTTCCompilationUnit comp){ Log.clearFindings(); TypeCheckTestCoCoChecker checker = getAbstractChecker(); checker.checkAll(comp); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); } protected void testValidOO(ASTTCCompilationUnit comp){ Log.clearFindings(); TypeCheckTestCoCoChecker checker = getOOChecker(); checker.checkAll(comp); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); } protected TypeCheckTestCoCoChecker getOOChecker(){ diff --git a/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/CD2EHelper.java b/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/CD2EHelper.java index 90760b685e..3313536531 100644 --- a/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/CD2EHelper.java +++ b/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/CD2EHelper.java @@ -19,7 +19,7 @@ import mc.testcd4analysis._symboltable.CDTypeSymbolSurrogate; import mc.typescalculator.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -29,13 +29,13 @@ public class CD2EHelper { private IOOSymbolsScope iOOSymbolsScope; - private Map symTypeExpressionMap = new HashMap<>(); + private Map symTypeExpressionMap = new LinkedHashMap<>(); - private Map typeSymbolMap = new HashMap<>(); + private Map typeSymbolMap = new LinkedHashMap<>(); - private Map fieldSymbolMap = new HashMap<>(); + private Map fieldSymbolMap = new LinkedHashMap<>(); - private Map methodSymbolMap = new HashMap<>(); + private Map methodSymbolMap = new LinkedHashMap<>(); public CD2EHelper() { this.iOOSymbolsScope = OOSymbolsMill.scope(); diff --git a/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/CombineExpressionsWithLiteralsTest.java b/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/CombineExpressionsWithLiteralsTest.java index 472b465f70..7b15c0d4e1 100644 --- a/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/CombineExpressionsWithLiteralsTest.java +++ b/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/CombineExpressionsWithLiteralsTest.java @@ -21,7 +21,6 @@ import mc.typescalculator.combineexpressionswithliterals._symboltable.CombineExpressionsWithLiteralsScopesGenitorDelegator; import mc.typescalculator.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsArtifactScope; import mc.typescalculator.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsGlobalScope; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,8 +29,8 @@ import java.util.Optional; import static de.monticore.types.check.SymTypePrimitive.unbox; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CombineExpressionsWithLiteralsTest { @@ -70,10 +69,10 @@ public void testCD() throws IOException { globalScope1.addAdaptedTypeSymbolResolver(adapter); Optional classD = globalScope1.resolveOOType("mc.typescalculator.TestCD.D"); - Assertions.assertTrue(classD.isPresent()); + assertTrue(classD.isPresent()); Optional classB = globalScope1.resolveOOType("mc.typescalculator.TestCD.B"); - Assertions.assertTrue(classB.isPresent()); + assertTrue(classB.isPresent()); OOTypeSymbol dSurrogate = new OOTypeSymbolSurrogate("D"); dSurrogate.setEnclosingScope(classD.get().getEnclosingScope()); @@ -101,46 +100,46 @@ public void testCD() throws IOException { Optional expr = p.parse_StringExpression("d.s+=d.s"); CombineExpressionsWithLiteralsScopesGenitorDelegator del = new CombineExpressionsWithLiteralsScopesGenitorDelegator(); - Assertions.assertTrue(expr.isPresent()); + assertTrue(expr.isPresent()); ICombineExpressionsWithLiteralsArtifactScope art = del.createFromAST(expr.get()); art.setName(""); art.setImportsList(Lists.newArrayList(new ImportStatement("mc.typescalculator.TestCD.D", true))); TypeCheckResult j = calc.deriveType(expr.get()); - Assertions.assertTrue(j.isPresentResult()); - Assertions.assertEquals("int", unbox(j.getResult().print())); + assertTrue(j.isPresentResult()); + assertEquals("int", unbox(j.getResult().print())); Optional exprC = p.parse_StringExpression("d.f = mc.typescalculator.TestCD.C.f"); - Assertions.assertTrue(exprC.isPresent()); + assertTrue(exprC.isPresent()); ICombineExpressionsWithLiteralsArtifactScope artifactScope = del.createFromAST(exprC.get()); artifactScope.setName(""); j = calc.deriveType(exprC.get()); - Assertions.assertTrue(j.isPresentResult()); - Assertions.assertEquals("G", j.getResult().print()); + assertTrue(j.isPresentResult()); + assertEquals("G", j.getResult().print()); Optional exprD = p.parse_StringExpression("(b.a)++"); - Assertions.assertTrue(exprD.isPresent()); + assertTrue(exprD.isPresent()); artifactScope = del.createFromAST(exprD.get()); artifactScope.setName(""); TypeCheckResult j3 = calc.deriveType(exprD.get()); - Assertions.assertTrue(j3.isPresentResult()); - Assertions.assertEquals("double", j3.getResult().print()); + assertTrue(j3.isPresentResult()); + assertEquals("double", j3.getResult().print()); Optional exprB = p.parse_StringExpression("b.x = mc.typescalculator.TestCD.B.z"); - Assertions.assertTrue(exprB.isPresent()); + assertTrue(exprB.isPresent()); artifactScope = del.createFromAST(exprB.get()); artifactScope.setName(""); ASTExpression eb = exprB.get(); TypeCheckResult k = calc.deriveType(eb); - Assertions.assertTrue(k.isPresentResult()); - Assertions.assertEquals("C", k.getResult().print()); + assertTrue(k.isPresentResult()); + assertEquals("C", k.getResult().print()); Optional complicated = p.parse_StringExpression("b.z.f.toString()"); - Assertions.assertTrue(complicated.isPresent()); + assertTrue(complicated.isPresent()); artifactScope = del.createFromAST(complicated.get()); artifactScope.setName(""); TypeCheckResult sym = calc.deriveType(complicated.get()); - Assertions.assertTrue(sym.isPresentResult()); - Assertions.assertEquals("String", sym.getResult().print()); + assertTrue(sym.isPresentResult()); + assertEquals("String", sym.getResult().print()); } } diff --git a/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/SynthesizeSymTypeFromMyOwnLanguageTest.java b/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/SynthesizeSymTypeFromMyOwnLanguageTest.java index 117fb84daa..f5be513219 100644 --- a/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/SynthesizeSymTypeFromMyOwnLanguageTest.java +++ b/monticore-test/monticore-grammar-it/src/test/java/mc/typescalculator/SynthesizeSymTypeFromMyOwnLanguageTest.java @@ -14,7 +14,6 @@ import mc.typescalculator.myownlanguage._parser.MyOwnLanguageParser; import mc.typescalculator.myownlanguage._symboltable.IMyOwnLanguageGlobalScope; import mc.typescalculator.unittypes._ast.ASTMinuteType; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,8 +21,8 @@ import java.util.Arrays; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class SynthesizeSymTypeFromMyOwnLanguageTest { @@ -79,19 +78,19 @@ protected static TypeVarSymbol buildTypeParam(String typeParamName) { @Test public void testMCCollectionTypes() throws IOException { Optional type = parser.parse_StringMCType("List"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); type.get().setEnclosingScope(MyOwnLanguageMill.globalScope()); ((ASTMCListType)(type.get())).getMCTypeArgument().getMCTypeOpt().get().setEnclosingScope(MyOwnLanguageMill.globalScope()); - Assertions.assertEquals("List", tc.symTypeFromAST(type.get()).printFullName()); + assertEquals("List", tc.symTypeFromAST(type.get()).printFullName()); } @Test public void testUnitTypes() throws IOException { Optional type = parser.parse_StringMinuteType("min"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); // pretend to use the scope genitor type.get().setEnclosingScope(MyOwnLanguageMill.globalScope()); - Assertions.assertEquals("min", tc.symTypeFromAST(type.get()).print()); + assertEquals("min", tc.symTypeFromAST(type.get()).print()); } diff --git a/monticore-test/montitrans/build.gradle b/monticore-test/montitrans/build.gradle index a743145cd6..6cff8c4881 100644 --- a/monticore-test/montitrans/build.gradle +++ b/monticore-test/montitrans/build.gradle @@ -1,43 +1,39 @@ /* (c) https://github.com/MontiCore/monticore */ plugins { - id "monticore" id "jacoco" + id "de.monticore.generator-withtr" apply false } description = 'MontiCore-MontiTrans Integration Test' -ext.grammarDir = 'src/main/grammars' ext.junit_version = '5.10.3' -configurations {grammar} sonarqube { skipProject = true } subprojects { - apply plugin: 'monticore' + apply plugin: 'de.monticore.generator-withtr' apply plugin: 'jacoco' + + configurations.trafoGrammarSymbolDependencies.extendsFrom(configurations.grammarSymbolDependencies) + dependencies { - // Note: the dependencies are required, because this test does not yet use the transitive grammar dependencies - implementation project(':monticore-runtime') - implementation project(':monticore-grammar') - implementation project(path: ':monticore-grammar', configuration: 'trafoCompileClasspathForLegacyCompat') - implementation "de.se_rwth.commons:se-commons-utilities:$se_commons_version" + // project-dependencies using trafos are not properly working + grammarSymbolDependencies (project(path: ":monticore-grammar", configuration: "grammarSymbolOutElements")) + implementation (project(path: ":monticore-grammar")) + + trafoGrammarSymbolDependencies(project(path: ":monticore-grammar", configuration: "trafoGrammarSymbolOutElements")) + trafoImplementation(project(path: ":monticore-grammar", configuration: "trafoCompileClasspathForLegacyCompat")) + trafoImplementation files(project(":monticore-grammar").sourceSets.trafo.output.classesDirs) + + + testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" - testImplementation "org.junit.vintage:junit-vintage-engine:$junit_version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version" - grammar (project(path: ':monticore-grammar')){ - capabilities { - requireCapability("de.monticore:monticore-grammar-grammars") - } - } - grammar (project(path: ':monticore-grammar', configuration: 'trafoGrammarSymbolOutElements')) { - // Due to using the old MCGradle plugin here, no attributes filter the trafo artifacts - // and gradle is unsure whether to select runtimeElements or grammarSymbolOutElements - transitive(false) - } + testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" + testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junit_platform_version" } java { @@ -45,13 +41,11 @@ subprojects { languageVersion = JavaLanguageVersion.of(11) } } -} - - -clean.dependsOn(subprojects.collect{it.getTasksByName("clean", false)}) - -build.dependsOn(subprojects.collect{it.getTasksByName("build", false)}) + test { + useJUnitPlatform() + } +} jar.enabled = false sourcesJar.enabled = false diff --git a/monticore-test/montitrans/test-dstl-gen/build.gradle b/monticore-test/montitrans/test-dstl-gen/build.gradle index 912189b3b9..7d76f1fb3c 100644 --- a/monticore-test/montitrans/test-dstl-gen/build.gradle +++ b/monticore-test/montitrans/test-dstl-gen/build.gradle @@ -1,164 +1,32 @@ /* (c) https://github.com/MontiCore/monticore */ description = 'MontiTrans Test: DSTLGen' -def grammarsDir = "$projectDir/src/main/grammars" -def _outputDir = "$buildDir/generated-sources" - -task generateSocialNetwork (type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/social/SocialNetwork.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/social/SocialNetwork.mc4") - outputs.upToDateWhen { uptoDate } -} -task generateSocialNetworkTR (type: MCTask, dependsOn: generateSocialNetwork) { - grammar = file "$_outputDir/mc/testcases/social/tr/SocialNetworkTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/social/tr/SocialNetworkTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true -} -task generateStatechart (type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/statechart/Statechart.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/statechart/Statechart.mc4") - outputs.upToDateWhen { uptoDate } -} -task generateStatechartTR (type: MCTask, dependsOn: generateStatechart) { - grammar = file "$_outputDir/mc/testcases/statechart/tr/StatechartTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/statechart/tr/StatechartTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true -} - -task generateAutomaton (type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/automaton/Automaton.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/automaton/Automaton.mc4") - outputs.upToDateWhen { uptoDate } -} -task generateAutomatonTR (type: MCTask, dependsOn: generateAutomaton) { - grammar = file "$_outputDir/mc/testcases/automaton/tr/AutomatonTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/automaton/tr/AutomatonTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true -} - -task generatePropertiesAutomatonComponent (type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/DSLWithOtherPropertiesThanAutomatonComponent.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/DSLWithOtherPropertiesThanAutomatonComponent.mc4") - outputs.upToDateWhen { uptoDate } -} -task generatePropertiesAutomatonComponentTR (type: MCTask, dependsOn: generatePropertiesAutomatonComponent) { - grammar = file "$_outputDir/mc/testcases/tr/DSLWithOtherPropertiesThanAutomatonComponentTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/tr/DSLWithOtherPropertiesThanAutomatonComponentTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true -} - -task generatePropertiesAutomaton (type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/DSLWithOtherPropertiesThanAutomaton.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/DSLWithOtherPropertiesThanAutomaton.mc4") - outputs.upToDateWhen { uptoDate } -} -task generatePropertiesAutomatonTR (type: MCTask, dependsOn: [generatePropertiesAutomaton, generatePropertiesAutomatonComponent, generateAutomaton]) { - grammar = file "$_outputDir/mc/testcases/tr/DSLWithOtherPropertiesThanAutomatonTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/tr/DSLWithOtherPropertiesThanAutomatonTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true -} - -task generateGenericDSL (type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/GenericDSL.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/GenericDSL.mc4") - outputs.upToDateWhen { uptoDate } -} -task generateGenericDSLTR (type: MCTask, dependsOn: generateGenericDSL) { - grammar = file "$_outputDir/mc/testcases/tr/GenericDSLTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/tr/GenericDSLTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true -} -task generateExpressionDSL(type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/ExpressionDSL.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/ExpressionDSL.mc4") - outputs.upToDateWhen { uptoDate } -} -task generateExpressionDSLTR(type: MCTask, dependsOn: generateExpressionDSL) { - grammar = file "$_outputDir/mc/testcases/tr/ExpressionDSLTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/tr/ExpressionDSLTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true -} - -task generateEmptyComponentGrammar (type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/EmptyComponentGrammar.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/EmptyComponentGrammar.mc4") - outputs.upToDateWhen { uptoDate } +// Make the trafo sourceset available to tests +sourceSets { + test { + compileClasspath += sourceSets.trafo.output + runtimeClasspath += sourceSets.trafo.output + } } -task generateEmptyComponentGrammarTR (type: MCTask, dependsOn: generateEmptyComponentGrammar) { - grammar = file "$_outputDir/mc/testcases/tr/EmptyComponentGrammarTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/tr/EmptyComponentGrammarTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true - dependsOn generateEmptyComponentGrammar +configurations { + testImplementation.extendsFrom(trafoImplementation) } -task generateUsingEmptyComponentGrammar (type: MCTask) { - grammar = file "$grammarsDir/mc/testcases/UsingEmptyComponentGrammar.mc4" - outputDir = file _outputDir - def uptoDate = incCheck("mc/testcases/UsingEmptyComponentGrammar.mc4") - outputs.upToDateWhen { uptoDate } - dependsOn generateEmptyComponentGrammar -} -task generateUsingEmptyComponentGrammarTR (type: MCTask, dependsOn: generateEmptyComponentGrammar) { - grammar = file "$_outputDir/mc/testcases/tr/UsingEmptyComponentGrammarTR.mc4" - outputDir = file _outputDir - modelPath += file grammarsDir - modelPath += file _outputDir - def uptoDate = incCheck("mc/testcases/tr/UsingEmptyComponentGrammarTR.mc4") - outputs.upToDateWhen { uptoDate } - isDSTL = true - dependsOn generateEmptyComponentGrammarTR +tasks.named('testClasses') { + dependsOn tasks.named('trafoClasses') } -// The following explicit task dependencies are required in order to upgrade to Gradle 8+ -// They are not required when using the de.monticore.generator / MCGenTask -tasks.withType(MCTask.class).configureEach { - dependsOn(":monticore-grammar:grammarsJar") - dependsOn(":monticore-grammar:trafoGrammarsJar") -} +// Expose the trafo sources -compileJava { - dependsOn project.collect { it.tasks.withType(MCTask) } +configurations { + trafoOut { + extendsFrom(trafoImplementation) + } } -sourceSets { - main.java.srcDirs += [ _outputDir ] +tasks.register("trafoJar", Jar) { + archiveClassifier = "trafo" + from sourceSets.trafo.output } +artifacts { + trafoOut trafoJar +} \ No newline at end of file diff --git a/monticore-test/montitrans/test-dstl-gen/src/main/grammars/mc/testcases/odname/ODNameBasis.mc4 b/monticore-test/montitrans/test-dstl-gen/src/main/grammars/mc/testcases/odname/ODNameBasis.mc4 new file mode 100644 index 0000000000..5d4f630fc5 --- /dev/null +++ b/monticore-test/montitrans/test-dstl-gen/src/main/grammars/mc/testcases/odname/ODNameBasis.mc4 @@ -0,0 +1,8 @@ +/* (c) https://github.com/MontiCore/monticore */ +package mc.testcases.odname; + +component grammar ODNameBasis extends de.monticore.MCBasics { + interface ODValue; + + ODName implements ODValue = Name; +} \ No newline at end of file diff --git a/monticore-test/montitrans/test-dstl-gen/src/main/grammars/mc/testcases/odname/ODNameReport.mc4 b/monticore-test/montitrans/test-dstl-gen/src/main/grammars/mc/testcases/odname/ODNameReport.mc4 new file mode 100644 index 0000000000..ed525e8ed0 --- /dev/null +++ b/monticore-test/montitrans/test-dstl-gen/src/main/grammars/mc/testcases/odname/ODNameReport.mc4 @@ -0,0 +1,17 @@ +/* (c) https://github.com/MontiCore/monticore */ +package mc.testcases.odname; + +component grammar ODNameReport extends mc.testcases.odname.ODNameBasis { + token ODSpecialName = '@' Name; + + @Override + ODName implements ODValue = Name | ODSpecialName; + + astrule ODName = + method public String getName() { + if (isPresentName()) { + return this.name.get(); + } + return "noname"; + }; +} \ No newline at end of file diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_cocos/NoOptOnRHSCoCoTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_cocos/NoOptOnRHSCoCoTest.java index fd6de0be79..790d032159 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_cocos/NoOptOnRHSCoCoTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_cocos/NoOptOnRHSCoCoTest.java @@ -7,27 +7,26 @@ import mc.testcases.automaton.tr.automatontr._cocos.AutomatonTRCoCoChecker; import mc.testcases.automaton.tr.automatontr._cocos.NoOptOnRHSCoCo; import mc.testcases.automaton.tr.automatontr._parser.AutomatonTRParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Created by DW */ public class NoOptOnRHSCoCoTest { - @Before + @BeforeEach public void disableFailQuick() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() { Log.getFindings().clear(); } diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_cocos/NoOptWithinNotCoCoTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_cocos/NoOptWithinNotCoCoTest.java index 978b8cabe6..2f6f78f79a 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_cocos/NoOptWithinNotCoCoTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_cocos/NoOptWithinNotCoCoTest.java @@ -7,28 +7,26 @@ import mc.testcases.automaton.tr.automatontr._cocos.AutomatonTRCoCoChecker; import mc.testcases.automaton.tr.automatontr._cocos.NoOptWithinNotCoCo; import mc.testcases.automaton.tr.automatontr._ast.*; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Created by DW */ public class NoOptWithinNotCoCoTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() { Log.getFindings().clear(); } diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleParserTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleParserTest.java index e7743e4782..6d0c83fe88 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleParserTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleParserTest.java @@ -3,21 +3,21 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; +import mc.testcases.automaton.tr.automatontr.AutomatonTRMill; import mc.testcases.automaton.tr.automatontr._ast.*; import mc.testcases.automaton.tr.automatontr._parser.AutomatonTRParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class AutomatonTransformationRuleParserTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -63,7 +63,8 @@ public void testForwardToInitialRule() throws IOException { assertTrue(Log.getFindings().isEmpty()); } - @Test @Ignore + @Test + @Disabled public void testIsIdentifierFix() throws IOException { String inputFile = "src/test/resources/IsIdentifierFix.mtr"; AutomatonTRParser parser = new AutomatonTRParser(); @@ -153,4 +154,22 @@ public void testNameAsType() throws IOException { assertTrue(Log.getFindings().isEmpty()); } + + @Test + public void testRulePresence() throws IOException { + AutomatonTRParser parser = new AutomatonTRParser(); + Optional astA = parser.parse_String("automaton MyAut {}"); + assertFalse(parser.hasErrors()); + assertTrue(astA.isPresent()); + + Optional astB = parser.parse_String("Automaton [[ automaton MyAut {} ]]"); + assertFalse(parser.hasErrors()); + assertTrue(astB.isPresent()); + + // The existence of the rule name might be relevant, e.g. + // "Expression [[ a+b ]]" vs "PlusExpression [[ a+b ]]" + assertFalse(astA.get().deepEquals(astB.get())); + + assertTrue(Log.getFindings().isEmpty()); + } } diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleState_PatternMCConcreteParserTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleState_PatternMCConcreteParserTest.java index a9205d2a7f..e4028a3f5d 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleState_PatternMCConcreteParserTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleState_PatternMCConcreteParserTest.java @@ -4,21 +4,19 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton.tr.automatontr._ast.ASTState_Pat; import mc.testcases.automaton.tr.automatontr._parser.AutomatonTRParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class AutomatonTransformationRuleState_PatternMCConcreteParserTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransistion_PatternMCConcreteParserTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransistion_PatternMCConcreteParserTest.java index 7a8b761d56..99756c3191 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransistion_PatternMCConcreteParserTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransistion_PatternMCConcreteParserTest.java @@ -4,19 +4,19 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton.tr.automatontr._ast.ASTTransition_Pat; import mc.testcases.automaton.tr.automatontr._parser.AutomatonTRParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class AutomatonTransformationRuleTransistion_PatternMCConcreteParserTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransitionMCConcreteParserTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransitionMCConcreteParserTest.java index 060d87c82c..5c61556f17 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransitionMCConcreteParserTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransitionMCConcreteParserTest.java @@ -3,18 +3,18 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton.tr.automatontr._parser.AutomatonTRParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; -import static org.junit.Assert.*; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class AutomatonTransformationRuleTransitionMCConcreteParserTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransition_ReplacementMCConcreteParserTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransition_ReplacementMCConcreteParserTest.java index c797a84142..2d9ae8db2f 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransition_ReplacementMCConcreteParserTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/_parser/AutomatonTransformationRuleTransition_ReplacementMCConcreteParserTest.java @@ -5,16 +5,16 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton.tr.automatontr._parser.AutomatonTRParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class AutomatonTransformationRuleTransition_ReplacementMCConcreteParserTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/translation/AutomatonRule2ODToolTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/translation/AutomatonRule2ODToolTest.java index c3e2e8f928..b52a7c446d 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/translation/AutomatonRule2ODToolTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/automaton/transformation/rule/translation/AutomatonRule2ODToolTest.java @@ -1,11 +1,11 @@ /* (c) https://github.com/MontiCore/monticore */ package mc.testcases.automaton.transformation.rule.translation; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; public class AutomatonRule2ODToolTest { - @Before + @BeforeEach public void setUp() { } diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/expressiondsl/ExpressionDSLTRParseTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/expressiondsl/ExpressionDSLTRParseTest.java index 872938f453..147a95e330 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/expressiondsl/ExpressionDSLTRParseTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/expressiondsl/ExpressionDSLTRParseTest.java @@ -7,23 +7,24 @@ import de.monticore.literals.mccommonliterals._ast.ASTStringLiteral; import de.monticore.tf.tfcommons._ast.ASTAssign; import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; import mc.testcases.tr.expressiondsltr.ExpressionDSLTRMill; import mc.testcases.tr.expressiondsltr._parser.ExpressionDSLTRParser; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + /** * Test for literal support in left recursive grammars (aka expressions) */ public class ExpressionDSLTRParseTest { - @Before + @BeforeEach public void beforeEach() { - Log.init(); + LogStub.init(); Log.enableFailQuick(false); ExpressionDSLTRMill.init(); Log.clearFindings(); @@ -57,23 +58,23 @@ public void testTypes() throws IOException { @Test public void testAssigns() throws IOException { ASTAssign ast = test("$exp1 = $exp2 ;", ExpressionDSLTRParser::parse_StringAssign); - Assert.assertEquals(ASTNameExpression.class.getName(), ast.getValue().getClass().getName()); + assertEquals(ASTNameExpression.class.getName(), ast.getValue().getClass().getName()); ast = test("$exp1 = \"string\" ;", ExpressionDSLTRParser::parse_StringAssign); - Assert.assertEquals(ASTLiteralExpression.class.getName(), ast.getValue().getClass().getName()); - Assert.assertEquals(ASTStringLiteral.class.getName(), ((ASTLiteralExpression)ast.getValue()).getLiteral().getClass().getName()); - Assert.assertEquals("string", ((ASTStringLiteral)((ASTLiteralExpression)ast.getValue()).getLiteral()).getValue()); + assertEquals(ASTLiteralExpression.class.getName(), ast.getValue().getClass().getName()); + assertEquals(ASTStringLiteral.class.getName(), ((ASTLiteralExpression)ast.getValue()).getLiteral().getClass().getName()); + assertEquals("string", ((ASTStringLiteral)((ASTLiteralExpression)ast.getValue()).getLiteral()).getValue()); ast = test("$exp1 = $exp1 + \"string\" ;", ExpressionDSLTRParser::parse_StringAssign); - Assert.assertEquals(ASTPlusExpression.class.getName(), ast.getValue().getClass().getName()); - Assert.assertEquals(ASTNameExpression.class.getName(), ((ASTPlusExpression)ast.getValue()).getLeft().getClass().getName()); - Assert.assertEquals(ASTLiteralExpression.class.getName(), ((ASTPlusExpression)ast.getValue()).getRight().getClass().getName()); - Assert.assertEquals("string", ((ASTStringLiteral)((ASTLiteralExpression)((ASTPlusExpression)ast.getValue()).getRight()).getLiteral()).getValue()); + assertEquals(ASTPlusExpression.class.getName(), ast.getValue().getClass().getName()); + assertEquals(ASTNameExpression.class.getName(), ((ASTPlusExpression)ast.getValue()).getLeft().getClass().getName()); + assertEquals(ASTLiteralExpression.class.getName(), ((ASTPlusExpression)ast.getValue()).getRight().getClass().getName()); + assertEquals("string", ((ASTStringLiteral)((ASTLiteralExpression)((ASTPlusExpression)ast.getValue()).getRight()).getLiteral()).getValue()); } protected
A test(String exp, ParserFunction parserFunction) throws IOException { ExpressionDSLTRParser parser = ExpressionDSLTRMill.parser(); Optional typeOptional = parserFunction.parse(parser, exp); - Assert.assertFalse("Parser error while parsing: " + exp, parser.hasErrors()); - Assert.assertTrue("Failed to parse: " + exp, typeOptional.isPresent()); + assertFalse(parser.hasErrors(), "Parser error while parsing: " + exp); + assertTrue(typeOptional.isPresent(), "Failed to parse: " + exp); return typeOptional.get(); } diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/grammartransformation/TFLanguageOverrideTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/grammartransformation/TFLanguageOverrideTest.java index 7776bfdb9b..09625c5c96 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/grammartransformation/TFLanguageOverrideTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/grammartransformation/TFLanguageOverrideTest.java @@ -6,21 +6,18 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.tr.genericdsltr._ast.ASTNewClassProd; import mc.testcases.tr.genericdsltr._parser.GenericDSLTRParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; - import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TFLanguageOverrideTest { - @Before + @BeforeEach public void disableFailQuick() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/transformation/rule/translation/DSLWithOtherPropertiesThanAutomatonRule2ODVisitorTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/transformation/rule/translation/DSLWithOtherPropertiesThanAutomatonRule2ODVisitorTest.java index ebb6dc88bc..6d45ed656c 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/transformation/rule/translation/DSLWithOtherPropertiesThanAutomatonRule2ODVisitorTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/testcases/transformation/rule/translation/DSLWithOtherPropertiesThanAutomatonRule2ODVisitorTest.java @@ -20,14 +20,13 @@ import de.monticore.tf.odrules._ast.ASTODRule; import de.monticore.tf.rule2od.Variable2AttributeMap; import de.monticore.tf.ruletranslation.Rule2ODState; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class DSLWithOtherPropertiesThanAutomatonRule2ODVisitorTest { private static void createSymboltable(ASTODRule od) { @@ -35,13 +34,13 @@ private static void createSymboltable(ASTODRule od) { symbolTable.createFromAST(od); } - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @BeforeClass + @BeforeAll public static void disableFailQuick() { DSLWithOtherPropertiesThanAutomatonTRMill.init(); } diff --git a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/tfcs/TransformationRuleParserTest.java b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/tfcs/TransformationRuleParserTest.java index 327c94db93..ef1fc3940b 100644 --- a/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/tfcs/TransformationRuleParserTest.java +++ b/monticore-test/montitrans/test-dstl-gen/src/test/java/mc/tfcs/TransformationRuleParserTest.java @@ -2,23 +2,22 @@ package mc.tfcs; import de.se_rwth.commons.logging.LogStub; -import junit.framework.TestCase; import mc.testcases.automaton.tr.automatontr._ast.ASTITFAutomaton; import mc.testcases.automaton.tr.automatontr._ast.ASTAutomatonTFRule; import mc.testcases.automaton.tr.automatontr._parser.AutomatonTRParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class TransformationRuleParserTest extends TestCase { +import static org.junit.jupiter.api.Assertions.*; + +public class TransformationRuleParserTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-generated-dstls/build.gradle b/monticore-test/montitrans/test-generated-dstls/build.gradle index 7d8c47b193..8a2d7cc5cc 100644 --- a/monticore-test/montitrans/test-generated-dstls/build.gradle +++ b/monticore-test/montitrans/test-generated-dstls/build.gradle @@ -1,53 +1,56 @@ /* (c) https://github.com/MontiCore/monticore */ description = 'MontiTrans Test: Generated DSTL Test' -def _outputDir = "$buildDir/generated-sources" +def _outputDir = "$buildDir/generated-sources/trafogen" dependencies { - implementation project(':monticore-test:montitrans:test-dstl-gen') + grammar project(':monticore-test:montitrans:test-dstl-gen') + implementation project(path:':monticore-test:montitrans:test-dstl-gen', configuration: 'trafoOut') } -task generateStatechartTRRules { +import de.monticore.MontiTransExec + +tasks.register('generateStatechartTRRules') { group = "montitrans" } fileTree(dir: "$projectDir/src/main/models/statechart/mtr", include: '**/**.mtr').each { def g = it def taskname = "generateStatechartTRRules${it.getName().substring(0, it.getName().lastIndexOf('.'))}" - task "$taskname"(type: MontiTransExec) { - getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.main.runtimeClasspath) + tasks.register(taskname, MontiTransExec) { + getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.trafo.runtimeClasspath) TFGenTool = 'mc.testcases.statechart.tr.StatechartTFGenTool' input = file(g) - outputDir = file("$buildDir/generated-sources") + outputDir = file(_outputDir) } generateStatechartTRRules.dependsOn("$taskname") } -task generateSocialNetworkTRRules { +tasks.register('generateSocialNetworkTRRules') { group = "montitrans" } fileTree(dir: "$projectDir/src/main/models/social/mtr", include: '**/**.mtr').each { def g = it def taskname = "generateSocialNetworkTRRules${it.getName().substring(0, it.getName().lastIndexOf('.'))}" - task "$taskname"(type: MontiTransExec) { - getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.main.runtimeClasspath) + tasks.register(taskname, MontiTransExec) { + getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.trafo.runtimeClasspath) TFGenTool = 'mc.testcases.social.tr.SocialNetworkTFGenTool' input = file(g) - outputDir = file("$buildDir/generated-sources") + outputDir = file(_outputDir) } generateSocialNetworkTRRules.dependsOn("$taskname") } -task generateExpressionDSLTRRules { +tasks.register('generateExpressionDSLTRRules') { group = "montitrans" } fileTree(dir: "$projectDir/src/main/models/expressiondsl/mtr", include: '**/**.mtr').each { def g = it def taskname = "generateExpressionDSLTRRules${it.getName().substring(0, it.getName().lastIndexOf('.'))}" - task "$taskname"(type: MontiTransExec) { - getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.main.runtimeClasspath) + tasks.register(taskname, MontiTransExec) { + getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.trafo.runtimeClasspath) TFGenTool = 'mc.testcases.tr.ExpressionDSLTFGenTool' input = file(g) - outputDir = file("$buildDir/generated-sources") + outputDir = file(_outputDir) } generateExpressionDSLTRRules.dependsOn("$taskname") } @@ -60,3 +63,22 @@ compileJava { sourceSets { main.java.srcDirs += [ _outputDir ] } +// As we add the MontiTrans output as a main java output, we have to add this crude dependsOn +tasks.named("generateMCGrammars") { + dependsOn(tasks.withType(MontiTransExec)) +} + +// Make the trafo sourceset available to tests +sourceSets { + test { + compileClasspath += sourceSets.trafo.output + runtimeClasspath += sourceSets.trafo.output + } +} +configurations { + testImplementation.extendsFrom(trafoImplementation) +} + +tasks.named('testClasses') { + dependsOn tasks.named('trafoClasses') +} \ No newline at end of file diff --git a/monticore-test/montitrans/test-generated-dstls/src/main/grammars/mc/testcases/statechart/Statechart.mc4 b/monticore-test/montitrans/test-generated-dstls/src/main/grammars/mc/testcases/statechart/Statechart.mc4 deleted file mode 100644 index 58ee36f727..0000000000 --- a/monticore-test/montitrans/test-generated-dstls/src/main/grammars/mc/testcases/statechart/Statechart.mc4 +++ /dev/null @@ -1,90 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package mc.testcases.statechart; - -grammar Statechart extends de.monticore.MCBasics{ - - - Statechart implements SCStructure = - "statechart" - Name - "{" - State* - Transition* - "}"; - - - EntryAction= "entry" ":" Block:BlockStatement; - - ExitAction= "exit" ":" Block:BlockStatement; - - DoAction= "do" ":" Block:BlockStatement; - - InternTransition = "-intern>" - ( ":" - (Event:Name ( - "(" (Argument:Argument ( "," Argument:Argument)*) ")" )? - )? - ("[" PreCondition: Expression "]")? - ("/" Action: BlockStatement ("[" PostCondition: Expression "]")?)? ";" - | ";"); - - State implements SCStructure = - "state" Name ("<<" (Initial:["initial"] | Final:["final"]) ">>")* - ( ("{" ("[" Invariant:Expression ( "&&" Invariant:Expression)* "]")? - (EntryAction)? - (DoAction)? - (ExitAction)? - State* - Transition* - InternTransition* - "}") | ";") - ; - - Transition = From:Name "->" To:Name - (":" (Event:Name ( - "(" ((Argument:Argument ( "," Argument:Argument)*)?) ")" )? )? - ("[" PreCondition: Expression "]")? - ("/" Action: BlockStatement ("[" PostCondition: Expression "]")?)? ";" - | ";"); - - Argument= ParamType:Name ParamName:Name; - - interface SCStructure; - - astrule SCStructure = - Name - State* - Transition* - // method public String toString() {return getName();} - ; - - - interface Statement; - - BlockStatement implements Statement = - "{" (Statement:Statement)* "}" - ; - - interface Expression; - - ExpStatement implements Statement = - Expression:Expression ";" - ; - - EqualityExpression implements Expression = - LeftOperand:Name - Operator:["!=" | "=="] RightOperand:Name - ; - - MethodInvocationWithQualifiedName implements Expression = - Name ( "." Name)* - "(" - (Argument: Expression ("," Argument: Expression)*)? - ")" - ; - - FieldAccess implements Expression = - Name - ; - -} diff --git a/monticore-test/montitrans/test-generated-dstls/src/test/java/expressiondsl/ExpressionDSLTest.java b/monticore-test/montitrans/test-generated-dstls/src/test/java/expressiondsl/ExpressionDSLTest.java index 99a95eb1d3..a97ecdf519 100644 --- a/monticore-test/montitrans/test-generated-dstls/src/test/java/expressiondsl/ExpressionDSLTest.java +++ b/monticore-test/montitrans/test-generated-dstls/src/test/java/expressiondsl/ExpressionDSLTest.java @@ -13,28 +13,31 @@ import de.monticore.visitor.ITraverser; import de.monticore.visitor.IVisitor; import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; import mc.testcases.expressiondsl.ExpressionDSLMill; import mc.testcases.expressiondsl._ast.ASTCDAttribute; import mc.testcases.expressiondsl._ast.ASTFoo; import mc.testcases.tr.expressiondsltr.ExpressionDSLTRMill; -import org.junit.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; import java.util.function.Function; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class ExpressionDSLTest { - @Before + @BeforeEach public void beforeEach() { Log.clearFindings(); } - @BeforeClass + @BeforeAll public static void beforeClass() { - Log.init(); + LogStub.init(); Log.enableFailQuick(false); ExpressionDSLMill.init(); } @@ -116,12 +119,12 @@ public void testChangeSetterCall() throws IOException { @Test public void testExpressionInterfacePatternPriority() throws IOException { Optional astExpressionOpt = ExpressionDSLTRMill.parser().parse_StringExpression_Pat("Expression $name"); - Assert.assertTrue(astExpressionOpt.isPresent()); - Assert.assertEquals(ASTExpression_Pat.class.getName(), astExpressionOpt.get().getClass().getName()); + assertTrue(astExpressionOpt.isPresent()); + assertEquals(ASTExpression_Pat.class.getName(), astExpressionOpt.get().getClass().getName()); Optional astitfExpressionOpt = ExpressionDSLTRMill.parser().parse_StringITFExpression("Expression $name"); - Assert.assertTrue(astitfExpressionOpt.isPresent()); - Assert.assertEquals(ASTExpression_Pat.class.getName(), astitfExpressionOpt.get().getClass().getName()); + assertTrue(astitfExpressionOpt.isPresent()); + assertEquals(ASTExpression_Pat.class.getName(), astitfExpressionOpt.get().getClass().getName()); } @@ -142,10 +145,10 @@ public void testCDAttributeChangeTypeFull() throws IOException { protected void test(String input, Function rule, String expected) throws IOException { Optional fooOpt = ExpressionDSLMill.parser().parse_String(input); - Assert.assertTrue(fooOpt.isPresent()); + assertTrue(fooOpt.isPresent()); ODRule trafo = rule.apply(fooOpt.get()); - assertTrue("Failed to match pattern", trafo.doPatternMatching()); + assertTrue(trafo.doPatternMatching(), "Failed to match pattern"); trafo.doReplacement(); testDeepEqualsFoo(fooOpt.get(), expected); @@ -153,10 +156,10 @@ protected void test(String input, Function rule, String expected protected void testCDAttribute(String input, Function rule, String expected) throws IOException { Optional fooOpt = ExpressionDSLMill.parser().parse_StringCDAttribute(input); - Assert.assertTrue(fooOpt.isPresent()); + assertTrue(fooOpt.isPresent()); ODRule trafo = rule.apply(fooOpt.get()); - assertTrue("Failed to match pattern", trafo.doPatternMatching()); + assertTrue(trafo.doPatternMatching(), "Failed to match pattern"); trafo.doReplacement(); testDeepEqualsCDAttribute(fooOpt.get(), expected); @@ -173,13 +176,13 @@ protected void testDeepEqualsCDAttribute(ASTCDAttribute ast, String expected) th } private void testDeepEquals(ASTNode ast, String expected, Optional fooOpt) { - Assert.assertTrue("Failed to parse expected", fooOpt.isPresent()); + assertTrue(fooOpt.isPresent(), "Failed to parse expected"); if (!fooOpt.get().deepEquals(ast)) { - Assert.assertEquals(ExpressionDSLMill.prettyPrint(fooOpt.get(), false), ExpressionDSLMill.prettyPrint(ast, false)); - Assert.assertEquals(astPrinter(fooOpt.get(), ExpressionDSLMill.inheritanceTraverser()), + assertEquals(ExpressionDSLMill.prettyPrint(fooOpt.get(), false), ExpressionDSLMill.prettyPrint(ast, false)); + assertEquals(astPrinter(fooOpt.get(), ExpressionDSLMill.inheritanceTraverser()), astPrinter(ast, ExpressionDSLMill.inheritanceTraverser())); - Assert.fail("Failed to deep equal: " + ExpressionDSLMill.prettyPrint(fooOpt.get(), false) + ", expected " + expected); + fail("Failed to deep equal: " + ExpressionDSLMill.prettyPrint(fooOpt.get(), false) + ", expected " + expected); } } diff --git a/monticore-test/montitrans/test-generated-dstls/src/test/java/social/DeleteAllEntriesFromUserTest.java b/monticore-test/montitrans/test-generated-dstls/src/test/java/social/DeleteAllEntriesFromUserTest.java index ebea71f706..b3c64c1b73 100644 --- a/monticore-test/montitrans/test-generated-dstls/src/test/java/social/DeleteAllEntriesFromUserTest.java +++ b/monticore-test/montitrans/test-generated-dstls/src/test/java/social/DeleteAllEntriesFromUserTest.java @@ -6,18 +6,18 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.social.socialnetwork._ast.ASTNetwork; import mc.testcases.social.socialnetwork._parser.SocialNetworkParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DeleteAllEntriesFromUserTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test01_ParsePedestrianLightTest.java b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test01_ParsePedestrianLightTest.java index 16708c0b89..84c96faaac 100644 --- a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test01_ParsePedestrianLightTest.java +++ b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test01_ParsePedestrianLightTest.java @@ -2,23 +2,25 @@ package trafo; import de.se_rwth.commons.logging.LogStub; -import junit.framework.TestCase; import mc.testcases.statechart.statechart._ast.ASTStatechart; import mc.testcases.statechart.statechart._parser.StatechartParser; -import org.junit.Before; -import org.junit.BeforeClass; import java.io.IOException; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class Test01_ParsePedestrianLightTest extends TestCase { +import static org.junit.jupiter.api.Assertions.*; + +public class Test01_ParsePedestrianLightTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } + @Test public void testDoAll() throws IOException { StatechartParser px = new StatechartParser(); ASTStatechart sc =px.parse("src/test/resources/trafo/PedestrianLight.sc").get(); diff --git a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test02_EliminateDoTest.java b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test02_EliminateDoTest.java index 838f14bad6..0170c8c463 100644 --- a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test02_EliminateDoTest.java +++ b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test02_EliminateDoTest.java @@ -3,23 +3,25 @@ import de.monticore.tf.EliminateDo; import de.se_rwth.commons.logging.LogStub; -import junit.framework.TestCase; import mc.testcases.statechart.statechart._ast.*; import mc.testcases.statechart.statechart._parser.StatechartParser; -import org.junit.Before; -import org.junit.BeforeClass; import java.io.IOException; import de.se_rwth.commons.logging.Log; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class Test02_EliminateDoTest extends TestCase { +import static org.junit.jupiter.api.Assertions.*; + +public class Test02_EliminateDoTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } + @Test public void testDoAll() throws IOException { StatechartParser p = new StatechartParser(); @@ -36,20 +38,20 @@ public void testDoAll() throws IOException { assertNotNull(state); ASTEntryAction entryAction = state.getEntryAction(); - assertNotNull("entry action has not been added", entryAction); - assertNotNull("entry action is empty", entryAction.getBlock()); + assertNotNull(entryAction, "entry action has not been added"); + assertNotNull(entryAction.getBlock(), "entry action is empty"); - assertFalse("do action has not been removed", state.isPresentDoAction()); + assertFalse(state.isPresentDoAction(), "do action has not been removed"); ASTExitAction exitAction = state.getExitAction(); - assertNotNull("exit action has not been added", exitAction); - assertNotNull("exit action is empty", exitAction.getBlock()); + assertNotNull(exitAction, "exit action has not been added"); + assertNotNull(exitAction.getBlock(), "exit action is empty"); ASTInternTransition internTransition = state.getInternTransition(0); - assertNotNull("intern transition has not been created", internTransition); + assertNotNull(internTransition, "intern transition has not been created"); ASTBlockStatement internAction = internTransition.getAction(); - assertNotNull("intern transition has no action", internAction); - assertEquals("incorrect number of statements in intern action", 2, internAction.getStatementList().size()); + assertNotNull(internAction, "intern transition has no action"); + assertEquals(2, internAction.getStatementList().size(), "incorrect number of statements in intern action"); testee.undoReplacement(); assertFalse(state.isPresentEntryAction()); diff --git a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test08_InsertStatesTest.java b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test08_InsertStatesTest.java index 256c96d113..2aa524632e 100644 --- a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test08_InsertStatesTest.java +++ b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test08_InsertStatesTest.java @@ -7,18 +7,18 @@ import de.monticore.tf.InsertStateRelative; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import junit.framework.TestCase; import mc.testcases.statechart.statechart._ast.*; import mc.testcases.statechart.statechart._parser.StatechartParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -public class Test08_InsertStatesTest extends TestCase { +import static org.junit.jupiter.api.Assertions.*; + +public class Test08_InsertStatesTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test09_CopyTransitionTest.java b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test09_CopyTransitionTest.java index efc388610b..70ca4da052 100644 --- a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test09_CopyTransitionTest.java +++ b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test09_CopyTransitionTest.java @@ -4,19 +4,19 @@ import de.monticore.tf.CopyTransitionToSubstate; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import junit.framework.TestCase; import mc.testcases.statechart.statechart._ast.ASTState; import mc.testcases.statechart.statechart._ast.ASTStatechart; import mc.testcases.statechart.statechart._parser.StatechartParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -public class Test09_CopyTransitionTest extends TestCase { +import static org.junit.jupiter.api.Assertions.*; + +public class Test09_CopyTransitionTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test10_DeleteTransitionTest.java b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test10_DeleteTransitionTest.java index b4960b4a27..497d072141 100644 --- a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test10_DeleteTransitionTest.java +++ b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test10_DeleteTransitionTest.java @@ -4,19 +4,19 @@ import de.monticore.tf.DeleteTransition; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import junit.framework.TestCase; import mc.testcases.statechart.statechart._ast.ASTState; import mc.testcases.statechart.statechart._ast.ASTStatechart; import mc.testcases.statechart.statechart._parser.StatechartParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -public class Test10_DeleteTransitionTest extends TestCase { +import static org.junit.jupiter.api.Assertions.*; + +public class Test10_DeleteTransitionTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test11_SetInitialTest.java b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test11_SetInitialTest.java index 6a5184145f..0197bcecaa 100644 --- a/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test11_SetInitialTest.java +++ b/monticore-test/montitrans/test-generated-dstls/src/test/java/trafo/Test11_SetInitialTest.java @@ -4,19 +4,19 @@ import de.monticore.tf.SetInitial; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import junit.framework.TestCase; import mc.testcases.statechart.statechart._ast.ASTState; import mc.testcases.statechart.statechart._ast.ASTStatechart; import mc.testcases.statechart.statechart._parser.StatechartParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -public class Test11_SetInitialTest extends TestCase { +import static org.junit.jupiter.api.Assertions.*; + +public class Test11_SetInitialTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/build.gradle b/monticore-test/montitrans/test-odrules/build.gradle index e6d1845289..52e6cd92d8 100644 --- a/monticore-test/montitrans/test-odrules/build.gradle +++ b/monticore-test/montitrans/test-odrules/build.gradle @@ -1,76 +1,71 @@ -import de.monticore.MCTask - /* (c) https://github.com/MontiCore/monticore */ description = 'MontiTrans Test: ODRules' -def grammarsDir = "$projectDir/src/main/grammars" + def modelsDir = "$projectDir/src/main/models" -def _outputDir = "$buildDir/generated-sources" +def _outputDir = "$buildDir/generated-sources/trafogen" dependencies { - implementation project(':monticore-test:montitrans:test-dstl-gen') + grammar project(':monticore-test:montitrans:test-dstl-gen') } - -// Generate test languages -// create a task for each grammar in grammarDir -fileTree(grammarsDir).each { - def g = it - task "generate${it.getName().substring(0,it.getName().lastIndexOf('.'))}" (type: MCTask) { - grammar = file g - outputDir = file "$buildDir/generated-sources" - def uptoDate = incCheck(g.toString().substring(grammarsDir.length() + 1)) - outputs.upToDateWhen { uptoDate } - } -} - -task generateMTOD { +tasks.register('generateMTOD') { group = "montitrans" - dependsOn(tasks.withType(MCTask)) } +import de.monticore.MontiTransExec +import de.monticore.gradle.gen.MCGenTask + fileTree(dir: "$modelsDir/automaton", include: '*.mtod').each { def g = it def taskname = "generateAutomatonTRRule${it.getName().substring(0, it.getName().lastIndexOf('.'))}" - task "$taskname"(type: MontiTransExec) { + tasks.register(taskname, MontiTransExec) { group = "montitrans" - getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.main.runtimeClasspath) + getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.trafo.runtimeClasspath) TFGenTool = 'de.monticore.tf.odrules.ODRulesCLI' input = file(g) - outputDir = file("$buildDir/generated-sources") + outputDir = file(_outputDir) } generateMTOD.dependsOn("$taskname") } fileTree(dir: "$modelsDir/misc", include: '*.mtod').each { def g = it def taskname = "generateMiscTRRules${it.getName().substring(0, it.getName().lastIndexOf('.'))}" - task "$taskname"(type: MontiTransExec) { - getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.main.runtimeClasspath) + tasks.register(taskname, MontiTransExec) { + getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.trafo.runtimeClasspath) TFGenTool = 'de.monticore.tf.odrules.ODRulesCLI' input = file(g) - outputDir = file("$buildDir/generated-sources") + outputDir = file(_outputDir) } generateMTOD.dependsOn("$taskname") } -task generatePetrinetTRRules { +tasks.register('generatePetrinetTRRules') { group = "montitrans" } fileTree(dir: "$modelsDir/petrinet", include: '**/**.mtod').each { def g = it def taskname = "generatePetrinetTRRules${it.getName().substring(0, it.getName().lastIndexOf('.'))}" - task "$taskname"(type: MontiTransExec) { - getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.main.runtimeClasspath) + tasks.register(taskname, MontiTransExec) { + getClassPath().setFrom(project(':monticore-test:montitrans:test-dstl-gen').sourceSets.trafo.runtimeClasspath) TFGenTool = 'de.monticore.tf.odrules.ODRulesCLI' input = file(g) - outputDir = file("$buildDir/generated-sources") + outputDir = file(_outputDir) } generateMTOD.dependsOn("$taskname") } compileJava { - dependsOn project.collect { it.tasks.withType(MCTask) } dependsOn "generateMTOD" } +// As we add the MontiTrans output as a main java output, we have to add this crude dependsOn +tasks.named("generateMCGrammars") { + dependsOn(tasks.withType(MontiTransExec)) +} + sourceSets { main.java.srcDirs += [ _outputDir ] } +// As we add the MontiTrans output as a main java output, we have to add this crude dependsOn +tasks.named("generateMCGrammars", MCGenTask) { + handWrittenCodeDir.setFrom(["empty_path"]) // Disable handwritten +} diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/AtMostOneStateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/AtMostOneStateTest.java index 54666a6e4f..aeb8fbab08 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/AtMostOneStateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/AtMostOneStateTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class AtMostOneStateTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/AtMostOneSubstateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/AtMostOneSubstateTest.java index 4931705ed5..e1e1ef9461 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/AtMostOneSubstateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/AtMostOneSubstateTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class AtMostOneSubstateTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ChangeFixNameTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ChangeFixNameTest.java index 2fa254ca44..8d4417e827 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ChangeFixNameTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ChangeFixNameTest.java @@ -7,26 +7,25 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class ChangeFixNameTest { private ASTState state; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() throws IOException { String inputFile = "src/main/models/automaton/AutomatonWithSingleState.aut"; AutomatonParser parser = new AutomatonParser(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ChangeMarkerTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ChangeMarkerTest.java index 09a58e929c..52de972785 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ChangeMarkerTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ChangeMarkerTest.java @@ -5,27 +5,26 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.petrinet._ast.ASTPetrinet; import mc.testcases.petrinet._parser.PetrinetParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ChangeMarkerTest { ChangeMarker cm; ASTPetrinet petri; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void doBefore() throws IOException { String inputFile = "src/main/models/petrinet/TestPetriNet.pn"; PetrinetParser parser = new PetrinetParser(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintAlongOptionalTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintAlongOptionalTest.java index 5698f18714..7bca4ba6c5 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintAlongOptionalTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintAlongOptionalTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class ConstraintAlongOptionalTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintEmbeddingTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintEmbeddingTest.java index e773d0ee55..0ac2926156 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintEmbeddingTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintEmbeddingTest.java @@ -5,19 +5,18 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConstraintEmbeddingTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintForOptionalTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintForOptionalTest.java index 6c76a647cf..67bcb88bd0 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintForOptionalTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ConstraintForOptionalTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class ConstraintForOptionalTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopySubListDefInListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopySubListDefInListTest.java index 8298bacfc8..50530f61ae 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopySubListDefInListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopySubListDefInListTest.java @@ -6,15 +6,15 @@ import mc.testcases.misc.MiscMill; import mc.testcases.misc._ast.ASTDef; import mc.testcases.misc._ast.ASTSub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CopySubListDefInListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -23,7 +23,7 @@ public void before() { ASTDef def, def2, def3, def4; ASTSub sub, sub2; - @Before + @BeforeEach public void setUp() { def = MiscMill.defBuilder().uncheckedBuild(); def2 = MiscMill.defBuilder().uncheckedBuild(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopySubListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopySubListTest.java index faf61f9eec..637da12c47 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopySubListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopySubListTest.java @@ -6,16 +6,15 @@ import mc.testcases.misc.MiscMill; import mc.testcases.misc._ast.ASTDef; import mc.testcases.misc._ast.ASTSub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CopySubListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -26,7 +25,7 @@ public void before() { ASTDef def2; ASTSub sub; - @Before + @BeforeEach public void setUp() { rootdef = MiscMill.defBuilder().uncheckedBuild(); def1 = MiscMill.defBuilder().uncheckedBuild(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopyTransitionsTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopyTransitionsTest.java index b53438d16d..d7d83cd393 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopyTransitionsTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CopyTransitionsTest.java @@ -6,19 +6,18 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CopyTransitionsTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CreateInOptionalTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CreateInOptionalTest.java index ebeff1f6fa..022f04d5cb 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CreateInOptionalTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CreateInOptionalTest.java @@ -5,21 +5,19 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class CreateInOptionalTest { private ASTAutomaton automaton; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CreateStateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CreateStateTest.java index 1000b6876f..0c233ecdc2 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CreateStateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/CreateStateTest.java @@ -5,25 +5,24 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class CreateStateTest { ASTAutomaton aut; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() throws IOException { String inputFile = "src/main/models/automaton/EmptyAutomaton.aut"; AutomatonParser parser = new AutomatonParser(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteOptionalStateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteOptionalStateTest.java index 5d980ba793..b6c0af6ff7 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteOptionalStateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteOptionalStateTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class DeleteOptionalStateTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteStateListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteStateListTest.java index c1c3feb0a5..67a5fa6aad 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteStateListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteStateListTest.java @@ -7,28 +7,26 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DeleteStateListTest { ASTAutomaton aut; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() throws IOException { String inputFile = "src/main/models/automaton/AutomatonTwoStatesAndSubstate.aut"; AutomatonParser parser = new AutomatonParser(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteStateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteStateTest.java index 753b90aada..35a0c6af52 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteStateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteStateTest.java @@ -5,27 +5,25 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DeleteStateTest { ASTAutomaton aut; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() throws IOException { String inputFile = "src/main/models/automaton/AutomatonWithSingleState.aut"; AutomatonParser parser = new AutomatonParser(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteSubListDefInListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteSubListDefInListTest.java index 71b7d88a09..3a2b8ef9dc 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteSubListDefInListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteSubListDefInListTest.java @@ -6,15 +6,15 @@ import mc.testcases.misc.MiscMill; import mc.testcases.misc._ast.ASTDef; import mc.testcases.misc._ast.ASTSub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DeleteSubListDefInListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -25,7 +25,7 @@ public void before() { ASTSub sub; ASTSub sub2; - @Before + @BeforeEach public void setUp() { def = MiscMill.defBuilder().uncheckedBuild(); def2 = MiscMill.defBuilder().uncheckedBuild(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteSubListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteSubListTest.java index 9328d73bfb..191dffcb49 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteSubListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteSubListTest.java @@ -6,15 +6,14 @@ import mc.testcases.misc.MiscMill; import mc.testcases.misc._ast.ASTDef; import mc.testcases.misc._ast.ASTSub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class DeleteSubListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -23,7 +22,7 @@ public void before() { ASTDef def; ASTSub sub; - @Before + @BeforeEach public void setUp() { def = MiscMill.defBuilder().uncheckedBuild(); sub = MiscMill.subBuilder().uncheckedBuild(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteTransitionsTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteTransitionsTest.java index da85424dba..0f77aecc4c 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteTransitionsTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DeleteTransitionsTest.java @@ -6,20 +6,18 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DeleteTransitionsTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DoBlockTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DoBlockTest.java index 63eeff3642..322c02cb08 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DoBlockTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/DoBlockTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DoBlockTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ExpandInitialTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ExpandInitialTest.java index 5b534cae5f..f1e1e1f73e 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ExpandInitialTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ExpandInitialTest.java @@ -5,20 +5,18 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ExpandInitialTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FlattenStateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FlattenStateTest.java index c0bea15750..6d500f6b27 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FlattenStateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FlattenStateTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class FlattenStateTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FlattenStateWithAtMostTwoSubstatesTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FlattenStateWithAtMostTwoSubstatesTest.java index 2e388db7f4..4b32137c89 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FlattenStateWithAtMostTwoSubstatesTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FlattenStateWithAtMostTwoSubstatesTest.java @@ -5,19 +5,18 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class FlattenStateWithAtMostTwoSubstatesTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -120,7 +119,7 @@ public void testAutomatonWithTwoStatesAndSubstate() throws IOException { } // Todo: patternMatching doesnt terminate - @Ignore + @Disabled @Test public void testAutomatonWithThreeSubstates() throws IOException { String inputFile = "src/main/models/automaton/AutomatonStateWithThreeSubstates.aut"; diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FoldListStateRuleTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FoldListStateRuleTest.java index 108d0886a3..a499e9f6be 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FoldListStateRuleTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FoldListStateRuleTest.java @@ -6,20 +6,18 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.*; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.*; public class FoldListStateRuleTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FoldStateRuleTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FoldStateRuleTest.java index 37593b80ae..af9c480ca2 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FoldStateRuleTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/FoldStateRuleTest.java @@ -6,19 +6,17 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class FoldStateRuleTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -42,7 +40,7 @@ public void testEmptyAutomat() throws IOException { assertFalse(state_1.isInitial()); ASTState state_2 = rule.get_state_2(); // compare by object identity - assertTrue(state_1 == state_2); + assertSame(state_1, state_2); assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ForwardTransitionRuleTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ForwardTransitionRuleTest.java index e7f10c29ba..4ea0e43109 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ForwardTransitionRuleTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ForwardTransitionRuleTest.java @@ -6,20 +6,19 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ForwardTransitionRuleTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListPrototypeCopyTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListPrototypeCopyTest.java index 9a655cf2ab..9d16bc2b91 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListPrototypeCopyTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListPrototypeCopyTest.java @@ -6,27 +6,26 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ListPrototypeCopyTest { ASTAutomaton aut; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() throws IOException { String inputFile = "src/main/models/automaton/AutomatonSubstateWithSubstate.aut"; AutomatonParser parser = new AutomatonParser(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListPrototypeTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListPrototypeTest.java index 857c71d6ed..093684d6ce 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListPrototypeTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListPrototypeTest.java @@ -7,30 +7,27 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ListPrototypeTest { ASTAutomaton aut; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); } - @Before + @BeforeEach public void setUp() throws IOException { String inputFile = "src/main/models/automaton/AutomatonSubstateWithSubstate.aut"; AutomatonParser parser = new AutomatonParser(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListStateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListStateTest.java index 31c93dc42d..c9f27fb273 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListStateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListStateTest.java @@ -6,20 +6,18 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.*; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.*; public class ListStateTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -44,7 +42,7 @@ public void testEmptyAutomat() throws IOException { List list_state_1 = rule.get_list_1_state_1(); assertEquals(2, list_state_1.size()); for (ASTState s : list_state_1) { - assertTrue(s.getName() + "is not initial", s.isInitial()); + assertTrue(s.isInitial(), s.getName() + "is not initial"); } assertTrue(Log.getFindings().isEmpty()); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListThenNotTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListThenNotTest.java index 244d69dbba..441ea3a702 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListThenNotTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListThenNotTest.java @@ -6,20 +6,18 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.List; import java.util.Optional; -import static org.junit.Assert.*; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ListThenNotTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListWithAssignTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListWithAssignTest.java index 82f03ea8f9..361e956736 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListWithAssignTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListWithAssignTest.java @@ -6,20 +6,18 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.List; import java.util.Optional; -import static org.junit.Assert.*; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ListWithAssignTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListWithConstraintTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListWithConstraintTest.java index c93088dea3..8b4ff0d06f 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListWithConstraintTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/ListWithConstraintTest.java @@ -6,20 +6,17 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.List; import java.util.Optional; -import static org.junit.Assert.*; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ListWithConstraintTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubListDefInListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubListDefInListTest.java index 619128bc40..6ecd08322a 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubListDefInListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubListDefInListTest.java @@ -6,16 +6,15 @@ import mc.testcases.misc.MiscMill; import mc.testcases.misc._ast.ASTDef; import mc.testcases.misc._ast.ASTSub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MoveSubListDefInListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -24,7 +23,7 @@ public void before() { ASTDef def, def2, def3, def4; ASTSub sub, sub2; - @Before + @BeforeEach public void setUp() { def = MiscMill.defBuilder().uncheckedBuild(); def2 = MiscMill.defBuilder().uncheckedBuild(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubListTest.java index 860652782d..87ddf601dd 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubListTest.java @@ -6,15 +6,15 @@ import mc.testcases.misc.MiscMill; import mc.testcases.misc._ast.ASTDef; import mc.testcases.misc._ast.ASTSub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MoveSubListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -25,7 +25,7 @@ public void before() { ASTDef def2; ASTSub sub; - @Before + @BeforeEach public void setUp() { rootdef = MiscMill.defBuilder().uncheckedBuild(); def1 = MiscMill.defBuilder().uncheckedBuild(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubTest.java index 8fde8e74bc..4d67481e79 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubTest.java @@ -7,18 +7,17 @@ import mc.testcases.misc.MiscMill; import mc.testcases.misc._ast.ASTDef; import mc.testcases.misc._ast.ASTSub; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class MoveSubTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); @@ -27,7 +26,7 @@ public void before() { ASTDef oldParent, newParent; ASTSub child; - @Before + @BeforeEach public void setUp() { oldParent = MiscMill.defBuilder().uncheckedBuild(); newParent = MiscMill.defBuilder().uncheckedBuild(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubstateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubstateTest.java index 2e9b0403e3..7a7aa0faea 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubstateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveSubstateTest.java @@ -5,21 +5,19 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MoveSubstateTest { ASTAutomaton aut; - @Before + @BeforeEach public void setUp() throws IOException { String inputFile = "src/main/models/automaton/AutomatonTwoStatesAndSubstate.aut"; AutomatonParser parser = new AutomatonParser(); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveTransitionsTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveTransitionsTest.java index 59d930fbd6..00e79ac995 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveTransitionsTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/MoveTransitionsTest.java @@ -6,19 +6,18 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MoveTransitionsTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NonEmptyListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NonEmptyListTest.java index 02ffc09e47..8705304929 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NonEmptyListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NonEmptyListTest.java @@ -6,18 +6,17 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class NonEmptyListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotInListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotInListTest.java index 42f6fc1a07..08ee919b7e 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotInListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotInListTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class NotInListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotStateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotStateTest.java index 37a7448564..5cda0f6581 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotStateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotStateTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class NotStateTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotStateWithConditionsTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotStateWithConditionsTest.java index a11914e734..0e71725791 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotStateWithConditionsTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/NotStateWithConditionsTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class NotStateWithConditionsTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptInListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptInListTest.java index 563587a098..762b9b3d8d 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptInListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptInListTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class OptInListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptStateWithOptSubstateTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptStateWithOptSubstateTest.java index dea0f6a3e3..69c211812f 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptStateWithOptSubstateTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptStateWithOptSubstateTest.java @@ -5,18 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class OptStateWithOptSubstateTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptionalChangeFixNameTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptionalChangeFixNameTest.java index f4c0f92e75..d93731bb34 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptionalChangeFixNameTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptionalChangeFixNameTest.java @@ -1,25 +1,23 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.tf; -import com.google.common.collect.Lists; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class OptionalChangeFixNameTest { private ASTAutomaton automaton; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptionalListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptionalListTest.java index 4eb72899b4..0769941713 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptionalListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/OptionalListTest.java @@ -5,21 +5,19 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class OptionalListTest { private ASTAutomaton automaton; - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/SetInitialToFalseInListTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/SetInitialToFalseInListTest.java index c6ca16cfd2..656fb13044 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/SetInitialToFalseInListTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/SetInitialToFalseInListTest.java @@ -5,19 +5,17 @@ import de.se_rwth.commons.logging.LogStub; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class SetInitialToFalseInListTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/SetInitialToFalseTest.java b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/SetInitialToFalseTest.java index a9b0cb030e..75db10e25e 100644 --- a/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/SetInitialToFalseTest.java +++ b/monticore-test/montitrans/test-odrules/src/test/java/de/monticore/tf/SetInitialToFalseTest.java @@ -6,18 +6,16 @@ import mc.testcases.automaton._ast.ASTAutomaton; import mc.testcases.automaton._ast.ASTState; import mc.testcases.automaton._parser.AutomatonParser; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class SetInitialToFalseTest { - @Before + @BeforeEach public void before() { LogStub.init(); Log.enableFailQuick(false); diff --git a/prepare-next-release/0001-use-next-snapshot.patch b/prepare-next-release/0001-use-next-snapshot.patch new file mode 100644 index 0000000000..f0699c2ec0 --- /dev/null +++ b/prepare-next-release/0001-use-next-snapshot.patch @@ -0,0 +1,57 @@ +From 28259ce5949049ee78bb720c13636850ebca0f1c Mon Sep 17 00:00:00 2001 +From: Janik Rapp +Date: Fri, 2 Jan 2026 14:32:48 +0100 +Subject: [PATCH] [PATCH] use next snapshot + + +diff --git a/gradle.properties b/gradle.properties +index 3bc21f46d..26a2df7a3 100644 +--- a/gradle.properties ++++ b/gradle.properties +@@ -14,11 +14,11 @@ org.gradle.caching=true + # org.gradle.caching.debug=true + + # versions used +-version=7.9.0-SNAPSHOT +-previous_mc_version =7.8.0 ++version=7.10.0-SNAPSHOT ++previous_mc_version =7.9.0-SNAPSHOT + + commons_cli_version = 1.4 +-se_commons_version =7.8.0 ++se_commons_version =7.9.0-SNAPSHOT + antlr_version =4.12.0 + junit_version = 5.14.1 + junit_platform_version = 1.14.1 +@@ -29,4 +29,4 @@ freemarker_version = 2.3.34 + guava_version =31.1-jre + shadow_plugin_version=7.1.2 + +-cd4a_version =7.8.0 ++cd4a_version =7.9.0-SNAPSHOT +diff --git a/monticore-generator/gradle.properties b/monticore-generator/gradle.properties +index a4171758b..5249f4006 100644 +--- a/monticore-generator/gradle.properties ++++ b/monticore-generator/gradle.properties +@@ -9,14 +9,14 @@ useLocalRepo=false + showTestOutput=false + + # versions used +-version=7.9.0-SNAPSHOT +-previous_mc_version =7.8.0 ++version=7.10.0-SNAPSHOT ++previous_mc_version =7.9.0-SNAPSHOT + +-se_commons_version =7.8.0 ++se_commons_version =7.9.0-SNAPSHOT + antlr_version =4.12.0 + junit_version = 5.14.1 + junit_platform_version = 1.14.1 +-cd4a_version =7.8.0 ++cd4a_version =7.9.0-SNAPSHOT + commons_lang3_version = 3.8.1 + commons_cli_version = 1.4 + freemarker_version = 2.3.28 +-- +2.47.1.windows.1 + diff --git a/prepare-next-release/PreparingTheNextRelease.md b/prepare-next-release/PreparingTheNextRelease.md new file mode 100644 index 0000000000..c262ec7b77 --- /dev/null +++ b/prepare-next-release/PreparingTheNextRelease.md @@ -0,0 +1,44 @@ + + +Due to MontiCore bootstrapping itself via the grammar and cd DSLs, +creating the next snapshot version is always a hassle. +This directory aims to catch breaking changes of the new version early +and collects patches for the next release. + +To this aim, git patches with the required changes are collected in this directory. + +> This document is still a work in progress + +## Your PR breaks the next MontiCore release + +Please create a patch for your changes, +such that the next MontiCore release is easier. + +Work in your git branch, but please do not have any local, uncommited changes. +You can reset your local working tree via `git reset --hard yourBranchName` + +Apply all previous patches: `./prepare-next-release/applyPatches.sh` +(this applies all patch files and switches to a new branch) + +Modify the source files and ensure that the previously failing tests now work. +Then create a commit as usual +(e.g., `git add ` & `git commit -m `). +To build the patch file and change back to your original branch, +use: `./prepare-next-release/buildPatches.sh` + +We can't commit and push the soon-to-be-required changes to the repository. +Instead, add and commit the patch file to your branch. +(This patch file will now be used after building the next release.) +(You can ignore the changes to the hash of the previous patch files.) + +_Note: Any breaking changes in upstream projects may trigger the build jobs failure._ + +## Post-Release work + +Congratulations, you have just released MontiCore, etc. + +* Delete the first patch file (as it uses the snapshot version instead of full releases) +* Next, apply all remaining patches & push them. +* Remove all patch files & recreate the first patch, by using the next snapshot version. + The first patch, 0001-..., should always update the various versions. + diff --git a/prepare-next-release/applyPatches.sh b/prepare-next-release/applyPatches.sh new file mode 100644 index 0000000000..a63b7941db --- /dev/null +++ b/prepare-next-release/applyPatches.sh @@ -0,0 +1,34 @@ +#! /bin/bash +# (c) https://github.com/MontiCore/monticore +# Script for applying all patches to check if we are about to break the next release of MontiCore + +# Start by switching to a new branch (using the suffix -crystal-ball) +currentBranch=`git rev-parse --abbrev-ref HEAD` + +if [[ "$currentBranch" == *"-crystal-ball"* ]]; then + echo "Script may not be executed on a branch with applied patches!" + exit 1 +fi + +git diff-index --quiet --cached HEAD -- +if [ "$?" != "0" ]; then + echo "Dirty index: won't be able to apply patched" + git diff-index --cached HEAD -- + exit 1 +fi + +git checkout -b $currentBranch-crystal-ball +if [ "$?" != "0" ]; then + echo "Failed to switch to new branch $currentBranch-crystal-ball" + exit 1 +fi +# And apply all patches +git am --abort >/dev/null 2>&1 +git am --3way prepare-next-release/*.patch +if [ "$?" != "0" ]; then + echo "Failed to apply the patches." + echo "Please consult the 'PreparingTheNextRelease' documentation " + exit 1 +else + echo "Cleanly applied patches" +fi \ No newline at end of file diff --git a/prepare-next-release/buildPatches.sh b/prepare-next-release/buildPatches.sh new file mode 100644 index 0000000000..f3310e9eff --- /dev/null +++ b/prepare-next-release/buildPatches.sh @@ -0,0 +1,21 @@ +#! /bin/bash +# (c) https://github.com/MontiCore/monticore +# Script for creating new patch files + + +currentBranch=`git rev-parse --abbrev-ref HEAD` + +if [[ "$currentBranch" != *"-crystal-ball"* ]]; then + echo "Script may only be executed on a branch with applied patches!" + exit 1 +fi +originalBranch="${currentBranch/-crystal-ball/}" + +echo "Creating patch difference to $originalBranch" +git format-patch --no-stat --minimal -N -o ./prepare-next-release/ $originalBranch -- +if [ "$?" != "0" ]; then + echo "Failed to create patch differences" + exit 1 +fi +echo "Switching back to branch: $originalBranch" +git checkout $originalBranch diff --git a/settings.gradle b/settings.gradle index 232a89166a..7243bccbaf 100644 --- a/settings.gradle +++ b/settings.gradle @@ -6,14 +6,17 @@ pluginManagement { mavenLocal() } maven { - credentials.username mavenUser - credentials.password mavenPassword - url repo + credentials.username = mavenUser + credentials.password = mavenPassword + url = repo } gradlePluginPortal() } } +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.9.0' +} boolean isCi = System.getenv().containsKey("CI") @@ -82,6 +85,7 @@ include(':monticore-test:01experiments:lexicalModes') include(':monticore-test:01experiments:patternAccess') include(':monticore-test:01experiments:prettyPrinters') include(':monticore-test:01experiments:questionnaire') +include(':monticore-test:01experiments:runtimeOnly') include(':monticore-test:01experiments:S01_intro') include(':monticore-test:01experiments:scannerless') include(':monticore-test:01experiments:spaceOnOff-negative') @@ -131,5 +135,20 @@ if ("true".equals(getProperty('genEMF'))) { // Only test EMF if the flag is set include(':monticore-test:01experiments:forEmfAst') } -// include 'example' -// project(':example').projectDir = file("monticore-test/example") +if (!inComposite) { + // Gradle's project substitution due to composite builds would prevent us from using the previous grammar version + // We avoid this by using the result of the shadowed generator jar + gradle.beforeProject { p -> + p.configurations.configureEach { + if (it.name == "mcTool") { + p.dependencies { + mcTool("de.monticore:monticore-generator:$version") { + capabilities { + requireCapability("de.monticore:monticore-generator-shadow") + } + } + } + } + } + } +} From e5cac5035475d9472abd32df7f1b21df98ea783d Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Fri, 27 Feb 2026 14:14:56 +0100 Subject: [PATCH 24/37] Use ISymbol/MIValue and add simple equations demo --- .../interpreter/InterpreterUtils.java | 6 +- .../de/monticore/interpreter/MIScope.java | 15 +-- .../interpreter/ModelInterpreter.java | 11 +- .../expressions/AbstractInterpreterTest.java | 17 ++- .../LambdaExpressionsInterpreterTest.java | 17 ++- .../_symboltable/TypeSymbolSurrogateTest.java | 4 +- .../de/monticore/types3/AbstractTypeTest.java | 5 +- .../src/main/grammars/Numerals.mc4 | 15 +++ .../src/main/grammars/SimpleEquations.mc4 | 21 ++++ .../_visitor/NumeralsInterpreter.java | 28 +++++ .../_visitor/SimpleEquationsInterpreter.java | 100 ++++++++++++++++++ .../SimpleEquationsInterpreterTest.java | 6 +- .../01.experiments/runtimeOnly/build.gradle | 1 + 13 files changed, 211 insertions(+), 35 deletions(-) create mode 100644 monticore-test/01.experiments/interpreter/src/main/grammars/Numerals.mc4 create mode 100644 monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 create mode 100644 monticore-test/01.experiments/interpreter/src/main/java/numerals/_visitor/NumeralsInterpreter.java create mode 100644 monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java index 4de627f1d8..b99bb55732 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/InterpreterUtils.java @@ -109,7 +109,7 @@ public static MIValue calcShiftPrimitive(MIValue v1, MIValue v2, /** * Calculates the result of a binary operation with the given result type by * using the given lambdas for the calculation. Operation should support - * int, long, float & double. + * int, long, float {@literal &} double. * * @param v1 left operand * @param v2 right operand @@ -138,7 +138,7 @@ public static MIValue calcOp(MIValue v1, MIValue v2, /** * Calculates the result of a bitwise binary operation with the given result type by using - * the given lambdas for the calculation. Operation should support int & long. + * the given lambdas for the calculation. Operation should support int {@literal &} long. * * @param v1 left operand * @param v2 right operand @@ -165,7 +165,7 @@ public static MIValue calcBitwiseOp(MIValue v1, MIValue v2, /** * Calculates the result of a bitwise or logical binary operation with the * given result type by using the given lambdas for the calculation. - * Operation should support boolean, int & long. + * Operation should support boolean, int {@literal &} long. * * @param v1 left operand * @param v2 right operand diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java index b110fcf4f0..e85a6b28f8 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java @@ -4,6 +4,7 @@ import de.monticore.interpreter.values.FunctionMIValue; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symboltable.ISymbol; import de.se_rwth.commons.logging.Log; import java.util.HashMap; @@ -12,8 +13,8 @@ public class MIScope implements IMIScope { - protected Map functionMap = new HashMap<>(); - protected Map> variableMap = new HashMap<>(); + protected Map functionMap = new HashMap<>(); + protected Map> variableMap = new HashMap<>(); protected Optional parent; @@ -33,14 +34,14 @@ public MIScope clone() { return clone; } - public void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { + public void declareFunction(ISymbol symbol, MIValue value) { if (functionMap.containsKey(symbol)) { Log.error("0x57068 Function was already declared"); } this.functionMap.put(symbol, value); } - public MIValue loadFunction(FunctionSymbol symbol) { + public MIValue loadFunction(ISymbol symbol) { if (functionMap.containsKey(symbol)) { return functionMap.get(symbol); } @@ -54,14 +55,14 @@ public MIValue loadFunction(FunctionSymbol symbol) { return new ErrorMIValue(errorMsg); } - public void declareVariable(VariableSymbol symbol, Optional value) { + public void declareVariable(ISymbol symbol, Optional value) { if (variableMap.containsKey(symbol)) { Log.error("0x57070 Variable was already declared"); } this.variableMap.put(symbol, value); } - public MIValue loadVariable(VariableSymbol symbol) { + public MIValue loadVariable(ISymbol symbol) { Optional value = variableMap.get(symbol); if (value != null) { if (value.isPresent()) { @@ -83,7 +84,7 @@ public MIValue loadVariable(VariableSymbol symbol) { return new ErrorMIValue(errorMsg); } - public void storeVariable(VariableSymbol symbol, MIValue value) { + public void storeVariable(ISymbol symbol, MIValue value) { if (variableMap.containsKey(symbol)) { variableMap.put(symbol, Optional.of(value)); } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java index e7df6fe2f8..27492b80ed 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java @@ -4,6 +4,7 @@ import de.monticore.interpreter.values.FunctionMIValue; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symboltable.ISymbol; import java.util.Optional; import java.util.Stack; @@ -47,23 +48,23 @@ default void popScope() { getRealThis().getScopeCallstack().pop(); } - default void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { + default void declareFunction(ISymbol symbol, MIValue value) { getCurrentScope().declareFunction(symbol, value); } - default MIValue loadFunction(FunctionSymbol symbol) { + default MIValue loadFunction(ISymbol symbol) { return getCurrentScope().loadFunction(symbol); } - default void declareVariable(VariableSymbol symbol, Optional value) { + default void declareVariable(ISymbol symbol, Optional value) { getCurrentScope().declareVariable(symbol, value); } - default MIValue loadVariable(VariableSymbol symbol) { + default MIValue loadVariable(ISymbol symbol) { return getCurrentScope().loadVariable(symbol); } - default void storeVariable(VariableSymbol symbol, MIValue value) { + default void storeVariable(ISymbol symbol, MIValue value) { getCurrentScope().storeVariable(symbol, value); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java index bf6067edec..a2d8d6b561 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java @@ -6,8 +6,8 @@ import de.monticore.expressions.combineexpressionswithliterals._parser.CombineExpressionsWithLiteralsParser; import de.monticore.expressions.combineexpressionswithliterals._symboltable.CombineExpressionsWithLiteralsScopesGenitorDelegator; import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsInterpreter; -import de.monticore.interpreter.Value; -import de.monticore.interpreter.values.NotAValue; +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symboltable.modifiers.AccessModifier; import de.monticore.types.check.SymTypeExpressionFactory; @@ -200,9 +200,9 @@ protected void initString() throws IOException { interpreter.interpret(ast); } - protected void testValidExpression(String expr, Value expected) { + protected void testValidExpression(String expr, MIValue expected) { Log.clearFindings(); - Value interpretationResult = null; + MIValue interpretationResult = null; try { interpretationResult = parseExpressionAndInterpret(expr); } catch (IOException e) { @@ -228,9 +228,6 @@ protected void testValidExpression(String expr, Value expected) { } else if (expected.isChar()) { assertTrue(interpretationResult.isChar()); assertEquals(interpretationResult.asChar(), expected.asChar()); - } else if (expected.isString()) { - assertTrue(interpretationResult.isString()); - assertEquals(interpretationResult.asString(), expected.asString()); } else if (expected.isObject()) { assertTrue(interpretationResult.isObject()); assertEquals(interpretationResult.asObject(), expected.asObject()); @@ -240,7 +237,7 @@ protected void testValidExpression(String expr, Value expected) { protected void testInvalidExpression(String expr) { Log.clearFindings(); - Value interpretationResult = null; + MIValue interpretationResult = null; try { interpretationResult = parseExpressionAndInterpret(expr); } catch (IOException e) { @@ -248,10 +245,10 @@ protected void testInvalidExpression(String expr) { } assertNotNull(interpretationResult); assertEquals(Log.getFindings().size(), 1); - assertInstanceOf(NotAValue.class, interpretationResult); + assertInstanceOf(ErrorMIValue.class, interpretationResult); } - protected Value parseExpressionAndInterpret(String expr) throws IOException { + protected MIValue parseExpressionAndInterpret(String expr) throws IOException { final Optional optAST = parser.parse_String("bar " + expr); assertTrue(optAST.isPresent()); final ASTFoo ast = optAST.get(); diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java index 77ab303bbb..b3f58c4344 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/lambdaexpressions/LambdaExpressionsInterpreterTest.java @@ -10,7 +10,22 @@ public class LambdaExpressionsInterpreterTest extends AbstractExpressionInterpre @Test public void testSimpleLambda() { - testValidExpression("(() -> \"a\"+1)()", createValue(1)); + // testValidExpression("(() -> \"a\"+1)()", createValue("a1")); + // #0 : 0x57037 Plus operation with result of type R"(a)(.*)" is not supported. + // This default method is called and the we get an error + // /** + // * Am I primitive? (such as "int") + // * (default: no) + // */ + // public boolean isPrimitive() { + // return false; + // } + + // testValidExpression("(() -> a+1)()", createValue("1")); + // #0 : StringReader:<1,7> - StringReader:<1,8>: 0xFD118 could not find symbol for expression "a" + // #1 : Invalid Model: (() -> a+1)() + + //testValidExpression("(() -> \"a\"+1)()", createValue("a1")); testValidExpression("(() -> 1)()", createValue(1)); testValidExpression("(() -> () -> 2)()()", createValue(2)); testValidExpression("((long a) -> a + 1)(41L)", createValue(42L)); diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolSurrogateTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolSurrogateTest.java index 662dcf3393..19294ddc81 100644 --- a/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolSurrogateTest.java +++ b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolSurrogateTest.java @@ -2,7 +2,7 @@ package de.monticore.symbols.basicsymbols._symboltable; import de.monticore.ast.ASTNode; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symboltable.IScope; import de.monticore.symboltable.ISymbol; @@ -330,7 +330,7 @@ public IScope getEnclosingScope() { public void setAccessModifier(AccessModifier accessModifier) { } @Override - public Map> getStereoinfo() { + public Map> getStereoinfo() { return null; } @Override diff --git a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java index a8c3fbf147..195a3dc14f 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java @@ -6,6 +6,7 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import java.util.stream.Collectors; @@ -37,10 +38,6 @@ protected static String getAllFindingsAsString() { ; } - protected static void assertNoFindings() { - MCAssertions.assertNoFindings(); - } - @BeforeEach public void initAbstract() { defaultInitAbstract(); diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/Numerals.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/Numerals.mc4 new file mode 100644 index 0000000000..dee899a64b --- /dev/null +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/Numerals.mc4 @@ -0,0 +1,15 @@ +/* (c) https://github.com/MontiCore/monticore */ + +component grammar Numerals extends de.monticore.MCBasics { + + interface Number; + + Integer implements Number = negative:["-"]? Digits; + + Float implements Number = negative:["-"]? pre:Digits "." post:Digits; + + token Digits = Digit+; + + fragment token Digit = '0'..'9'; + +} \ No newline at end of file diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 new file mode 100644 index 0000000000..b7a6eb7159 --- /dev/null +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -0,0 +1,21 @@ +/* (c) https://github.com/MontiCore/monticore */ + +grammar SimpleEquations extends Numerals { + + Program = (Statement ";")* (Expression ";")? ; + + interface Statement; + interface Expression; + + PlusEquation implements Expression = left:Expression "+" right:Expression; + MinusEquation implements Expression = left:Expression "-" right:Expression; + MultiplyEquation implements Expression = left:Expression "*" right:Expression; + DivideEquation implements Expression = left:Expression "/" right:Expression; + + symbol VariableDefinition implements Statement = "var" Name "=" value:Expression; + VariableUsage implements Statement = Name "=" value:Expression; + PrintStatement implements Statement = "print" "(" Expression ")"; + + NameExpression implements Expression = Name; + NumberExpression implements Expression = Number; +} \ No newline at end of file diff --git a/monticore-test/01.experiments/interpreter/src/main/java/numerals/_visitor/NumeralsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/numerals/_visitor/NumeralsInterpreter.java new file mode 100644 index 0000000000..02c2442871 --- /dev/null +++ b/monticore-test/01.experiments/interpreter/src/main/java/numerals/_visitor/NumeralsInterpreter.java @@ -0,0 +1,28 @@ +/* (c) https://github.com/MontiCore/monticore */ +package numerals._visitor; + +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.MIValueFactory; +import de.monticore.interpreter.ModelInterpreter; +import numerals._ast.ASTFloat; +import numerals._ast.ASTInteger; + +public class NumeralsInterpreter extends NumeralsInterpreterTOP { + + public NumeralsInterpreter(ModelInterpreter realThis) { + super(realThis); + } + + public MIValue interpret(ASTFloat node) { + return MIValueFactory.createValue((float) + (Integer.parseInt(node.getPre()) + + Integer.parseInt(node.getPost()) * Math.pow(10, -node.getPost().length())) + * (node.isNegative() ? -1 : 1)); + } + + public MIValue interpret(ASTInteger node) { + return MIValueFactory.createValue( + Integer.parseInt(node.getDigits()) * (node.isNegative() ? -1 : 1)); + } + +} \ No newline at end of file diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java new file mode 100644 index 0000000000..6ad1ba3fe8 --- /dev/null +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java @@ -0,0 +1,100 @@ +/* (c) https://github.com/MontiCore/monticore */ +package simpleequations._visitor; + +import de.monticore.interpreter.MIValue; +import de.monticore.interpreter.MIValueFactory; +import de.monticore.interpreter.values.ErrorMIValue; +import simpleequations._ast.*; + +public class SimpleEquationsInterpreter extends SimpleEquationsInterpreterTOP { + + public SimpleEquationsInterpreter() { + super(); + } + + public MIValue interpret(ASTProgram node) { + node.forEachStatements(s -> s.evaluate(getRealThis())); + if (node.isPresentExpression()) { + return node.getExpression().evaluate(getRealThis()); + } + return new ErrorMIValue("Error ASTProgram node"); + } + + public MIValue interpret(ASTPlusEquation node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); + + if (left.isInt() && right.isInt()) { + return MIValueFactory.createValue(left.asInt() + right.asInt()); + } + return MIValueFactory.createValue(left.asFloat() + right.asFloat()); + } + + public MIValue interpret(ASTMinusEquation node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); + + if (left.isInt() && right.isInt()) { + return MIValueFactory.createValue(left.asInt() - right.asInt()); + } + return MIValueFactory.createValue(left.asFloat() - right.asFloat()); + } + + public MIValue interpret(ASTMultiplyEquation node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); + + if (left.isInt() && right.isInt()) { + return MIValueFactory.createValue(left.asInt() * right.asInt()); + } + return MIValueFactory.createValue(left.asFloat() * right.asFloat()); + } + + public MIValue interpret(ASTDivideEquation node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); + + if (left.isInt() && right.isInt()) { + return MIValueFactory.createValue(left.asInt() / right.asInt()); + } + return MIValueFactory.createValue(left.asFloat() / right.asFloat()); + } + + public MIValue interpret(ASTVariableDefinition node) { + MIValue value = node.getValue().evaluate(getRealThis()); + getRealThis().declareVariable(node.getSymbol(), java.util.Optional.of(value)); + return new ErrorMIValue("Error ASTVariableDefinition node"); + } + + public MIValue interpret(ASTVariableUsage node) { + var symbol = node.getEnclosingScope().resolveVariableDefinition(node.getName()); + MIValue value = node.getValue().evaluate(getRealThis()); + symbol.ifPresent(s -> getRealThis().storeVariable(s, value)); + return new ErrorMIValue("Error ASTVariableUsage node"); + } + + public MIValue interpret(ASTPrintStatement node) { + MIValue output = node.getExpression().evaluate(getRealThis()); + + if (output.isInt()) { + System.out.println(output.asInt()); + } else if (output.isFloat()) { + System.out.println(output.asFloat()); + } + return new ErrorMIValue("Error ASTPrintStatement node"); + } + + public MIValue interpret(ASTNameExpression node) { + var optSymbol = node.getEnclosingScope().resolveVariableDefinition(node.getName()); + if (optSymbol.isPresent()) { + return getRealThis().loadVariable(optSymbol.get()); + }else{ + return new ErrorMIValue("Error ASTNameExpression node"); + } + } + + public MIValue interpret(ASTNumberExpression node) { + return node.getNumber().evaluate(getRealThis()); + } + +} \ No newline at end of file diff --git a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java index 2d750570f6..0389d5498b 100644 --- a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java +++ b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java @@ -1,7 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package simpleequations._visitor; -import de.monticore.interpreter.Value; +import de.monticore.interpreter.MIValue; import org.junit.jupiter.api.Test; import simpleequations.SimpleEquationsMill; import simpleequations._ast.ASTProgram; @@ -25,10 +25,10 @@ public void test() throws IOException { ASTProgram program = parser.parse_StringProgram("var a=3.5; var b=4; print(a); var c=a+b; c;").get(); delegator.createFromAST(program); - Value result = interpreter.interpret(program); + MIValue result = interpreter.interpret(program); assertTrue(result.isFloat()); - assertEquals(result.asFloat(), 7.5f, 0.0001f); + assertEquals(7.5f, result.asFloat(), 0.0001f); SimpleEquationsMill.reset(); SimpleEquationsMill.init(); diff --git a/monticore-test/01.experiments/runtimeOnly/build.gradle b/monticore-test/01.experiments/runtimeOnly/build.gradle index 3acc2b7b8e..2d1ae52ff9 100644 --- a/monticore-test/01.experiments/runtimeOnly/build.gradle +++ b/monticore-test/01.experiments/runtimeOnly/build.gradle @@ -3,6 +3,7 @@ description = 'Experiments: runtimeOnly' dependencies { implementation project(path: ':monticore-runtime') + implementation project(path: ':monticore-grammar') } /* From 9713c037d2a4d060060c7be302fb3894029517f6 Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Fri, 27 Feb 2026 16:30:50 +0100 Subject: [PATCH 25/37] fix pipeline --- .../interpreter/InterpreterDecoratorTest.java | 122 +++++------------- monticore-grammar/build.gradle | 2 +- 2 files changed, 36 insertions(+), 88 deletions(-) diff --git a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java index b7de1d16c5..ab77c3e529 100644 --- a/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java +++ b/monticore-generator/src/test/java/de/monticore/codegen/cd2java/interpreter/InterpreterDecoratorTest.java @@ -12,22 +12,21 @@ import de.monticore.types.mcbasictypes._ast.ASTMCObjectType; import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; import de.monticore.types.mccollectiontypes._ast.ASTMCGenericType; +import de.monticore.types.mccollectiontypes._ast.ASTMCMapType; +import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericType; import de.se_rwth.commons.logging.Log; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; - import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; public class InterpreterDecoratorTest extends DecoratorTestCase { - + protected ASTCDCompilationUnit originalCompilationUnit; protected ASTCDClass decoratedClass; @@ -56,14 +55,14 @@ public void testConstructors() { assertTrue(constructors.get(0).getCDParameterList().isEmpty()); assertEquals( - 1, - constructors.get(1).getCDParameterList().size()); + 1, + constructors.get(1).getCDParameterList().size()); assertEquals( - "realThis", - constructors.get(1).getCDParameter(0).getName()); + "realThis", + constructors.get(1).getCDParameter(0).getName()); assertEquals( - InterpreterConstants.MODELINTERPRETER_FULLNAME, - constructors.get(1).getCDParameter(0).getMCType().printType()); + InterpreterConstants.MODELINTERPRETER_FULLNAME, + constructors.get(1).getCDParameter(0).getMCType().printType()); } @Test @@ -73,8 +72,8 @@ public void testSuperInterfaces() { assertEquals(1, interfaces.size()); assertEquals( - "IAutomatonInterpreter", - ((ASTMCQualifiedType) interfaces.get(0)).getMCQualifiedName().getQName()); + "IAutomatonInterpreter", + ((ASTMCQualifiedType) interfaces.get(0)).getMCQualifiedName().getQName()); } @Test @@ -84,29 +83,26 @@ public void testClassAttributes() { assertEquals(3, attributes.size()); assertEquals( - "lexicalsInterpreter", - attributes.get(0).getName()); + "lexicalsInterpreter", + attributes.get(0).getName()); assertEquals( - "de.monticore.codegen.ast.lexicals._visitor.ILexicalsInterpreter", - attributes.get(0).getMCType().printType()); + "de.monticore.codegen.ast.lexicals._visitor.ILexicalsInterpreter", + attributes.get(0).getMCType().printType()); assertEquals( - "realThis", - attributes.get(1).getName()); + "realThis", + attributes.get(1).getName()); assertEquals( - InterpreterConstants.MODELINTERPRETER_FULLNAME, - attributes.get(1).getMCType().printType()); + InterpreterConstants.MODELINTERPRETER_FULLNAME, + attributes.get(1).getMCType().printType()); assertEquals( - "contextMap", - attributes.get(2).getName()); - assertInstanceOf(ASTMCMapType.class, attributes.get(2).getMCType()); - assertEquals( - InterpreterConstants.SYMBOL_FULLNAME, - ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(0).printType()); + "scopeCallstack", + attributes.get(2).getName()); + assertInstanceOf(ASTMCBasicGenericType.class, attributes.get(2).getMCType()); assertEquals( - InterpreterConstants.VALUE_FULLNAME, - ((ASTMCMapType) attributes.get(2).getMCType()).getMCTypeArgument(1).printType()); + "java.util.Stack<"+InterpreterConstants.INTERPRETER_SCOPE_FULLNAME+">", + attributes.get(2).getMCType().printType()); } @Test @@ -121,8 +117,8 @@ public void testRealThisMethods() { assertTrue(getMethod.getCDParameterList().isEmpty()); assertEquals( - InterpreterConstants.MODELINTERPRETER_FULLNAME, - getMethod.getMCReturnType().printType()); + InterpreterConstants.MODELINTERPRETER_FULLNAME, + getMethod.getMCReturnType().printType()); Optional optSetMethod = decoratedClass.getCDMethodList() .stream() @@ -134,11 +130,11 @@ public void testRealThisMethods() { assertEquals(1, setMethod.getCDParameterList().size()); assertEquals( - InterpreterConstants.MODELINTERPRETER_FULLNAME, - setMethod.getCDParameter(0).getMCType().printType()); + InterpreterConstants.MODELINTERPRETER_FULLNAME, + setMethod.getCDParameter(0).getMCType().printType()); assertEquals( - "realThis", - setMethod.getCDParameter(0).getName()); + "realThis", + setMethod.getCDParameter(0).getName()); assertTrue(setMethod.getMCReturnType().isPresentMCVoidType()); } @@ -148,63 +144,15 @@ public void testScopeCallstackMethod() { .stream() .filter(m -> m.getName().equals("getScopeCallstack")) .findAny(); - + assertTrue(optScopeCallstackMethod.isPresent()); ASTCDMethod scopeCallstackMethod = optScopeCallstackMethod.get(); ASTMCGenericType returnTypeType = (ASTMCGenericType)scopeCallstackMethod.getMCReturnType().getMCType(); assertEquals("java.util.Stack", returnTypeType.printWithoutTypeArguments()); assertEquals(InterpreterConstants.INTERPRETER_SCOPE_FULLNAME, - returnTypeType.getMCTypeArgument(0).printType()); - assertTrue(optStoreMethod.isPresent()); - ASTCDMethod storeMethod = optStoreMethod.get(); - - assertTrue(storeMethod.getMCReturnType().isPresentMCVoidType()); - assertEquals(2, storeMethod.getCDParameterList().size()); - assertEquals("symbol", storeMethod.getCDParameter(0).getName()); - assertEquals( - InterpreterConstants.SYMBOL_FULLNAME, - storeMethod.getCDParameter(0).getMCType().printType()); - assertEquals("value", storeMethod.getCDParameter(1).getName()); - assertEquals( - InterpreterConstants.VALUE_FULLNAME, - storeMethod.getCDParameter(1).getMCType().printType()); - - Optional optLoadMethod = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("load")) - .findAny(); - - assertTrue(optLoadMethod.isPresent()); - ASTCDMethod loadMethod = optLoadMethod.get(); - - assertEquals( - InterpreterConstants.VALUE_FULLNAME, - loadMethod.getMCReturnType().printType()); - assertEquals(1, loadMethod.getCDParameterList().size()); - assertEquals( - InterpreterConstants.SYMBOL_FULLNAME, - loadMethod.getCDParameter(0).getMCType().printType()); - assertEquals( - "symbol", - loadMethod.getCDParameter(0).getName()); - - Optional optGetMap = decoratedClass.getCDMethodList() - .stream() - .filter(m -> m.getName().equals("getContextMap")) - .findAny(); - - assertTrue(optGetMap.isPresent()); - ASTCDMethod getMapMethod = optGetMap.get(); - - assertTrue(getMapMethod.getCDParameterList().isEmpty()); - assertInstanceOf(ASTMCMapType.class, getMapMethod.getMCReturnType().getMCType()); - assertEquals( - InterpreterConstants.SYMBOL_FULLNAME, - ((ASTMCMapType) getMapMethod.getMCReturnType().getMCType()).getMCTypeArgument(0).printType()); - assertEquals( - InterpreterConstants.VALUE_FULLNAME, - ((ASTMCMapType) getMapMethod.getMCReturnType().getMCType()).getMCTypeArgument(1).printType()); + returnTypeType.getMCTypeArgument(0).printType()); + assertTrue(scopeCallstackMethod.getCDParameterList().isEmpty()); } @Test @@ -229,4 +177,4 @@ public void after() { Log.getFindings().clear(); } -} +} \ No newline at end of file diff --git a/monticore-grammar/build.gradle b/monticore-grammar/build.gradle index d70a425ae2..e7c4a39a5c 100644 --- a/monticore-grammar/build.gradle +++ b/monticore-grammar/build.gradle @@ -76,7 +76,7 @@ dependencies { api project(':monticore-runtime') implementation "com.google.guava:guava:$guava_version" implementation "org.apache.commons:commons-lang3:$commons_lang3_version" - testImplementation "de.monticore:class2mc:$version" + testImplementation "de.monticore:class2mc:$previous_mc_version" testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version" testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_version" testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version" From cc195596e9e8d768b7cdd778948646efd0a2c1cd Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Wed, 4 Mar 2026 22:37:18 +0100 Subject: [PATCH 26/37] revert change of a generic ModelInterpreter and fix grammar --- .../java/de/monticore/interpreter/MIScope.java | 15 +++++++-------- .../monticore/interpreter/ModelInterpreter.java | 11 +++++------ .../src/main/grammars/SimpleEquations.mc4 | 7 ++++--- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java index e85a6b28f8..b110fcf4f0 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/MIScope.java @@ -4,7 +4,6 @@ import de.monticore.interpreter.values.FunctionMIValue; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; -import de.monticore.symboltable.ISymbol; import de.se_rwth.commons.logging.Log; import java.util.HashMap; @@ -13,8 +12,8 @@ public class MIScope implements IMIScope { - protected Map functionMap = new HashMap<>(); - protected Map> variableMap = new HashMap<>(); + protected Map functionMap = new HashMap<>(); + protected Map> variableMap = new HashMap<>(); protected Optional parent; @@ -34,14 +33,14 @@ public MIScope clone() { return clone; } - public void declareFunction(ISymbol symbol, MIValue value) { + public void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { if (functionMap.containsKey(symbol)) { Log.error("0x57068 Function was already declared"); } this.functionMap.put(symbol, value); } - public MIValue loadFunction(ISymbol symbol) { + public MIValue loadFunction(FunctionSymbol symbol) { if (functionMap.containsKey(symbol)) { return functionMap.get(symbol); } @@ -55,14 +54,14 @@ public MIValue loadFunction(ISymbol symbol) { return new ErrorMIValue(errorMsg); } - public void declareVariable(ISymbol symbol, Optional value) { + public void declareVariable(VariableSymbol symbol, Optional value) { if (variableMap.containsKey(symbol)) { Log.error("0x57070 Variable was already declared"); } this.variableMap.put(symbol, value); } - public MIValue loadVariable(ISymbol symbol) { + public MIValue loadVariable(VariableSymbol symbol) { Optional value = variableMap.get(symbol); if (value != null) { if (value.isPresent()) { @@ -84,7 +83,7 @@ public MIValue loadVariable(ISymbol symbol) { return new ErrorMIValue(errorMsg); } - public void storeVariable(ISymbol symbol, MIValue value) { + public void storeVariable(VariableSymbol symbol, MIValue value) { if (variableMap.containsKey(symbol)) { variableMap.put(symbol, Optional.of(value)); } diff --git a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java index 27492b80ed..e7df6fe2f8 100644 --- a/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java +++ b/monticore-grammar/src/main/java/de/monticore/interpreter/ModelInterpreter.java @@ -4,7 +4,6 @@ import de.monticore.interpreter.values.FunctionMIValue; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; -import de.monticore.symboltable.ISymbol; import java.util.Optional; import java.util.Stack; @@ -48,23 +47,23 @@ default void popScope() { getRealThis().getScopeCallstack().pop(); } - default void declareFunction(ISymbol symbol, MIValue value) { + default void declareFunction(FunctionSymbol symbol, FunctionMIValue value) { getCurrentScope().declareFunction(symbol, value); } - default MIValue loadFunction(ISymbol symbol) { + default MIValue loadFunction(FunctionSymbol symbol) { return getCurrentScope().loadFunction(symbol); } - default void declareVariable(ISymbol symbol, Optional value) { + default void declareVariable(VariableSymbol symbol, Optional value) { getCurrentScope().declareVariable(symbol, value); } - default MIValue loadVariable(ISymbol symbol) { + default MIValue loadVariable(VariableSymbol symbol) { return getCurrentScope().loadVariable(symbol); } - default void storeVariable(ISymbol symbol, MIValue value) { + default void storeVariable(VariableSymbol symbol, MIValue value) { getCurrentScope().storeVariable(symbol, value); } diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index b7a6eb7159..085f13093e 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -1,19 +1,20 @@ /* (c) https://github.com/MontiCore/monticore */ -grammar SimpleEquations extends Numerals { +grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { Program = (Statement ";")* (Expression ";")? ; interface Statement; interface Expression; + interface NewVariable extends Variable; PlusEquation implements Expression = left:Expression "+" right:Expression; MinusEquation implements Expression = left:Expression "-" right:Expression; MultiplyEquation implements Expression = left:Expression "*" right:Expression; DivideEquation implements Expression = left:Expression "/" right:Expression; - symbol VariableDefinition implements Statement = "var" Name "=" value:Expression; - VariableUsage implements Statement = Name "=" value:Expression; + symbol VariableDefinition implements Statement, NewVariable = "var" Name "=" value:Expression; + VariableUsage implements Statement, NewVariable = Name "=" value:Expression; PrintStatement implements Statement = "print" "(" Expression ")"; NameExpression implements Expression = Name; From 9a43462a85ad5e5a2b1f9d9bf222f452a40c8b65 Mon Sep 17 00:00:00 2001 From: Hendrik7889 Date: Sun, 8 Mar 2026 18:39:25 +0100 Subject: [PATCH 27/37] sync --- .../src/main/grammars/SimpleEquations.mc4 | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index 085f13093e..241828b0d6 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -2,11 +2,24 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { - Program = (Statement ";")* (Expression ";")? ; + Program = (Statement ";" || FunctionCall ";")* (Expression ";")? ; interface Statement; interface Expression; interface NewVariable extends Variable; + interface NewFunction extends Functions; + + FunctionCall implements Expression = Name "(" ArgList ")"; + + ArgList = (args:Expr ("," args:Expr)*)?; + + FunctionDefinition implements NewFunction = "func" name:Name FormalParameters "{" Program "}"; + + FormalParameterListing + = (VariableAsParameter || ",")+; + + FormalParameters + = "(" FormalParameterListing? ")"; PlusEquation implements Expression = left:Expression "+" right:Expression; MinusEquation implements Expression = left:Expression "-" right:Expression; @@ -15,6 +28,7 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { symbol VariableDefinition implements Statement, NewVariable = "var" Name "=" value:Expression; VariableUsage implements Statement, NewVariable = Name "=" value:Expression; + VariableAsParameter implements NewVariable = Name; PrintStatement implements Statement = "print" "(" Expression ")"; NameExpression implements Expression = Name; From 33567514fe63aaac6b9dbeb68b557de98d55ee20 Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Mon, 9 Mar 2026 11:12:45 +0100 Subject: [PATCH 28/37] add functions (lcoal vars are not working --- .../src/main/grammars/SimpleEquations.mc4 | 22 +-- .../_visitor/SimpleEquationsInterpreter.java | 126 ++++++++++++++++-- .../SimpleEquationsInterpreterTest.java | 22 +++ 3 files changed, 152 insertions(+), 18 deletions(-) diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index 241828b0d6..b4e1573dc8 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -2,21 +2,20 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { - Program = (Statement ";" || FunctionCall ";")* (Expression ";")? ; + Program = (Statement ";" | FunctionCall ";" | FunctionDefinition)* (Expression ";")? ; + FunctionBlock = (Statement ";")* (Expression ";")?; interface Statement; interface Expression; - interface NewVariable extends Variable; - interface NewFunction extends Functions; - FunctionCall implements Expression = Name "(" ArgList ")"; + FunctionCall implements Expression, Statement = Name "(" ArgList ")"; - ArgList = (args:Expr ("," args:Expr)*)?; + ArgList = (args:Expression ("," args:Expression)*)?; - FunctionDefinition implements NewFunction = "func" name:Name FormalParameters "{" Program "}"; + FunctionDefinition implements Function, Statement = "func" name:Name FormalParameters "{" Program "}"; FormalParameterListing - = (VariableAsParameter || ",")+; + = (VariableAsParameter | ",")+; FormalParameters = "(" FormalParameterListing? ")"; @@ -25,11 +24,14 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { MinusEquation implements Expression = left:Expression "-" right:Expression; MultiplyEquation implements Expression = left:Expression "*" right:Expression; DivideEquation implements Expression = left:Expression "/" right:Expression; + GreaterThanExpression implements Expression = left:Expression ">" right:Expression; - symbol VariableDefinition implements Statement, NewVariable = "var" Name "=" value:Expression; - VariableUsage implements Statement, NewVariable = Name "=" value:Expression; - VariableAsParameter implements NewVariable = Name; + symbol VariableDefinition implements Statement, Variable = "var" Name "=" value:Expression; + VariableUsage implements Statement = Name "=" value:Expression; + VariableAsParameter implements Variable = Name; PrintStatement implements Statement = "print" "(" Expression ")"; + IfStatement implements Statement = "if" "(" condition:Expression ")" "{" thenBlock:FunctionBlock "}" ("else" "{" elseBlock:FunctionBlock "}")?; + ReturnStatement implements Statement = "return" Expression; NameExpression implements Expression = Name; NumberExpression implements Expression = Number; diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java index 6ad1ba3fe8..10eecfc682 100644 --- a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java @@ -1,10 +1,19 @@ /* (c) https://github.com/MontiCore/monticore */ package simpleequations._visitor; +import de.monticore.interpreter.MIScope; import de.monticore.interpreter.MIValue; import de.monticore.interpreter.MIValueFactory; import de.monticore.interpreter.values.ErrorMIValue; +import de.monticore.interpreter.values.MIReturnSignal; +import de.monticore.interpreter.values.ModelFunctionMIValue; import simpleequations._ast.*; +import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; public class SimpleEquationsInterpreter extends SimpleEquationsInterpreterTOP { @@ -13,11 +22,19 @@ public SimpleEquationsInterpreter() { } public MIValue interpret(ASTProgram node) { - node.forEachStatements(s -> s.evaluate(getRealThis())); + MIValue result = new ErrorMIValue("Error ASTProgram node"); + for (ASTStatement s : node.getStatementList()) { + //we can skip this as we only need to interpret it when it is getting called + if (s instanceof ASTFunctionDefinition) continue; + result = s.evaluate(getRealThis()); + if (result.isReturn()) { + return result; + } + } if (node.isPresentExpression()) { return node.getExpression().evaluate(getRealThis()); } - return new ErrorMIValue("Error ASTProgram node"); + return result; } public MIValue interpret(ASTPlusEquation node) { @@ -60,17 +77,33 @@ public MIValue interpret(ASTDivideEquation node) { return MIValueFactory.createValue(left.asFloat() / right.asFloat()); } + public MIValue interpret(ASTGreaterThanExpression node) { + MIValue left = node.getLeft().evaluate(getRealThis()); + MIValue right = node.getRight().evaluate(getRealThis()); + + if (left.isInt() && right.isInt()) { + return MIValueFactory.createValue(left.asInt() > right.asInt()); + } + return MIValueFactory.createValue(left.asFloat() > right.asFloat()); + } + public MIValue interpret(ASTVariableDefinition node) { MIValue value = node.getValue().evaluate(getRealThis()); - getRealThis().declareVariable(node.getSymbol(), java.util.Optional.of(value)); - return new ErrorMIValue("Error ASTVariableDefinition node"); + getRealThis().declareVariable(node.getSymbol(), Optional.of(value)); + return value; } public MIValue interpret(ASTVariableUsage node) { - var symbol = node.getEnclosingScope().resolveVariableDefinition(node.getName()); MIValue value = node.getValue().evaluate(getRealThis()); - symbol.ifPresent(s -> getRealThis().storeVariable(s, value)); - return new ErrorMIValue("Error ASTVariableUsage node"); + var symbol = node.getEnclosingScope().resolveVariableDefinition(node.getName()); + + if (symbol.isPresent()) { + getRealThis().storeVariable(symbol.get(), value); + } else { + return new ErrorMIValue("Error ASTVariableUsage variable not found"); + } + + return value; } public MIValue interpret(ASTPrintStatement node) { @@ -81,7 +114,7 @@ public MIValue interpret(ASTPrintStatement node) { } else if (output.isFloat()) { System.out.println(output.asFloat()); } - return new ErrorMIValue("Error ASTPrintStatement node"); + return output; } public MIValue interpret(ASTNameExpression node) { @@ -93,6 +126,83 @@ public MIValue interpret(ASTNameExpression node) { } } + public MIValue interpret(ASTFunctionCall node) { + Optional functionSymbol = node.getEnclosingScope().resolveFunction(node.getName()); + if(functionSymbol.isPresent()){ + ASTFunctionDefinition functionDefinition = (ASTFunctionDefinition) functionSymbol.get().getAstNode(); + List args = new ArrayList<>(); + + for(ASTExpression expr : node.getArgList().getArgsList()){ + args.add(expr.evaluate(getRealThis())); + } + + MIScope newScope = new MIScope(getRealThis().getCurrentScope()); + getRealThis().pushScope(newScope); + + try { + List parameters = functionDefinition.getFormalParameters().getFormalParameterListing().streamVariableAsParameters().collect(Collectors.toList()); + for(int i = 0; i < parameters.size(); i++){ + VariableSymbol param = parameters.get(i).getSymbol(); + getRealThis().declareVariable(param, Optional.of(args.get(i))); + } + + MIValue result = functionDefinition.getProgram().evaluate(getRealThis()); + + while (result.isReturn()){ + result = result.asReturnValue(); + } + + if (result.isError()) { + System.out.println("Error in function call"); + } + return result; + } finally { + getRealThis().popScope(); + } + } + return new ErrorMIValue("Error ASTFunctionCall node"); + } + + public MIValue interpret(ASTIfStatement node) { + MIValue condition = node.getCondition().evaluate(getRealThis()); + if (condition.asBoolean()) { + MIValue returnValue = node.getThenBlock().evaluate(getRealThis()); + return returnValue; + } else if (node.isPresentElseBlock()) { + MIValue returnValue = node.getElseBlock().evaluate(getRealThis()); + return returnValue; + } + return new ErrorMIValue("IfStatement no branch executed"); + } + + public MIValue interpret(ASTFunctionBlock node) { + MIValue result = new ErrorMIValue("Error ASTFunctionBlock node"); + + for (ASTStatement s : node.getStatementList()) { + result = s.evaluate(getRealThis()); + + if (result.isReturn()) { + return result; + } + } + + // Evaluate the optional trailing expression, if present + if (node.isPresentExpression()) { + return node.getExpression().evaluate(getRealThis()); + } + + return result; + } + + public MIValue interpret(ASTReturnStatement node) { + MIValue value = node.getExpression().evaluate(getRealThis()); + if(value.isError()){ + return new ErrorMIValue("error in return statement"); + } + return new MIReturnSignal(value); + } + + public MIValue interpret(ASTNumberExpression node) { return node.getNumber().evaluate(getRealThis()); } diff --git a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java index 0389d5498b..54d53fadbc 100644 --- a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java +++ b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java @@ -22,6 +22,28 @@ public void test() throws IOException { SimpleEquationsInterpreter interpreter = new SimpleEquationsInterpreter(); SimpleEquationsScopesGenitorDelegator delegator = SimpleEquationsMill.scopesGenitorDelegator(); + ASTProgram function = parser.parse_StringProgram("" + + "var a = 3; " + + "var b = 3; " + + "func func1(a, b){ " + + " var c = a; " + + " if( b > 0 ){ " + + " b = b - 1; " + + " c = a * 3; " + + " var d = func1(c, b);" + + " return d;" + + " } else { " + + " return a;" + + " };" + + "}"+ + "var result = func1(a, b);" + + "print(result);").get(); + delegator.createFromAST(function); + MIValue functionResult = interpreter.interpret(function); + assertTrue(functionResult.isInt()); + assertEquals(functionResult.asInt(), 81); + + ASTProgram program = parser.parse_StringProgram("var a=3.5; var b=4; print(a); var c=a+b; c;").get(); delegator.createFromAST(program); From 5e5130dbb374d2e3b8d1cd683550f2a95406d11b Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Mon, 9 Mar 2026 13:09:53 +0100 Subject: [PATCH 29/37] Update SimpleEquationsInterpreter.java --- .../_visitor/SimpleEquationsInterpreter.java | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java index 10eecfc682..61d4781b2f 100644 --- a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.Stack; import java.util.stream.Collectors; public class SimpleEquationsInterpreter extends SimpleEquationsInterpreterTOP { @@ -95,12 +96,22 @@ public MIValue interpret(ASTVariableDefinition node) { public MIValue interpret(ASTVariableUsage node) { MIValue value = node.getValue().evaluate(getRealThis()); - var symbol = node.getEnclosingScope().resolveVariableDefinition(node.getName()); + List symbols = node.getEnclosingScope().resolveVariableMany(node.getName()); + + if (!symbols.isEmpty()) { + if (symbols.size() > 1) { + Stack scopeStack = getScopeCallstack(); + System.out.println(scopeStack.size() + " scopes on stack:"); + System.err.println("DEBUG: MontiCore found " + symbols.size() + " symbols for '" + node.getName() + "'!"); + for (VariableSymbol sym : symbols) { + System.err.println(" -> Created by: " + (sym.isPresentAstNode() ? sym.getAstNode().getClass().getSimpleName() + " " + sym.getFullName() : "Unknown")); + } + } - if (symbol.isPresent()) { - getRealThis().storeVariable(symbol.get(), value); - } else { - return new ErrorMIValue("Error ASTVariableUsage variable not found"); + // needed as there exists b, func1.b func1.b .. for every interation. We need to grab the first + getRealThis().storeVariable(symbols.get(0), value); + }else { + throw new RuntimeException("CRITICAL: Variable '" + node.getName() + "' not found in scope!"); } return value; @@ -118,11 +129,12 @@ public MIValue interpret(ASTPrintStatement node) { } public MIValue interpret(ASTNameExpression node) { - var optSymbol = node.getEnclosingScope().resolveVariableDefinition(node.getName()); - if (optSymbol.isPresent()) { - return getRealThis().loadVariable(optSymbol.get()); - }else{ - return new ErrorMIValue("Error ASTNameExpression node"); + List symbols = node.getEnclosingScope().resolveVariableMany(node.getName()); + + if (!symbols.isEmpty()) { + return getRealThis().loadVariable(symbols.get(0)); + } else { + throw new RuntimeException("CRITICAL: Cannot evaluate '" + node.getName() + "', symbol is missing!"); } } From a352004303a8f5e0d26b8a3e090c08e581b889a5 Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Mon, 9 Mar 2026 13:23:20 +0100 Subject: [PATCH 30/37] use declareFunction --- .../src/main/grammars/SimpleEquations.mc4 | 6 +- .../_visitor/SimpleEquationsInterpreter.java | 127 +++++++++++------- .../SimpleEquationsInterpreterTest.java | 13 +- 3 files changed, 89 insertions(+), 57 deletions(-) diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index b4e1573dc8..70804bb316 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -12,7 +12,7 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { ArgList = (args:Expression ("," args:Expression)*)?; - FunctionDefinition implements Function, Statement = "func" name:Name FormalParameters "{" Program "}"; + symbol scope FunctionDefinition implements Function, Statement = returnType:Name "func" name:Name FormalParameters "{" Program "}"; FormalParameterListing = (VariableAsParameter | ",")+; @@ -26,9 +26,9 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { DivideEquation implements Expression = left:Expression "/" right:Expression; GreaterThanExpression implements Expression = left:Expression ">" right:Expression; - symbol VariableDefinition implements Statement, Variable = "var" Name "=" value:Expression; + symbol VariableDefinition implements Statement, Variable = type:Name Name "=" value:Expression; VariableUsage implements Statement = Name "=" value:Expression; - VariableAsParameter implements Variable = Name; + VariableAsParameter implements Variable = type:Name Name; PrintStatement implements Statement = "print" "(" Expression ")"; IfStatement implements Statement = "if" "(" condition:Expression ")" "{" thenBlock:FunctionBlock "}" ("else" "{" elseBlock:FunctionBlock "}")?; ReturnStatement implements Statement = "return" Expression; diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java index 61d4781b2f..44aace3106 100644 --- a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java @@ -7,6 +7,10 @@ import de.monticore.interpreter.values.ErrorMIValue; import de.monticore.interpreter.values.MIReturnSignal; import de.monticore.interpreter.values.ModelFunctionMIValue; +import de.monticore.interpreter.values.VoidMIValue; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import de.monticore.types.check.SymTypeExpressionFactory; import simpleequations._ast.*; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; @@ -24,12 +28,15 @@ public SimpleEquationsInterpreter() { public MIValue interpret(ASTProgram node) { MIValue result = new ErrorMIValue("Error ASTProgram node"); + + for (ASTFunctionDefinition funcDef : node.getFunctionDefinitionList()) { + funcDef.evaluate(getRealThis()); + } + for (ASTStatement s : node.getStatementList()) { - //we can skip this as we only need to interpret it when it is getting called - if (s instanceof ASTFunctionDefinition) continue; result = s.evaluate(getRealThis()); if (result.isReturn()) { - return result; + return result; } } if (node.isPresentExpression()) { @@ -110,7 +117,7 @@ public MIValue interpret(ASTVariableUsage node) { // needed as there exists b, func1.b func1.b .. for every interation. We need to grab the first getRealThis().storeVariable(symbols.get(0), value); - }else { + } else { throw new RuntimeException("CRITICAL: Variable '" + node.getName() + "' not found in scope!"); } @@ -138,53 +145,72 @@ public MIValue interpret(ASTNameExpression node) { } } + public MIValue interpret(ASTFunctionDefinition node) { + //this must be init to create int types + BasicSymbolsMill.initializePrimitives(); + + FunctionSymbol funcSym = node.getSymbol(); + + //set return type of function like specified (only primitive allowed) + funcSym.setType(SymTypeExpressionFactory.createPrimitive(node.getReturnType())); + + List parameterSymbols = node.getFormalParameters() + .getFormalParameterListing() + .streamVariableAsParameters() + .map(ASTVariableAsParameter::getSymbol) + .collect(Collectors.toList()); + + //set types of the parameters + for (VariableSymbol param : parameterSymbols) { + String typeName = param.getType() != null ? param.getType().print() : "int"; + param.setType(SymTypeExpressionFactory.createPrimitive(typeName)); + } + + ModelFunctionMIValue functionValue = new ModelFunctionMIValue( + getRealThis().getCurrentScope(), + parameterSymbols, + node.getProgram() + ); + + getRealThis().declareFunction(funcSym, functionValue); + return new VoidMIValue(); + } + public MIValue interpret(ASTFunctionCall node) { Optional functionSymbol = node.getEnclosingScope().resolveFunction(node.getName()); - if(functionSymbol.isPresent()){ - ASTFunctionDefinition functionDefinition = (ASTFunctionDefinition) functionSymbol.get().getAstNode(); - List args = new ArrayList<>(); - - for(ASTExpression expr : node.getArgList().getArgsList()){ - args.add(expr.evaluate(getRealThis())); - } - MIScope newScope = new MIScope(getRealThis().getCurrentScope()); - getRealThis().pushScope(newScope); + if (functionSymbol.isPresent()) { + MIValue funcValue = getRealThis().loadFunction(functionSymbol.get()); - try { - List parameters = functionDefinition.getFormalParameters().getFormalParameterListing().streamVariableAsParameters().collect(Collectors.toList()); - for(int i = 0; i < parameters.size(); i++){ - VariableSymbol param = parameters.get(i).getSymbol(); - getRealThis().declareVariable(param, Optional.of(args.get(i))); - } + if (funcValue instanceof ModelFunctionMIValue) { + ModelFunctionMIValue modelFunc = (ModelFunctionMIValue) funcValue; - MIValue result = functionDefinition.getProgram().evaluate(getRealThis()); + List args = new ArrayList<>(); + for (ASTExpression expr : node.getArgList().getArgsList()) { + args.add(expr.evaluate(getRealThis())); + } - while (result.isReturn()){ - result = result.asReturnValue(); - } + MIValue result = modelFunc.execute(getRealThis(), args); - if (result.isError()) { - System.out.println("Error in function call"); - } - return result; - } finally { - getRealThis().popScope(); + while (result.isReturn()){ + result = result.asReturnValue(); + } + return result; } } - return new ErrorMIValue("Error ASTFunctionCall node"); + return new ErrorMIValue("Function '" + node.getName() + "' not found."); } - + public MIValue interpret(ASTIfStatement node) { - MIValue condition = node.getCondition().evaluate(getRealThis()); - if (condition.asBoolean()) { - MIValue returnValue = node.getThenBlock().evaluate(getRealThis()); - return returnValue; - } else if (node.isPresentElseBlock()) { - MIValue returnValue = node.getElseBlock().evaluate(getRealThis()); - return returnValue; - } - return new ErrorMIValue("IfStatement no branch executed"); + MIValue condition = node.getCondition().evaluate(getRealThis()); + if (condition.asBoolean()) { + MIValue returnValue = node.getThenBlock().evaluate(getRealThis()); + return returnValue; + } else if (node.isPresentElseBlock()) { + MIValue returnValue = node.getElseBlock().evaluate(getRealThis()); + return returnValue; + } + return new ErrorMIValue("IfStatement no branch executed"); } public MIValue interpret(ASTFunctionBlock node) { @@ -193,27 +219,32 @@ public MIValue interpret(ASTFunctionBlock node) { for (ASTStatement s : node.getStatementList()) { result = s.evaluate(getRealThis()); + if (result.isError()) { + throw new RuntimeException("Execution failed inside block: " + result.toString()); + } if (result.isReturn()) { return result; } } - // Evaluate the optional trailing expression, if present if (node.isPresentExpression()) { return node.getExpression().evaluate(getRealThis()); } return result; } - - public MIValue interpret(ASTReturnStatement node) { - MIValue value = node.getExpression().evaluate(getRealThis()); - if(value.isError()){ - return new ErrorMIValue("error in return statement"); - } - return new MIReturnSignal(value); + + public MIValue interpret(ASTVariableAsParameter node) { + return new ErrorMIValue("Error ASTVariableAsParameter node"); } + public MIValue interpret(ASTReturnStatement node) { + MIValue value = node.getExpression().evaluate(getRealThis()); + if(value.isError()){ + return new ErrorMIValue("error in return statement"); + } + return new MIReturnSignal(value); + } public MIValue interpret(ASTNumberExpression node) { return node.getNumber().evaluate(getRealThis()); diff --git a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java index 54d53fadbc..0925697905 100644 --- a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java +++ b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java @@ -23,20 +23,21 @@ public void test() throws IOException { SimpleEquationsScopesGenitorDelegator delegator = SimpleEquationsMill.scopesGenitorDelegator(); ASTProgram function = parser.parse_StringProgram("" + - "var a = 3; " + - "var b = 3; " + - "func func1(a, b){ " + - " var c = a; " + + "int a = 3; " + + "int b = 3; " + + "int func func1(int a, int b){ " + + " int c = a; " + " if( b > 0 ){ " + " b = b - 1; " + + " a = a;" + " c = a * 3; " + - " var d = func1(c, b);" + + " int d = func1(c, b);" + " return d;" + " } else { " + " return a;" + " };" + "}"+ - "var result = func1(a, b);" + + "int result = func1(a, b);" + "print(result);").get(); delegator.createFromAST(function); MIValue functionResult = interpreter.interpret(function); From 0de65c1d8c59eb140552f9b9b93264ea0adcfaeb Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Mon, 9 Mar 2026 14:01:21 +0100 Subject: [PATCH 31/37] scope error preserves --- .../src/main/grammars/SimpleEquations.mc4 | 12 +++++------- .../_visitor/SimpleEquationsInterpreter.java | 11 ++++++----- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index 70804bb316..919e013ebf 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -3,7 +3,8 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { Program = (Statement ";" | FunctionCall ";" | FunctionDefinition)* (Expression ";")? ; - FunctionBlock = (Statement ";")* (Expression ";")?; + + scope FunctionBlock = (Statement ";")* (Expression ";")?; interface Statement; interface Expression; @@ -12,13 +13,10 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { ArgList = (args:Expression ("," args:Expression)*)?; - symbol scope FunctionDefinition implements Function, Statement = returnType:Name "func" name:Name FormalParameters "{" Program "}"; - - FormalParameterListing - = (VariableAsParameter | ",")+; + symbol scope FunctionDefinition implements Function, Statement = returnType:Name "func" name:Name FormalParameters "{" FunctionBlock "}"; - FormalParameters - = "(" FormalParameterListing? ")"; + FormalParameterListing = (VariableAsParameter | ",")+; + FormalParameters = "(" FormalParameterListing? ")"; PlusEquation implements Expression = left:Expression "+" right:Expression; MinusEquation implements Expression = left:Expression "-" right:Expression; diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java index 44aace3106..22fed0dae4 100644 --- a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java @@ -9,6 +9,7 @@ import de.monticore.interpreter.values.ModelFunctionMIValue; import de.monticore.interpreter.values.VoidMIValue; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; import de.monticore.types.check.SymTypeExpressionFactory; import simpleequations._ast.*; @@ -136,12 +137,12 @@ public MIValue interpret(ASTPrintStatement node) { } public MIValue interpret(ASTNameExpression node) { - List symbols = node.getEnclosingScope().resolveVariableMany(node.getName()); + List typeVars = node.getEnclosingScope().resolveVariableMany(node.getName()); - if (!symbols.isEmpty()) { - return getRealThis().loadVariable(symbols.get(0)); + if (!typeVars.isEmpty()) { + return getRealThis().loadVariable(typeVars.get(0)); } else { - throw new RuntimeException("CRITICAL: Cannot evaluate '" + node.getName() + "', symbol is missing!"); + throw new RuntimeException("0x57071: Variable '" + node.getName() + "' not found."); } } @@ -169,7 +170,7 @@ public MIValue interpret(ASTFunctionDefinition node) { ModelFunctionMIValue functionValue = new ModelFunctionMIValue( getRealThis().getCurrentScope(), parameterSymbols, - node.getProgram() + node.getFunctionBlock() ); getRealThis().declareFunction(funcSym, functionValue); From e6f791f48a1a43ab38446b9c5f43c45f3209255f Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Mon, 9 Mar 2026 15:33:43 +0100 Subject: [PATCH 32/37] still there --- .../src/main/grammars/SimpleEquations.mc4 | 10 +++--- .../_visitor/SimpleEquationsInterpreter.java | 25 ++------------ .../SimpleEquationsInterpreterTest.java | 33 +++++++++++++++---- 3 files changed, 32 insertions(+), 36 deletions(-) diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index 919e013ebf..cd215d7b48 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -2,18 +2,16 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { - Program = (Statement ";" | FunctionCall ";" | FunctionDefinition)* (Expression ";")? ; - - scope FunctionBlock = (Statement ";")* (Expression ";")?; + scope ProgramBlock = (Statement ";" | FunctionCall ";" | FunctionDefinition)* (Expression ";")? ; interface Statement; interface Expression; - FunctionCall implements Expression, Statement = Name "(" ArgList ")"; + scope FunctionCall implements Expression, Statement = Name "(" ArgList ")"; ArgList = (args:Expression ("," args:Expression)*)?; - symbol scope FunctionDefinition implements Function, Statement = returnType:Name "func" name:Name FormalParameters "{" FunctionBlock "}"; + symbol scope FunctionDefinition implements Function, Statement = returnType:Name "func" name:Name FormalParameters "{" ProgramBlock "}"; FormalParameterListing = (VariableAsParameter | ",")+; FormalParameters = "(" FormalParameterListing? ")"; @@ -28,7 +26,7 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { VariableUsage implements Statement = Name "=" value:Expression; VariableAsParameter implements Variable = type:Name Name; PrintStatement implements Statement = "print" "(" Expression ")"; - IfStatement implements Statement = "if" "(" condition:Expression ")" "{" thenBlock:FunctionBlock "}" ("else" "{" elseBlock:FunctionBlock "}")?; + IfStatement implements Statement = "if" "(" condition:Expression ")" "{" thenBlock:ProgramBlock "}" ("else" "{" elseBlock:ProgramBlock "}")?; ReturnStatement implements Statement = "return" Expression; NameExpression implements Expression = Name; diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java index 22fed0dae4..04b8e4d58b 100644 --- a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java @@ -27,7 +27,7 @@ public SimpleEquationsInterpreter() { super(); } - public MIValue interpret(ASTProgram node) { + public MIValue interpret(ASTProgramBlock node) { MIValue result = new ErrorMIValue("Error ASTProgram node"); for (ASTFunctionDefinition funcDef : node.getFunctionDefinitionList()) { @@ -170,7 +170,7 @@ public MIValue interpret(ASTFunctionDefinition node) { ModelFunctionMIValue functionValue = new ModelFunctionMIValue( getRealThis().getCurrentScope(), parameterSymbols, - node.getFunctionBlock() + node.getProgramBlock() ); getRealThis().declareFunction(funcSym, functionValue); @@ -214,27 +214,6 @@ public MIValue interpret(ASTIfStatement node) { return new ErrorMIValue("IfStatement no branch executed"); } - public MIValue interpret(ASTFunctionBlock node) { - MIValue result = new ErrorMIValue("Error ASTFunctionBlock node"); - - for (ASTStatement s : node.getStatementList()) { - result = s.evaluate(getRealThis()); - - if (result.isError()) { - throw new RuntimeException("Execution failed inside block: " + result.toString()); - } - if (result.isReturn()) { - return result; - } - } - - if (node.isPresentExpression()) { - return node.getExpression().evaluate(getRealThis()); - } - - return result; - } - public MIValue interpret(ASTVariableAsParameter node) { return new ErrorMIValue("Error ASTVariableAsParameter node"); } diff --git a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java index 0925697905..837abf4216 100644 --- a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java +++ b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java @@ -4,7 +4,7 @@ import de.monticore.interpreter.MIValue; import org.junit.jupiter.api.Test; import simpleequations.SimpleEquationsMill; -import simpleequations._ast.ASTProgram; +import simpleequations._ast.ASTProgramBlock; import simpleequations._parser.SimpleEquationsParser; import simpleequations._symboltable.SimpleEquationsScopesGenitorDelegator; @@ -22,7 +22,7 @@ public void test() throws IOException { SimpleEquationsInterpreter interpreter = new SimpleEquationsInterpreter(); SimpleEquationsScopesGenitorDelegator delegator = SimpleEquationsMill.scopesGenitorDelegator(); - ASTProgram function = parser.parse_StringProgram("" + + ASTProgramBlock program = parser.parse_StringProgramBlock("" + "int a = 3; " + "int b = 3; " + "int func func1(int a, int b){ " + @@ -39,13 +39,32 @@ public void test() throws IOException { "}"+ "int result = func1(a, b);" + "print(result);").get(); - delegator.createFromAST(function); - MIValue functionResult = interpreter.interpret(function); + delegator.createFromAST(program); + MIValue functionResult = interpreter.interpret(program); assertTrue(functionResult.isInt()); - assertEquals(functionResult.asInt(), 81); + assertEquals(81, functionResult.asInt()); + + //test recursive method definition + //program = parser.parse_StringProgramBlock("" + + // "int a = 3;" + + // "int b = 3;" + + // "int func func1(int a, int b){" + + // " int func func1(int a, int b) {" + + // " return a + b;" + + // " };" + + // " a = a * a;" + + // " b = b * b;" + + // " return func1(a,b);" + + // "};" + + // "int result = func1(a,b); " + + // "print(result);").get(); + //delegator.createFromAST(program); + //MIValue recursiveResult = interpreter.interpret(program); + //assertTrue(recursiveResult.isInt()); + //assertEquals(18, recursiveResult.asInt() ); - ASTProgram program = parser.parse_StringProgram("var a=3.5; var b=4; print(a); var c=a+b; c;").get(); + program = parser.parse_StringProgramBlock("var a=3.5; var b=4; print(a); var c=a+b; c;").get(); delegator.createFromAST(program); MIValue result = interpreter.interpret(program); @@ -56,7 +75,7 @@ public void test() throws IOException { SimpleEquationsMill.reset(); SimpleEquationsMill.init(); interpreter = new SimpleEquationsInterpreter(); - program = parser.parse_StringProgram( + program = parser.parse_StringProgramBlock( "var a = 40; " + "a = 45;" + "a;").get(); From fe89db50fea6e4ad7935a769e2ec95bb9f9aaf56 Mon Sep 17 00:00:00 2001 From: Hendrik7889 Date: Mon, 9 Mar 2026 17:35:30 +0100 Subject: [PATCH 33/37] Update SimpleEquations.mc4 --- .../src/main/grammars/SimpleEquations.mc4 | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index cd215d7b48..ed0b4bb95f 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -2,19 +2,19 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { - scope ProgramBlock = (Statement ";" | FunctionCall ";" | FunctionDefinition)* (Expression ";")? ; + symbol scope SimpleEquationCompilationUnit = Name "{" (ProgramBlock | FunctionDefinition )+ "}"; + scope ProgramBlock = (Statement ";" | FunctionCall ";")* (Expression ";")? ; interface Statement; interface Expression; - scope FunctionCall implements Expression, Statement = Name "(" ArgList ")"; - + FunctionCall implements Expression, Statement = Name "(" ArgList ")"; ArgList = (args:Expression ("," args:Expression)*)?; symbol scope FunctionDefinition implements Function, Statement = returnType:Name "func" name:Name FormalParameters "{" ProgramBlock "}"; - - FormalParameterListing = (VariableAsParameter | ",")+; FormalParameters = "(" FormalParameterListing? ")"; + FormalParameterListing = (VariableAsParameter | ",")+; + VariableAsParameter implements Variable = type:Name Name; PlusEquation implements Expression = left:Expression "+" right:Expression; MinusEquation implements Expression = left:Expression "-" right:Expression; @@ -22,9 +22,8 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { DivideEquation implements Expression = left:Expression "/" right:Expression; GreaterThanExpression implements Expression = left:Expression ">" right:Expression; - symbol VariableDefinition implements Statement, Variable = type:Name Name "=" value:Expression; + VariableDefinition implements Statement, Variable = type:Name Name "=" value:Expression; VariableUsage implements Statement = Name "=" value:Expression; - VariableAsParameter implements Variable = type:Name Name; PrintStatement implements Statement = "print" "(" Expression ")"; IfStatement implements Statement = "if" "(" condition:Expression ")" "{" thenBlock:ProgramBlock "}" ("else" "{" elseBlock:ProgramBlock "}")?; ReturnStatement implements Statement = "return" Expression; From 9ef432bab2f5f4e956f46732ef7b8e20aa6d8f6a Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Mon, 9 Mar 2026 18:06:03 +0100 Subject: [PATCH 34/37] sync --- .../src/main/grammars/SimpleEquations.mc4 | 4 +- ...SimpleEquationsScopesGenitorDelegator.java | 20 ++++++ .../_visitor/SimpleEquationsInterpreter.java | 12 +++- .../SimpleEquationsInterpreterTest.java | 62 ++++++++++++------- 4 files changed, 70 insertions(+), 28 deletions(-) create mode 100644 monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_symboltable/SimpleEquationsScopesGenitorDelegator.java diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index ed0b4bb95f..f315f4b8c6 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -2,8 +2,8 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { - symbol scope SimpleEquationCompilationUnit = Name "{" (ProgramBlock | FunctionDefinition )+ "}"; - scope ProgramBlock = (Statement ";" | FunctionCall ";")* (Expression ";")? ; + symbol scope SimpleEquationCompilationUnit = Name "{" (ProgramBlock | FunctionDefinition)+ "}"; + scope ProgramBlock = (Statement ";" | FunctionCall ";")+ (Expression ";")? ; interface Statement; interface Expression; diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_symboltable/SimpleEquationsScopesGenitorDelegator.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_symboltable/SimpleEquationsScopesGenitorDelegator.java new file mode 100644 index 0000000000..13728cda97 --- /dev/null +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_symboltable/SimpleEquationsScopesGenitorDelegator.java @@ -0,0 +1,20 @@ +package simpleequations._symboltable; + +public class SimpleEquationsScopesGenitorDelegator extends SimpleEquationsScopesGenitorDelegatorTOP{ + + @Override + public simpleequations._symboltable.ISimpleEquationsArtifactScope createFromAST (simpleequations._ast.ASTSimpleEquationCompilationUnit rootNode) { + simpleequations._symboltable.ISimpleEquationsArtifactScope as = symbolTable.createFromAST(rootNode); + //only add this here + as.setName(rootNode.getName()); + //until here + if (as.isPresentName()){ + if (!as.getPackageName().isEmpty()){ + globalScope.addLoadedFile(as.getPackageName() + "." + as.getName()); + } else { + globalScope.addLoadedFile(as.getName()); + } + } + return as; + } +} diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java index 04b8e4d58b..c9981276e4 100644 --- a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java @@ -27,12 +27,20 @@ public SimpleEquationsInterpreter() { super(); } - public MIValue interpret(ASTProgramBlock node) { - MIValue result = new ErrorMIValue("Error ASTProgram node"); + public MIValue interpret(ASTSimpleEquationCompilationUnit node) { + MIValue result = new ErrorMIValue("Error ASTSimpleEquationCompilationUnit node"); for (ASTFunctionDefinition funcDef : node.getFunctionDefinitionList()) { funcDef.evaluate(getRealThis()); } + for(ASTProgramBlock progBlock : node.getProgramBlockList()){ + progBlock.evaluate(getRealThis()); + } + return result; + } + + public MIValue interpret(ASTProgramBlock node) { + MIValue result = new ErrorMIValue("Error ASTProgram node"); for (ASTStatement s : node.getStatementList()) { result = s.evaluate(getRealThis()); diff --git a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java index 837abf4216..9398b57df4 100644 --- a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java +++ b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java @@ -5,6 +5,7 @@ import org.junit.jupiter.api.Test; import simpleequations.SimpleEquationsMill; import simpleequations._ast.ASTProgramBlock; +import simpleequations._ast.ASTSimpleEquationCompilationUnit; import simpleequations._parser.SimpleEquationsParser; import simpleequations._symboltable.SimpleEquationsScopesGenitorDelegator; @@ -22,30 +23,33 @@ public void test() throws IOException { SimpleEquationsInterpreter interpreter = new SimpleEquationsInterpreter(); SimpleEquationsScopesGenitorDelegator delegator = SimpleEquationsMill.scopesGenitorDelegator(); - ASTProgramBlock program = parser.parse_StringProgramBlock("" + - "int a = 3; " + - "int b = 3; " + - "int func func1(int a, int b){ " + - " int c = a; " + - " if( b > 0 ){ " + - " b = b - 1; " + - " a = a;" + - " c = a * 3; " + - " int d = func1(c, b);" + - " return d;" + - " } else { " + - " return a;" + - " };" + - "}"+ - "int result = func1(a, b);" + - "print(result);").get(); + ASTSimpleEquationCompilationUnit program = parser.parse_StringSimpleEquationCompilationUnit("" + + "Program {" + + " int a = 3; " + + " int b = 3; " + + " int func func1(int a, int b){ " + + " int c = a; " + + " if( b > 0 ){ " + + " b = b - 1; " + + " a = a;" + + " c = a * 3; " + + " int d = func1(c, b);" + + " return d;" + + " } else { " + + " return a;" + + " };" + + " }"+ + " int result = func1(a, b);" + + " print(result);" + + "}").get(); delegator.createFromAST(program); MIValue functionResult = interpreter.interpret(program); assertTrue(functionResult.isInt()); assertEquals(81, functionResult.asInt()); //test recursive method definition - //program = parser.parse_StringProgramBlock("" + + //program = parser.parse_StringSimpleEquationCompilationUnit("" + + // "Program {" + // "int a = 3;" + // "int b = 3;" + // "int func func1(int a, int b){" + @@ -57,14 +61,22 @@ public void test() throws IOException { // " return func1(a,b);" + // "};" + // "int result = func1(a,b); " + - // "print(result);").get(); + // "print(result);" + // "}").get(); //delegator.createFromAST(program); //MIValue recursiveResult = interpreter.interpret(program); //assertTrue(recursiveResult.isInt()); //assertEquals(18, recursiveResult.asInt() ); - program = parser.parse_StringProgramBlock("var a=3.5; var b=4; print(a); var c=a+b; c;").get(); + program = parser.parse_StringSimpleEquationCompilationUnit("" + + "Program {" + + " var a=3.5; " + + " var b=4; " + + " print(a); " + + " var c=a+b; " + + " c;" + + "}").get(); delegator.createFromAST(program); MIValue result = interpreter.interpret(program); @@ -75,10 +87,12 @@ public void test() throws IOException { SimpleEquationsMill.reset(); SimpleEquationsMill.init(); interpreter = new SimpleEquationsInterpreter(); - program = parser.parse_StringProgramBlock( - "var a = 40; " + - "a = 45;" + - "a;").get(); + program = parser.parse_StringSimpleEquationCompilationUnit( + "Program {" + + " var a = 40; " + + " a = 45;" + + " a;" + + "}").get(); delegator.createFromAST(program); result = interpreter.interpret(program); From 2a4eb3b35904f1fad5d866f26b8e9b3566ad9088 Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Tue, 10 Mar 2026 10:56:44 +0100 Subject: [PATCH 35/37] fixed double resolve --- .../src/main/grammars/SimpleEquations.mc4 | 9 +-- .../_visitor/SimpleEquationsInterpreter.java | 62 ++++++++++--------- .../SimpleEquationsInterpreterTest.java | 7 +-- 3 files changed, 41 insertions(+), 37 deletions(-) diff --git a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 index f315f4b8c6..8b84a06743 100644 --- a/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 +++ b/monticore-test/01.experiments/interpreter/src/main/grammars/SimpleEquations.mc4 @@ -2,8 +2,9 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { - symbol scope SimpleEquationCompilationUnit = Name "{" (ProgramBlock | FunctionDefinition)+ "}"; - scope ProgramBlock = (Statement ";" | FunctionCall ";")+ (Expression ";")? ; + symbol scope SimpleEquationCompilationUnit = Name "{" ProgramBlock (FunctionDefinition)* "}"; + scope ProgramBlock = (Statement ";")+ (Expression ";")? ; + FunctionBlock = (Statement ";")+ (Expression ";")? ; interface Statement; interface Expression; @@ -11,7 +12,7 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { FunctionCall implements Expression, Statement = Name "(" ArgList ")"; ArgList = (args:Expression ("," args:Expression)*)?; - symbol scope FunctionDefinition implements Function, Statement = returnType:Name "func" name:Name FormalParameters "{" ProgramBlock "}"; + symbol scope FunctionDefinition implements Function, Statement = returnType:Name "func" name:Name FormalParameters "{" FunctionBlock "}"; FormalParameters = "(" FormalParameterListing? ")"; FormalParameterListing = (VariableAsParameter | ",")+; VariableAsParameter implements Variable = type:Name Name; @@ -22,7 +23,7 @@ grammar SimpleEquations extends Numerals, de.monticore.symbols.BasicSymbols { DivideEquation implements Expression = left:Expression "/" right:Expression; GreaterThanExpression implements Expression = left:Expression ">" right:Expression; - VariableDefinition implements Statement, Variable = type:Name Name "=" value:Expression; + symbol VariableDefinition implements Statement, Variable = type:Name Name "=" value:Expression; VariableUsage implements Statement = Name "=" value:Expression; PrintStatement implements Statement = "print" "(" Expression ")"; IfStatement implements Statement = "if" "(" condition:Expression ")" "{" thenBlock:ProgramBlock "}" ("else" "{" elseBlock:ProgramBlock "}")?; diff --git a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java index c9981276e4..580e987720 100644 --- a/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java +++ b/monticore-test/01.experiments/interpreter/src/main/java/simpleequations/_visitor/SimpleEquationsInterpreter.java @@ -8,9 +8,8 @@ import de.monticore.interpreter.values.MIReturnSignal; import de.monticore.interpreter.values.ModelFunctionMIValue; import de.monticore.interpreter.values.VoidMIValue; +import de.monticore.javalight._ast.ASTMethodDeclaration; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; -import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; import de.monticore.types.check.SymTypeExpressionFactory; import simpleequations._ast.*; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; @@ -29,12 +28,14 @@ public SimpleEquationsInterpreter() { public MIValue interpret(ASTSimpleEquationCompilationUnit node) { - MIValue result = new ErrorMIValue("Error ASTSimpleEquationCompilationUnit node"); - for (ASTFunctionDefinition funcDef : node.getFunctionDefinitionList()) { - funcDef.evaluate(getRealThis()); + MIValue result; + for(ASTFunctionDefinition method : node.getFunctionDefinitionList()){ + method.evaluate(getRealThis()); } - for(ASTProgramBlock progBlock : node.getProgramBlockList()){ - progBlock.evaluate(getRealThis()); + + result = node.getProgramBlock().evaluate(getRealThis()); + if(result.isError()){ + return new ErrorMIValue("Error ASTSimpleEquationCompilationUnit wrong return type from ASTProgramBlock"); } return result; } @@ -112,20 +113,10 @@ public MIValue interpret(ASTVariableDefinition node) { public MIValue interpret(ASTVariableUsage node) { MIValue value = node.getValue().evaluate(getRealThis()); - List symbols = node.getEnclosingScope().resolveVariableMany(node.getName()); - - if (!symbols.isEmpty()) { - if (symbols.size() > 1) { - Stack scopeStack = getScopeCallstack(); - System.out.println(scopeStack.size() + " scopes on stack:"); - System.err.println("DEBUG: MontiCore found " + symbols.size() + " symbols for '" + node.getName() + "'!"); - for (VariableSymbol sym : symbols) { - System.err.println(" -> Created by: " + (sym.isPresentAstNode() ? sym.getAstNode().getClass().getSimpleName() + " " + sym.getFullName() : "Unknown")); - } - } + Optional symbols = node.getEnclosingScope().resolveVariable(node.getName()); - // needed as there exists b, func1.b func1.b .. for every interation. We need to grab the first - getRealThis().storeVariable(symbols.get(0), value); + if (symbols.isPresent()) { + getRealThis().storeVariable(symbols.get(), value); } else { throw new RuntimeException("CRITICAL: Variable '" + node.getName() + "' not found in scope!"); } @@ -136,19 +127,20 @@ public MIValue interpret(ASTVariableUsage node) { public MIValue interpret(ASTPrintStatement node) { MIValue output = node.getExpression().evaluate(getRealThis()); - if (output.isInt()) { - System.out.println(output.asInt()); - } else if (output.isFloat()) { - System.out.println(output.asFloat()); - } + //if (output.isInt()) { + // System.out.println(output.asInt()); + //} else if (output.isFloat()) { + // System.out.println(output.asFloat()); + //} + return output; } public MIValue interpret(ASTNameExpression node) { - List typeVars = node.getEnclosingScope().resolveVariableMany(node.getName()); + Optional typeVars = node.getEnclosingScope().resolveVariable(node.getName()); if (!typeVars.isEmpty()) { - return getRealThis().loadVariable(typeVars.get(0)); + return getRealThis().loadVariable(typeVars.get()); } else { throw new RuntimeException("0x57071: Variable '" + node.getName() + "' not found."); } @@ -178,13 +170,27 @@ public MIValue interpret(ASTFunctionDefinition node) { ModelFunctionMIValue functionValue = new ModelFunctionMIValue( getRealThis().getCurrentScope(), parameterSymbols, - node.getProgramBlock() + node.getFunctionBlock() ); getRealThis().declareFunction(funcSym, functionValue); return new VoidMIValue(); } + public MIValue interpret(ASTFunctionBlock node){ + MIValue result = new ErrorMIValue("Error ASTFunctionBlock node"); + for (ASTStatement s : node.getStatementList()) { + result = s.evaluate(getRealThis()); + if (result.isReturn()) { + return result; + } + } + if (node.isPresentExpression()) { + return node.getExpression().evaluate(getRealThis()); + } + return result; + } + public MIValue interpret(ASTFunctionCall node) { Optional functionSymbol = node.getEnclosingScope().resolveFunction(node.getName()); diff --git a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java index 9398b57df4..69b19dc2c2 100644 --- a/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java +++ b/monticore-test/01.experiments/interpreter/src/test/java/simpleequations/_visitor/SimpleEquationsInterpreterTest.java @@ -4,13 +4,10 @@ import de.monticore.interpreter.MIValue; import org.junit.jupiter.api.Test; import simpleequations.SimpleEquationsMill; -import simpleequations._ast.ASTProgramBlock; import simpleequations._ast.ASTSimpleEquationCompilationUnit; import simpleequations._parser.SimpleEquationsParser; import simpleequations._symboltable.SimpleEquationsScopesGenitorDelegator; - import java.io.IOException; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -27,6 +24,8 @@ public void test() throws IOException { "Program {" + " int a = 3; " + " int b = 3; " + + " int result = func1(a, b);" + + " print(result);" + " int func func1(int a, int b){ " + " int c = a; " + " if( b > 0 ){ " + @@ -39,8 +38,6 @@ public void test() throws IOException { " return a;" + " };" + " }"+ - " int result = func1(a, b);" + - " print(result);" + "}").get(); delegator.createFromAST(program); MIValue functionResult = interpreter.interpret(program); From b82daec3b01b192a2c0d6562e47a35393936d768 Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Tue, 31 Mar 2026 14:26:50 +0200 Subject: [PATCH 36/37] fix pipeline --- monticore-test/01.experiments/forParser/build.gradle | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/monticore-test/01.experiments/forParser/build.gradle b/monticore-test/01.experiments/forParser/build.gradle index 59efeb1aa2..42b60e6a30 100644 --- a/monticore-test/01.experiments/forParser/build.gradle +++ b/monticore-test/01.experiments/forParser/build.gradle @@ -3,13 +3,12 @@ description = 'Experiments: forParser' dependencies { implementation group:'de.monticore', name:'monticore-generator', version:version - implementation group:'de.monticore', name:'monticore-grammar', version:previous_mc_version implementation group:'de.monticore', name:'monticore-runtime', version:previous_mc_version implementation 'de.se_rwth.commons:se-commons-logging:' + se_commons_version - implementation group:'de.monticore', name:'monticore-grammar', version:previous_mc_version, classifier:"grammars" implementation group:'de.monticore.lang', name:'cd4analysis', version:cd4a_version implementation ("com.google.guava:guava:$guava_version!!") implementation project(path: ':monticore-runtime') + implementation project(path: ':monticore-grammar') } test { From ceee953a88478a503888c3c00fdc07e1146376b4 Mon Sep 17 00:00:00 2001 From: Hendrik7889 <44064629+Hendrik7889@users.noreply.github.com> Date: Thu, 16 Apr 2026 09:40:39 +0200 Subject: [PATCH 37/37] Update build.gradle --- monticore-test/01.experiments/forParser/build.gradle | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/monticore-test/01.experiments/forParser/build.gradle b/monticore-test/01.experiments/forParser/build.gradle index 42b60e6a30..59efeb1aa2 100644 --- a/monticore-test/01.experiments/forParser/build.gradle +++ b/monticore-test/01.experiments/forParser/build.gradle @@ -3,12 +3,13 @@ description = 'Experiments: forParser' dependencies { implementation group:'de.monticore', name:'monticore-generator', version:version + implementation group:'de.monticore', name:'monticore-grammar', version:previous_mc_version implementation group:'de.monticore', name:'monticore-runtime', version:previous_mc_version implementation 'de.se_rwth.commons:se-commons-logging:' + se_commons_version + implementation group:'de.monticore', name:'monticore-grammar', version:previous_mc_version, classifier:"grammars" implementation group:'de.monticore.lang', name:'cd4analysis', version:cd4a_version implementation ("com.google.guava:guava:$guava_version!!") implementation project(path: ':monticore-runtime') - implementation project(path: ':monticore-grammar') } test {

* note: Exception is not supposed to happen, * thus, never rely on this(!) Error being logged (here) * some error should be logged, though. @@ -384,7 +482,7 @@ public static void reset() { protected static void setDelegate( WithinScopeBasicSymbolsResolver newDelegate ) { - WithinScopeBasicSymbolsResolver.delegate = Log.errorIfNull(newDelegate); + WithinScopeBasicSymbolsResolver.delegate = Preconditions.checkNotNull(newDelegate); } protected static WithinScopeBasicSymbolsResolver getDelegate() { diff --git a/monticore-grammar/src/main/java/de/monticore/types3/util/WithinTypeBasicSymbolsResolver.java b/monticore-grammar/src/main/java/de/monticore/types3/util/WithinTypeBasicSymbolsResolver.java index bc1688f087..b936484577 100644 --- a/monticore-grammar/src/main/java/de/monticore/types3/util/WithinTypeBasicSymbolsResolver.java +++ b/monticore-grammar/src/main/java/de/monticore/types3/util/WithinTypeBasicSymbolsResolver.java @@ -1,6 +1,7 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.util; +import com.google.common.base.Preconditions; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; @@ -8,11 +9,12 @@ import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.symbols.basicsymbols._util.IBasicSymbolsTypeDispatcher; +import de.monticore.symbols.basicsymbols._visitor.BasicSymbolsTraverser; +import de.monticore.symbols.basicsymbols._visitor.BasicSymbolsVisitor2; import de.monticore.symboltable.IScope; import de.monticore.symboltable.ISymbol; import de.monticore.symboltable.modifiers.AccessModifier; import de.monticore.symboltable.modifiers.BasicAccessModifier; -import de.monticore.symboltable.resolving.ResolvedSeveralEntriesForSymbolException; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.check.SymTypeInferenceVariable; @@ -26,8 +28,9 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -67,6 +70,14 @@ protected Optional _resolveVariable( String name, AccessModifier accessModifier, Predicate predicate) { + return resolveVariableRecursive(thisType, name, accessModifier, predicate); + } + + protected Optional resolveVariableRecursive( + SymTypeExpression thisType, + String name, + AccessModifier accessModifier, + Predicate predicate) { Optional resolvedSymType; Optional spannedScopeOpt = getSpannedScope(thisType); if (spannedScopeOpt.isEmpty()) { @@ -100,11 +111,16 @@ protected Optional _resolveVariable( resolvedSymType = Optional.empty(); for (SymTypeExpression superType : superTypes) { Optional resolvedInSuper = - resolveVariable(superType, name, superModifier, predicate); + resolveVariableRecursive(superType, name, superModifier, predicate); if (resolvedSymType.isPresent() && resolvedInSuper.isPresent()) { Log.error("0xFD222 found variables with name \"" - + name + "\" in multiple super types of \"" - + thisType.printFullName() + "\""); + + name + "\" in multiple super types of \"" + + thisType.printFullName() + "\"." + + " Nominal super types:" + + superTypes.stream().map(st -> + System.lineSeparator() + st.printFullName() + ) + ); } else if (resolvedSymType.isEmpty() && resolvedInSuper.isPresent()) { resolvedSymType = resolvedInSuper; @@ -128,6 +144,34 @@ else if (resolvedSymType.isEmpty() && resolvedInSuper.isPresent()) { return resolvedSymType; } + /** + * resolves all variables within the type including supertypes + */ + public static Map getAllVariables( + SymTypeExpression thisType, + AccessModifier accessModifier, + Predicate predicate + ) { + return getDelegate()._getAllVariables(thisType, accessModifier, predicate); + } + + protected Map _getAllVariables( + SymTypeExpression thisType, + AccessModifier accessModifier, + Predicate predicate + ) { + Map allVariables = new LinkedHashMap<>(); + Collection names = _internal_getMemberNames(thisType); + for (String name : names) { + Optional varOpt = + resolveVariable(thisType, name, accessModifier, predicate); + if (varOpt.isPresent()) { + allVariables.put(name, varOpt.get()); + } + } + return allVariables; + } + /** * resolves within a type including supertypes */ @@ -142,6 +186,54 @@ public static List resolveFunctions( } protected List _resolveFunctions( + SymTypeExpression thisType, + String name, + AccessModifier accessModifier, + Predicate predicate + ) { + return resolveFunctionsRecursive(thisType, name, accessModifier, predicate); + } + + protected List resolveFunctionsRecursive( + SymTypeExpression thisType, + String name, + AccessModifier accessModifier, + Predicate predicate + ) { + List resolvedSymTypes = new ArrayList<>(); + List resolvedInThis = + resolveFunctionsInThisType( + thisType, name, accessModifier, predicate + ); + resolvedSymTypes.addAll(resolvedInThis); + // search in super types + List resolvedInSuper = + resolvedFunctionsInSuperTypes( + thisType, name, accessModifier, predicate + ); + // filter based on being overridden / hidden (static) + // Java Spec 20 8.4.8.1 overriding methods need to have the SAME signature, + // e.g., Integer getX() overrides Number getX() + // e.g., void setX(Number x) does not override void setX(Integer x) + // we assume that CoCos corresponding to the compile time errors of + // Java Spec 20 8.4.8 are used + for (SymTypeOfFunction superFunc : resolvedInSuper) { + if (resolvedInThis.stream() + .noneMatch((f -> f.deepEqualsSignature(superFunc)))) { + resolvedSymTypes.add(superFunc); + } + } + + // replace type variables + List symTypesFreeVarsReplaced = resolvedSymTypes.stream() + .map(t -> replaceFreeTypeVariables(thisType, t)) + .map(SymTypeExpression::asFunctionType) + .collect(Collectors.toList()); + + return symTypesFreeVarsReplaced; + } + + protected List resolveFunctionsInThisType( SymTypeExpression thisType, String name, AccessModifier accessModifier, @@ -154,7 +246,7 @@ protected List _resolveFunctions( // search in this scope else { //todo outer types (and vs. supertypes) not really? - List resolvedSymbols = resolveFunctionLocally( + List resolvedSymbols = resolveFunctionLocallyMany( thisType.getTypeInfo().getSpannedScope(), name, accessModifier, @@ -170,28 +262,21 @@ protected List _resolveFunctions( resolvedSymTypes.add(funcType); } } - // search in super types + return resolvedSymTypes; + } + + protected List resolvedFunctionsInSuperTypes( + SymTypeExpression thisType, + String name, + AccessModifier accessModifier, + Predicate predicate) { // private -> protected while searching in super types AccessModifier superModifier = private2Protected(accessModifier); List superTypes = getSuperTypes(thisType); List superFuncs = new ArrayList<>(); for (SymTypeExpression superType : superTypes) { List resolvedInSuper = - resolveFunctions(superType, name, superModifier, predicate); - // filter based on being overridden / hidden (static) - // Java Spec 20 8.4.8.1 overriding methods need to have the SAME signature, - // e.g., Integer getX() overrides Number getX() - // e.g., void setX(Number x) does not override void setX(Integer x) - // we assume that CoCos corresponding to the compile time errors of - // Java Spec 20 8.4.8 are used - for (Iterator fItr = resolvedInSuper.iterator(); - fItr.hasNext(); ) { - SymTypeOfFunction superFunc = fItr.next(); - if (resolvedSymTypes.stream() - .anyMatch(f -> f.deepEqualsSignature(superFunc))) { - fItr.remove(); - } - } + resolveFunctionsRecursive(superType, name, superModifier, predicate); superFuncs.addAll(resolvedInSuper); } // filter based on being inherited twice (diamond pattern) @@ -209,15 +294,35 @@ protected List _resolveFunctions( filteredSuperFuncs.add(func1); } } - resolvedSymTypes.addAll(filteredSuperFuncs); + return filteredSuperFuncs; + } - // replace type variables - List symTypesFreeVarsReplaced = resolvedSymTypes.stream() - .map(t -> replaceFreeTypeVariables(thisType, t)) - .map(SymTypeExpression::asFunctionType) - .collect(Collectors.toList()); + /** + * resolves all functions within the type including supertypes + */ + public static Map> getAllFunctions( + SymTypeExpression thisType, + AccessModifier accessModifier, + Predicate predicate + ) { + return getDelegate()._getAllFunctions(thisType, accessModifier, predicate); + } - return symTypesFreeVarsReplaced; + protected Map> _getAllFunctions( + SymTypeExpression thisType, + AccessModifier accessModifier, + Predicate predicate + ) { + Map> allFunctions = new LinkedHashMap<>(); + Collection names = _internal_getMemberNames(thisType); + for (String name : names) { + List functions = + resolveFunctions(thisType, name, accessModifier, predicate); + if (!functions.isEmpty()) { + allFunctions.put(name, functions); + } + } + return allFunctions; } /** @@ -238,6 +343,14 @@ protected Optional _resolveType( String name, AccessModifier accessModifier, Predicate predicate) { + return resolveTypeRecursive(thisType, name, accessModifier, predicate); + } + + protected Optional resolveTypeRecursive( + SymTypeExpression thisType, + String name, + AccessModifier accessModifier, + Predicate predicate) { Optional resolvedSymType; Optional spannedScopeOpt = getSpannedScope(thisType); if (spannedScopeOpt.isEmpty()) { @@ -271,11 +384,16 @@ protected Optional _resolveType( resolvedSymType = Optional.empty(); for (SymTypeExpression superType : superTypes) { Optional resolvedInSuper = - resolveType(superType, name, superModifier, predicate); + resolveTypeRecursive(superType, name, superModifier, predicate); if (resolvedSymType.isPresent() && resolvedInSuper.isPresent()) { Log.error("0xFD224 found type with name \"" - + name + "\" in multiple super types of \"" - + thisType.printFullName() + "\""); + + name + "\" in multiple super types of \"" + + thisType.printFullName() + "\"." + + " Nominal super types:" + + superTypes.stream().map(st -> + System.lineSeparator() + st.printFullName() + ) + ); } resolvedSymType = resolvedInSuper; } @@ -287,6 +405,34 @@ protected Optional _resolveType( return symTypeFreeVarsReplaced; } + /** + * resolves all types within the type including supertypes + */ + public static Map getAllTypes( + SymTypeExpression thisType, + AccessModifier accessModifier, + Predicate predicate + ) { + return getDelegate()._getAllTypes(thisType, accessModifier, predicate); + } + + protected Map _getAllTypes( + SymTypeExpression thisType, + AccessModifier accessModifier, + Predicate predicate + ) { + Map allTypes = new LinkedHashMap<>(); + Collection names = _internal_getMemberNames(thisType); + for (String name : names) { + Optional typeOpt = + resolveType(thisType, name, accessModifier, predicate); + if (typeOpt.isPresent()) { + allTypes.put(name, typeOpt.get()); + } + } + return allTypes; + } + /** * checks if the symtypeExpression is of a (sym)type to be resolved in, * e.g., this includes objects but excludes primitives. @@ -309,58 +455,59 @@ protected boolean _canResolveIn(SymTypeExpression thisType) { // array.size not supported yet } - // Helper + // Helper / Extension Points /** - * resolves locally, EXCLUDING supertypes + * Resolves locally, EXCLUDING supertypes. + * This can be used as an extension point. + * S.a. {@link WithinScopeBasicSymbolsResolver#resolveType(IBasicSymbolsScope, String, AccessModifier, Predicate)} */ protected Optional resolveVariableLocally( IBasicSymbolsScope scope, String name, AccessModifier accessModifier, Predicate predicate) { - // may include symbols of supertypes, thus the predicate - Optional resolved; - // work around for resolver throwing RuntimeExceptions - try { - resolved = scope.resolveVariable( - name, - accessModifier, - predicate.and(getIsLocalSymbolPredicate(scope)) - ); - } - catch (ResolvedSeveralEntriesForSymbolException e) { - // note: Exception is not supposed to happen, - // thus, never rely on this(!) Error being logged (here) - // some error should be logged, though. - Log.error("0xFD225 internal error: resolved " + e.getSymbols().size() - + "occurences of variable " + name - + ", but expected only one:" + System.lineSeparator() - + e.getSymbols().stream() - .map(ISymbol::getFullName) - .collect(Collectors.joining(System.lineSeparator())), - e + // todo replace with resolveVariableLocally, as soon as it supports + // Accessmodifier and Predicate. + List resolved = scope.resolveVariableLocallyMany( + false, + name, + accessModifier, + // assure that no symbols of supertypes are added by the resolver + predicate.and(getIsLocalSymbolPredicate(scope)) + ); + // todo remove given a fixed resolver + resolved = resolved.stream() + .filter(predicate.and(getIsLocalSymbolPredicate(scope))) + .collect(Collectors.toList()); + // todo remove as soon as resolveVariableLocally is used + if (resolved.size() > 1) { + Log.error("0xFD225 resolved " + resolved.size() + + "occurences of variable " + name + + ", but expected only one:" + System.lineSeparator() + + resolved.stream() + .map(ISymbol::getFullName) + .collect(Collectors.joining(System.lineSeparator())) ); - resolved = Optional.empty(); + resolved = Collections.emptyList(); } - // todo remove given a fixed resolver - resolved = resolved.filter(predicate.and(getIsLocalSymbolPredicate(scope))); - return resolved; + return resolved.stream().findAny(); } /** - * resolves locally, EXCLUDING supertypes + * Resolves locally, EXCLUDING supertypes. + * This can be used as an extension point. */ - protected List resolveFunctionLocally( + protected List resolveFunctionLocallyMany( IBasicSymbolsScope scope, String name, AccessModifier accessModifier, Predicate predicate) { - // may include symbols of supertypes, thus the predicate List resolved = scope.resolveFunctionLocallyMany( false, name, accessModifier, + // assure that no symbols of supertypes are added by the resolver predicate.and(getIsLocalSymbolPredicate(scope)) ); // todo remove given a fixed resolver @@ -371,20 +518,39 @@ protected List resolveFunctionLocally( } /** - * resolves locally, EXCLUDING supertypes + * @deprecated renamend to + * {@link #resolveFunctionLocallyMany(IBasicSymbolsScope, String, AccessModifier, Predicate)} + */ + @Deprecated(forRemoval = true) + protected List resolveFunctionLocally( + IBasicSymbolsScope scope, + String name, + AccessModifier accessModifier, + Predicate predicate) { + return resolveFunctionLocallyMany(scope, name, accessModifier, predicate); + } + + /** + * Resolves locally, EXCLUDING supertypes. + * This can be used as an extension point. + * S.a. {@link WithinScopeBasicSymbolsResolver#resolveType(IBasicSymbolsScope, String, AccessModifier, Predicate)} */ protected Optional resolveTypeLocally( IBasicSymbolsScope scope, String name, AccessModifier accessModifier, Predicate predicate) { - // may include symbols of supertypes, thus the predicate + // todo replace with resolveTypeLocally, as soon as it supports + // Accessmodifier and Predicate. List resolved = scope.resolveTypeLocallyMany( false, name, accessModifier, predicate + // todo removed as soon as + // TypeVarSymbol does not extend TypeSymbol anymore .and(getIsNotTypeVarSymbolPredicate()) + // assure that no symbols of supertypes are added by the resolver .and(getIsLocalSymbolPredicate(scope)) ); // todo remove given a fixed resolver @@ -394,6 +560,7 @@ protected Optional resolveTypeLocally( .and(getIsLocalSymbolPredicate(scope)) ) .collect(Collectors.toList()); + // todo remove as soon as resolveTypeLocally is used if (resolved.size() > 1) { Log.error("0xFD221 resolved multiple types \"" + name + "\" (locally in the same scope)"); @@ -506,6 +673,66 @@ protected List getSuperTypes(SymTypeExpression thisType) { return SymTypeRelations.getNominalSuperTypes(thisType); } + /** + * internal; gets all member names, + * does not filter in any way, thus not generally applicable + */ + protected List _internal_getMemberNames(SymTypeExpression thisType) { + LinkedHashSet names = new LinkedHashSet<>(); + Optional thisScopeOpt = getSpannedScope(thisType); + if (thisScopeOpt.isPresent()) { + IBasicSymbolsScope thisScope = thisScopeOpt.get(); + names.addAll(_internal_getMemberNamesLocally(thisScope)); + } + List superTypes = getSuperTypes(thisType); + // in rare cases exponential, could be optimized + for (SymTypeExpression superType : superTypes) { + names.addAll(_internal_getMemberNames(superType)); + } + return new ArrayList<>(names); + } + + protected List _internal_getMemberNamesLocally( + IBasicSymbolsScope scope + ) { + LinkedHashSet names = new LinkedHashSet<>(); + // todo severely inefficient, replace after https://git.rwth-aachen.de/monticore/monticore/-/issues/4732 + BasicSymbolsTraverser traverser = BasicSymbolsMill.inheritanceTraverser(); + traverser.add4BasicSymbols( + new BasicSymbolsVisitor2() { + @Override + public void visit(TypeSymbol sym) { + if (sym.getEnclosingScope() == scope) { + names.add(sym.getName()); + } + } + + @Override + public void visit(TypeVarSymbol sym) { + if (sym.getEnclosingScope() == scope) { + names.add(sym.getName()); + } + } + + @Override + public void visit(VariableSymbol sym) { + if (sym.getEnclosingScope() == scope) { + names.add(sym.getName()); + } + } + + @Override + public void visit(FunctionSymbol sym) { + if (sym.getEnclosingScope() == scope) { + names.add(sym.getName()); + } + } + } + ); + scope.accept(traverser); + return new ArrayList<>(names); + } + /** * replaces any private access with protected access * this is done to resolve in supertypes @@ -521,6 +748,21 @@ protected AccessModifier private2Protected(AccessModifier accessModifier) { return newModifier; } + protected Map getUnboundVariableReplaceMap( + List varsNotToReplace, SymTypeExpression type) { + // 1. find all variables + Map allVarMap = + TypeParameterRelations.getFreeVariableReplaceMap(type, BasicSymbolsMill.scope()); + // 2. get variables that actually need to be replaced (unbound) + Map freeVarMap = new LinkedHashMap<>(); + for (Map.Entry e : allVarMap.entrySet()) { + if (varsNotToReplace.stream().noneMatch(e.getKey()::deepEquals)) { + freeVarMap.put(e.getKey(), e.getValue()); + } + } + return freeVarMap; + } + protected SymTypeExpression replaceFreeTypeVariables( SymTypeExpression thisType, SymTypeExpression type @@ -535,26 +777,18 @@ protected SymTypeExpression replaceFreeTypeVariables( // In the example above, resolving f in B will result in // () -> C<#FV,T,R> where #FV is a free type variable - // 1. find all variables - Map allVarMap = TypeParameterRelations - .getFreeVariableReplaceMap(type, BasicSymbolsMill.scope()); - // 2. find all type variables already bound by the type resolved in - List varsAlreadyBound = new SymTypeCollectionVisitor() - .calculate(thisType, SymTypeExpression::isTypeVariable).stream() - .map(SymTypeExpression::asTypeVariable) - .collect(Collectors.toList()); - // 3. get variables that actually need to be replaced (unbound) - Map freeVarMap = new HashMap<>(); - for (Map.Entry e : allVarMap.entrySet()) { - if (varsAlreadyBound.stream().noneMatch(e.getKey()::deepEquals)) { - freeVarMap.put(e.getKey(), e.getValue()); - } - } - // 3.5 double check that the symTab does make any sense + // 1. find all type variables already bound by the type resolved in + List varsAlreadyBound = + new SymTypeCollectionVisitor().calculate(thisType, SymTypeExpression::isTypeVariable) + .stream().map(SymTypeExpression::asTypeVariable).collect(Collectors.toList()); + // 2. get unbound variable replacement map + Map freeVarMap = + getUnboundVariableReplaceMap(varsAlreadyBound, type); + // 2.5 double check that the symTab does make any sense assertTypeVarsAreIncluded(type, freeVarMap.keySet()); - // 4. actually replace the free variables - SymTypeExpression typeVarsReplaced = TypeParameterRelations - .replaceTypeVariables(type, freeVarMap); + // 3. actually replace the free variables + SymTypeExpression typeVarsReplaced = + TypeParameterRelations.replaceTypeVariables(type, freeVarMap); return typeVarsReplaced; } @@ -573,7 +807,7 @@ protected void assertTypeVarsAreIncluded( .map(SymTypeExpressionFactory::createTypeVariable) .collect(Collectors.toList()); if (freeTypeVars.stream().anyMatch( - ftv -> includedVars.stream().noneMatch(ftv::denotesSameVar)) + ftv -> includedVars.stream().noneMatch(ftv::deepEquals)) ) { Log.error("0xFD570 resolved " + fSym.getFullName() + " with type " + type.printFullName() @@ -603,7 +837,7 @@ public static void reset() { protected static void setDelegate( WithinTypeBasicSymbolsResolver newDelegate ) { - WithinTypeBasicSymbolsResolver.delegate = Log.errorIfNull(newDelegate); + WithinTypeBasicSymbolsResolver.delegate = Preconditions.checkNotNull(newDelegate); } protected static WithinTypeBasicSymbolsResolver getDelegate() { diff --git a/monticore-grammar/src/test/grammars/de/monticore/types/ComponentSymbolsWithMCBasicTypesTest.mc4 b/monticore-grammar/src/test/grammars/de/monticore/types/ComponentSymbolsWithMCBasicTypesTest.mc4 new file mode 100644 index 0000000000..0fcc3b9ec2 --- /dev/null +++ b/monticore-grammar/src/test/grammars/de/monticore/types/ComponentSymbolsWithMCBasicTypesTest.mc4 @@ -0,0 +1,10 @@ +/* (c) https://github.com/MontiCore/monticore */ + +package de.monticore.types; + +component grammar ComponentSymbolsWithMCBasicTypesTest extends + de.monticore.symbols.CompSymbols, + de.monticore.symbols.OOSymbols, + de.monticore.types.MCBasicTypes, + de.monticore.types.MCSimpleGenericTypes { +} \ No newline at end of file diff --git a/monticore-grammar/src/test/java/de/monticore/MCCommonUnitTest.java b/monticore-grammar/src/test/java/de/monticore/MCCommonUnitTest.java index c70bf822b3..528f582fdf 100644 --- a/monticore-grammar/src/test/java/de/monticore/MCCommonUnitTest.java +++ b/monticore-grammar/src/test/java/de/monticore/MCCommonUnitTest.java @@ -12,7 +12,6 @@ import de.monticore.umlstereotype._ast.ASTStereotype; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,6 +19,8 @@ import java.util.List; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCCommonUnitTest { // setup the language infrastructure @@ -42,19 +43,19 @@ public void init() { @Test public void testNat1() throws IOException { ASTNatLiteral ast = parser.parse_StringNatLiteral( " 9" ).get(); - Assertions.assertEquals("9", ast.getSource()); - Assertions.assertEquals(9, ast.getValue()); + assertEquals("9", ast.getSource()); + assertEquals(9, ast.getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNat4() throws IOException { ASTNatLiteral ast = parser.parse_StringNatLiteral( " 42 " ).get(); - Assertions.assertEquals("42", ast.getSource()); - Assertions.assertEquals(42, ast.getValue()); + assertEquals("42", ast.getSource()); + assertEquals(42, ast.getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -65,11 +66,11 @@ public void testNat4() throws IOException { @Test public void testModifier() throws IOException { ASTModifier ast = parser.parse_StringModifier( "# final" ).get(); - Assertions.assertEquals(true, ast.isProtected()); - Assertions.assertEquals(true, ast.isFinal()); - Assertions.assertEquals(false, ast.isLocal()); + assertTrue(ast.isProtected()); + assertTrue(ast.isFinal()); + assertFalse(ast.isLocal()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -77,15 +78,15 @@ public void testModifier() throws IOException { @Test public void testModifierStereo() throws IOException { ASTModifier ast = parser.parse_StringModifier( "<>#+?" ).get(); - Assertions.assertEquals(true, ast.isProtected()); - Assertions.assertEquals(true, ast.isPublic()); - Assertions.assertEquals(true, ast.isReadonly()); - Assertions.assertEquals(false, ast.isFinal()); - Assertions.assertEquals(true, ast.isPresentStereotype()); + assertTrue(ast.isProtected()); + assertTrue(ast.isPublic()); + assertTrue(ast.isReadonly()); + assertFalse(ast.isFinal()); + assertTrue(ast.isPresentStereotype()); ASTStereotype sty = ast.getStereotype(); - Assertions.assertEquals("x1", sty.getValue("bla")); + assertEquals("x1", sty.getValue("bla")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -98,12 +99,12 @@ public void testModifierStereo() throws IOException { @Test public void testStereoValue() throws IOException { ASTStereoValue ast = parser.parse_StringStereoValue( "bla=\"17\"" ).get(); - Assertions.assertEquals("bla", ast.getName()); - Assertions.assertEquals(true, ast.isPresentText()); - Assertions.assertEquals("17", ast.getText().getValue()); - Assertions.assertEquals("17", ast.getValue()); + assertEquals("bla", ast.getName()); + assertTrue(ast.isPresentText()); + assertEquals("17", ast.getText().getValue()); + assertEquals("17", ast.getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -111,11 +112,11 @@ public void testStereoValue() throws IOException { @Test public void testStereoValue2() throws IOException { ASTStereoValue ast = parser.parse_StringStereoValue( "cc" ).get(); - Assertions.assertEquals("cc", ast.getName()); - Assertions.assertEquals(false, ast.isPresentText()); - Assertions.assertEquals("", ast.getValue()); + assertEquals("cc", ast.getName()); + assertFalse(ast.isPresentText()); + assertEquals("", ast.getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -123,12 +124,12 @@ public void testStereoValue2() throws IOException { @Test public void testStereoValueExpr() throws IOException { ASTStereoValue ast = parser.parse_StringStereoValue( "bla=name1" ).get(); - Assertions.assertEquals("bla", ast.getName()); - Assertions.assertEquals(false, ast.isPresentText()); - Assertions.assertEquals(true, ast.getExpression() instanceof ASTNameExpression); - Assertions.assertEquals(true, ((ASTNameExpression) ast.getExpression()).getName().equals("name1")); + assertEquals("bla", ast.getName()); + assertFalse(ast.isPresentText()); + assertTrue(ast.getExpression() instanceof ASTNameExpression); + assertTrue(((ASTNameExpression) ast.getExpression()).getName().equals("name1")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -136,13 +137,13 @@ public void testStereoValueExpr() throws IOException { public void testStereotype() throws IOException { ASTStereotype ast = parser.parse_StringStereotype( "<< a1 >>" ).get(); List svl = ast.getValuesList(); - Assertions.assertEquals(1, svl.size()); - Assertions.assertEquals(true, ast.contains("a1")); - Assertions.assertEquals(false, ast.contains("bla")); - Assertions.assertEquals(true, ast.contains("a1","")); - Assertions.assertEquals(false, ast.contains("a1","wert1")); + assertEquals(1, svl.size()); + assertTrue(ast.contains("a1")); + assertFalse(ast.contains("bla")); + assertTrue(ast.contains("a1", "")); + assertFalse(ast.contains("a1", "wert1")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -152,12 +153,12 @@ public void testStereotype2() throws IOException { ASTStereotype ast = parser.parse_StringStereotype( "<< bla, a1=\"wert1\" >>" ).get(); List svl = ast.getValuesList(); - Assertions.assertEquals(2, svl.size()); - Assertions.assertEquals(true, ast.contains("a1")); - Assertions.assertEquals(false, ast.contains("a1","")); - Assertions.assertEquals(true, ast.contains("a1","wert1")); + assertEquals(2, svl.size()); + assertTrue(ast.contains("a1")); + assertFalse(ast.contains("a1", "")); + assertTrue(ast.contains("a1", "wert1")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -166,15 +167,15 @@ public void testStereotype2() throws IOException { public void testStereotype3() throws IOException { ASTStereotype ast = parser.parse_StringStereotype( "<< a1=name1 >>" ).get(); List svl = ast.getValuesList(); - Assertions.assertEquals(1, svl.size()); - Assertions.assertEquals(true, ast.contains("a1")); - Assertions.assertEquals(false, ast.contains("bla")); - Assertions.assertEquals(true, ast.contains("a1","")); - Assertions.assertEquals(false, ast.contains("a1","name1")); - Assertions.assertEquals(true, ast.getValues(0).getExpression() instanceof ASTNameExpression); - Assertions.assertEquals(true, ((ASTNameExpression) ast.getValues(0).getExpression()).getName().equals("name1")); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertEquals(1, svl.size()); + assertTrue(ast.contains("a1")); + assertFalse(ast.contains("bla")); + assertTrue(ast.contains("a1", "")); + assertFalse(ast.contains("a1", "name1")); + assertInstanceOf(ASTNameExpression.class, ast.getValues(0).getExpression()); + assertEquals("name1", ((ASTNameExpression) ast.getValues(0).getExpression()).getName()); + + assertTrue(Log.getFindings().isEmpty()); } @@ -183,14 +184,14 @@ public void testStereotype3() throws IOException { public void testGetValue() throws IOException { ASTStereotype ast = parser.parse_StringStereotype( "<< bla, a1=\"wert1\" >>" ).get(); - Assertions.assertEquals("wert1", ast.getValue("a1")); + assertEquals("wert1", ast.getValue("a1")); try { - Assertions.assertEquals("", ast.getValue("foo")); - Assertions.fail("Expected an Exception to be thrown"); + assertEquals("", ast.getValue("foo")); + fail("Expected an Exception to be thrown"); } catch (java.util.NoSuchElementException ex) { } - Assertions.assertEquals("", ast.getValue("bla")); + assertEquals("", ast.getValue("bla")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -198,7 +199,7 @@ public void testGetValue() throws IOException { public void testEnding() throws IOException { Optional oast = parser.parse_StringStereotype( "<< bla, a1=\"wert1\" > >" ); - Assertions.assertEquals(false, oast.isPresent()); + assertFalse(oast.isPresent()); } @@ -211,10 +212,10 @@ public void testEnding() throws IOException { @Test public void testBasics() throws IOException { ASTCompleteness ast = parser.parse_StringCompleteness( "(c)" ).get(); - Assertions.assertEquals(true, ast.isComplete()); - Assertions.assertEquals(false, ast.isIncomplete()); + assertTrue(ast.isComplete()); + assertFalse(ast.isIncomplete()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -222,12 +223,12 @@ public void testBasics() throws IOException { @Test public void testBasics2() throws IOException { ASTCompleteness ast = parser.parse_StringCompleteness( "(...)" ).get(); - Assertions.assertEquals(false, ast.isComplete()); - Assertions.assertEquals(true, ast.isIncomplete()); - Assertions.assertEquals(false, ast.isRightComplete()); - Assertions.assertEquals(false, ast.isLeftComplete()); + assertFalse(ast.isComplete()); + assertTrue(ast.isIncomplete()); + assertFalse(ast.isRightComplete()); + assertFalse(ast.isLeftComplete()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -235,12 +236,12 @@ public void testBasics2() throws IOException { @Test public void testBasics3() throws IOException { ASTCompleteness ast = parser.parse_StringCompleteness( "(...,c)" ).get(); - Assertions.assertEquals(false, ast.isComplete()); - Assertions.assertEquals(false, ast.isIncomplete()); - Assertions.assertEquals(true, ast.isRightComplete()); - Assertions.assertEquals(false, ast.isLeftComplete()); + assertFalse(ast.isComplete()); + assertFalse(ast.isIncomplete()); + assertTrue(ast.isRightComplete()); + assertFalse(ast.isLeftComplete()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -249,7 +250,7 @@ public void testBasics3() throws IOException { public void testIllegalComplete() throws IOException { Optional ast = parser.parse_StringCompleteness( "(...,d)" ); - Assertions.assertEquals(false, ast.isPresent()); + assertFalse(ast.isPresent()); } // -------------------------------------------------------------------- @@ -260,11 +261,11 @@ public void testIllegalComplete() throws IOException { @Test public void testMany() throws IOException { ASTCardinality ast = parser.parse_StringCardinality("[*]").get(); - Assertions.assertEquals(true, ast.isMany()); - Assertions.assertEquals(0, ast.getLowerBound()); - Assertions.assertEquals(0, ast.getUpperBound()); + assertTrue(ast.isMany()); + assertEquals(0, ast.getLowerBound()); + assertEquals(0, ast.getUpperBound()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -272,12 +273,12 @@ public void testMany() throws IOException { @Test public void testLowAndStar() throws IOException { ASTCardinality ast = parser.parse_StringCardinality("[7..*]").get(); - Assertions.assertEquals(false, ast.isMany()); - Assertions.assertEquals(true, ast.isNoUpperLimit()); - Assertions.assertEquals(7, ast.getLowerBound()); - Assertions.assertEquals(0, ast.getUpperBound()); + assertFalse(ast.isMany()); + assertTrue(ast.isNoUpperLimit()); + assertEquals(7, ast.getLowerBound()); + assertEquals(0, ast.getUpperBound()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -285,11 +286,11 @@ public void testLowAndStar() throws IOException { @Test public void testLowAndUp() throws IOException { ASTCardinality ast = parser.parse_StringCardinality("[17..235]").get(); - Assertions.assertEquals(false, ast.isMany()); - Assertions.assertEquals(17, ast.getLowerBound()); - Assertions.assertEquals(235, ast.getUpperBound()); + assertFalse(ast.isMany()); + assertEquals(17, ast.getLowerBound()); + assertEquals(235, ast.getUpperBound()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -297,11 +298,11 @@ public void testLowAndUp() throws IOException { @Test public void testSpace() throws IOException { ASTCardinality ast = parser.parse_StringCardinality(" [ 34 .. 15 ] ").get(); - Assertions.assertEquals(false, ast.isMany()); - Assertions.assertEquals(34, ast.getLowerBound()); - Assertions.assertEquals(15, ast.getUpperBound()); + assertFalse(ast.isMany()); + assertEquals(34, ast.getLowerBound()); + assertEquals(15, ast.getUpperBound()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -312,7 +313,7 @@ public void testSpace() throws IOException { public void testHex() throws IOException { Optional oast = parser.parse_StringCardinality( "[0x34..0x15]"); - Assertions.assertEquals(false, oast.isPresent()); + assertFalse(oast.isPresent()); } diff --git a/monticore-grammar/src/test/java/de/monticore/SymbolImportTest.java b/monticore-grammar/src/test/java/de/monticore/SymbolImportTest.java index c47fc74581..8e49bbd04a 100644 --- a/monticore-grammar/src/test/java/de/monticore/SymbolImportTest.java +++ b/monticore-grammar/src/test/java/de/monticore/SymbolImportTest.java @@ -9,7 +9,6 @@ import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +17,8 @@ import java.util.Optional; import java.util.stream.Collectors; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class SymbolImportTest { @BeforeEach @@ -68,24 +69,24 @@ public void testTestStarImportGrammar() throws IOException { protected void test(String filename) throws IOException { Optional grammarOpt = Grammar_WithConceptsMill.parser().parse(filename); - Assertions.assertTrue(grammarOpt.isPresent()); + assertTrue(grammarOpt.isPresent()); Grammar_WithConceptsMill.scopesGenitorDelegator().createFromAST(grammarOpt.get()); MCGrammarSymbol symbol = grammarOpt.get().getSymbol(); for (MCGrammarSymbolSurrogate surrogate : symbol.getSuperGrammars()) { - Assertions.assertTrue(surrogate.checkLazyLoadDelegate(), "Unable to lazy load delegate " + surrogate.getName() + " of " + surrogate.getEnclosingScope()); + assertTrue(surrogate.checkLazyLoadDelegate(), "Unable to lazy load delegate " + surrogate.getName() + " of " + surrogate.getEnclosingScope()); } String allSuperGrammars = symbol.getSuperGrammars().stream().map(MCGrammarSymbol::getFullName).collect(Collectors.joining(", ")); String allSuperGrammarsLazy = symbol.getSuperGrammars().stream().map(MCGrammarSymbolSurrogate::lazyLoadDelegate).map(MCGrammarSymbol::getFullName).collect(Collectors.joining(", ")); // check if the surrogate is returning the correct symbol - Assertions.assertTrue(symbol.getSuperGrammars().stream().anyMatch(x -> x.lazyLoadDelegate().getFullName().equals("de.monticore.grammar.SamePackage")), "SamePackage import failed: " + allSuperGrammars); - Assertions.assertTrue(symbol.getSuperGrammars().stream().anyMatch(x -> x.lazyLoadDelegate().getFullName().equals("de.monticore.grammar.pack.DifferentPackage")), "DifferentPackage import failed: " + allSuperGrammars); + assertTrue(symbol.getSuperGrammars().stream().anyMatch(x -> x.lazyLoadDelegate().getFullName().equals("de.monticore.grammar.SamePackage")), "SamePackage import failed: " + allSuperGrammars); + assertTrue(symbol.getSuperGrammars().stream().anyMatch(x -> x.lazyLoadDelegate().getFullName().equals("de.monticore.grammar.pack.DifferentPackage")), "DifferentPackage import failed: " + allSuperGrammars); // check if the surrogate is returning the correct fullname - Assertions.assertTrue(symbol.getSuperGrammars().stream().anyMatch(x -> x.getFullName().equals("de.monticore.grammar.SamePackage")), "SamePackage lazy import failed: " + allSuperGrammarsLazy); - Assertions.assertTrue(symbol.getSuperGrammars().stream().anyMatch(x -> x.getFullName().equals("de.monticore.grammar.pack.DifferentPackage")), "DifferentPackage lazy import failed: " + allSuperGrammarsLazy); + assertTrue(symbol.getSuperGrammars().stream().anyMatch(x -> x.getFullName().equals("de.monticore.grammar.SamePackage")), "SamePackage lazy import failed: " + allSuperGrammarsLazy); + assertTrue(symbol.getSuperGrammars().stream().anyMatch(x -> x.getFullName().equals("de.monticore.grammar.pack.DifferentPackage")), "DifferentPackage lazy import failed: " + allSuperGrammarsLazy); } } diff --git a/monticore-grammar/src/test/java/de/monticore/aggregation/AggregationTest.java b/monticore-grammar/src/test/java/de/monticore/aggregation/AggregationTest.java index 955cc8d34f..97197e5024 100644 --- a/monticore-grammar/src/test/java/de/monticore/aggregation/AggregationTest.java +++ b/monticore-grammar/src/test/java/de/monticore/aggregation/AggregationTest.java @@ -15,23 +15,21 @@ import de.monticore.aggregation.foo._symboltable.FooGlobalScope; import de.monticore.aggregation.foo._symboltable.FooScopesGenitorDelegator; import de.monticore.aggregation.foo._symboltable.IFooArtifactScope; +import de.monticore.runtime.junit.AbstractMCTest; import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class AggregationTest { +public class AggregationTest extends AbstractMCTest { @BeforeEach public void init() { - LogStub.init(); - Log.enableFailQuick(false); FooMill.reset(); FooMill.init(); BlahMill.reset(); @@ -54,7 +52,7 @@ public void test() throws IOException { FooGlobalScope globalScope = (FooGlobalScope) FooMill.globalScope(); //Parse blah model - BlahParser blahParser = new BlahParser(); + BlahParser blahParser = BlahMill.parser(); Optional blahModel = blahParser.parse_String( "blahmodel {" + "blubScope blubScope1 {" + @@ -79,14 +77,14 @@ public void test() throws IOException { // check dummy symbol is present in local scope Optional blubSymbol1 = blahSymbolTable.resolveDummy("blahmodel.blubScope1.blubSymbol1"); - Assertions.assertTrue(blubSymbol1.isPresent()); + assertTrue(blubSymbol1.isPresent()); // // // check dummy symbol is present in global scope Optional barSymbol = globalScope.resolveBar("blahmodel.blubScope1.blubSymbol1"); - Assertions.assertTrue(barSymbol.isPresent()); + assertTrue(barSymbol.isPresent()); /* *************************************************************************************************************** @@ -96,11 +94,11 @@ public void test() throws IOException { */ //parse foo model - FooParser fooParser = new FooParser(); + FooParser fooParser = FooMill.parser(); Optional fooModel = fooParser.parse_String("bar { blubSymbol1() } name"); // Check foo model is parsed - Assertions.assertTrue(fooModel.isPresent()); + assertTrue(fooModel.isPresent()); // create symbol table for "foo" FooScopesGenitorDelegator fooSymbolTableCreator = FooMill.scopesGenitorDelegator(); @@ -108,10 +106,15 @@ public void test() throws IOException { // check symbol is resolvable Optional k = fooScope.resolveBar("name"); - Assertions.assertTrue(k.isPresent()); + assertTrue(k.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); + } + + @AfterEach + public void afterEach() { + FooMill.reset(); + BlahMill.reset(); } - } diff --git a/monticore-grammar/src/test/java/de/monticore/comments/CommentsOnASTTest.java b/monticore-grammar/src/test/java/de/monticore/comments/CommentsOnASTTest.java index 75d30dbb9e..eaa788ae46 100644 --- a/monticore-grammar/src/test/java/de/monticore/comments/CommentsOnASTTest.java +++ b/monticore-grammar/src/test/java/de/monticore/comments/CommentsOnASTTest.java @@ -13,6 +13,8 @@ import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + /** * This test should document the current comment behavior * Note: The location of comments has changed as of MC 7.7.0 @@ -38,57 +40,57 @@ public void before() { @Test public void testComments() throws IOException { Optional ast = parser.parse("src/test/resources/de/monticore/comments/CommentsTest.jlight"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMethodDeclaration m = (ASTMethodDeclaration) ast.get(); - Assertions.assertEquals(1, m.get_PreCommentList().size()); - Assertions.assertEquals("// (c) https://github.com/MontiCore/monticore", m.get_PreComment(0).getText()); - Assertions.assertEquals(1, m.get_PreCommentList().size()); - Assertions.assertEquals("// After doStuff", m.get_PostComment(0).getText()); + assertEquals(1, m.get_PreCommentList().size()); + assertEquals("// (c) https://github.com/MontiCore/monticore", m.get_PreComment(0).getText()); + assertEquals(1, m.get_PreCommentList().size()); + assertEquals("// After doStuff", m.get_PostComment(0).getText()); - Assertions.assertEquals(1, m.sizeMCModifiers()); - Assertions.assertEquals(0, m.getMCModifier(0).get_PostCommentList().size()); - Assertions.assertEquals(0, m.getMCModifier(0).get_PostCommentList().size()); + assertEquals(1, m.sizeMCModifiers()); + assertEquals(0, m.getMCModifier(0).get_PostCommentList().size()); + assertEquals(0, m.getMCModifier(0).get_PostCommentList().size()); - Assertions.assertEquals(1, m.getMCReturnType().get_PreCommentList().size()); - Assertions.assertEquals("/* t2 */", m.getMCReturnType().get_PreComment(0).getText()); - Assertions.assertEquals(0, m.getMCReturnType().get_PostCommentList().size()); + assertEquals(1, m.getMCReturnType().get_PreCommentList().size()); + assertEquals("/* t2 */", m.getMCReturnType().get_PreComment(0).getText()); + assertEquals(0, m.getMCReturnType().get_PostCommentList().size()); - Assertions.assertEquals(1, m.getFormalParameters().get_PreCommentList().size()); - Assertions.assertEquals("/* t4 */", m.getFormalParameters().get_PreComment(0).getText()); - Assertions.assertEquals(0, m.getFormalParameters().get_PostCommentList().size()); + assertEquals(1, m.getFormalParameters().get_PreCommentList().size()); + assertEquals("/* t4 */", m.getFormalParameters().get_PreComment(0).getText()); + assertEquals(0, m.getFormalParameters().get_PostCommentList().size()); - Assertions.assertEquals(1, m.getMCJavaBlock().get_PreCommentList().size()); - Assertions.assertEquals("/* t6 */", m.getMCJavaBlock().get_PreComment(0).getText()); - Assertions.assertEquals(1, m.getMCJavaBlock().get_PostCommentList().size()); - Assertions.assertEquals("// Final doStuff", m.getMCJavaBlock().get_PostComment(0).getText()); + assertEquals(1, m.getMCJavaBlock().get_PreCommentList().size()); + assertEquals("/* t6 */", m.getMCJavaBlock().get_PreComment(0).getText()); + assertEquals(1, m.getMCJavaBlock().get_PostCommentList().size()); + assertEquals("// Final doStuff", m.getMCJavaBlock().get_PostComment(0).getText()); ASTConstDeclaration c = (ASTConstDeclaration) m.getMCJavaBlock().getMCBlockStatement(0); - Assertions.assertEquals(1, c.get_PreCommentList().size()); - Assertions.assertEquals("// First doStuff", c.get_PreComment(0).getText()); - Assertions.assertEquals(2, c.get_PostCommentList().size()); + assertEquals(1, c.get_PreCommentList().size()); + assertEquals("// First doStuff", c.get_PreComment(0).getText()); + assertEquals(2, c.get_PostCommentList().size()); // Note: When pretty-printing /*A*/;//B , // the result will look like ; /*A*/ //B - Assertions.assertEquals("/* after value */", c.get_PostComment(0).getText()); - Assertions.assertEquals("// after line", c.get_PostComment(1).getText()); + assertEquals("/* after value */", c.get_PostComment(0).getText()); + assertEquals("// after line", c.get_PostComment(1).getText()); - Assertions.assertEquals(0, c.getLocalVariableDeclaration().sizeMCModifiers()); + assertEquals(0, c.getLocalVariableDeclaration().sizeMCModifiers()); - Assertions.assertEquals(0, c.getLocalVariableDeclaration().getMCType().get_PreCommentList().size()); - Assertions.assertEquals(0, c.getLocalVariableDeclaration().getMCType().get_PostCommentList().size()); + assertEquals(0, c.getLocalVariableDeclaration().getMCType().get_PreCommentList().size()); + assertEquals(0, c.getLocalVariableDeclaration().getMCType().get_PostCommentList().size()); - Assertions.assertEquals(1, c.getLocalVariableDeclaration().getVariableDeclarator(0).get_PreCommentList().size()); - Assertions.assertEquals("/* pre name */", c.getLocalVariableDeclaration().getVariableDeclarator(0).get_PreComment(0).getText()); + assertEquals(1, c.getLocalVariableDeclaration().getVariableDeclarator(0).get_PreCommentList().size()); + assertEquals("/* pre name */", c.getLocalVariableDeclaration().getVariableDeclarator(0).get_PreComment(0).getText()); - Assertions.assertEquals(2, c.getLocalVariableDeclaration().getVariableDeclarator(0) + assertEquals(2, c.getLocalVariableDeclaration().getVariableDeclarator(0) .getVariableInit().get_PreCommentList().size()); - Assertions.assertEquals("/* pre op */", c.getLocalVariableDeclaration().getVariableDeclarator(0) + assertEquals("/* pre op */", c.getLocalVariableDeclaration().getVariableDeclarator(0) .getVariableInit().get_PreComment(0).getText()); - Assertions.assertEquals("/* pre value */", c.getLocalVariableDeclaration().getVariableDeclarator(0) + assertEquals("/* pre value */", c.getLocalVariableDeclaration().getVariableDeclarator(0) .getVariableInit().get_PreComment(1).getText()); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java new file mode 100644 index 0000000000..bf6067edec --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/expressions/AbstractInterpreterTest.java @@ -0,0 +1,262 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.expressions; + +import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; +import de.monticore.expressions.combineexpressionswithliterals._ast.ASTFoo; +import de.monticore.expressions.combineexpressionswithliterals._parser.CombineExpressionsWithLiteralsParser; +import de.monticore.expressions.combineexpressionswithliterals._symboltable.CombineExpressionsWithLiteralsScopesGenitorDelegator; +import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsInterpreter; +import de.monticore.interpreter.Value; +import de.monticore.interpreter.values.NotAValue; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symboltable.modifiers.AccessModifier; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; + +import java.io.IOException; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +public abstract class AbstractInterpreterTest { + + protected static final double delta = 0.00001; + + protected static final int BOOL = 1; + protected static final int INT = 2; + protected static final int LONG = 4; + protected static final int FLOAT = 8; + protected static final int DOUBLE = 16; + protected static final int CHAR = 32; + protected static final int STRING = 64; + + protected CombineExpressionsWithLiteralsInterpreter interpreter; + protected CombineExpressionsWithLiteralsParser parser; + protected CombineExpressionsWithLiteralsScopesGenitorDelegator delegator; + + public void init(int values) { + CombineExpressionsWithLiteralsMill.reset(); + CombineExpressionsWithLiteralsMill.init(); + BasicSymbolsMill.initializePrimitives(); + BasicSymbolsMill.initializeString(); + LogStub.init(); + Log.clearFindings(); + Log.enableFailQuick(false); + + parser = CombineExpressionsWithLiteralsMill.parser(); + delegator = CombineExpressionsWithLiteralsMill.scopesGenitorDelegator(); + interpreter = new CombineExpressionsWithLiteralsInterpreter(); + + try { + if ((values & BOOL) != 0) { + initBool(); + } + + if ((values & INT) != 0) { + initInt(); + } + + if ((values & LONG) != 0) { + initLong(); + } + + if ((values & FLOAT) != 0) { + initFloat(); + } + + if ((values & DOUBLE) != 0) { + initDouble(); + } + + if ((values & CHAR) != 0) { + initChar(); + } + + if ((values & STRING) != 0) { + initString(); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + protected void initBool() throws IOException { + final Optional optAST = parser.parse_String("bar b = true"); + assertTrue(optAST.isPresent()); + final ASTFoo ast = optAST.get(); + delegator.createFromAST(ast); + CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("b", + CombineExpressionsWithLiteralsMill.variableSymbolBuilder() + .setType(SymTypeExpressionFactory.createPrimitive("boolean")) + .setName("b") + .setFullName("b") + .setPackageName("") + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) + .build()); + interpreter.interpret(ast); + } + + protected void initInt() throws IOException { + final Optional optAST = parser.parse_String("bar i = 1"); + assertTrue(optAST.isPresent()); + final ASTFoo ast = optAST.get(); + delegator.createFromAST(ast); + CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("i", + CombineExpressionsWithLiteralsMill.variableSymbolBuilder() + .setType(SymTypeExpressionFactory.createPrimitive("int")) + .setName("i") + .setFullName("i") + .setPackageName("") + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) + .build()); + interpreter.interpret(ast); + } + + protected void initLong() throws IOException { + final Optional optAST = parser.parse_String("bar l = 5L"); + assertTrue(optAST.isPresent()); + final ASTFoo ast = optAST.get(); + delegator.createFromAST(ast); + CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("l", + CombineExpressionsWithLiteralsMill.variableSymbolBuilder() + .setType(SymTypeExpressionFactory.createPrimitive("long")) + .setName("l") + .setFullName("l") + .setPackageName("") + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) + .build()); + interpreter.interpret(ast); + } + + protected void initFloat() throws IOException { + final Optional optAST = parser.parse_String("bar f = 1.5f"); + assertTrue(optAST.isPresent()); + final ASTFoo ast = optAST.get(); + delegator.createFromAST(ast); + CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("f", + CombineExpressionsWithLiteralsMill.variableSymbolBuilder() + .setType(SymTypeExpressionFactory.createPrimitive("float")) + .setName("f") + .setFullName("f") + .setPackageName("") + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) + .build()); + interpreter.interpret(ast); + } + + protected void initDouble() throws IOException { + final Optional optAST = parser.parse_String("bar d = 3.14"); + assertTrue(optAST.isPresent()); + final ASTFoo ast = optAST.get(); + delegator.createFromAST(ast); + CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("d", + CombineExpressionsWithLiteralsMill.variableSymbolBuilder() + .setType(SymTypeExpressionFactory.createPrimitive("double")) + .setName("d") + .setFullName("d") + .setPackageName("") + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) + .build()); + interpreter.interpret(ast); + } + + protected void initChar() throws IOException { + final Optional optAST = parser.parse_String("bar c = 'a'"); + assertTrue(optAST.isPresent()); + final ASTFoo ast = optAST.get(); + delegator.createFromAST(ast); + CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("c", + CombineExpressionsWithLiteralsMill.variableSymbolBuilder() + .setType(SymTypeExpressionFactory.createPrimitive("char")) + .setName("c") + .setFullName("c") + .setPackageName("") + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) + .build()); + interpreter.interpret(ast); + } + + protected void initString() throws IOException { + final Optional optAST = parser.parse_String("bar s = \"hello\""); + assertTrue(optAST.isPresent()); + final ASTFoo ast = optAST.get(); + delegator.createFromAST(ast); + CombineExpressionsWithLiteralsMill.globalScope().getVariableSymbols().put("s", + CombineExpressionsWithLiteralsMill.variableSymbolBuilder() + .setType(SymTypeExpressionFactory.createPrimitive("String")) + .setName("s") + .setFullName("s") + .setPackageName("") + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()) + .build()); + interpreter.interpret(ast); + } + + protected void testValidExpression(String expr, Value expected) { + Log.clearFindings(); + Value interpretationResult = null; + try { + interpretationResult = parseExpressionAndInterpret(expr); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + assertNotNull(interpretationResult); + assertTrue(Log.getFindings().isEmpty()); + if (expected.isBoolean()) { + assertTrue(interpretationResult.isBoolean()); + assertEquals(interpretationResult.asBoolean(), expected.asBoolean()); + } else if (expected.isInt()) { + assertTrue(interpretationResult.isInt()); + assertEquals(interpretationResult.asInt(), expected.asInt()); + } else if (expected.isLong()) { + assertTrue(interpretationResult.isLong()); + assertEquals(interpretationResult.asLong(), expected.asLong()); + } else if (expected.isFloat()) { + assertTrue(interpretationResult.isFloat()); + assertEquals(interpretationResult.asFloat(), expected.asFloat(), delta); + } else if (expected.isDouble()) { + assertTrue(interpretationResult.isDouble()); + assertEquals(interpretationResult.asDouble(), expected.asDouble(), delta); + } else if (expected.isChar()) { + assertTrue(interpretationResult.isChar()); + assertEquals(interpretationResult.asChar(), expected.asChar()); + } else if (expected.isString()) { + assertTrue(interpretationResult.isString()); + assertEquals(interpretationResult.asString(), expected.asString()); + } else if (expected.isObject()) { + assertTrue(interpretationResult.isObject()); + assertEquals(interpretationResult.asObject(), expected.asObject()); + } + assertTrue(Log.getFindings().isEmpty()); + } + + protected void testInvalidExpression(String expr) { + Log.clearFindings(); + Value interpretationResult = null; + try { + interpretationResult = parseExpressionAndInterpret(expr); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + assertNotNull(interpretationResult); + assertEquals(Log.getFindings().size(), 1); + assertInstanceOf(NotAValue.class, interpretationResult); + } + + protected Value parseExpressionAndInterpret(String expr) throws IOException { + final Optional optAST = parser.parse_String("bar " + expr); + assertTrue(optAST.isPresent()); + final ASTFoo ast = optAST.get(); + delegator.createFromAST(ast); + return interpreter.interpret(ast); + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/cocos/AssignmentExpressionsOnlyAssignToLValuesCoCoTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/cocos/AssignmentExpressionsOnlyAssignToLValuesCoCoTest.java index 2a2b900e2a..2920b583a7 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/cocos/AssignmentExpressionsOnlyAssignToLValuesCoCoTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/cocos/AssignmentExpressionsOnlyAssignToLValuesCoCoTest.java @@ -8,14 +8,14 @@ import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AssignmentExpressionsOnlyAssignToLValuesCoCoTest { @@ -187,14 +187,14 @@ public void testFurtherInvalidAssignments() throws IOException { protected void testValid(String exprStr) throws IOException { check(exprStr); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); Log.clearFindings(); } protected void testInvalid(String exprStr) throws IOException { check(exprStr); - Assertions.assertTrue(!Log.getFindings().isEmpty()); - Assertions.assertTrue(Log.getFindings().stream().anyMatch( + assertFalse(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().stream().anyMatch( f -> f.getMsg().contains("0xFDD47") )); Log.clearFindings(); @@ -203,8 +203,8 @@ protected void testInvalid(String exprStr) throws IOException { protected void check(String exprStr) throws IOException { Optional exprOpt = CombineExpressionsWithLiteralsMill .parser().parse_StringExpression(exprStr); - Assertions.assertTrue(exprOpt.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(exprOpt.isPresent()); + assertTrue(Log.getFindings().isEmpty()); getChecker().checkAll(exprOpt.get()); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/cocos/LiteralAssignmentMatchesRegExExpressionCoCoTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/cocos/LiteralAssignmentMatchesRegExExpressionCoCoTest.java index dd8704bd9d..c850ed917a 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/cocos/LiteralAssignmentMatchesRegExExpressionCoCoTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/assignmentexpressions/cocos/LiteralAssignmentMatchesRegExExpressionCoCoTest.java @@ -13,14 +13,13 @@ import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.*; public class LiteralAssignmentMatchesRegExExpressionCoCoTest { @@ -86,14 +85,14 @@ public void testIncorrectAssignments() throws IOException { protected void testValid(String type, String exprStr) throws IOException { check(type, exprStr); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); Log.clearFindings(); } protected void testInvalid(String type, String exprStr) throws IOException { check(type, exprStr); - Assertions.assertEquals(1, Log.getFindings().size()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xFD724")); + assertEquals(1, Log.getFindings().size()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xFD724")); Log.clearFindings(); } @@ -107,7 +106,7 @@ protected void check(String type, String exprStr) throws IOException { Optional optType = CombineExpressionsWithLiteralsMill .parser() .parse_StringMCType(type); - Assertions.assertTrue(optType.isPresent()); + assertTrue(optType.isPresent()); SymTypeExpression typeExpression = TypeCheck3.symTypeFromAST(optType.get()); assertFalse(typeExpression.isObscureType()); @@ -121,11 +120,11 @@ protected void check(String type, String exprStr) throws IOException { Optional exprOpt = CombineExpressionsWithLiteralsMill .parser().parse_StringExpression(exprStr); - Assertions.assertTrue(exprOpt.isPresent()); + assertTrue(exprOpt.isPresent()); generateScopes(exprOpt.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); getChecker().checkAll(exprOpt.get()); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/cocos/ExpressionValidTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/cocos/ExpressionValidTest.java index 4c61c1dafa..f61dc0e5b9 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/cocos/ExpressionValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/cocos/ExpressionValidTest.java @@ -10,13 +10,15 @@ import de.monticore.types.check.FullDeriveFromCombineExpressionsWithLiterals; import de.monticore.types.check.TypeCalculator; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ExpressionValidTest extends CocoTest { protected ExpressionsBasisCoCoChecker checker; @@ -35,19 +37,19 @@ public void init() { public void checkValid(String expressionString) throws IOException { CombineExpressionsWithLiteralsParser parser = new CombineExpressionsWithLiteralsParser(); Optional optAST = parser.parse_StringExpression(expressionString); - Assertions.assertTrue(optAST.isPresent()); + assertTrue(optAST.isPresent()); Log.getFindings().clear(); checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty(), Log.getFindings().toString()); + assertTrue(Log.getFindings().isEmpty(), Log.getFindings().toString()); } public void checkInvalid(String expressionString) throws IOException { CombineExpressionsWithLiteralsParser parser = new CombineExpressionsWithLiteralsParser(); Optional optAST = parser.parse_StringExpression(expressionString); - Assertions.assertTrue(optAST.isPresent()); + assertTrue(optAST.isPresent()); Log.getFindings().clear(); checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); + assertFalse(Log.getFindings().isEmpty()); } @Test diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/ParserTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/ParserTest.java index 5661fa77f5..1edee256e1 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/ParserTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/ParserTest.java @@ -3,18 +3,27 @@ import de.monticore.expressions.combineexpressionswithliterals._parser.CombineExpressionsWithLiteralsParser; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; -import org.junit.Test; +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ParserTest { +class ParserTest { - @Test - public void parseBigExpr() throws IOException { + @BeforeAll + public static void setup() { + LogStub.init(); + Log.enableFailQuick(false); + CombineExpressionsWithLiteralsMill.init(); + } + @Test + void parseBigExpr() throws IOException { String expr = "(!(x1 && x2) || !(x1 && x3) || !(x1 && x4) || !(x1 && x5) " + "|| !(x1 && x6) || !(x1 && x7) || !(x1 && x8) || !(x1 && x9) " + "|| !(x1 && x10) || !(x1 && x11) || !(x1 && x12) || !(x1 && x13) " + @@ -29,7 +38,7 @@ public void parseBigExpr() throws IOException { } @Test - public void parseBigExpr2() throws IOException { + void parseBigExpr2() throws IOException { String expr = "((f1 + f2) * (f1 + f3) * (f1 + f4) / (f1 + f5) + (f1 + f6) / (f1 + f7) + (f1 + f8) * (f1 + f9) + (f1 + f10) + (f1 + f11) / (f1 + f12) + (f1 + f13) + (f + f14) +\n" + @@ -42,7 +51,7 @@ public void parseBigExpr2() throws IOException { } @Test - public void parseWithMode() throws IOException { + void parseWithMode() throws IOException { CombineExpressionsWithLiteralsParser parser = CombineExpressionsWithLiteralsMill.parser(); parser.setLexerMode("REGEX"); parser.parse_StringCharRange("a-c").get(); diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/_cocos/TestNoClassExpressionForGenerics.java b/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/_cocos/TestNoClassExpressionForGenerics.java index 1d5bb88549..12c8787156 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/_cocos/TestNoClassExpressionForGenerics.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/combineexpressionswithliterals/_cocos/TestNoClassExpressionForGenerics.java @@ -6,13 +6,15 @@ import de.monticore.expressions.javaclassexpressions._ast.ASTJavaClassExpressionsNode; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class TestNoClassExpressionForGenerics { CombineExpressionsWithLiteralsParser p = new CombineExpressionsWithLiteralsParser(); @@ -27,22 +29,22 @@ public void setup(){ public void testValid() throws IOException { Optional optClass = p.parse_StringClassExpression("Integer.class"); - Assertions.assertTrue(optClass.isPresent()); + assertTrue(optClass.isPresent()); CombineExpressionsWithLiteralsCoCoChecker coCoChecker = new CombineExpressionsWithLiteralsCoCoChecker().getCombineExpressionsWithLiteralsCoCoChecker(); coCoChecker.checkAll((ASTJavaClassExpressionsNode) optClass.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testValid2() throws IOException{ Optional optClass = p.parse_StringClassExpression("int.class"); - Assertions.assertTrue(optClass.isPresent()); + assertTrue(optClass.isPresent()); CombineExpressionsWithLiteralsCoCoChecker coCoChecker = new CombineExpressionsWithLiteralsCoCoChecker().getCombineExpressionsWithLiteralsCoCoChecker(); coCoChecker.checkAll((ASTJavaClassExpressionsNode) optClass.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -50,12 +52,12 @@ public void testInvalidGeneric() throws IOException{ //MCListType Optional optClass = p.parse_StringClassExpression("List.class"); - Assertions.assertTrue(optClass.isPresent()); + assertTrue(optClass.isPresent()); CombineExpressionsWithLiteralsCoCoChecker coCoChecker = new CombineExpressionsWithLiteralsCoCoChecker().getCombineExpressionsWithLiteralsCoCoChecker(); coCoChecker.checkAll((ASTJavaClassExpressionsNode) optClass.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size()-1).getMsg().startsWith(NoClassExpressionForGenerics.ERROR_CODE)); + assertFalse(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().get(Log.getFindings().size()-1).getMsg().startsWith(NoClassExpressionForGenerics.ERROR_CODE)); } @Test @@ -63,12 +65,12 @@ public void testInvalidGeneric2() throws IOException{ //MCBasicGenericType Optional optClass = p.parse_StringClassExpression("a.b.List.class"); - Assertions.assertTrue(optClass.isPresent()); + assertTrue(optClass.isPresent()); CombineExpressionsWithLiteralsCoCoChecker coCoChecker = new CombineExpressionsWithLiteralsCoCoChecker().getCombineExpressionsWithLiteralsCoCoChecker(); coCoChecker.checkAll((ASTJavaClassExpressionsNode) optClass.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size()-1).getMsg().startsWith(NoClassExpressionForGenerics.ERROR_CODE)); + assertFalse(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().get(Log.getFindings().size()-1).getMsg().startsWith(NoClassExpressionForGenerics.ERROR_CODE)); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/CommonExpressionsBuilderTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/CommonExpressionsBuilderTest.java new file mode 100644 index 0000000000..7906087a37 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/CommonExpressionsBuilderTest.java @@ -0,0 +1,22 @@ +/* (c) https://github.com/MontiCore/monticore */ + +package de.monticore.expressions.commonexpressions; + +import de.monticore.runtime.junit.TestWithMCLanguage; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestWithMCLanguage(CommonExpressionsMill.class) +public class CommonExpressionsBuilderTest { + @Test + public void testBooleanAndOpExpression() { + // Test that we can build a && expression without specifying the operator + var elem = CommonExpressionsMill.booleanAndOpExpressionBuilder() + .setLeft(CommonExpressionsMill.nameExpressionBuilder().setName("l").build()) + .setRight(CommonExpressionsMill.nameExpressionBuilder().setName("r").build()) + .build(); + // And that the actual operator is "&&" (instead of "" from the infix operator) + assertEquals("&&", elem.getOperator()); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/cocos/FunctionCallArgumentsMatchesRegExCoCoTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/cocos/FunctionCallArgumentsMatchesRegExCoCoTest.java index cfaed9e3d6..a05e5831ad 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/cocos/FunctionCallArgumentsMatchesRegExCoCoTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/commonexpressions/cocos/FunctionCallArgumentsMatchesRegExCoCoTest.java @@ -7,6 +7,7 @@ import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsTraverser; import de.monticore.expressions.commonexpressions._cocos.CommonExpressionsCoCoChecker; import de.monticore.expressions.expressionsbasis._ast.ASTExpression; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.IDerive; import de.monticore.types.check.SymTypeExpression; @@ -14,11 +15,9 @@ import de.monticore.types.check.types3wrapper.TypeCheck3AsIDerive; import de.monticore.types3.Type4Ast; import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; -import de.monticore.types3.util.DefsTypesForTests; import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -28,6 +27,8 @@ import java.util.Optional; import java.util.stream.Collectors; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class FunctionCallArgumentsMatchesRegExCoCoTest { @BeforeEach @@ -141,7 +142,7 @@ public void testIncorrectFunctionCalls() throws IOException { protected void testValid(String expression, List> functions, boolean varArgs) throws IOException { check(expression, functions, varArgs); - Assertions.assertTrue(Log.getFindings().isEmpty(), Log.getFindings().stream() + assertTrue(Log.getFindings().isEmpty(), Log.getFindings().stream() .map(Finding::buildMsg) .collect(Collectors.joining(System.lineSeparator()))); Log.clearFindings(); @@ -149,7 +150,7 @@ protected void testValid(String expression, List> functions, boolea protected void testInvalid(String expression, List> functions, boolean varArgs) throws IOException { check(expression, functions, varArgs); - Assertions.assertTrue(Log.getFindings().stream().anyMatch( + assertTrue(Log.getFindings().stream().anyMatch( f -> f.getMsg().startsWith("0xFD725") )); Log.clearFindings(); @@ -179,11 +180,11 @@ protected void check(String expression, List> functions, boolean va Optional optExpr = CombineExpressionsWithLiteralsMill .parser().parse_StringExpression(expression); - Assertions.assertTrue(optExpr.isPresent()); + assertTrue(optExpr.isPresent()); ASTExpression expr = optExpr.get(); generateScopes(expr); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); getChecker(derive).checkAll(expr); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/AssignmentExpressionsJavaPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/AssignmentExpressionsJavaPrinterTest.java index d96a01f534..897942eadf 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/AssignmentExpressionsJavaPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/AssignmentExpressionsJavaPrinterTest.java @@ -10,7 +10,6 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +17,7 @@ import java.util.Optional; import static de.monticore.expressions.assignmentexpressions._ast.ASTConstantsAssignmentExpressions.*; +import static org.junit.jupiter.api.Assertions.*; public class AssignmentExpressionsJavaPrinterTest { @@ -38,78 +38,78 @@ public void init() { @Test public void testIncPrefixExpression() throws IOException { Optional result = parser.parse_StringIncPrefixExpression("++a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTIncPrefixExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringIncPrefixExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDecPrefixExpression() throws IOException { Optional result = parser.parse_StringDecPrefixExpression("--a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTDecPrefixExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringDecPrefixExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIncSuffixExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); ASTIncSuffixExpression result = AssignmentExpressionsMill.incSuffixExpressionBuilder() .setExpression(a.get()) .build(); String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a++", output); + assertEquals("a++", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDecSuffixExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); ASTDecSuffixExpression result = AssignmentExpressionsMill.decSuffixExpressionBuilder() .setExpression(a.get()) .build(); String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a--", output); + assertEquals("a--", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -118,18 +118,18 @@ public void testRegularAssignmentEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a=b", output); + assertEquals("a=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentPlusEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -138,18 +138,18 @@ public void testRegularAssignmentPlusEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a+=b", output); + assertEquals("a+=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentMinusExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -158,18 +158,18 @@ public void testRegularAssignmentMinusExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a-=b", output); + assertEquals("a-=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentPercentEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -178,18 +178,18 @@ public void testRegularAssignmentPercentEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a%=b", output); + assertEquals("a%=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentAndEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -198,18 +198,18 @@ public void testRegularAssignmentAndEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a&=b", output); + assertEquals("a&=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentRoofEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -218,18 +218,18 @@ public void testRegularAssignmentRoofEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a^=b", output); + assertEquals("a^=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentSlashEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -238,18 +238,18 @@ public void testRegularAssignmentSlashEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a/=b", output); + assertEquals("a/=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentStarEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -258,18 +258,18 @@ public void testRegularAssignmentStarEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a*=b", output); + assertEquals("a*=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentPipeEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -278,18 +278,18 @@ public void testRegularAssignmentPipeEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a|=b", output); + assertEquals("a|=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentLTLTEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -298,18 +298,18 @@ public void testRegularAssignmentLTLTEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a<<=b", output); + assertEquals("a<<=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentGTGTEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -318,18 +318,18 @@ public void testRegularAssignmentGTGTEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a>>=b", output); + assertEquals("a>>=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentGTGTGTEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -338,8 +338,8 @@ public void testRegularAssignmentGTGTGTEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a>>>=b", output); + assertEquals("a>>>=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/BitExpressionsJavaPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/BitExpressionsJavaPrinterTest.java index ef7c955f62..77488488b3 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/BitExpressionsJavaPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/BitExpressionsJavaPrinterTest.java @@ -8,15 +8,14 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class BitExpressionsJavaPrinterTest { @@ -37,115 +36,115 @@ public void init() { @Test public void testLeftShiftExpression() throws IOException { Optional result = parser.parse_StringExpression("a< result = parser.parse_StringExpression("a>>b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLogicalRightShiftExpression() throws IOException { Optional result = parser.parse_StringExpression("a>>>b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBinaryOrOpExpression() throws IOException { Optional result = parser.parse_StringExpression("a|b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBinaryXorExpression() throws IOException { Optional result = parser.parse_StringExpression("a^b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBinaryAndExpression() throws IOException { Optional result = parser.parse_StringExpression("a&b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/CommonExpressionsJavaPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/CommonExpressionsJavaPrinterTest.java index d626879315..9565c018a5 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/CommonExpressionsJavaPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/CommonExpressionsJavaPrinterTest.java @@ -11,14 +11,13 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; public class CommonExpressionsJavaPrinterTest { @@ -46,119 +45,119 @@ public void init() { @Test public void testMinusPrefixExpression() throws IOException { Optional result = parser.parse_StringMinusPrefixExpression("-a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMinusPrefixExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringMinusPrefixExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPlusPrefixExpression() throws IOException { Optional result = parser.parse_StringPlusPrefixExpression("+a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTPlusPrefixExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringPlusPrefixExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBooleanNotExpression() throws IOException { Optional result = parser.parse_StringBooleanNotExpression("~a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBooleanNotExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringBooleanNotExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLogicalNotExpression() throws IOException { Optional result = parser.parse_StringLogicalNotExpression("!a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTLogicalNotExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringLogicalNotExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBracketExpression() throws IOException { Optional result = parser.parse_StringBracketExpression("(a == b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBracketExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringBracketExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testArguments() throws IOException { Optional result = parser.parse_StringArguments("(a , b , c)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTArguments ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringArguments(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCallExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional arguments = parser.parse_StringArguments("(b, c)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(arguments.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(arguments.isPresent()); ASTCallExpression result = CommonExpressionsMill.callExpressionBuilder() .setExpression(a.get()) .setArguments(arguments.get()) @@ -166,16 +165,16 @@ public void testCallExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a(b,c)", output); + assertEquals("a(b,c)", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFieldAccessExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); ASTFieldAccessExpression result = CommonExpressionsMill.fieldAccessExpressionBuilder() .setExpression(a.get()) .setName("foo") @@ -183,18 +182,18 @@ public void testFieldAccessExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a.getFoo()", output); + assertEquals("a.getFoo()", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMultExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTMultExpression result = CommonExpressionsMill.multExpressionBuilder() .setLeft(a.get()) .setOperator("*") @@ -203,18 +202,18 @@ public void testMultExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a*b", output); + assertEquals("a*b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDivideExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTDivideExpression result = CommonExpressionsMill.divideExpressionBuilder() .setLeft(a.get()) .setOperator("/") @@ -223,18 +222,18 @@ public void testDivideExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a/b", output); + assertEquals("a/b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testModuloExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTModuloExpression result = CommonExpressionsMill.moduloExpressionBuilder() .setLeft(a.get()) .setOperator("%") @@ -243,18 +242,18 @@ public void testModuloExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a%b", output); + assertEquals("a%b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPlusExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTPlusExpression result = CommonExpressionsMill.plusExpressionBuilder() .setLeft(a.get()) .setOperator("+") @@ -263,18 +262,18 @@ public void testPlusExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a+b", output); + assertEquals("a+b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMinusExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTMinusExpression result = CommonExpressionsMill.minusExpressionBuilder() .setLeft(a.get()) .setOperator("-") @@ -283,18 +282,18 @@ public void testMinusExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a-b", output); + assertEquals("a-b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLessEqualExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTLessEqualExpression result = CommonExpressionsMill.lessEqualExpressionBuilder() .setLeft(a.get()) .setOperator("<=") @@ -303,18 +302,18 @@ public void testLessEqualExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a<=b", output); + assertEquals("a<=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testGreaterEqualExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTGreaterEqualExpression result = CommonExpressionsMill.greaterEqualExpressionBuilder() .setLeft(a.get()) .setOperator(">=") @@ -323,18 +322,18 @@ public void testGreaterEqualExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a>=b", output); + assertEquals("a>=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLessThanExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTLessThanExpression result = CommonExpressionsMill.lessThanExpressionBuilder() .setLeft(a.get()) .setOperator("<") @@ -343,18 +342,18 @@ public void testLessThanExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTGreaterThanExpression result = CommonExpressionsMill.greaterThanExpressionBuilder() .setLeft(a.get()) .setOperator(">") @@ -363,18 +362,18 @@ public void testGreaterThanExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a>b", output); + assertEquals("a>b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTEqualsExpression result = CommonExpressionsMill.equalsExpressionBuilder() .setLeft(a.get()) .setOperator("==") @@ -383,18 +382,18 @@ public void testEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a==b", output); + assertEquals("a==b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNotEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTNotEqualsExpression result = CommonExpressionsMill.notEqualsExpressionBuilder() .setLeft(a.get()) .setOperator("!=") @@ -403,18 +402,18 @@ public void testNotEqualsExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a!=b", output); + assertEquals("a!=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBooleanAndOpExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTBooleanAndOpExpression result = CommonExpressionsMill.booleanAndOpExpressionBuilder() .setLeft(a.get()) .setOperator("&&") @@ -423,18 +422,18 @@ public void testBooleanAndOpExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a&&b", output); + assertEquals("a&&b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBooleanOrOpExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTBooleanOrOpExpression result = CommonExpressionsMill.booleanOrOpExpressionBuilder() .setLeft(a.get()) .setOperator("||") @@ -443,9 +442,9 @@ public void testBooleanOrOpExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a||b", output); + assertEquals("a||b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -453,10 +452,10 @@ public void testConditionalExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); Optional c = parser.parse_StringExpression("c"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); - Assertions.assertTrue(c.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); + assertTrue(c.isPresent()); ASTConditionalExpression result = CommonExpressionsMill.conditionalExpressionBuilder() .setCondition(a.get()) .setTrueExpression(b.get()) @@ -465,18 +464,18 @@ public void testConditionalExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a ? b:c", output); + assertEquals("a ? b:c", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testArrayExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTArrayAccessExpression result = CommonExpressionsMill.arrayAccessExpressionBuilder() .setExpression(a.get()) @@ -485,9 +484,9 @@ public void testArrayExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a[b]", output); + assertEquals("a[b]", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/JavaClassExpressionsJavaPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/JavaClassExpressionsJavaPrinterTest.java index 59f55f89b0..99d617fe7d 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/JavaClassExpressionsJavaPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/JavaClassExpressionsJavaPrinterTest.java @@ -10,13 +10,14 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class JavaClassExpressionsJavaPrinterTest { protected TestJavaClassExpressionsParser parser; @@ -36,62 +37,62 @@ public void init() { @Test public void testPrimaryThisExpression() throws IOException { Optional result = parser.parse_StringPrimaryThisExpression("this"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTPrimaryThisExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringPrimaryThisExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPrimarySuperExpression() throws IOException { Optional result = parser.parse_StringPrimarySuperExpression("super"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTPrimarySuperExpression ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringPrimarySuperExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testThisExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); ASTThisExpression result = JavaClassExpressionsMill.thisExpressionBuilder() .setExpression(a.get()) .build(); String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a.this", output); + assertEquals("a.this", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSuperExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringSuperSuffix("(b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTSuperExpression result = JavaClassExpressionsMill.superExpressionBuilder() .setExpression(a.get()) .setSuperSuffix(b.get()) @@ -99,81 +100,81 @@ public void testSuperExpression() throws IOException { String output = javaPrinter.prettyprint(result); - Assertions.assertEquals("a.super(b)", output); + assertEquals("a.super(b)", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testGenericInvocationSuffixThis() throws IOException { Optional result = parser.parse_StringGenericInvocationSuffix("this(a)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTGenericInvocationSuffix ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringGenericInvocationSuffix(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testGenericInvocationSuffixSuper() throws IOException { Optional result = parser.parse_StringGenericInvocationSuffix("super(b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTGenericInvocationSuffix ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringGenericInvocationSuffix(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testGenericInvocationSuffixSimple() throws IOException { Optional result = parser.parse_StringGenericInvocationSuffix("a(b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTGenericInvocationSuffix ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringGenericInvocationSuffix(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testTypePattern() throws IOException { Optional result = parser.parse_StringTypePattern("String s"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTTypePattern ast = result.get(); String output = javaPrinter.prettyprint(ast); result = parser.parse_StringTypePattern(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/UglyExpressionsJavaPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/UglyExpressionsJavaPrinterTest.java index 644e2fb6c4..9da703508b 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/UglyExpressionsJavaPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/exptojava/UglyExpressionsJavaPrinterTest.java @@ -1,31 +1,7 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.expressions.exptojava; -import de.monticore.expressions.expressionsbasis._ast.ASTExpression; -import de.monticore.expressions.javaclassexpressions.JavaClassExpressionsMill; -import de.monticore.expressions.javaclassexpressions._ast.ASTGenericInvocationSuffix; -import de.monticore.expressions.javaclassexpressions._ast.ASTPrimarySuperExpression; -import de.monticore.expressions.javaclassexpressions._ast.ASTPrimaryThisExpression; -import de.monticore.expressions.javaclassexpressions._ast.ASTSuperExpression; -import de.monticore.expressions.javaclassexpressions._ast.ASTSuperSuffix; -import de.monticore.expressions.javaclassexpressions._ast.ASTThisExpression; -import de.monticore.expressions.javaclassexpressions._ast.ASTTypePattern; -import de.monticore.expressions.javaclassexpressions._prettyprint.JavaClassExpressionsFullPrettyPrinter; -import de.monticore.expressions.testjavaclassexpressions.TestJavaClassExpressionsMill; -import de.monticore.expressions.testjavaclassexpressions._parser.TestJavaClassExpressionsParser; import de.monticore.expressions.uglyexpressions._prettyprint.UglyExpressionsFullPrettyPrinter; -import de.monticore.prettyprint.IndentPrinter; -import de.se_rwth.commons.logging.Log; -import de.se_rwth.commons.logging.LogStub; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.Optional; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; public class UglyExpressionsJavaPrinterTest { diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/AssignmentExpressionsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/AssignmentExpressionsPrettyPrinterTest.java index 52ba69fb30..645c9d65e1 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/AssignmentExpressionsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/AssignmentExpressionsPrettyPrinterTest.java @@ -10,7 +10,6 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +17,7 @@ import java.util.Optional; import static de.monticore.expressions.assignmentexpressions._ast.ASTConstantsAssignmentExpressions.*; +import static org.junit.jupiter.api.Assertions.*; public class AssignmentExpressionsPrettyPrinterTest { @@ -38,78 +38,78 @@ public void init() { @Test public void testIncPrefixExpression() throws IOException { Optional result = parser.parse_StringIncPrefixExpression("++a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTIncPrefixExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringIncPrefixExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDecPrefixExpression() throws IOException { Optional result = parser.parse_StringDecPrefixExpression("--a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTDecPrefixExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringDecPrefixExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIncSuffixExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); ASTIncSuffixExpression result = AssignmentExpressionsMill.incSuffixExpressionBuilder() .setExpression(a.get()) .build(); String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a++", output); + assertEquals("a++", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDecSuffixExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); ASTDecSuffixExpression result = AssignmentExpressionsMill.decSuffixExpressionBuilder() .setExpression(a.get()) .build(); String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a--", output); + assertEquals("a--", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -118,18 +118,18 @@ public void testRegularAssignmentEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a=b", output); + assertEquals("a=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentPlusEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -138,18 +138,18 @@ public void testRegularAssignmentPlusEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a+=b", output); + assertEquals("a+=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentMinusExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -158,18 +158,18 @@ public void testRegularAssignmentMinusExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a-=b", output); + assertEquals("a-=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentPercentEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -178,18 +178,18 @@ public void testRegularAssignmentPercentEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a%=b", output); + assertEquals("a%=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentAndEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -198,18 +198,18 @@ public void testRegularAssignmentAndEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a&=b", output); + assertEquals("a&=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentRoofEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -218,18 +218,18 @@ public void testRegularAssignmentRoofEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a^=b", output); + assertEquals("a^=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentSlashEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -238,18 +238,18 @@ public void testRegularAssignmentSlashEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a/=b", output); + assertEquals("a/=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentStarEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -258,18 +258,18 @@ public void testRegularAssignmentStarEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a*=b", output); + assertEquals("a*=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentPipeEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -278,18 +278,18 @@ public void testRegularAssignmentPipeEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a|=b", output); + assertEquals("a|=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentLTLTEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -298,18 +298,18 @@ public void testRegularAssignmentLTLTEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a<<=b", output); + assertEquals("a<<=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentGTGTEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -318,18 +318,18 @@ public void testRegularAssignmentGTGTEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a>>=b", output); + assertEquals("a>>=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRegularAssignmentGTGTGTEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTAssignmentExpression result = AssignmentExpressionsMill.assignmentExpressionBuilder() .setLeft(a.get()) .setRight(b.get()) @@ -338,8 +338,8 @@ public void testRegularAssignmentGTGTGTEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result).trim(); - Assertions.assertEquals("a>>>=b", output); + assertEquals("a>>>=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/BitExpressionsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/BitExpressionsPrettyPrinterTest.java index 957c4d4ea1..3097709eb4 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/BitExpressionsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/BitExpressionsPrettyPrinterTest.java @@ -8,13 +8,15 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class BitExpressionsPrettyPrinterTest { protected TestBitExpressionsParser parser; protected BitExpressionsFullPrettyPrinter prettyPrinter; @@ -33,120 +35,114 @@ public void init() { @Test public void testLeftShiftExpression() throws IOException { Optional result = parser.parse_StringExpression("a< result = parser.parse_StringExpression("a>>b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLogicalRightShiftExpression() throws IOException { Optional result = parser.parse_StringExpression("a>>>b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBinaryOrOpExpression() throws IOException { Optional result = parser.parse_StringExpression("a|b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBinaryXorExpression() throws IOException { Optional result = parser.parse_StringExpression("a^b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBinaryAndExpression() throws IOException { Optional result = parser.parse_StringExpression("a&b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/CommonExpressionsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/CommonExpressionsPrettyPrinterTest.java index 8b8e526108..3c878cb812 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/CommonExpressionsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/CommonExpressionsPrettyPrinterTest.java @@ -11,13 +11,14 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class CommonExpressionsPrettyPrinterTest { protected TestCommonExpressionsParser parser; @@ -37,119 +38,119 @@ public void init() { @Test public void testMinusPrefixExpression() throws IOException { Optional result = parser.parse_StringMinusPrefixExpression("-a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMinusPrefixExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringMinusPrefixExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPlusPrefixExpression() throws IOException { Optional result = parser.parse_StringPlusPrefixExpression("+a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTPlusPrefixExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringPlusPrefixExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBooleanNotExpression() throws IOException { Optional result = parser.parse_StringBooleanNotExpression("~a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBooleanNotExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringBooleanNotExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLogicalNotExpression() throws IOException { Optional result = parser.parse_StringLogicalNotExpression("!a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTLogicalNotExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringLogicalNotExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBracketExpression() throws IOException { Optional result = parser.parse_StringBracketExpression("(a == b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBracketExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringBracketExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testArguments() throws IOException { Optional result = parser.parse_StringArguments("(a , b , c)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTArguments ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringArguments(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCallExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional arguments = parser.parse_StringArguments("(b, c)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(arguments.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(arguments.isPresent()); ASTCallExpression result = CommonExpressionsMill.callExpressionBuilder() .setExpression(a.get()) .setArguments(arguments.get()) @@ -157,16 +158,16 @@ public void testCallExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a(b,c)", output); + assertEquals("a(b,c)", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFieldAccessExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); ASTFieldAccessExpression result = CommonExpressionsMill.fieldAccessExpressionBuilder() .setExpression(a.get()) .setName("foo") @@ -174,18 +175,18 @@ public void testFieldAccessExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a.foo", output); + assertEquals("a.foo", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMultExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTMultExpression result = CommonExpressionsMill.multExpressionBuilder() .setLeft(a.get()) .setOperator("*") @@ -194,18 +195,18 @@ public void testMultExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a*b", output); + assertEquals("a*b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDivideExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTDivideExpression result = CommonExpressionsMill.divideExpressionBuilder() .setLeft(a.get()) .setOperator("/") @@ -214,18 +215,18 @@ public void testDivideExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a/b", output); + assertEquals("a/b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testModuloExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTModuloExpression result = CommonExpressionsMill.moduloExpressionBuilder() .setLeft(a.get()) .setOperator("%") @@ -234,18 +235,18 @@ public void testModuloExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a%b", output); + assertEquals("a%b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPlusExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTPlusExpression result = CommonExpressionsMill.plusExpressionBuilder() .setLeft(a.get()) .setOperator("+") @@ -254,18 +255,18 @@ public void testPlusExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a+b", output); + assertEquals("a+b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMinusExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTMinusExpression result = CommonExpressionsMill.minusExpressionBuilder() .setLeft(a.get()) .setOperator("-") @@ -274,18 +275,18 @@ public void testMinusExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a-b", output); + assertEquals("a-b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLessEqualExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTLessEqualExpression result = CommonExpressionsMill.lessEqualExpressionBuilder() .setLeft(a.get()) .setOperator("<=") @@ -294,18 +295,18 @@ public void testLessEqualExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a<=b", output); + assertEquals("a<=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testGreaterEqualExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTGreaterEqualExpression result = CommonExpressionsMill.greaterEqualExpressionBuilder() .setLeft(a.get()) .setOperator(">=") @@ -314,18 +315,18 @@ public void testGreaterEqualExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a>=b", output); + assertEquals("a>=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLessThanExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTLessThanExpression result = CommonExpressionsMill.lessThanExpressionBuilder() .setLeft(a.get()) .setOperator("<") @@ -334,18 +335,18 @@ public void testLessThanExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTGreaterThanExpression result = CommonExpressionsMill.greaterThanExpressionBuilder() .setLeft(a.get()) .setOperator(">") @@ -354,18 +355,18 @@ public void testGreaterThanExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a>b", output); + assertEquals("a>b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTEqualsExpression result = CommonExpressionsMill.equalsExpressionBuilder() .setLeft(a.get()) .setOperator("==") @@ -374,18 +375,18 @@ public void testEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a==b", output); + assertEquals("a==b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNotEqualsExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTNotEqualsExpression result = CommonExpressionsMill.notEqualsExpressionBuilder() .setLeft(a.get()) .setOperator("!=") @@ -394,18 +395,18 @@ public void testNotEqualsExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a!=b", output); + assertEquals("a!=b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBooleanAndOpExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTBooleanAndOpExpression result = CommonExpressionsMill.booleanAndOpExpressionBuilder() .setLeft(a.get()) .setOperator("&&") @@ -414,18 +415,18 @@ public void testBooleanAndOpExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a&&b", output); + assertEquals("a&&b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBooleanOrOpExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTBooleanOrOpExpression result = CommonExpressionsMill.booleanOrOpExpressionBuilder() .setLeft(a.get()) .setOperator("||") @@ -434,9 +435,9 @@ public void testBooleanOrOpExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a||b", output); + assertEquals("a||b", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -444,10 +445,10 @@ public void testConditionalExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); Optional c = parser.parse_StringExpression("c"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); - Assertions.assertTrue(c.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); + assertTrue(c.isPresent()); ASTConditionalExpression result = CommonExpressionsMill.conditionalExpressionBuilder() .setCondition(a.get()) .setTrueExpression(b.get()) @@ -456,8 +457,8 @@ public void testConditionalExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a ? b:c", output); + assertEquals("a ? b:c", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/JavaClassExpressionsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/JavaClassExpressionsPrettyPrinterTest.java index 07b2a165e8..d189fa9f5f 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/JavaClassExpressionsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/JavaClassExpressionsPrettyPrinterTest.java @@ -14,13 +14,14 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class JavaClassExpressionsPrettyPrinterTest { private TestJavaClassExpressionsParser parser = new TestJavaClassExpressionsParser(); @@ -41,44 +42,44 @@ public void init() { @Test public void testPrimaryThisExpression() throws IOException { Optional result = parser.parse_StringPrimaryThisExpression("this"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTPrimaryThisExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringPrimaryThisExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testPrimarySuperExpression() throws IOException { Optional result = parser.parse_StringPrimarySuperExpression("super"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTPrimarySuperExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringPrimarySuperExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testTypeCaseExpression() throws IOException { Optional result = parser.parse_StringTypeCastExpression("(Integer) a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTTypeCastExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); @@ -87,72 +88,72 @@ public void testTypeCaseExpression() throws IOException { // prettyprinter of langauge that fills the external String pattern = "^\\(.*\\)a$"; boolean matches = output.matches(pattern); - Assertions.assertEquals(matches, true); + assertEquals(matches, true); } @Test public void testClassExpression() throws IOException { Optional result = parser.parse_StringClassExpression("Integer.class"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTClassExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); - Assertions.assertEquals("Integer.class", output); + assertEquals("Integer.class", output); } @Test public void testPrimaryGenericInvocationExpressionExpression() throws IOException { Optional result = parser.parse_StringPrimaryGenericInvocationExpression(" super(a)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTPrimaryGenericInvocationExpression ast = result.get(); String output = prettyPrinter.prettyprint(ast); - Assertions.assertEquals("super(a)", output); + assertEquals("super(a)", output); } @Test public void testInstanceofExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional type = parser.parse_StringMCType("Integer"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(type.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(type.isPresent()); ASTInstanceofExpression result = JavaClassExpressionsMill.instanceofExpressionBuilder() .setExpression(a.get()) .setMCType(type.get()) .build(); String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a instanceof Integer", output); + assertEquals("a instanceof Integer", output); } @Test public void testThisExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); ASTThisExpression result = JavaClassExpressionsMill.thisExpressionBuilder() .setExpression(a.get()) .build(); String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a.this", output); + assertEquals("a.this", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testArrayExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringExpression("b"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTArrayAccessExpression result = JavaClassExpressionsMill.arrayAccessExpressionBuilder() .setExpression(a.get()) .setIndexExpression(b.get()) @@ -160,18 +161,18 @@ public void testArrayExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a[b]", output); + assertEquals("a[b]", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSuperExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringSuperSuffix("(b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTSuperExpression result = JavaClassExpressionsMill.superExpressionBuilder() .setExpression(a.get()) .setSuperSuffix(b.get()) @@ -179,17 +180,17 @@ public void testSuperExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a.super(b)", output); + assertEquals("a.super(b)", output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testGenericInvocationExpressionExpression() throws IOException { Optional a = parser.parse_StringExpression("a"); Optional b = parser.parse_StringPrimaryGenericInvocationExpression(" c(b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(a.isPresent()); - Assertions.assertTrue(b.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(a.isPresent()); + assertTrue(b.isPresent()); ASTGenericInvocationExpression result = JavaClassExpressionsMill.genericInvocationExpressionBuilder() .setExpression(a.get()) .setPrimaryGenericInvocationExpression(b.get()) @@ -197,60 +198,60 @@ public void testGenericInvocationExpressionExpression() throws IOException { String output = prettyPrinter.prettyprint(result); - Assertions.assertEquals("a.c(b)", output); + assertEquals("a.c(b)", output); } @Test public void testGenericInvocationSuffixThis() throws IOException { Optional result = parser.parse_StringGenericInvocationSuffix("this(a)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTGenericInvocationSuffix ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringGenericInvocationSuffix(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testGenericInvocationSuffixSuper() throws IOException { Optional result = parser.parse_StringGenericInvocationSuffix("super(b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTGenericInvocationSuffix ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringGenericInvocationSuffix(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testGenericInvocationSuffixSimple() throws IOException { Optional result = parser.parse_StringGenericInvocationSuffix("a(b)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTGenericInvocationSuffix ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringGenericInvocationSuffix(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/LambdaExpressionsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/LambdaExpressionsPrettyPrinterTest.java index 86c042c8bb..557effc273 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/LambdaExpressionsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/LambdaExpressionsPrettyPrinterTest.java @@ -8,7 +8,6 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import java.util.Optional; import java.util.regex.Pattern; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class LambdaExpressionsPrettyPrinterTest { @@ -40,21 +39,21 @@ public void init() { public void testLambdaWithoutParameter() throws IOException { testLambdaExpression("() -> a"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLambdaWithoutTypeWithoutParenthesis() throws IOException { testLambdaExpression("a -> a"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLambdaWithoutTypeWithParenthesis() throws IOException { testLambdaExpression("(a) -> a"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -78,16 +77,16 @@ public void testLambdaWithType() throws IOException { // "a" + "a" ); - Assertions.assertTrue(pattern.asPredicate().test(output)); + assertTrue(pattern.asPredicate().test(output)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLambdaMultipeParametersWithoutType() throws IOException { testLambdaExpression("(a, b) -> a"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -117,24 +116,24 @@ public void testLambdaMultipeParametersWithType() throws IOException { // "a" + "a" ); - Assertions.assertTrue(pattern.asPredicate().test(output)); + assertTrue(pattern.asPredicate().test(output)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } public void testLambdaExpression(String exp) throws IOException { ASTLambdaExpression ast = parseLambdaExpression(exp); String output = prettyPrinter.prettyprint(ast); ASTLambdaExpression ast2 = parseLambdaExpression(output); - Assertions.assertTrue(ast.deepEquals(ast2), "Parse equals: " + exp + " vs " + output); + assertTrue(ast.deepEquals(ast2), "Parse equals: " + exp + " vs " + output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } public ASTLambdaExpression parseLambdaExpression(String exp) throws IOException { Optional result = parser.parse_StringLambdaExpression(exp); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); return result.get(); } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/StreamExpressionsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/StreamExpressionsPrettyPrinterTest.java index 52406247ea..82073264fe 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/StreamExpressionsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/prettyprint/StreamExpressionsPrettyPrinterTest.java @@ -6,7 +6,6 @@ import de.monticore.expressions.teststreamexpressions._parser.TestStreamExpressionsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -14,6 +13,9 @@ import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class StreamExpressionsPrettyPrinterTest { protected TestStreamExpressionsParser parser; @@ -44,18 +46,18 @@ public void init() { }) public void testPrettyPrint(String input) throws IOException { Optional result = parser.parse_StringExpression(input); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpression ast = result.get(); String output = TestStreamExpressionsMill.prettyPrint(ast, true); result = parser.parse_StringExpression(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/expressions/streamexpressions/parser/CombinedStreamsExpressionsParserTest.java b/monticore-grammar/src/test/java/de/monticore/expressions/streamexpressions/parser/CombinedStreamsExpressionsParserTest.java index 79fd763da5..caa31e1bea 100644 --- a/monticore-grammar/src/test/java/de/monticore/expressions/streamexpressions/parser/CombinedStreamsExpressionsParserTest.java +++ b/monticore-grammar/src/test/java/de/monticore/expressions/streamexpressions/parser/CombinedStreamsExpressionsParserTest.java @@ -19,7 +19,6 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -31,9 +30,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * This test checks for parser clashes of stream expressions with the expression universe. Additionally, it checks if @@ -248,7 +245,7 @@ public static void cleanUp() { // Helpers, could in part be generalized? protected static void assertNoFindings() { - Assertions.assertTrue(Log.getFindings().isEmpty(), "Expected no Log findings, but got:" + assertTrue(Log.getFindings().isEmpty(), "Expected no Log findings, but got:" + System.lineSeparator() + getAllFindingsAsString()); } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/MCGrammarParserTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/MCGrammarParserTest.java index b337367c00..c1e76e8384 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/MCGrammarParserTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/MCGrammarParserTest.java @@ -8,7 +8,6 @@ import de.monticore.grammar.grammar_withconcepts._parser.Grammar_WithConceptsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,6 +15,8 @@ import java.io.StringReader; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCGrammarParserTest { @BeforeEach @@ -33,16 +34,16 @@ public void testParse() throws IOException { Grammar_WithConceptsParser parser = Grammar_WithConceptsMill.parser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); - Assertions.assertEquals("Statechart", grammar.getName()); - Assertions.assertEquals(7, grammar.getClassProdList().size()); - Assertions.assertEquals(3, grammar.getExternalProdList().size()); - Assertions.assertEquals(1, grammar.getInterfaceProdList().size()); + assertEquals("Statechart", grammar.getName()); + assertEquals(7, grammar.getClassProdList().size()); + assertEquals(3, grammar.getExternalProdList().size()); + assertEquals(1, grammar.getInterfaceProdList().size()); GrammarTransformer.transform(grammar); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -52,15 +53,15 @@ public void testASTRule() throws IOException { str = "astrule MCGrammar = GrammarOption max=1 ;"; Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseASTRule(new StringReader(str)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); str = " astrule State = method public String getName(){ return \"\";};"; result = parser.parseASTRule(new StringReader(str)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -70,10 +71,10 @@ public void testSematicPred() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseSemanticpredicateOrAction(new StringReader(str)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -82,10 +83,10 @@ public void testScript() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -94,10 +95,10 @@ public void testAutomatonV1() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -106,10 +107,10 @@ public void testAutomatonV2() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -118,8 +119,8 @@ public void testAutomatonV3() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); } @Test @@ -128,10 +129,10 @@ public void testHierarchicalAutomaton() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -140,11 +141,11 @@ public void testAutomatonWithInvsComp() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertEquals(1, Log.getFindings().size()); - Assertions.assertEquals("0xA4003 The grammar name InvAutomaton must be identical to the file name" + + assertEquals(1, Log.getFindings().size()); + assertEquals("0xA4003 The grammar name InvAutomaton must be identical to the file name" + " AutomatonWithInvsComp of the grammar (without its file extension).", Log.getFindings().get(0).getMsg()); Log.getFindings().clear(); @@ -156,8 +157,8 @@ public void testAutomatonWithInvs() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); } @Test @@ -166,8 +167,8 @@ public void testAutomatonWithInvsAndStartRule() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); } @Test @@ -176,22 +177,22 @@ public void testGrammarSymbolTableInfo() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parse(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); - Assertions.assertEquals(4, grammar.getClassProdList().size()); + assertEquals(4, grammar.getClassProdList().size()); ASTClassProd transition = grammar.getClassProdList().get(2); ASTNonTerminal fromState = (ASTNonTerminal) transition.getAltList().get(0).getComponentList().get(0); - Assertions.assertTrue(fromState.isPresentReferencedSymbol()); - Assertions.assertEquals("State", fromState.getReferencedSymbol()); + assertTrue(fromState.isPresentReferencedSymbol()); + assertEquals("State", fromState.getReferencedSymbol()); ASTNonTerminal toState = (ASTNonTerminal) transition.getAltList().get(0).getComponentList().get(0); - Assertions.assertTrue(toState.isPresentReferencedSymbol()); - Assertions.assertEquals("State", toState.getReferencedSymbol()); + assertTrue(toState.isPresentReferencedSymbol()); + assertEquals("State", toState.getReferencedSymbol()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -200,8 +201,8 @@ public void testPackageNameWithPointsDefined() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); parser.parse(model); - Assertions.assertEquals(1, Log.getFindings().size()); - Assertions.assertEquals("0xA4004 The package declaration point.in.packagename of the grammar must not differ from " + + assertEquals(1, Log.getFindings().size()); + assertEquals("0xA4004 The package declaration point.in.packagename of the grammar must not differ from " + "the package of the grammar file.", Log.getFindings().get(0).getMsg()); Log.getFindings().clear(); @@ -213,8 +214,8 @@ public void testPackageWrongPackageDefined() throws IOException { Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); parser.parse(model); - Assertions.assertEquals(1, Log.getFindings().size()); - Assertions.assertEquals("0xA4004 The package declaration de.ronticore of the grammar " + + assertEquals(1, Log.getFindings().size()); + assertEquals("0xA4004 The package declaration de.ronticore of the grammar " + "must not differ from the package of the grammar file.", Log.getFindings().get(0).getMsg()); Log.getFindings().clear(); diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/MCGrammarPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/MCGrammarPrettyPrinterTest.java index 09b73bd833..a8576fb251 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/MCGrammarPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/MCGrammarPrettyPrinterTest.java @@ -9,7 +9,6 @@ import de.monticore.prettyprint.IndentPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,8 +16,8 @@ import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCGrammarPrettyPrinterTest { @@ -38,8 +37,8 @@ public void testStatechart() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -48,12 +47,12 @@ public void testStatechart() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader (output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get()), "Failed to deep equals: \n" + output); + assertTrue(grammar.deepEquals(result.get()), "Failed to deep equals: \n" + output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -64,8 +63,8 @@ public void testAutomaton() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -74,12 +73,12 @@ public void testAutomaton() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get()), "Failed to deep equals: \n" + output); + assertTrue(grammar.deepEquals(result.get()), "Failed to deep equals: \n" + output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -90,8 +89,8 @@ public void testGrammar() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -100,12 +99,12 @@ public void testGrammar() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get()), "Failed to deep equals: \n" + output); + assertTrue(grammar.deepEquals(result.get()), "Failed to deep equals: \n" + output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -116,8 +115,8 @@ public void testLexicals() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -126,12 +125,12 @@ public void testLexicals() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get())); + assertTrue(grammar.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -142,8 +141,8 @@ public void testAnnotations() throws IOException { // Parsing input Grammar_WithConceptsParser parser = new Grammar_WithConceptsParser(); Optional result = parser.parseMCGrammar(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCGrammar grammar = result.get(); // Prettyprinting input @@ -152,12 +151,12 @@ public void testAnnotations() throws IOException { // Parsing printed input result = parser.parseMCGrammar(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(grammar.deepEquals(result.get()), "Failed to deep equals: \n" + output); + assertTrue(grammar.deepEquals(result.get()), "Failed to deep equals: \n" + output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/CocoTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/CocoTest.java index f64f278c11..5da803bd1e 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/CocoTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/CocoTest.java @@ -10,9 +10,10 @@ import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; +import static org.junit.jupiter.api.Assertions.*; + public abstract class CocoTest { protected Grammar_WithConceptsCoCoChecker checker; @@ -32,13 +33,13 @@ protected void testValidGrammar(String grammar, Grammar_WithConceptsCoCoChecker final MCGrammarSymbol grammarSymbol = globalScope .resolveMCGrammar(grammar) .orElse(null); - Assertions.assertNotNull(grammarSymbol); - Assertions.assertTrue(grammarSymbol.getAstGrammar().isPresent()); + assertNotNull(grammarSymbol); + assertTrue(grammarSymbol.getAstGrammar().isPresent()); Log.getFindings().clear(); checker.checkAll(grammarSymbol.getAstGrammar().get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } protected void testInvalidGrammar(String grammar, String code, String message, @@ -54,16 +55,16 @@ protected void testInvalidGrammar(String grammar, String code, String message, final MCGrammarSymbol grammarSymbol = globalScope .resolveMCGrammar(grammar) .orElse(null); - Assertions.assertNotNull(grammarSymbol); - Assertions.assertTrue(grammarSymbol.getAstGrammar().isPresent()); + assertNotNull(grammarSymbol); + assertTrue(grammarSymbol.getAstGrammar().isPresent()); Log.getFindings().clear(); checker.checkAll(grammarSymbol.getAstGrammar().get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertEquals(numberOfFindings, Log.getFindings().size()); + assertFalse(Log.getFindings().isEmpty()); + assertEquals(numberOfFindings, Log.getFindings().size()); for (Finding f : Log.getFindings()) { - Assertions.assertEquals(code + message, f.getMsg()); + assertEquals(code + message, f.getMsg()); } } @@ -75,13 +76,13 @@ protected void testInvalidGrammarKeepFindings(String grammar, String code, Strin final MCGrammarSymbol grammarSymbol = globalScope .resolveMCGrammar(grammar) .orElse(null); - Assertions.assertNotNull(grammarSymbol); - Assertions.assertTrue(grammarSymbol.getAstGrammar().isPresent()); + assertNotNull(grammarSymbol); + assertTrue(grammarSymbol.getAstGrammar().isPresent()); checker.checkAll(grammarSymbol.getAstGrammar().get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertEquals(1, Log.getFindings().size()); + assertFalse(Log.getFindings().isEmpty()); + assertEquals(1, Log.getFindings().size()); for (Finding f : Log.getFindings()) { - Assertions.assertEquals(code + message, f.getMsg()); + assertEquals(code + message, f.getMsg()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/GrammarInheritanceCycleTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/GrammarInheritanceCycleTest.java index 150741ded7..071b996fbb 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/GrammarInheritanceCycleTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/GrammarInheritanceCycleTest.java @@ -6,7 +6,6 @@ import de.monticore.grammar.grammar_withconcepts._cocos.Grammar_WithConceptsCoCoChecker; import de.monticore.grammar.grammar_withconcepts._parser.Grammar_WithConceptsParser; import de.se_rwth.commons.logging.Finding; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import static de.monticore.grammar.cocos.GrammarInheritanceCycle.ERROR_CODE; import static de.se_rwth.commons.logging.Log.getFindings; import static java.lang.String.format; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; public class GrammarInheritanceCycleTest extends CocoTest { @@ -36,10 +35,10 @@ public void testInvalid() throws IOException { getFindings().clear(); checker.checkAll(grammar.get()); - Assertions.assertFalse(getFindings().isEmpty()); - Assertions.assertEquals(1, getFindings().size()); + assertFalse(getFindings().isEmpty()); + assertEquals(1, getFindings().size()); for (Finding f : getFindings()) { - Assertions.assertEquals(format(ERROR_CODE + MESSAGE, ""), f.getMsg()); + assertEquals(format(ERROR_CODE + MESSAGE, ""), f.getMsg()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/GrammarNameEqualsFileNameTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/GrammarNameEqualsFileNameTest.java index 6ad0f0dbe2..1d663ed342 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/GrammarNameEqualsFileNameTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/GrammarNameEqualsFileNameTest.java @@ -5,14 +5,13 @@ import de.monticore.grammar.grammar_withconcepts._parser.Grammar_WithConceptsParser; import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; public class GrammarNameEqualsFileNameTest extends CocoTest { @@ -26,9 +25,9 @@ public void testInvalidFilename() throws IOException { Log.getFindings().clear(); parser.parse("src/test/resources/de/monticore/grammar/cocos/invalid/A4003/A4003.mc4"); - Assertions.assertFalse(Log.getFindings().isEmpty()); + assertFalse(Log.getFindings().isEmpty()); for(Finding f : Log.getFindings()){ - Assertions.assertEquals("0"+"xA4003 The grammar name A4002 must be identical to the file name" + assertEquals("0"+"xA4003 The grammar name A4002 must be identical to the file name" + " A4003 of the grammar (without its file extension).", f.getMsg()); } } @@ -38,9 +37,9 @@ public void testInvalidPackage() throws IOException { Log.getFindings().clear(); parser.parse("src/test/resources/de/monticore/grammar/cocos/invalid/A4004/A4004.mc4"); - Assertions.assertFalse(Log.getFindings().isEmpty()); + assertFalse(Log.getFindings().isEmpty()); for(Finding f : Log.getFindings()){ - Assertions.assertEquals("0"+"xA4004 The package declaration de.monticore.grammar.cocos.invalid.A4003 of the grammar must not" + assertEquals("0"+"xA4004 The package declaration de.monticore.grammar.cocos.invalid.A4003 of the grammar must not" + " differ from the package of the grammar file.", f.getMsg()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/KeywordAlternativeNameTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/KeywordAlternativeNameTest.java index d804674acc..273ac69424 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/KeywordAlternativeNameTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/KeywordAlternativeNameTest.java @@ -7,12 +7,11 @@ import de.monticore.grammar.grammar_withconcepts._symboltable.Grammar_WithConceptsGlobalScope; import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; public class KeywordAlternativeNameTest extends CocoTest { private final String MESSAGE = " The name of the constant group could't be ascertained"; @@ -33,10 +32,10 @@ public void testKeywordAlternativeWithoutName() throws IllegalArgumentException // test grammar symbol globalScope.resolveMCGrammar(grammar).orElse(null); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertEquals(1, Log.getFindings().size()); + assertFalse(Log.getFindings().isEmpty()); + assertEquals(1, Log.getFindings().size()); for (Finding f : Log.getFindings()) { - Assertions.assertEquals("0xA2345" + MESSAGE, f.getMsg()); + assertEquals("0xA2345" + MESSAGE, f.getMsg()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NTUniqueIgnoreCaseTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NTUniqueIgnoreCaseTest.java index 352bbbe0f5..2841190561 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NTUniqueIgnoreCaseTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NTUniqueIgnoreCaseTest.java @@ -5,12 +5,11 @@ import de.monticore.grammar.grammar_withconcepts._cocos.Grammar_WithConceptsCoCoChecker; import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; public class NTUniqueIgnoreCaseTest extends CocoTest { @@ -28,10 +27,10 @@ public void init() { public void testInvalid() { Log.getFindings().clear(); testInvalidGrammar(grammar, NTUniqueIgnoreCase.ERROR_CODE, MESSAGE, checker); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertEquals(1, Log.getFindings().size()); + assertFalse(Log.getFindings().isEmpty()); + assertEquals(1, Log.getFindings().size()); for (Finding f : Log.getFindings()) { - Assertions.assertEquals(NTUniqueIgnoreCase.ERROR_CODE + MESSAGE, f.getMsg()); + assertEquals(NTUniqueIgnoreCase.ERROR_CODE + MESSAGE, f.getMsg()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoForbiddenSymbolNameTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoForbiddenSymbolNameTest.java index 7c1e19f7f1..266a8f8426 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoForbiddenSymbolNameTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoForbiddenSymbolNameTest.java @@ -7,8 +7,11 @@ public class NoForbiddenSymbolNameTest extends CocoTest{ - private final String MESSAGE = " There must not exist a symbol production with the name A4099 in the grammar A4099Symbol."; - private final String grammar = "de.monticore.grammar.cocos.invalid.A4099.A4099Symbol"; + private final String MESSAGE1 = " There must not exist a symbol production with the name A4099 in the grammar A4099Symbol."; + private final String grammar1 = "de.monticore.grammar.cocos.invalid.A4099.A4099Symbol"; + + private final String MESSAGE2 = " There must not exist a symbol production with the name I in the grammar A4099."; + private final String grammar2 = "de.monticore.grammar.cocos.invalid.A4099.A4099"; @BeforeEach public void init() { @@ -18,7 +21,12 @@ public void init() { @Test public void testInvalid1(){ - testInvalidGrammar(grammar, NoForbiddenSymbolName.ERROR_CODE, MESSAGE, checker); + testInvalidGrammar(grammar1, NoForbiddenSymbolName.ERROR_CODE, MESSAGE1, checker); + } + + @Test + public void testInvalid2(){ + testInvalidGrammar(grammar2, NoForbiddenSymbolName.ERROR_CODE, MESSAGE2, checker); } @Test diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoNTInheritanceCycleTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoNTInheritanceCycleTest.java index 5dd57a1a7a..ee83ad68d0 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoNTInheritanceCycleTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/NoNTInheritanceCycleTest.java @@ -7,10 +7,11 @@ import de.monticore.grammar.grammar_withconcepts._cocos.Grammar_WithConceptsCoCoChecker; import de.monticore.grammar.grammar_withconcepts._symboltable.Grammar_WithConceptsGlobalScope; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class NoNTInheritanceCycleTest extends CocoTest { private final String grammar = "de.monticore.grammar.cocos.invalid.A4022.A4022"; @@ -33,15 +34,15 @@ public void testInvalid2() { // test grammar symbol final MCGrammarSymbol grammarSymbol = (MCGrammarSymbol) globalScope.resolveMCGrammar(grammar + "b").orElse(null); - Assertions.assertNotNull(grammarSymbol); - Assertions.assertTrue(grammarSymbol.getAstGrammar().isPresent()); + assertNotNull(grammarSymbol); + assertTrue(grammarSymbol.getAstGrammar().isPresent()); Log.getFindings().clear(); checker.checkAll(grammarSymbol.getAstGrammar().get()); - Assertions.assertEquals(2, Log.getFindings().size()); - Assertions.assertEquals(NoNTInheritanceCycle.ERROR_CODE + String.format(NoNTInheritanceCycle.ERROR_MSG_FORMAT, "de.monticore.grammar.cocos.invalid.A4022.A4022b.A"), Log.getFindings().get(0).getMsg()); - Assertions.assertEquals(NoNTInheritanceCycle.ERROR_CODE + String.format(NoNTInheritanceCycle.ERROR_MSG_FORMAT, "de.monticore.grammar.cocos.invalid.A4022.A4022b.B"), Log.getFindings().get(1).getMsg()); + assertEquals(2, Log.getFindings().size()); + assertEquals(NoNTInheritanceCycle.ERROR_CODE + String.format(NoNTInheritanceCycle.ERROR_MSG_FORMAT, "de.monticore.grammar.cocos.invalid.A4022.A4022b.A"), Log.getFindings().get(0).getMsg()); + assertEquals(NoNTInheritanceCycle.ERROR_CODE + String.format(NoNTInheritanceCycle.ERROR_MSG_FORMAT, "de.monticore.grammar.cocos.invalid.A4022.A4022b.B"), Log.getFindings().get(1).getMsg()); } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/UsedNTNotDefinedTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/UsedNTNotDefinedTest.java index 6e885a8d6e..38cee0641f 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/cocos/UsedNTNotDefinedTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/cocos/UsedNTNotDefinedTest.java @@ -5,10 +5,11 @@ import de.monticore.grammar.grammar_withconcepts._cocos.Grammar_WithConceptsCoCoChecker; import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class UsedNTNotDefinedTest extends CocoTest { private final String MESSAGE =" The production A must not use the nonterminal " + @@ -24,13 +25,13 @@ public void init() { @Test public void testInvalid() { testInvalidGrammar(grammar, UsedNTNotDefined.ERROR_CODE, MESSAGE, checker); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertEquals(1, Log.getFindings().size()); + assertFalse(Log.getFindings().isEmpty()); + assertEquals(1, Log.getFindings().size()); boolean found = false; for (Finding f : Log.getFindings()) { found |= f.getMsg().equals(UsedNTNotDefined.ERROR_CODE + MESSAGE); } - Assertions.assertTrue(found); + assertTrue(found); } @Test diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/symboltable/IGrammarScopeTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/symboltable/IGrammarScopeTest.java index 07c9f93efc..934af00d9f 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/symboltable/IGrammarScopeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/symboltable/IGrammarScopeTest.java @@ -10,15 +10,14 @@ import de.monticore.symboltable.modifiers.AccessModifier; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class IGrammarScopeTest { @@ -35,34 +34,34 @@ public void testCombiningGrammarSymbolTable() throws IOException { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); final Optional grammar = globalScope .resolveMCGrammar("de.monticore.CombiningGrammar"); - Assertions.assertTrue(grammar.isPresent()); - Assertions.assertTrue(grammar.get().isPresentAstNode()); + assertTrue(grammar.isPresent()); + assertTrue(grammar.get().isPresentAstNode()); ASTMCGrammar ast = grammar.get().getAstNode(); IGrammarScope innerScope = ast.getClassProd(0).getEnclosingScope(); - Assertions.assertTrue(innerScope.resolveProd("NewProd").isPresent()); + assertTrue(innerScope.resolveProd("NewProd").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("Automaton").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("Transition").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("State").isPresent()); + assertTrue(innerScope.resolveProd("Automaton").isPresent()); + assertTrue(innerScope.resolveProd("Transition").isPresent()); + assertTrue(innerScope.resolveProd("State").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("X").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("Y").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("J").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("G").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("K").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("N").isPresent()); + assertTrue(innerScope.resolveProd("X").isPresent()); + assertTrue(innerScope.resolveProd("Y").isPresent()); + assertTrue(innerScope.resolveProd("J").isPresent()); + assertTrue(innerScope.resolveProd("G").isPresent()); + assertTrue(innerScope.resolveProd("K").isPresent()); + assertTrue(innerScope.resolveProd("N").isPresent()); - Assertions.assertFalse(innerScope.resolveProd("Supergrammar").isPresent()); - Assertions.assertFalse(innerScope.resolveProd("de.monticore.inherited.Supergrammar").isPresent()); - Assertions.assertFalse(innerScope.resolveProd("CombiningGrammar").isPresent()); + assertFalse(innerScope.resolveProd("Supergrammar").isPresent()); + assertFalse(innerScope.resolveProd("de.monticore.inherited.Supergrammar").isPresent()); + assertFalse(innerScope.resolveProd("CombiningGrammar").isPresent()); - Assertions.assertTrue(innerScope.resolveMCGrammar("de.monticore.inherited.Supergrammar").isPresent()); - Assertions.assertTrue(innerScope.resolveMCGrammar("CombiningGrammar").isPresent()); - Assertions.assertTrue(innerScope.resolveMCGrammar("Automaton").isPresent()); + assertTrue(innerScope.resolveMCGrammar("de.monticore.inherited.Supergrammar").isPresent()); + assertTrue(innerScope.resolveMCGrammar("CombiningGrammar").isPresent()); + assertTrue(innerScope.resolveMCGrammar("Automaton").isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -70,28 +69,28 @@ public void testCombiningGrammarResolveInSuperGrammars() throws IOException { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); final Optional grammar = globalScope .resolveMCGrammar("de.monticore.CombiningGrammar"); - Assertions.assertTrue(grammar.isPresent()); - Assertions.assertTrue(grammar.get().isPresentAstNode()); + assertTrue(grammar.isPresent()); + assertTrue(grammar.get().isPresentAstNode()); ASTMCGrammar ast = grammar.get().getAstNode(); IGrammarScope innerScope = ast.getClassProd(0).getEnclosingScope(); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("Automaton", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("Transition", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("State", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("Automaton", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("Transition", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("State", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("X", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("Y", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("J", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("G", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("K", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("N", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("X", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("Y", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("J", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("G", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("K", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("N", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertFalse(innerScope.resolveInSuperGrammars("Supergrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertFalse(innerScope.resolveInSuperGrammars("de.monticore.inherited.Supergrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertFalse(innerScope.resolveInSuperGrammars("CombiningGrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertFalse(innerScope.resolveInSuperGrammars("Supergrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertFalse(innerScope.resolveInSuperGrammars("de.monticore.inherited.Supergrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertFalse(innerScope.resolveInSuperGrammars("CombiningGrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -99,43 +98,43 @@ public void testSubsubgrammarSymbolTable() throws IOException { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); final Optional grammar = globalScope .resolveMCGrammar("de.monticore.inherited.Subsubgrammar"); - Assertions.assertTrue(grammar.isPresent()); - Assertions.assertTrue(grammar.get().isPresentAstNode()); + assertTrue(grammar.isPresent()); + assertTrue(grammar.get().isPresentAstNode()); ASTMCGrammar ast = grammar.get().getAstNode(); IGrammarScope innerScope = ast.getClassProd(0).getEnclosingScope(); - Assertions.assertTrue(innerScope.resolveProd("N").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("S").isPresent()); - - Assertions.assertTrue(innerScope.resolveProd("A").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("B").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("M").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("D").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("L").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("O").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("M").isPresent()); - - Assertions.assertTrue(innerScope.resolveProd("X").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("Y").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("J").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("G").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("K").isPresent()); - Assertions.assertTrue(innerScope.resolveProd("N").isPresent()); - - Assertions.assertFalse(innerScope.resolveProd("Supergrammar").isPresent()); - Assertions.assertFalse(innerScope.resolveProd("de.monticore.inherited.Supergrammar").isPresent()); - Assertions.assertFalse(innerScope.resolveProd("Subgrammar").isPresent()); - Assertions.assertFalse(innerScope.resolveProd("de.monticore.inherited.Subgrammar").isPresent()); - Assertions.assertFalse(innerScope.resolveProd("Subsubgrammar").isPresent()); - Assertions.assertFalse(innerScope.resolveProd("de.monticore.inherited.Subsubgrammar").isPresent()); - - Assertions.assertTrue(innerScope.resolveMCGrammar("de.monticore.inherited.Supergrammar").isPresent()); - Assertions.assertTrue(innerScope.resolveMCGrammar("de.monticore.inherited.Subgrammar").isPresent()); - Assertions.assertTrue(innerScope.resolveMCGrammar("de.monticore.inherited.Subsubgrammar").isPresent()); - Assertions.assertTrue(innerScope.resolveMCGrammar("Subsubgrammar").isPresent()); + assertTrue(innerScope.resolveProd("N").isPresent()); + assertTrue(innerScope.resolveProd("S").isPresent()); + + assertTrue(innerScope.resolveProd("A").isPresent()); + assertTrue(innerScope.resolveProd("B").isPresent()); + assertTrue(innerScope.resolveProd("M").isPresent()); + assertTrue(innerScope.resolveProd("D").isPresent()); + assertTrue(innerScope.resolveProd("L").isPresent()); + assertTrue(innerScope.resolveProd("O").isPresent()); + assertTrue(innerScope.resolveProd("M").isPresent()); + + assertTrue(innerScope.resolveProd("X").isPresent()); + assertTrue(innerScope.resolveProd("Y").isPresent()); + assertTrue(innerScope.resolveProd("J").isPresent()); + assertTrue(innerScope.resolveProd("G").isPresent()); + assertTrue(innerScope.resolveProd("K").isPresent()); + assertTrue(innerScope.resolveProd("N").isPresent()); + + assertFalse(innerScope.resolveProd("Supergrammar").isPresent()); + assertFalse(innerScope.resolveProd("de.monticore.inherited.Supergrammar").isPresent()); + assertFalse(innerScope.resolveProd("Subgrammar").isPresent()); + assertFalse(innerScope.resolveProd("de.monticore.inherited.Subgrammar").isPresent()); + assertFalse(innerScope.resolveProd("Subsubgrammar").isPresent()); + assertFalse(innerScope.resolveProd("de.monticore.inherited.Subsubgrammar").isPresent()); + + assertTrue(innerScope.resolveMCGrammar("de.monticore.inherited.Supergrammar").isPresent()); + assertTrue(innerScope.resolveMCGrammar("de.monticore.inherited.Subgrammar").isPresent()); + assertTrue(innerScope.resolveMCGrammar("de.monticore.inherited.Subsubgrammar").isPresent()); + assertTrue(innerScope.resolveMCGrammar("Subsubgrammar").isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -143,35 +142,35 @@ public void testSubsubgrammarResolveInSuperGrammars() throws IOException { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); final Optional grammar = globalScope .resolveMCGrammar("de.monticore.inherited.Subsubgrammar"); - Assertions.assertTrue(grammar.isPresent()); - Assertions.assertTrue(grammar.get().isPresentAstNode()); + assertTrue(grammar.isPresent()); + assertTrue(grammar.get().isPresentAstNode()); ASTMCGrammar ast = grammar.get().getAstNode(); IGrammarScope innerScope = ast.getClassProd(0).getEnclosingScope(); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("N", AccessModifier.ALL_INCLUSION).isPresent()); - - Assertions.assertTrue(innerScope.resolveInSuperGrammars("A", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("B", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("M", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("D", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("L", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("O", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("M", AccessModifier.ALL_INCLUSION).isPresent()); - - Assertions.assertTrue(innerScope.resolveInSuperGrammars("X", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("Y", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("J", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("G", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("K", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(innerScope.resolveInSuperGrammars("N", AccessModifier.ALL_INCLUSION).isPresent()); - - Assertions.assertFalse(innerScope.resolveInSuperGrammars("Supergrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertFalse(innerScope.resolveInSuperGrammars("de.monticore.inherited.Supergrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertFalse(innerScope.resolveInSuperGrammars("Subgrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertFalse(innerScope.resolveInSuperGrammars("de.monticore.inherited.Subgrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertFalse(innerScope.resolveInSuperGrammars("Subsubgrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertFalse(innerScope.resolveInSuperGrammars("de.monticore.inherited.Subsubgrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("N", AccessModifier.ALL_INCLUSION).isPresent()); + + assertTrue(innerScope.resolveInSuperGrammars("A", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("B", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("M", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("D", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("L", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("O", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("M", AccessModifier.ALL_INCLUSION).isPresent()); + + assertTrue(innerScope.resolveInSuperGrammars("X", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("Y", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("J", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("G", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("K", AccessModifier.ALL_INCLUSION).isPresent()); + assertTrue(innerScope.resolveInSuperGrammars("N", AccessModifier.ALL_INCLUSION).isPresent()); + + assertFalse(innerScope.resolveInSuperGrammars("Supergrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertFalse(innerScope.resolveInSuperGrammars("de.monticore.inherited.Supergrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertFalse(innerScope.resolveInSuperGrammars("Subgrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertFalse(innerScope.resolveInSuperGrammars("de.monticore.inherited.Subgrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertFalse(innerScope.resolveInSuperGrammars("Subsubgrammar", AccessModifier.ALL_INCLUSION).isPresent()); + assertFalse(innerScope.resolveInSuperGrammars("de.monticore.inherited.Subsubgrammar", AccessModifier.ALL_INCLUSION).isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/grammar/symboltable/MontiCoreGrammarSymbolTableCreatorTest.java b/monticore-grammar/src/test/java/de/monticore/grammar/symboltable/MontiCoreGrammarSymbolTableCreatorTest.java index 82f304f714..d8b173283e 100644 --- a/monticore-grammar/src/test/java/de/monticore/grammar/symboltable/MontiCoreGrammarSymbolTableCreatorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/grammar/symboltable/MontiCoreGrammarSymbolTableCreatorTest.java @@ -9,7 +9,6 @@ import de.monticore.grammar.grammar_withconcepts._symboltable.Grammar_WithConceptsGlobalScope; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +17,8 @@ import java.util.Map; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MontiCoreGrammarSymbolTableCreatorTest { @BeforeEach @@ -35,140 +36,140 @@ public void testSymbolTableOfGrammarStatechartDSL() { final Optional grammar = globalScope .resolveMCGrammar("de.monticore.Statechart"); - Assertions.assertTrue(grammar.isPresent()); - Assertions.assertTrue(grammar.get().isPresentAstNode()); + assertTrue(grammar.isPresent()); + assertTrue(grammar.get().isPresentAstNode()); testGrammarSymbolOfStatechart(grammar.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void testGrammarSymbolOfStatechart(MCGrammarSymbol grammar) { - Assertions.assertNotNull(grammar); - Assertions.assertEquals("de.monticore.Statechart", grammar.getFullName()); - Assertions.assertEquals("de.monticore", grammar.getPackageName()); - Assertions.assertTrue(grammar.getStartProd().isPresent()); + assertNotNull(grammar); + assertEquals("de.monticore.Statechart", grammar.getFullName()); + assertEquals("de.monticore", grammar.getPackageName()); + assertTrue(grammar.getStartProd().isPresent()); - Assertions.assertTrue(grammar.isIsComponent()); - Assertions.assertEquals(1, grammar.getSuperGrammars().size()); + assertTrue(grammar.isIsComponent()); + assertEquals(1, grammar.getSuperGrammars().size()); - Assertions.assertEquals(12, grammar.getProds().size()); + assertEquals(12, grammar.getProds().size()); // AST - Assertions.assertTrue(grammar.isPresentAstNode()); - Assertions.assertSame(grammar.getEnclosingScope(), grammar.getAstNode().getEnclosingScope()); + assertTrue(grammar.isPresentAstNode()); + assertSame(grammar.getEnclosingScope(), grammar.getAstNode().getEnclosingScope()); final ProdSymbol stateChartProd = grammar.getProd("Statechart").orElse(null); - Assertions.assertNotNull(stateChartProd); - Assertions.assertEquals("Statechart", stateChartProd.getName()); - Assertions.assertEquals("de.monticore.Statechart.Statechart", stateChartProd.getFullName()); - Assertions.assertEquals("de.monticore", stateChartProd.getPackageName()); - Assertions.assertTrue(stateChartProd.isIsStartProd()); - Assertions.assertTrue(stateChartProd.isClass()); + assertNotNull(stateChartProd); + assertEquals("Statechart", stateChartProd.getName()); + assertEquals("de.monticore.Statechart.Statechart", stateChartProd.getFullName()); + assertEquals("de.monticore", stateChartProd.getPackageName()); + assertTrue(stateChartProd.isIsStartProd()); + assertTrue(stateChartProd.isClass()); // generic vs. specific Optional resolvedStateChartProd = grammar.getSpannedScope().resolveProd("Statechart"); - Assertions.assertTrue(resolvedStateChartProd.isPresent()); - Assertions.assertSame(stateChartProd, resolvedStateChartProd.get()); + assertTrue(resolvedStateChartProd.isPresent()); + assertSame(stateChartProd, resolvedStateChartProd.get()); // AST testLinkBetweenSymbolAndAst(stateChartProd); final ProdSymbol entryActionProd = grammar.getProd("EntryAction").orElse(null); - Assertions.assertNotNull(entryActionProd); - Assertions.assertEquals("EntryAction", entryActionProd.getName()); - Assertions.assertEquals("de.monticore.Statechart.EntryAction", entryActionProd.getFullName()); - Assertions.assertFalse(entryActionProd.isIsStartProd()); + assertNotNull(entryActionProd); + assertEquals("EntryAction", entryActionProd.getName()); + assertEquals("de.monticore.Statechart.EntryAction", entryActionProd.getFullName()); + assertFalse(entryActionProd.isIsStartProd()); testLinkBetweenSymbolAndAst(entryActionProd); // test prod components Collection rcsList = entryActionProd.getProdComponents(); - Assertions.assertEquals(1, rcsList.size()); + assertEquals(1, rcsList.size()); List prodComps = entryActionProd.getSpannedScope().resolveRuleComponentDownMany("block"); - Assertions.assertFalse(prodComps.isEmpty()); - Assertions.assertEquals("block", prodComps.get(0).getName()); - Assertions.assertTrue(prodComps.get(0).isIsNonterminal()); - Assertions.assertTrue(prodComps.get(0).isPresentAstNode()); - Assertions.assertFalse(prodComps.get(0).isIsList()); - Assertions.assertFalse(prodComps.get(0).isIsOptional()); - Assertions.assertSame(entryActionProd.getSpannedScope(), prodComps.get(0).getEnclosingScope()); + assertFalse(prodComps.isEmpty()); + assertEquals("block", prodComps.get(0).getName()); + assertTrue(prodComps.get(0).isIsNonterminal()); + assertTrue(prodComps.get(0).isPresentAstNode()); + assertFalse(prodComps.get(0).isIsList()); + assertFalse(prodComps.get(0).isIsOptional()); + assertSame(entryActionProd.getSpannedScope(), prodComps.get(0).getEnclosingScope()); // reference to defining prod - Assertions.assertEquals("BlockStatement", prodComps.get(0).getReferencedProd().get().getName()); - Assertions.assertTrue(prodComps.get(0).getReferencedProd().get().isIsExternal()); + assertEquals("BlockStatement", prodComps.get(0).getReferencedProd().get().getName()); + assertTrue(prodComps.get(0).getReferencedProd().get().isIsExternal()); ProdSymbol scStructure = grammar.getProd("SCStructure").orElse(null); - Assertions.assertNotNull(scStructure); - Assertions.assertEquals("SCStructure", scStructure.getName()); - Assertions.assertTrue(scStructure.isIsInterface()); - Assertions.assertEquals(0, scStructure.getProdComponents().size()); + assertNotNull(scStructure); + assertEquals("SCStructure", scStructure.getName()); + assertTrue(scStructure.isIsInterface()); + assertEquals(0, scStructure.getProdComponents().size()); testLinkBetweenSymbolAndAst(scStructure); ProdSymbol abstractAnything = grammar.getProd("AbstractAnything").orElse(null); - Assertions.assertNotNull(abstractAnything); - Assertions.assertEquals("AbstractAnything", abstractAnything.getName()); - Assertions.assertEquals("de.monticore.Statechart.AbstractAnything", abstractAnything.getFullName()); - Assertions.assertFalse(abstractAnything.isIsInterface()); - Assertions.assertFalse(abstractAnything.isIsSymbolDefinition()); - Assertions.assertEquals(0, abstractAnything.getProdComponents().size()); + assertNotNull(abstractAnything); + assertEquals("AbstractAnything", abstractAnything.getName()); + assertEquals("de.monticore.Statechart.AbstractAnything", abstractAnything.getFullName()); + assertFalse(abstractAnything.isIsInterface()); + assertFalse(abstractAnything.isIsSymbolDefinition()); + assertEquals(0, abstractAnything.getProdComponents().size()); testLinkBetweenSymbolAndAst(abstractAnything); final ProdSymbol stateProd = grammar.getProd("State").orElse(null); - Assertions.assertNotNull(stateProd); - Assertions.assertEquals("State", stateProd.getName()); - Assertions.assertEquals("de.monticore.Statechart.State", stateProd.getFullName()); - Assertions.assertTrue(stateProd.isClass()); + assertNotNull(stateProd); + assertEquals("State", stateProd.getName()); + assertEquals("de.monticore.Statechart.State", stateProd.getFullName()); + assertTrue(stateProd.isClass()); - Assertions.assertEquals(1, stateProd.getSuperInterfaceProds().size()); + assertEquals(1, stateProd.getSuperInterfaceProds().size()); final ProdSymbolSurrogate superInterfaceScStructure = stateProd.getSuperInterfaceProds() .get(0); - Assertions.assertSame(scStructure, superInterfaceScStructure.lazyLoadDelegate()); + assertSame(scStructure, superInterfaceScStructure.lazyLoadDelegate()); // AST testLinkBetweenSymbolAndAst(stateProd); List initialComponents = stateProd.getSpannedScope().resolveRuleComponentDownMany("initial"); - Assertions.assertFalse(initialComponents.isEmpty()); + assertFalse(initialComponents.isEmpty()); RuleComponentSymbol initialComponent = initialComponents.get(0); - Assertions.assertEquals("de.monticore.Statechart.State.initial", initialComponent.getFullName()); - Assertions.assertEquals("initial", initialComponent.getName()); + assertEquals("de.monticore.Statechart.State.initial", initialComponent.getFullName()); + assertEquals("initial", initialComponent.getName()); ProdSymbol classBody = grammar.getProd("Classbody").orElse(null); - Assertions.assertNotNull(classBody); - Assertions.assertEquals("Classbody", classBody.getName()); - Assertions.assertEquals(0, classBody.getProdComponents().size()); - Assertions.assertTrue(classBody.isIsExternal()); - Assertions.assertFalse(classBody.isIsSymbolDefinition()); + assertNotNull(classBody); + assertEquals("Classbody", classBody.getName()); + assertEquals(0, classBody.getProdComponents().size()); + assertTrue(classBody.isIsExternal()); + assertFalse(classBody.isIsSymbolDefinition()); testLinkBetweenSymbolAndAst(classBody); ProdSymbol codeProd = grammar.getProd("Code").orElse(null); - Assertions.assertNotNull(codeProd); - Assertions.assertEquals("Code", codeProd.getName()); - Assertions.assertEquals(1, codeProd.getProdComponents().size()); + assertNotNull(codeProd); + assertEquals("Code", codeProd.getName()); + assertEquals(1, codeProd.getProdComponents().size()); prodComps = codeProd.getSpannedScope().resolveRuleComponentDownMany("body"); - Assertions.assertFalse((prodComps.isEmpty())); - Assertions.assertTrue(prodComps.get(0).getReferencedProd().isPresent()); - Assertions.assertSame(classBody, prodComps.get(0).getReferencedProd().get().lazyLoadDelegate()); + assertFalse((prodComps.isEmpty())); + assertTrue(prodComps.get(0).getReferencedProd().isPresent()); + assertSame(classBody, prodComps.get(0).getReferencedProd().get().lazyLoadDelegate()); testLinkBetweenSymbolAndAst(codeProd); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void testLinkBetweenSymbolAndAst(ProdSymbol prodSymbol) { - Assertions.assertTrue(prodSymbol.isPresentAstNode()); - Assertions.assertSame(prodSymbol, prodSymbol.getAstNode().getSymbol()); - Assertions.assertSame(prodSymbol.getEnclosingScope(), prodSymbol.getAstNode().getEnclosingScope()); + assertTrue(prodSymbol.isPresentAstNode()); + assertSame(prodSymbol, prodSymbol.getAstNode().getSymbol()); + assertSame(prodSymbol.getEnclosingScope(), prodSymbol.getAstNode().getEnclosingScope()); if (prodSymbol.isClass()) { - Assertions.assertTrue(prodSymbol.getAstNode() instanceof ASTClassProd); + assertTrue(prodSymbol.getAstNode() instanceof ASTClassProd); } else if (prodSymbol.isIsInterface()) { - Assertions.assertTrue(prodSymbol.getAstNode() instanceof ASTInterfaceProd); + assertTrue(prodSymbol.getAstNode() instanceof ASTInterfaceProd); } else if (prodSymbol.isIsAbstract()) { - Assertions.assertTrue(prodSymbol.getAstNode() instanceof ASTAbstractProd); + assertTrue(prodSymbol.getAstNode() instanceof ASTAbstractProd); } else if (prodSymbol.isIsLexerProd()) { - Assertions.assertTrue(prodSymbol.getAstNode() instanceof ASTLexProd); + assertTrue(prodSymbol.getAstNode() instanceof ASTLexProd); } else if (prodSymbol.isIsExternal()) { - Assertions.assertTrue(prodSymbol.getAstNode() instanceof ASTExternalProd); + assertTrue(prodSymbol.getAstNode() instanceof ASTExternalProd); } } @@ -177,25 +178,25 @@ public void testGrammarTypeReferences() { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); MCGrammarSymbol grammar = globalScope.resolveMCGrammar("de.monticore.TypeReferences").orElse(null); - Assertions.assertNotNull(grammar); + assertNotNull(grammar); - Assertions.assertEquals(5, grammar.getProds().size()); + assertEquals(5, grammar.getProds().size()); ProdSymbol c = grammar.getProd("C").orElse(null); - Assertions.assertNotNull(c); - Assertions.assertEquals("C", c.getName()); - Assertions.assertTrue(c.isIsInterface()); - Assertions.assertEquals(0, c.getProdComponents().size()); + assertNotNull(c); + assertEquals("C", c.getName()); + assertTrue(c.isIsInterface()); + assertEquals(0, c.getProdComponents().size()); ProdSymbol q = grammar.getProd("Q").orElse(null); - Assertions.assertNotNull(q); - Assertions.assertEquals("Q", q.getName()); - Assertions.assertTrue(q.isClass()); + assertNotNull(q); + assertEquals("Q", q.getName()); + assertTrue(q.isClass()); ProdSymbol p = grammar.getProd("P").orElse(null); - Assertions.assertNotNull(p); + assertNotNull(p); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -205,44 +206,44 @@ public void testSuperGrammar() { MCGrammarSymbol grammar = globalScope .resolveMCGrammar("de.monticore.SubStatechart") .orElse(null); - Assertions.assertNotNull(grammar); - Assertions.assertEquals("de.monticore.SubStatechart", grammar.getFullName()); - Assertions.assertTrue(grammar.getStartProd().isPresent()); + assertNotNull(grammar); + assertEquals("de.monticore.SubStatechart", grammar.getFullName()); + assertTrue(grammar.getStartProd().isPresent()); - Assertions.assertEquals(1, grammar.getSuperGrammars().size()); + assertEquals(1, grammar.getSuperGrammars().size()); MCGrammarSymbolSurrogate superGrammarRef = grammar.getSuperGrammars().get(0); - Assertions.assertEquals("Statechart", superGrammarRef.getName()); - Assertions.assertEquals("de.monticore.Statechart", superGrammarRef.getFullName()); + assertEquals("Statechart", superGrammarRef.getName()); + assertEquals("de.monticore.Statechart", superGrammarRef.getFullName()); testGrammarSymbolOfStatechart(superGrammarRef.lazyLoadDelegate()); ProdSymbol firstProd = grammar.getProd("First").orElse(null); - Assertions.assertNotNull(firstProd); - Assertions.assertTrue(firstProd.isIsStartProd()); - Assertions.assertSame(grammar.getStartProd().get(), firstProd); + assertNotNull(firstProd); + assertTrue(firstProd.isIsStartProd()); + assertSame(grammar.getStartProd().get(), firstProd); ProdSymbol secondProd = grammar.getProd("Second").orElse(null); - Assertions.assertNotNull(secondProd); - Assertions.assertFalse(secondProd.isIsStartProd()); + assertNotNull(secondProd); + assertFalse(secondProd.isIsStartProd()); - Assertions.assertEquals(2, grammar.getProdNames().size()); - Assertions.assertEquals(19, grammar.getProdsWithInherited().size()); + assertEquals(2, grammar.getProdNames().size()); + assertEquals(19, grammar.getProdsWithInherited().size()); // get prod of super grammar - Assertions.assertFalse(grammar.getProd("State").isPresent()); + assertFalse(grammar.getProd("State").isPresent()); final ProdSymbol stateProd = grammar.getProdWithInherited("State").orElse(null); - Assertions.assertNotNull(stateProd); - Assertions.assertEquals("de.monticore.Statechart.State", stateProd.getFullName()); + assertNotNull(stateProd); + assertEquals("de.monticore.Statechart.State", stateProd.getFullName()); // generic vs. specific search in super grammar Optional resolvedProd = grammar.getSpannedScope().resolveProd("State"); - Assertions.assertTrue(resolvedProd.isPresent()); - Assertions.assertSame(stateProd, resolvedProd.get()); + assertTrue(resolvedProd.isPresent()); + assertSame(stateProd, resolvedProd.get()); Optional resolvedProd2 = firstProd.getEnclosingScope().resolveProd("State"); - Assertions.assertTrue(resolvedProd2.isPresent()); - Assertions.assertSame(stateProd, resolvedProd2.get()); + assertTrue(resolvedProd2.isPresent()); + assertSame(stateProd, resolvedProd2.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -251,22 +252,22 @@ public void testMontiCoreGrammar() { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); MCGrammarSymbol grammar = globalScope.resolveMCGrammar("de.monticore.TestGrammar").orElse(null); - Assertions.assertNotNull(grammar); - Assertions.assertEquals("de.monticore.TestGrammar", grammar.getFullName()); + assertNotNull(grammar); + assertEquals("de.monticore.TestGrammar", grammar.getFullName()); - Assertions.assertEquals(3, countExternalProd(grammar)); - Assertions.assertEquals(5, countInterfaceAndAbstractProds(grammar)); + assertEquals(3, countExternalProd(grammar)); + assertEquals(5, countInterfaceAndAbstractProds(grammar)); - Assertions.assertEquals(1, grammar.getSuperGrammars().size()); + assertEquals(1, grammar.getSuperGrammars().size()); final MCGrammarSymbolSurrogate superGrammarRef = grammar.getSuperGrammars().get(0); final String superGrammarFullName = superGrammarRef.lazyLoadDelegate().getFullName(); - Assertions.assertEquals("de.monticore.common.TestLiterals", superGrammarFullName); + assertEquals("de.monticore.common.TestLiterals", superGrammarFullName); ProdSymbol prod = grammar.getProdWithInherited("StringLiteral").orElse(null); - Assertions.assertNotNull(prod); - Assertions.assertEquals(superGrammarFullName + ".StringLiteral", prod.getFullName()); + assertNotNull(prod); + assertEquals(superGrammarFullName + ".StringLiteral", prod.getFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -275,18 +276,18 @@ public void testNonTerminalsWithSameName() { MCGrammarSymbol grammar = globalScope.resolveMCGrammar("de.monticore" + ".NonTerminalsWithSameName").orElse(null); - Assertions.assertNotNull(grammar); - Assertions.assertEquals("de.monticore.NonTerminalsWithSameName", grammar.getFullName()); + assertNotNull(grammar); + assertEquals("de.monticore.NonTerminalsWithSameName", grammar.getFullName()); - Assertions.assertEquals(2, grammar.getProds().size()); + assertEquals(2, grammar.getProds().size()); ProdSymbol transition = grammar.getProd("Transition").orElse(null); - Assertions.assertNotNull(transition); + assertNotNull(transition); List r = transition.getSpannedScope().resolveRuleComponentMany("arg"); - Assertions.assertEquals(2, r.size()); - Assertions.assertTrue(r.get(0).isIsList()); + assertEquals(2, r.size()); + assertTrue(r.get(0).isIsList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -294,16 +295,16 @@ public void testTokenModes() { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); MCGrammarSymbol grammar = globalScope.resolveMCGrammar("de.monticore.Modes").orElse(null); - Assertions.assertNotNull(grammar); - Assertions.assertEquals("de.monticore.Modes", grammar.getFullName()); + assertNotNull(grammar); + assertEquals("de.monticore.Modes", grammar.getFullName()); Map> tokenModes = grammar.getTokenModesWithInherited(); - Assertions.assertEquals(3, tokenModes.size()); - Assertions.assertEquals(4, tokenModes.get(MCGrammarSymbol.DEFAULT_MODE).size()); - Assertions.assertEquals(1, tokenModes.get("FOO_MODE").size()); - Assertions.assertEquals(1, tokenModes.get("BLA_MODE").size()); + assertEquals(3, tokenModes.size()); + assertEquals(4, tokenModes.get(MCGrammarSymbol.DEFAULT_MODE).size()); + assertEquals(1, tokenModes.get("FOO_MODE").size()); + assertEquals(1, tokenModes.get("BLA_MODE").size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -311,14 +312,14 @@ public void testReplaceKeywords() { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); MCGrammarSymbol grammar = globalScope.resolveMCGrammar("de.monticore.Keywords").orElse(null); - Assertions.assertNotNull(grammar); + assertNotNull(grammar); Map> keywords = grammar.getReplacedKeywordsWithInherited(); - Assertions.assertEquals(2, keywords.size()); - Assertions.assertEquals(1, keywords.get("A").size()); - Assertions.assertEquals(4, keywords.get("B").size()); + assertEquals(2, keywords.size()); + assertEquals(1, keywords.get("A").size()); + assertEquals(4, keywords.get("B").size()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private int countExternalProd(MCGrammarSymbol grammar) { @@ -347,21 +348,21 @@ public void testSymbolTableOfAutomaton() { // test grammar symbol MCGrammarSymbol grammar = globalScope.resolveMCGrammar("Automaton").orElse(null); - Assertions.assertNotNull(grammar); - Assertions.assertTrue(grammar.isPresentAstNode()); + assertNotNull(grammar); + assertTrue(grammar.isPresentAstNode()); ProdSymbol autProd = grammar.getSpannedScope() .resolveProd("Automaton").orElse(null); - Assertions.assertNotNull(autProd); - Assertions.assertTrue(autProd.isIsScopeSpanning()); - Assertions.assertTrue(autProd.isIsSymbolDefinition()); + assertNotNull(autProd); + assertTrue(autProd.isIsScopeSpanning()); + assertTrue(autProd.isIsSymbolDefinition()); ProdSymbol stateProd = grammar.getSpannedScope().resolveProd("State").orElse(null); - Assertions.assertNotNull(stateProd); - Assertions.assertFalse(stateProd.isIsScopeSpanning()); - Assertions.assertTrue(stateProd.isIsSymbolDefinition()); + assertNotNull(stateProd); + assertFalse(stateProd.isIsScopeSpanning()); + assertTrue(stateProd.isIsSymbolDefinition()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -370,41 +371,41 @@ public void testRuleWithSymbolReference() { MCGrammarSymbol grammar = globalScope.resolveMCGrammar("de.monticore" + ".RuleWithSymbolReference").orElse(null); - Assertions.assertNotNull(grammar); - Assertions.assertEquals("de.monticore.RuleWithSymbolReference", grammar.getFullName()); + assertNotNull(grammar); + assertEquals("de.monticore.RuleWithSymbolReference", grammar.getFullName()); - Assertions.assertEquals(7, grammar.getProds().size()); + assertEquals(7, grammar.getProds().size()); ProdSymbol s = grammar.getProd("S").orElse(null); - Assertions.assertNotNull(s); - Assertions.assertTrue(s.isIsSymbolDefinition()); - Assertions.assertEquals("S", s.getName()); + assertNotNull(s); + assertTrue(s.isIsSymbolDefinition()); + assertEquals("S", s.getName()); ProdSymbol t = grammar.getProd("T").orElse(null); - Assertions.assertEquals("T", t.getName()); - Assertions.assertFalse(t.isIsSymbolDefinition()); + assertEquals("T", t.getName()); + assertFalse(t.isIsSymbolDefinition()); ProdSymbol a = grammar.getProd("A").orElse(null); - Assertions.assertEquals("A", a.getName()); - Assertions.assertFalse(a.isIsSymbolDefinition()); + assertEquals("A", a.getName()); + assertFalse(a.isIsSymbolDefinition()); ProdSymbol b = grammar.getProd("B").orElse(null); - Assertions.assertFalse(b.isIsSymbolDefinition()); + assertFalse(b.isIsSymbolDefinition()); List comps = b.getSpannedScope().resolveRuleComponentDownMany("an"); - Assertions.assertFalse(comps.isEmpty()); + assertFalse(comps.isEmpty()); RuleComponentSymbol aComponent = comps.get(0); - Assertions.assertEquals("Name", aComponent.getReferencedProd().get().getName()); + assertEquals("Name", aComponent.getReferencedProd().get().getName()); ProdSymbol e = grammar.getProd("E").orElse(null); - Assertions.assertTrue(e.isIsExternal()); - Assertions.assertTrue(e.isIsSymbolDefinition()); + assertTrue(e.isIsExternal()); + assertTrue(e.isIsSymbolDefinition()); ProdSymbol r = grammar.getProd("R").orElse(null); - Assertions.assertTrue(r.isIsAbstract()); - Assertions.assertFalse(r.isIsInterface()); - Assertions.assertTrue(r.isIsSymbolDefinition()); + assertTrue(r.isIsAbstract()); + assertFalse(r.isIsInterface()); + assertTrue(r.isIsSymbolDefinition()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -416,59 +417,59 @@ public void testRuleWithSymbolReference() { public void testASTKeySymbolCreation() { final Grammar_WithConceptsGlobalScope globalScope = GrammarGlobalScopeTestFactory.create(); Optional grammarOpt = globalScope.resolveMCGrammar("de.monticore.KeyAndNext"); - Assertions.assertTrue(grammarOpt.isPresent()); + assertTrue(grammarOpt.isPresent()); MCGrammarSymbol grammar = grammarOpt.get(); - Assertions.assertNotNull(grammar); - Assertions.assertTrue(grammar.isPresentAstNode()); + assertNotNull(grammar); + assertTrue(grammar.isPresentAstNode()); // no usage name Optional aProd = grammar.getSpannedScope().resolveProd("A"); - Assertions.assertTrue(aProd.isPresent()); + assertTrue(aProd.isPresent()); List comps = aProd.get().getSpannedScope().resolveRuleComponentDownMany("b"); - Assertions.assertFalse(comps.isEmpty()); + assertFalse(comps.isEmpty()); RuleComponentSymbol aBRule= comps.get(0); - Assertions.assertFalse(aBRule.isIsList()); + assertFalse(aBRule.isIsList()); // with usage name Optional bProd = grammar.getSpannedScope().resolveProd("B"); - Assertions.assertTrue(bProd.isPresent()); + assertTrue(bProd.isPresent()); List bBRules = bProd.get().getSpannedScope().resolveRuleComponentMany("b"); - Assertions.assertTrue(!bBRules.isEmpty()); - Assertions.assertTrue(bBRules.get(0).isIsList()); + assertTrue(!bBRules.isEmpty()); + assertTrue(bBRules.get(0).isIsList()); // no usage name Optional cProd = grammar.getSpannedScope().resolveProd("C"); - Assertions.assertTrue(cProd.isPresent()); + assertTrue(cProd.isPresent()); List cBRules= cProd.get().getSpannedScope().resolveRuleComponentMany("b"); - Assertions.assertFalse(cBRules.isEmpty()); - Assertions.assertFalse(cBRules.get(0).isIsList()); + assertFalse(cBRules.isEmpty()); + assertFalse(cBRules.get(0).isIsList()); // no usage name Optional dProd = grammar.getSpannedScope().resolveProd("D"); - Assertions.assertTrue(dProd.isPresent()); + assertTrue(dProd.isPresent()); List dBRules= dProd.get().getSpannedScope().resolveRuleComponentMany("b"); - Assertions.assertFalse(dBRules.isEmpty()); - Assertions.assertFalse(dBRules.get(0).isIsList()); + assertFalse(dBRules.isEmpty()); + assertFalse(dBRules.get(0).isIsList()); // with usage name Optional eProd = grammar.getSpannedScope().resolveProd("E"); - Assertions.assertTrue(eProd.isPresent()); + assertTrue(eProd.isPresent()); List eBRules = eProd.get().getSpannedScope().resolveRuleComponentMany("b"); - Assertions.assertTrue(!eBRules.isEmpty()); - Assertions.assertTrue(eBRules.get(0).isIsList()); + assertTrue(!eBRules.isEmpty()); + assertTrue(eBRules.get(0).isIsList()); // no usage name Optional fProd = grammar.getSpannedScope().resolveProd("F"); - Assertions.assertTrue(fProd.isPresent()); + assertTrue(fProd.isPresent()); List fBRules = fProd.get().getSpannedScope().resolveRuleComponentMany("b"); - Assertions.assertTrue(fBRules.isEmpty()); + assertTrue(fBRules.isEmpty()); // with usage name Optional gProd = grammar.getSpannedScope().resolveProd("G"); - Assertions.assertTrue(gProd.isPresent()); + assertTrue(gProd.isPresent()); List gBRules = gProd.get().getSpannedScope().resolveRuleComponentMany("b"); - Assertions.assertFalse(gBRules.isEmpty()); + assertFalse(gBRules.isEmpty()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorFormalParametersDifferentNameTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorFormalParametersDifferentNameTest.java index c087052522..a475e8c9cc 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorFormalParametersDifferentNameTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorFormalParametersDifferentNameTest.java @@ -2,13 +2,13 @@ package de.monticore.javalight.cocos; import de.monticore.javalight._cocos.JavaLightCoCoChecker; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ConstructorFormalParametersDifferentNameTest extends JavaLightCocoTest{ private final String fileName = "de.monticore.javalight.cocos.invalid.A0821.A0821"; @BeforeEach @@ -33,7 +33,7 @@ public void testInvalid2() { public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.A0821", "const1", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorModifiersValidTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorModifiersValidTest.java index 858f00939d..43c3751947 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorModifiersValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorModifiersValidTest.java @@ -3,11 +3,10 @@ import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConstructorModifiersValidTest extends JavaLightCocoTest{ private final String fileName = "de.monticore.javalight.cocos.invalid.A0820.A0820"; @@ -28,7 +27,7 @@ public void testInvalid() { public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.A0820", "constructor", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorNoAccessModifierPairTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorNoAccessModifierPairTest.java index 393114d1a0..fa3086457a 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorNoAccessModifierPairTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorNoAccessModifierPairTest.java @@ -3,11 +3,10 @@ import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConstructorNoAccessModifierPairTest extends JavaLightCocoTest{ private final String fileName = "de.monticore.javalight.cocos.invalid.A0809.A0809"; @@ -28,7 +27,7 @@ public void testInvalid() { public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.A0809", "constructor", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorNoDuplicateModifierTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorNoDuplicateModifierTest.java index 4cc2f91d4b..1e90c6775d 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorNoDuplicateModifierTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ConstructorNoDuplicateModifierTest.java @@ -3,11 +3,10 @@ import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConstructorNoDuplicateModifierTest extends JavaLightCocoTest{ private final String fileName = "de.monticore.javalight.cocos.invalid.A0808.A0808"; @@ -28,6 +27,6 @@ public void testInvalid() { public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.A0808", "constructor", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/JavaLightCocoTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/JavaLightCocoTest.java index d0428da5bc..8eaee288bb 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/JavaLightCocoTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/JavaLightCocoTest.java @@ -7,6 +7,7 @@ import de.monticore.javalight._ast.ASTJavaMethod; import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.monticore.javalight.types3.JavaLightTypeCheck3; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.oosymbols._symboltable.MethodSymbol; import de.monticore.testjavalight.TestJavaLightMill; @@ -14,7 +15,6 @@ import de.monticore.testjavalight._symboltable.ITestJavaLightArtifactScope; import de.monticore.testjavalight._symboltable.ITestJavaLightGlobalScope; import de.monticore.testjavalight._symboltable.TestJavaLightArtifactScope; -import de.monticore.types3.util.DefsTypesForTests; import de.se_rwth.commons.Names; import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; @@ -28,6 +28,8 @@ import java.nio.file.Paths; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public abstract class JavaLightCocoTest { static protected ITestJavaLightGlobalScope globalScope; @@ -57,13 +59,13 @@ protected void testValid(String fileName, String methodName, JavaLightCoCoChecke final MethodSymbol methodSymbol = artifactScope .resolveMethod(methodName) .orElse(null); - Assertions.assertNotNull(methodSymbol); - Assertions.assertTrue(methodSymbol.isPresentAstNode()); + assertNotNull(methodSymbol); + assertTrue(methodSymbol.isPresentAstNode()); Log.getFindings().clear(); checker.checkAll((ASTJavaLightNode) methodSymbol.getAstNode()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } protected void testInvalid(String fileName, String methodName, String code, String message, @@ -78,16 +80,16 @@ protected void testInvalid(String fileName, String methodName, String code, Stri final MethodSymbol methodSymbol = artifactScope .resolveMethod(methodName) .orElse(null); - Assertions.assertNotNull(methodSymbol); - Assertions.assertTrue(methodSymbol.isPresentAstNode()); + assertNotNull(methodSymbol); + assertTrue(methodSymbol.isPresentAstNode()); Log.getFindings().clear(); checker.checkAll((ASTJavaLightNode) methodSymbol.getAstNode()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertEquals(numberOfFindings, Log.getFindings().size()); + assertFalse(Log.getFindings().isEmpty()); + assertEquals(numberOfFindings, Log.getFindings().size()); for (Finding f : Log.getFindings()) { - Assertions.assertEquals(code + message, f.getMsg()); + assertEquals(code + message, f.getMsg()); } } @@ -105,7 +107,7 @@ protected void loadFileForModelName(String modelName) { globalScope.addSubScope(artifactScope); } } catch (IOException e) { - Assertions.fail(); + fail(); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodAbstractAndOtherModifiersTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodAbstractAndOtherModifiersTest.java index 90cd981c88..4673f59c5b 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodAbstractAndOtherModifiersTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodAbstractAndOtherModifiersTest.java @@ -3,11 +3,10 @@ import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MethodAbstractAndOtherModifiersTest extends JavaLightCocoTest{ @@ -30,7 +29,7 @@ public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.A0802", "a", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodBodyAbsenceTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodBodyAbsenceTest.java index 3cfffc62d7..cfb6bd7aa0 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodBodyAbsenceTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodBodyAbsenceTest.java @@ -3,11 +3,10 @@ import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MethodBodyAbsenceTest extends JavaLightCocoTest{ private final String fileName = "de.monticore.javalight.cocos.invalid.A0804.A0804"; @@ -32,7 +31,7 @@ public void testInvalid2(){ public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.A0804", "method", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodBodyPresenceTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodBodyPresenceTest.java index f4ebf1e3eb..a797380bdc 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodBodyPresenceTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodBodyPresenceTest.java @@ -3,11 +3,10 @@ import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MethodBodyPresenceTest extends JavaLightCocoTest{ private final String fileName = "de.monticore.javalight.cocos.invalid.A0803.A0803"; @@ -32,7 +31,7 @@ public void testInvalid2(){ public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.A0803", "method", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodExceptionThrowsTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodExceptionThrowsTest.java index 2330eda6e7..07b0a7961b 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodExceptionThrowsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodExceptionThrowsTest.java @@ -3,17 +3,13 @@ package de.monticore.javalight.cocos; import de.monticore.javalight._cocos.JavaLightCoCoChecker; -import de.monticore.testjavalight.TestJavaLightMill; -import de.monticore.testjavalight._symboltable.ITestJavaLightScope; -import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types.check.SymTypeOfObject; import de.monticore.types3.util.DefsTypesForTests; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static de.monticore.types3.util.DefsTypesForTests.oOtype; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; + import de.se_rwth.commons.logging.Log; import java.util.List; @@ -41,7 +37,7 @@ public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.MethodDecl", "meth1", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodFormalParametersDifferentNameTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodFormalParametersDifferentNameTest.java index acd69a89ea..a13bd1419b 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodFormalParametersDifferentNameTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodFormalParametersDifferentNameTest.java @@ -4,11 +4,10 @@ import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MethodFormalParametersDifferentNameTest extends JavaLightCocoTest { private final String fileName = "de.monticore.javalight.cocos.invalid.A0812.A0812"; @@ -35,7 +34,7 @@ public void testInvalid2() { public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.MethodDecl", "meth1", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodNoNativeAndStrictfpTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodNoNativeAndStrictfpTest.java index a976962a0c..079a1187c1 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodNoNativeAndStrictfpTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/MethodNoNativeAndStrictfpTest.java @@ -3,11 +3,10 @@ import de.monticore.javalight._cocos.JavaLightCoCoChecker; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MethodNoNativeAndStrictfpTest extends JavaLightCocoTest{ private final String fileName = "de.monticore.javalight.cocos.invalid.A0819.A0819"; @@ -27,7 +26,7 @@ public void testInvalid1(){ public void testCorrect() { testValid("de.monticore.javalight.cocos.valid.A0819", "method", checker); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ReturnTypeAssignmentIsValidTest.java b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ReturnTypeAssignmentIsValidTest.java index 33cb65233d..2771c3aa5a 100644 --- a/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ReturnTypeAssignmentIsValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/javalight/cocos/ReturnTypeAssignmentIsValidTest.java @@ -2,26 +2,21 @@ package de.monticore.javalight.cocos; import de.monticore.javalight._cocos.JavaLightCoCoChecker; -import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._ast.ASTBasicSymbolsNode; import de.monticore.symbols.oosymbols._ast.ASTMethod; import de.monticore.testjavalight.TestJavaLightMill; import de.monticore.testjavalight._parser.TestJavaLightParser; import de.monticore.testjavalight._visitor.TestJavaLightTraverser; import de.monticore.types.check.FlatExpressionScopeSetter; -import de.monticore.types.check.FullDeriveFromCombineExpressionsWithLiterals; -import de.monticore.types.check.FullSynthesizeFromCombineExpressionsWithLiterals; -import de.monticore.types.check.TypeCalculator; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ReturnTypeAssignmentIsValidTest extends JavaLightCocoTest { @@ -35,12 +30,12 @@ public void checkValid(String expressionString) throws IOException { TestJavaLightParser parser = new TestJavaLightParser(); Optional optAST = parser.parse_StringMethod(expressionString); - Assertions.assertTrue(optAST.isPresent()); + assertTrue(optAST.isPresent()); Log.getFindings().clear(); TestJavaLightTraverser traverser = getFlatExpressionScopeSetter(); optAST.get().accept(traverser); checker.checkAll((ASTBasicSymbolsNode) optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -48,12 +43,12 @@ public void checkInvalid(String expressionString) throws IOException { TestJavaLightParser parser = new TestJavaLightParser(); Optional optAST = parser.parse_StringMethod(expressionString); - Assertions.assertTrue(optAST.isPresent()); + assertTrue(optAST.isPresent()); Log.getFindings().clear(); TestJavaLightTraverser traverser = getFlatExpressionScopeSetter(); optAST.get().accept(traverser); checker.checkAll((ASTBasicSymbolsNode) optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); + assertFalse(Log.getFindings().isEmpty()); } diff --git a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/DoubleCommonLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/DoubleCommonLiteralsTest.java index 491d868f3c..a14fb70955 100644 --- a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/DoubleCommonLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/DoubleCommonLiteralsTest.java @@ -8,7 +8,6 @@ import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,6 +15,8 @@ import java.io.StringReader; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class DoubleCommonLiteralsTest { @BeforeEach @@ -29,15 +30,15 @@ public void init() { private void checkDoubleLiteral(double d, String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseLiteral(new StringReader(s)); - Assertions.assertTrue(lit.isPresent()); - Assertions.assertTrue(lit.get() instanceof ASTBasicDoubleLiteral); - Assertions.assertEquals(d, ((ASTBasicDoubleLiteral) lit.get()).getValue(), 0); + assertTrue(lit.isPresent()); + assertInstanceOf(ASTBasicDoubleLiteral.class, lit.get()); + assertEquals(d, ((ASTBasicDoubleLiteral) lit.get()).getValue(), 0); } private void checkFalse(String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseBasicDoubleLiteral(new StringReader(s)); - Assertions.assertTrue(!lit.isPresent()); + assertFalse(lit.isPresent()); } @Test @@ -50,10 +51,10 @@ public void testDoubleLiterals() { checkDoubleLiteral(3.0, "3.0"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -68,7 +69,7 @@ public void testFalseDoubleLiterals() { checkFalse("0.0 d"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/FloatCommonLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/FloatCommonLiteralsTest.java index 54d29098df..3bd909afde 100644 --- a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/FloatCommonLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/FloatCommonLiteralsTest.java @@ -8,7 +8,6 @@ import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,6 +15,8 @@ import java.io.StringReader; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class FloatCommonLiteralsTest { @BeforeEach @@ -29,18 +30,18 @@ public void init() { private void checkFloatLiteral(float f, String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseLiteral(new StringReader(s)); - Assertions.assertTrue(lit.isPresent()); - Assertions.assertTrue(lit.get() instanceof ASTBasicFloatLiteral); - Assertions.assertEquals(f, ((ASTBasicFloatLiteral) lit.get()).getValue(), 0); - Assertions.assertTrue(true); + assertTrue(lit.isPresent()); + assertInstanceOf(ASTBasicFloatLiteral.class, lit.get()); + assertEquals(f, ((ASTBasicFloatLiteral) lit.get()).getValue(), 0); + assertTrue(true); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void checkFalse(String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseBasicFloatLiteral(new StringReader(s)); - Assertions.assertTrue(!lit.isPresent()); + assertFalse(lit.isPresent()); } @Test @@ -51,7 +52,7 @@ public void testFloatLiterals() { } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -103,7 +104,7 @@ public void checkFalseLiterals() { } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/IntCommonLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/IntCommonLiteralsTest.java index 65c78775ba..b0a5bf26e2 100644 --- a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/IntCommonLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/IntCommonLiteralsTest.java @@ -9,7 +9,6 @@ import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,6 +16,8 @@ import java.io.StringReader; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class IntCommonLiteralsTest { @BeforeEach @@ -30,35 +31,35 @@ public void init() { private void checkIntLiteral(int i, String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseLiteral(new StringReader(s)); - Assertions.assertTrue(lit.isPresent()); - Assertions.assertTrue(lit.get() instanceof ASTNatLiteral); - Assertions.assertEquals(i, ((ASTNatLiteral) lit.get()).getValue()); + assertTrue(lit.isPresent()); + assertInstanceOf(ASTNatLiteral.class, lit.get()); + assertEquals(i, ((ASTNatLiteral) lit.get()).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void checkSignedIntLiteral(int i, String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseSignedNatLiteral(new StringReader(s)); - Assertions.assertTrue(lit.isPresent()); - Assertions.assertTrue(lit.get() instanceof ASTSignedNatLiteral); - Assertions.assertEquals(i, ((ASTSignedNatLiteral) lit.get()).getValue()); + assertTrue(lit.isPresent()); + assertInstanceOf(ASTSignedNatLiteral.class, lit.get()); + assertEquals(i, ((ASTSignedNatLiteral) lit.get()).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void checkFalse(String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseNatLiteral(new StringReader(s)); - Assertions.assertTrue(!lit.isPresent()); + assertFalse(lit.isPresent()); } private void checkSignedFalse(String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseSignedNatLiteral(new StringReader(s)); - Assertions.assertTrue(!lit.isPresent()); + assertFalse(lit.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -78,7 +79,7 @@ public void testIntLiterals() { checkIntLiteral(17, "00017"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -96,7 +97,7 @@ public void testFalse() { checkFalse("0x005f"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -117,7 +118,7 @@ public void testSignedIntLiterals() { checkSignedIntLiteral(-17, "-00017"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -130,7 +131,7 @@ public void testSignedFalse() { checkFalse("- 02"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/LongCommonLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/LongCommonLiteralsTest.java index e09eea41cb..9f4fd8a009 100644 --- a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/LongCommonLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/LongCommonLiteralsTest.java @@ -8,7 +8,6 @@ import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,6 +15,8 @@ import java.io.StringReader; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class LongCommonLiteralsTest { @BeforeEach @@ -29,17 +30,17 @@ public void init() { private void checkLongLiteral(long l, String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseLiteral(new StringReader(s)); - Assertions.assertTrue(lit.isPresent()); - Assertions.assertTrue(lit.get() instanceof ASTBasicLongLiteral); - Assertions.assertEquals(l, ((ASTBasicLongLiteral) lit.get()).getValue()); + assertTrue(lit.isPresent()); + assertInstanceOf(ASTBasicLongLiteral.class, lit.get()); + assertEquals(l, ((ASTBasicLongLiteral) lit.get()).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void checkFalse(String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseBasicLongLiteral(new StringReader(s)); - Assertions.assertTrue(!lit.isPresent()); + assertFalse(lit.isPresent()); } @Test @@ -55,7 +56,7 @@ public void testLongLiterals() { } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -74,7 +75,7 @@ public void testFalse() { checkFalse("0 L"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/NoLineBreaksInStringLiteralTest.java b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/NoLineBreaksInStringLiteralTest.java index 6c63cb6b61..8dd6cae2b1 100644 --- a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/NoLineBreaksInStringLiteralTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/NoLineBreaksInStringLiteralTest.java @@ -9,7 +9,6 @@ import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +17,7 @@ import java.util.Optional; import static de.monticore.literals.mccommonliterals.cocos.NoLineBreaksInStringLiteralCoCo.ERROR_CODE; +import static org.junit.jupiter.api.Assertions.*; public class NoLineBreaksInStringLiteralTest { @@ -33,7 +33,7 @@ private void checkStringLiteral(String s) throws IOException { // Parsing TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional lit = parser.parseLiteral(new StringReader(s)); - Assertions.assertTrue(lit.isPresent()); + assertTrue(lit.isPresent()); // check CoCo MCCommonLiteralsCoCoChecker checker = new MCCommonLiteralsCoCoChecker(); @@ -47,9 +47,9 @@ public void testStringLiterals() { checkStringLiteral("\"okay\""); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -59,10 +59,10 @@ public void testFalseStringLiterals() { checkStringLiteral("\"okay\r or not\""); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertEquals(2, Log.getFindings().size()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(ERROR_CODE)); - Assertions.assertTrue(Log.getFindings().get(1).getMsg().startsWith(ERROR_CODE)); + assertEquals(2, Log.getFindings().size()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(ERROR_CODE)); + assertTrue(Log.getFindings().get(1).getMsg().startsWith(ERROR_CODE)); } } diff --git a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/RangeCoCosTest.java b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/RangeCoCosTest.java index 49608fc5c2..f074a8820d 100644 --- a/monticore-grammar/src/test/java/de/monticore/mccommonliterals/RangeCoCosTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mccommonliterals/RangeCoCosTest.java @@ -7,7 +7,6 @@ import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; import de.monticore.literals.testmccommonliterals.TestMCCommonLiteralsMill; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,6 +15,8 @@ import java.math.BigInteger; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class RangeCoCosTest { @BeforeEach @@ -29,7 +30,7 @@ public void setup(){ protected final void checkLiteral(String expression, BigInteger min, BigInteger max) throws IOException { Log.clearFindings(); Optional astex = TestMCCommonLiteralsMill.parser().parse_StringLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCCommonLiteralsCoCoChecker checker = new MCCommonLiteralsCoCoChecker(); checker.addCoCo(new BasicFloatLiteralRangeCoCo(new BigDecimal(min), new BigDecimal(max))); @@ -39,13 +40,13 @@ protected final void checkLiteral(String expression, BigInteger min, BigInteger checker.checkAll(astex.get()); - Assertions.assertFalse(Log.getErrorCount() > 0); + assertFalse(Log.getErrorCount() > 0); } protected final void checkLiteral(String expression) throws IOException { Log.clearFindings(); Optional astex = TestMCCommonLiteralsMill.parser().parse_StringLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCCommonLiteralsCoCoChecker checker = new MCCommonLiteralsCoCoChecker(); checker.addCoCo(new BasicFloatLiteralRangeCoCo()); @@ -55,13 +56,13 @@ protected final void checkLiteral(String expression) throws IOException { checker.checkAll(astex.get()); - Assertions.assertFalse(Log.getErrorCount() > 0); + assertFalse(Log.getErrorCount() > 0); } protected final void checkSignedLiteral(String expression) throws IOException { Log.clearFindings(); Optional astex = TestMCCommonLiteralsMill.parser().parse_StringSignedLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCCommonLiteralsCoCoChecker checker = new MCCommonLiteralsCoCoChecker(); checker.addCoCo(new SignedBasicFloatLiteralRangeCoCo()); @@ -71,13 +72,13 @@ protected final void checkSignedLiteral(String expression) throws IOException { checker.checkAll(astex.get()); - Assertions.assertFalse(Log.getErrorCount() > 0); + assertFalse(Log.getErrorCount() > 0); } protected final void checkErrorLiteral(String expression, BigInteger min, BigInteger max, String expectedError) throws IOException { Log.clearFindings(); Optional astex = TestMCCommonLiteralsMill.parser().parse_StringLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCCommonLiteralsCoCoChecker checker = new MCCommonLiteralsCoCoChecker(); checker.addCoCo(new BasicFloatLiteralRangeCoCo(new BigDecimal(min), new BigDecimal(max))); @@ -87,14 +88,14 @@ protected final void checkErrorLiteral(String expression, BigInteger min, BigInt checker.checkAll(astex.get()); - Assertions.assertEquals(1, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); + assertEquals(1, Log.getErrorCount()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); } protected final void checkErrorLiteral(String expression, String expectedError) throws IOException { Log.clearFindings(); Optional astex = TestMCCommonLiteralsMill.parser().parse_StringLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCCommonLiteralsCoCoChecker checker = new MCCommonLiteralsCoCoChecker(); checker.addCoCo(new BasicFloatLiteralRangeCoCo()); @@ -104,14 +105,14 @@ protected final void checkErrorLiteral(String expression, String expectedError) checker.checkAll(astex.get()); - Assertions.assertEquals(1, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); + assertEquals(1, Log.getErrorCount()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); } protected final void checkErrorSignedLiteral(String expression, BigInteger min, BigInteger max, String expectedError) throws IOException { Log.clearFindings(); Optional astex = TestMCCommonLiteralsMill.parser().parse_StringSignedLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCCommonLiteralsCoCoChecker checker = new MCCommonLiteralsCoCoChecker(); checker.addCoCo(new SignedBasicFloatLiteralRangeCoCo(new BigDecimal(min), new BigDecimal(max))); @@ -121,14 +122,14 @@ protected final void checkErrorSignedLiteral(String expression, BigInteger min, checker.checkAll(astex.get()); - Assertions.assertEquals(1, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); + assertEquals(1, Log.getErrorCount()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); } protected final void checkErrorSignedLiteral(String expression, String expectedError) throws IOException { Log.clearFindings(); Optional astex = TestMCCommonLiteralsMill.parser().parse_StringSignedLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCCommonLiteralsCoCoChecker checker = new MCCommonLiteralsCoCoChecker(); checker.addCoCo(new SignedBasicFloatLiteralRangeCoCo()); @@ -138,8 +139,8 @@ protected final void checkErrorSignedLiteral(String expression, String expectedE checker.checkAll(astex.get()); - Assertions.assertEquals(1, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); + assertEquals(1, Log.getErrorCount()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); } diff --git a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/DoubleJavaLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/DoubleJavaLiteralsTest.java index 6f24987a03..9cb2df8a20 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/DoubleJavaLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/DoubleJavaLiteralsTest.java @@ -7,12 +7,13 @@ import de.monticore.literals.testmcjavaliterals.TestMCJavaLiteralsMill; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; +import static org.junit.jupiter.api.Assertions.*; + public class DoubleJavaLiteralsTest { @BeforeEach @@ -25,10 +26,10 @@ public void init() { private void checkDoubleLiteral(double d, String s) throws IOException { ASTLiteral lit = MCJavaLiteralsTestHelper.getInstance().parseLiteral(s); - Assertions.assertTrue(lit instanceof ASTDoubleLiteral); - Assertions.assertEquals(d, ((ASTDoubleLiteral) lit).getValue(), 0); + assertInstanceOf(ASTDoubleLiteral.class, lit); + assertEquals(d, ((ASTDoubleLiteral) lit).getValue(), 0); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -83,7 +84,7 @@ public void testDoubleLiterals() { checkDoubleLiteral(1e137, "1e137"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/FloatJavaLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/FloatJavaLiteralsTest.java index 39020bb9a1..8e0fbc130e 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/FloatJavaLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/FloatJavaLiteralsTest.java @@ -7,12 +7,13 @@ import de.monticore.literals.testmcjavaliterals.TestMCJavaLiteralsMill; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; +import static org.junit.jupiter.api.Assertions.*; + public class FloatJavaLiteralsTest { @BeforeEach @@ -25,11 +26,10 @@ public void init() { private void checkFloatLiteral(float f, String s) throws IOException { ASTLiteral lit = MCJavaLiteralsTestHelper.getInstance().parseLiteral(s); - Assertions.assertTrue(lit instanceof ASTFloatLiteral); - Assertions.assertEquals(f, ((ASTFloatLiteral) lit).getValue(), 0); - Assertions.assertTrue(true); + assertInstanceOf(ASTFloatLiteral.class, lit); + assertEquals(f, ((ASTFloatLiteral) lit).getValue(), 0); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -83,7 +83,7 @@ public void testFloatLiterals() { } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/IntJavaLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/IntJavaLiteralsTest.java index 411b2d04d2..753b6d4daf 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/IntJavaLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/IntJavaLiteralsTest.java @@ -13,6 +13,8 @@ import java.io.IOException; +import static org.junit.jupiter.api.Assertions.*; + public class IntJavaLiteralsTest { @BeforeEach @@ -25,10 +27,10 @@ public void init() { private void checkIntLiteral(int i, String s) throws IOException { ASTLiteral lit = MCJavaLiteralsTestHelper.getInstance().parseLiteral(s); - Assertions.assertTrue(lit instanceof ASTIntLiteral); - Assertions.assertEquals(i, ((ASTIntLiteral) lit).getValue()); + assertInstanceOf(ASTIntLiteral.class, lit); + assertEquals(i, ((ASTIntLiteral) lit).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -58,7 +60,7 @@ public void testIntLiterals() { checkIntLiteral(00017, "00017"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/LongJavaLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/LongJavaLiteralsTest.java index b76ee07838..c9f1ba8e3c 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/LongJavaLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/LongJavaLiteralsTest.java @@ -13,6 +13,8 @@ import java.io.IOException; +import static org.junit.jupiter.api.Assertions.*; + public class LongJavaLiteralsTest { @@ -26,10 +28,10 @@ public void init() { private void checkLongLiteral(long l, String s) throws IOException { ASTLiteral lit = MCJavaLiteralsTestHelper.getInstance().parseLiteral(s); - Assertions.assertTrue(lit instanceof ASTLongLiteral); - Assertions.assertEquals(l, ((ASTLongLiteral) lit).getValue()); + assertInstanceOf(ASTLongLiteral.class, lit); + assertEquals(l, ((ASTLongLiteral) lit).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -59,7 +61,7 @@ public void testLongLiterals() { checkLongLiteral(00017L, "00017L"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/MCJavaLiteralsTestHelper.java b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/MCJavaLiteralsTestHelper.java index 0db56550cf..e7de9267ba 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/MCJavaLiteralsTestHelper.java +++ b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/MCJavaLiteralsTestHelper.java @@ -4,12 +4,13 @@ import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; import de.monticore.literals.testmcjavaliterals._parser.TestMCJavaLiteralsParser; -import junit.framework.TestCase; import java.io.IOException; import java.io.StringReader; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * This class provides two methods that allow testing type grammar. The test * parses a given input string to an AST. The AST is printed via prettyprint and @@ -48,7 +49,7 @@ public static MCJavaLiteralsTestHelper getInstance() { public ASTLiteral parseLiteral(String input) throws IOException { TestMCJavaLiteralsParser parser = new TestMCJavaLiteralsParser(); Optional res = parser.parseLiteral(new StringReader(input)); - TestCase.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); return res.get(); } diff --git a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/RangeCoCosTest.java b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/RangeCoCosTest.java index 47dbbb88ed..28f0451526 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/RangeCoCosTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcjavaliterals/RangeCoCosTest.java @@ -9,7 +9,6 @@ import de.monticore.literals.mcjavaliterals.cocos.LongLiteralRangeCoCo; import de.monticore.literals.testmcjavaliterals.TestMCJavaLiteralsMill; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,7 +17,7 @@ import java.math.BigInteger; import java.util.Optional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; public class RangeCoCosTest { @@ -34,109 +33,109 @@ public void setup(){ protected final void checkIntLiteral(String expression, BigInteger min, BigInteger max) throws IOException { Log.clearFindings(); Optional astex = TestMCJavaLiteralsMill.parser().parse_StringIntLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCJavaLiteralsCoCoChecker checker = new MCJavaLiteralsCoCoChecker(); checker.addCoCo(new IntLiteralRangeCoCo(min, max)); checker.checkAll((ASTMCJavaLiteralsNode) astex.get()); - Assertions.assertFalse(Log.getErrorCount() > 0); + assertFalse(Log.getErrorCount() > 0); } protected final void checkLongLiteral(String expression, BigInteger min, BigInteger max) throws IOException { Log.clearFindings(); Optional astex = TestMCJavaLiteralsMill.parser().parse_StringLongLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCJavaLiteralsCoCoChecker checker = new MCJavaLiteralsCoCoChecker(); checker.addCoCo(new LongLiteralRangeCoCo(min, max)); checker.checkAll((ASTMCJavaLiteralsNode) astex.get()); - Assertions.assertFalse(Log.getErrorCount() > 0); + assertFalse(Log.getErrorCount() > 0); } protected final void checkDoubleLiteral(String expression, BigDecimal min, BigDecimal max) throws IOException { Log.clearFindings(); Optional astex = TestMCJavaLiteralsMill.parser().parse_StringDoubleLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCJavaLiteralsCoCoChecker checker = new MCJavaLiteralsCoCoChecker(); checker.addCoCo(new DoubleLiteralRangeCoCo(min, max)); checker.checkAll((ASTMCJavaLiteralsNode) astex.get()); - Assertions.assertFalse(Log.getErrorCount() > 0); + assertFalse(Log.getErrorCount() > 0); } protected final void checkFloatLiteral(String expression, BigDecimal min, BigDecimal max) throws IOException { Log.clearFindings(); Optional astex = TestMCJavaLiteralsMill.parser().parse_StringFloatLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCJavaLiteralsCoCoChecker checker = new MCJavaLiteralsCoCoChecker(); checker.addCoCo(new FloatLiteralRangeCoCo(min, max)); checker.checkAll((ASTMCJavaLiteralsNode) astex.get()); - Assertions.assertFalse(Log.getErrorCount() > 0); + assertFalse(Log.getErrorCount() > 0); } protected final void checkErrorIntLiteral(String expression, BigInteger min, BigInteger max, String expectedError) throws IOException { Log.clearFindings(); Optional astex = TestMCJavaLiteralsMill.parser().parse_StringIntLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCJavaLiteralsCoCoChecker checker = new MCJavaLiteralsCoCoChecker(); checker.addCoCo(new IntLiteralRangeCoCo(min, max)); checker.checkAll((ASTMCJavaLiteralsNode) astex.get()); - Assertions.assertEquals(1, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); + assertEquals(1, Log.getErrorCount()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); } protected final void checkErrorLongLiteral(String expression, BigInteger min, BigInteger max, String expectedError) throws IOException { Log.clearFindings(); Optional astex = TestMCJavaLiteralsMill.parser().parse_StringLongLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCJavaLiteralsCoCoChecker checker = new MCJavaLiteralsCoCoChecker(); checker.addCoCo(new LongLiteralRangeCoCo(min, max)); checker.checkAll((ASTMCJavaLiteralsNode) astex.get()); - Assertions.assertEquals(1, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); + assertEquals(1, Log.getErrorCount()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); } protected final void checkErrorDoubleLiteral(String expression, BigDecimal min, BigDecimal max, String expectedError) throws IOException { Log.clearFindings(); Optional astex = TestMCJavaLiteralsMill.parser().parse_StringDoubleLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCJavaLiteralsCoCoChecker checker = new MCJavaLiteralsCoCoChecker(); checker.addCoCo(new DoubleLiteralRangeCoCo(min, max)); checker.checkAll((ASTMCJavaLiteralsNode) astex.get()); - Assertions.assertEquals(1, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); + assertEquals(1, Log.getErrorCount()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); } protected final void checkErrorFloatLiteral(String expression, BigDecimal min, BigDecimal max, String expectedError) throws IOException { Log.clearFindings(); Optional astex = TestMCJavaLiteralsMill.parser().parse_StringFloatLiteral(expression); - Assertions.assertTrue(astex.isPresent()); + assertTrue(astex.isPresent()); MCJavaLiteralsCoCoChecker checker = new MCJavaLiteralsCoCoChecker(); checker.addCoCo(new FloatLiteralRangeCoCo(min, max)); checker.checkAll((ASTMCJavaLiteralsNode) astex.get()); - Assertions.assertEquals(1, Log.getErrorCount()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); + assertEquals(1, Log.getErrorCount()); + assertTrue(Log.getFindings().get(0).getMsg().startsWith(expectedError)); } @Test diff --git a/monticore-grammar/src/test/java/de/monticore/mcliterals/CharLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcliterals/CharLiteralsTest.java index 6a4d39d7de..5ca90c32f9 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcliterals/CharLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcliterals/CharLiteralsTest.java @@ -13,6 +13,8 @@ import java.io.IOException; +import static org.junit.jupiter.api.Assertions.*; + public class CharLiteralsTest { @BeforeEach @@ -25,10 +27,10 @@ public void init() { private void checkCharLiteral(char c, String s) throws IOException { ASTLiteral lit = MCLiteralsTestHelper.getInstance().parseLiteral(s); - Assertions.assertTrue(lit instanceof ASTCharLiteral); - Assertions.assertEquals(c, ((ASTCharLiteral) lit).getValue()); + assertInstanceOf(ASTCharLiteral.class, lit); + assertEquals(c, ((ASTCharLiteral) lit).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -55,7 +57,7 @@ public void testCharLiterals() { checkCharLiteral('\uffff', "'\\uffff'"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcliterals/MCLiteralsTestHelper.java b/monticore-grammar/src/test/java/de/monticore/mcliterals/MCLiteralsTestHelper.java index 4bfc3f62de..9e4442823b 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcliterals/MCLiteralsTestHelper.java +++ b/monticore-grammar/src/test/java/de/monticore/mcliterals/MCLiteralsTestHelper.java @@ -5,12 +5,13 @@ import de.monticore.literals.mccommonliterals._ast.ASTSignedLiteral; import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; -import junit.framework.TestCase; import java.io.IOException; import java.io.StringReader; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * This class provides two methods that allow testing type grammar. The test * parses a given input string to an AST. The AST is printed via prettyprint and @@ -50,7 +51,7 @@ public static MCLiteralsTestHelper getInstance() { public ASTLiteral parseLiteral(String input) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional res = parser.parseLiteral(new StringReader(input)); - TestCase.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); return res.get(); } @@ -65,7 +66,7 @@ public ASTSignedLiteral parseSignedLiteral(String input) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional res = parser.parseSignedLiteral(new StringReader(input)); - TestCase.assertTrue(res.isPresent()); + assertTrue(res.isPresent()); return res.get(); } diff --git a/monticore-grammar/src/test/java/de/monticore/mcliterals/MCLiteralsUnitTest.java b/monticore-grammar/src/test/java/de/monticore/mcliterals/MCLiteralsUnitTest.java index 6cfc2b14b1..1e6e0fc8b3 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcliterals/MCLiteralsUnitTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcliterals/MCLiteralsUnitTest.java @@ -10,7 +10,6 @@ import mcnumbers._ast.ASTDecimal; import mcnumbers._ast.ASTInteger; import mcnumbers._ast.ASTNumber; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import stringliterals._ast.ASTCharLiteral; @@ -18,8 +17,8 @@ import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; // import de.monticore.mcliteralsv2._ast.*; @@ -44,18 +43,18 @@ public void init() { @Test public void testCardinalityToken() throws IOException { ASTAnyTokenList ast = parser.parse_StringAnyTokenList( ":[65..67]:" ).get(); - Assertions.assertEquals(5, ast.sizeAnyTokens()); + assertEquals(5, ast.sizeAnyTokens()); ASTAnyToken t = ast.getAnyToken(0); t = ast.getAnyToken(1); - Assertions.assertTrue(t.isPresentDecimalToken()); - Assertions.assertEquals("65", t.getDecimalToken()); + assertTrue(t.isPresentDecimalToken()); + assertEquals("65", t.getDecimalToken()); t = ast.getAnyToken(2); t = ast.getAnyToken(3); - Assertions.assertTrue(t.isPresentDecimalToken()); - Assertions.assertEquals("67", t.getDecimalToken()); + assertTrue(t.isPresentDecimalToken()); + assertEquals("67", t.getDecimalToken()); t = ast.getAnyToken(4); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -66,62 +65,62 @@ public void testCardinalityToken() throws IOException { @Test public void testNat1() throws IOException { ASTDecimal ast = parser.parse_StringDecimal( " 9" ).get(); - Assertions.assertEquals("9", ast.getSource()); - Assertions.assertEquals(9, ast.getValue()); - Assertions.assertEquals(9, ast.getValueInt()); + assertEquals("9", ast.getSource()); + assertEquals(9, ast.getValue()); + assertEquals(9, ast.getValueInt()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNat2() throws IOException { ASTDecimal ast = parser.parse_StringDecimal( " 0" ).get(); - Assertions.assertEquals("0", ast.getSource()); - Assertions.assertEquals(0, ast.getValue()); + assertEquals("0", ast.getSource()); + assertEquals(0, ast.getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNat3() throws IOException { Optional os = parser.parse_StringDecimal( " 00 0 " ); - Assertions.assertEquals(false, os.isPresent()); + assertEquals(false, os.isPresent()); } @Test public void testNat4() throws IOException { ASTDecimal ast = parser.parse_StringDecimal( " 23 " ).get(); - Assertions.assertEquals("23", ast.getSource()); - Assertions.assertEquals(23, ast.getValue()); - Assertions.assertEquals(23, ast.getValueInt()); + assertEquals("23", ast.getSource()); + assertEquals(23, ast.getValue()); + assertEquals(23, ast.getValueInt()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testNat5() throws IOException { ASTDecimal ast = parser.parse_StringDecimal( " 463 " ).get(); - Assertions.assertEquals(463, ast.getValue()); + assertEquals(463, ast.getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @Test public void testNat6() throws IOException { Optional os = parser.parse_StringDecimal( " 0x23 " ); - Assertions.assertEquals(false, os.isPresent()); + assertEquals(false, os.isPresent()); } // -------------------------------------------------------------------- @Test public void testTokens() throws IOException { ASTAnyTokenList ast = parser.parse_StringAnyTokenList( ":463 23:" ).get(); - Assertions.assertEquals(2, ast.sizeAnyTokens()); + assertEquals(2, ast.sizeAnyTokens()); ASTAnyToken a0 = ast.getAnyToken(0); - Assertions.assertTrue(a0.isPresentDecimalToken()); - Assertions.assertEquals("463", a0.getDecimalToken()); + assertTrue(a0.isPresentDecimalToken()); + assertEquals("463", a0.getDecimalToken()); ASTAnyToken a1 = ast.getAnyToken(1); - Assertions.assertTrue(a1.isPresentDecimalToken()); - Assertions.assertEquals("23", a1.getDecimalToken()); + assertTrue(a1.isPresentDecimalToken()); + assertEquals("23", a1.getDecimalToken()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -129,27 +128,27 @@ public void testTokens() throws IOException { public void testTokens2() throws IOException { ASTAnyTokenList ast = parser.parse_StringAnyTokenList( ":9 'a' 45 00 47:" ).get(); - Assertions.assertEquals(6, ast.sizeAnyTokens()); - Assertions.assertEquals("9", ast.getAnyToken(0).getDecimalToken()); - Assertions.assertEquals("a", ast.getAnyToken(1).getCharToken()); - Assertions.assertEquals("45", ast.getAnyToken(2).getDecimalToken()); + assertEquals(6, ast.sizeAnyTokens()); + assertEquals("9", ast.getAnyToken(0).getDecimalToken()); + assertEquals("a", ast.getAnyToken(1).getCharToken()); + assertEquals("45", ast.getAnyToken(2).getDecimalToken()); // Observe the separated '0's! - Assertions.assertEquals("0", ast.getAnyToken(3).getDecimalToken()); - Assertions.assertEquals("0", ast.getAnyToken(4).getDecimalToken()); - Assertions.assertEquals("47", ast.getAnyToken(5).getDecimalToken()); + assertEquals("0", ast.getAnyToken(3).getDecimalToken()); + assertEquals("0", ast.getAnyToken(4).getDecimalToken()); + assertEquals("47", ast.getAnyToken(5).getDecimalToken()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @Test public void testAbstractInterfaceFunctions() throws IOException { ASTNumber ast = parser.parse_StringDecimal( " 234 " ).get(); - Assertions.assertEquals(234, ast.getValue()); - Assertions.assertEquals(234, ast.getValueInt()); - Assertions.assertEquals("234", ast.getSource()); + assertEquals(234, ast.getValue()); + assertEquals(234, ast.getValueInt()); + assertEquals("234", ast.getSource()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -160,11 +159,11 @@ public void testAbstractInterfaceFunctions() throws IOException { @Test public void testInt() throws IOException { ASTInteger ast = parser.parse_StringInteger( " -463 " ).get(); - Assertions.assertEquals(-463, ast.getValue()); - Assertions.assertEquals(-463, ast.getValueInt()); - Assertions.assertEquals("-463", ast.getSource()); + assertEquals(-463, ast.getValue()); + assertEquals(-463, ast.getValueInt()); + assertEquals("-463", ast.getSource()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -172,26 +171,26 @@ public void testInt() throws IOException { public void testIntTokens2() throws IOException { ASTIntegerList ast = parser.parse_StringIntegerList( "[9, -45, -0, - 47]" ).get(); - Assertions.assertEquals(4, ast.sizeIntegers()); - Assertions.assertEquals(9, ast.getInteger(0).getValue()); - Assertions.assertEquals("9", ast.getInteger(0).getSource()); - Assertions.assertEquals(-45, ast.getInteger(1).getValue()); - Assertions.assertEquals("-45", ast.getInteger(1).getSource()); - Assertions.assertEquals(0, ast.getInteger(2).getValue()); + assertEquals(4, ast.sizeIntegers()); + assertEquals(9, ast.getInteger(0).getValue()); + assertEquals("9", ast.getInteger(0).getSource()); + assertEquals(-45, ast.getInteger(1).getValue()); + assertEquals("-45", ast.getInteger(1).getSource()); + assertEquals(0, ast.getInteger(2).getValue()); // "-" is still present - Assertions.assertEquals("-0", ast.getInteger(2).getSource()); - Assertions.assertEquals(-47, ast.getInteger(3).getValue()); + assertEquals("-0", ast.getInteger(2).getSource()); + assertEquals(-47, ast.getInteger(3).getValue()); // space between the two token is missing - Assertions.assertEquals("-47", ast.getInteger(3).getSource()); + assertEquals("-47", ast.getInteger(3).getSource()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @Test public void testIntNEG() throws IOException { Optional os = parser.parse_StringInteger( " 0x34 " ); - Assertions.assertEquals(false, os.isPresent()); + assertEquals(false, os.isPresent()); } // -------------------------------------------------------------------- @@ -202,10 +201,10 @@ public void testIntNEG() throws IOException { @Test public void testB() throws IOException { ASTBTest ast = parser.parse_StringBTest( " X2X, XFF001DX" ).get(); - Assertions.assertEquals("X2X", ast.getXHexDigit(0)); - Assertions.assertEquals("XFF001DX", ast.getXHexDigit(1)); + assertEquals("X2X", ast.getXHexDigit(0)); + assertEquals("XFF001DX", ast.getXHexDigit(1)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -218,16 +217,16 @@ public void testB() throws IOException { public void testString() throws IOException { ASTStringList ast = parser.parse_StringStringList( "[\"ZWeR\",\"4\", \"',\\b,\\\\;\", \"S\\u34F4W\", \"o\"]" ).get(); - Assertions.assertEquals("ZWeR", ast.getStringLiteral(0).getValue()); - Assertions.assertEquals("4", ast.getStringLiteral(1).getValue()); - Assertions.assertEquals("',\b,\\;", ast.getStringLiteral(2).getValue()); - Assertions.assertEquals("S\u34F4W", ast.getStringLiteral(3).getValue()); - Assertions.assertEquals("o", ast.getStringLiteral(4).getValue()); + assertEquals("ZWeR", ast.getStringLiteral(0).getValue()); + assertEquals("4", ast.getStringLiteral(1).getValue()); + assertEquals("',\b,\\;", ast.getStringLiteral(2).getValue()); + assertEquals("S\u34F4W", ast.getStringLiteral(3).getValue()); + assertEquals("o", ast.getStringLiteral(4).getValue()); // repeat wg. buffering - Assertions.assertEquals("ZWeR", ast.getStringLiteral(0).getValue()); + assertEquals("ZWeR", ast.getStringLiteral(0).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -238,10 +237,10 @@ public void testString() throws IOException { @Test public void testChar() throws IOException { ASTCharLiteral ast = parser.parse_StringCharLiteral( " 'h'" ).get(); - Assertions.assertEquals("h", ast.getSource()); - Assertions.assertEquals('h', ast.getValue()); + assertEquals("h", ast.getSource()); + assertEquals('h', ast.getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -249,16 +248,16 @@ public void testChar() throws IOException { public void testChar2() throws IOException { ASTCharList ast = parser.parse_StringCharList( "['Z','4','\\'', '\\b', '\\\\', '\7', '\\7', 'o']" ).get(); - Assertions.assertEquals('Z', ast.getCharLiteral(0).getValue()); - Assertions.assertEquals('4', ast.getCharLiteral(1).getValue()); - Assertions.assertEquals('\'', ast.getCharLiteral(2).getValue()); - Assertions.assertEquals('\b', ast.getCharLiteral(3).getValue()); - Assertions.assertEquals('\\', ast.getCharLiteral(4).getValue()); + assertEquals('Z', ast.getCharLiteral(0).getValue()); + assertEquals('4', ast.getCharLiteral(1).getValue()); + assertEquals('\'', ast.getCharLiteral(2).getValue()); + assertEquals('\b', ast.getCharLiteral(3).getValue()); + assertEquals('\\', ast.getCharLiteral(4).getValue()); // Encoded by Java - Assertions.assertEquals('\7', ast.getCharLiteral(5).getValue()); - Assertions.assertEquals('o', ast.getCharLiteral(7).getValue()); + assertEquals('\7', ast.getCharLiteral(5).getValue()); + assertEquals('o', ast.getCharLiteral(7).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } // -------------------------------------------------------------------- @@ -267,12 +266,12 @@ public void testChar2() throws IOException { public void testCharUnicode() throws IOException { ASTCharList ast = parser.parse_StringCharList( "['\\u2345', '\\u23EF', '\\u0001', '\\uAFFA']" ).get(); - Assertions.assertEquals('\u2345', ast.getCharLiteral(0).getValue()); - Assertions.assertEquals('\u23EF', ast.getCharLiteral(1).getValue()); - Assertions.assertEquals('\u0001', ast.getCharLiteral(2).getValue()); - Assertions.assertEquals('\uAFFA', ast.getCharLiteral(3).getValue()); + assertEquals('\u2345', ast.getCharLiteral(0).getValue()); + assertEquals('\u23EF', ast.getCharLiteral(1).getValue()); + assertEquals('\u0001', ast.getCharLiteral(2).getValue()); + assertEquals('\uAFFA', ast.getCharLiteral(3).getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcliterals/NatLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcliterals/NatLiteralsTest.java index 552702f640..509eff7e7a 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcliterals/NatLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcliterals/NatLiteralsTest.java @@ -7,13 +7,14 @@ import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class NatLiteralsTest { @BeforeEach @@ -27,16 +28,16 @@ public void init() { private void checkNatLiteral(int i, String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional ast = parser.parse_StringNatLiteral(s); - Assertions.assertTrue(!parser.hasErrors()); - Assertions.assertEquals(i, ast.get().getValue()); + assertFalse(parser.hasErrors()); + assertEquals(i, ast.get().getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void checkFailingNatLiteral(String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); parser.parse_StringNatLiteral(s); - Assertions.assertTrue(parser.hasErrors()); + assertTrue(parser.hasErrors()); } @Test @@ -49,7 +50,7 @@ public void testNatLiterals() { checkNatLiteral(5, "5"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -60,7 +61,7 @@ public void testFailingNatLiterals() throws IOException { checkFailingNatLiteral("-5"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcliterals/NullAndBooleanLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcliterals/NullAndBooleanLiteralsTest.java index f91defb234..757238104f 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcliterals/NullAndBooleanLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcliterals/NullAndBooleanLiteralsTest.java @@ -8,12 +8,13 @@ import de.monticore.literals.testmccommonliterals.TestMCCommonLiteralsMill; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; +import static org.junit.jupiter.api.Assertions.*; + public class NullAndBooleanLiteralsTest { @BeforeEach @@ -28,13 +29,13 @@ public void initLog() { public void testNullLiteral() { try { ASTLiteral lit = MCLiteralsTestHelper.getInstance().parseLiteral("null"); - Assertions.assertTrue(lit instanceof ASTNullLiteral); + assertInstanceOf(ASTNullLiteral.class, lit); } catch (Exception e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -42,18 +43,18 @@ public void testBooleanLiterals() { try { // literal "true": ASTLiteral lit = MCLiteralsTestHelper.getInstance().parseLiteral("true"); - Assertions.assertTrue(lit instanceof ASTBooleanLiteral); - Assertions.assertTrue(((ASTBooleanLiteral) lit).getValue()); + assertInstanceOf(ASTBooleanLiteral.class, lit); + assertTrue(((ASTBooleanLiteral) lit).getValue()); // literal "false": lit = MCLiteralsTestHelper.getInstance().parseLiteral("false"); - Assertions.assertTrue(lit instanceof ASTBooleanLiteral); - Assertions.assertFalse(((ASTBooleanLiteral) lit).getValue()); + assertInstanceOf(ASTBooleanLiteral.class, lit); + assertFalse(((ASTBooleanLiteral) lit).getValue()); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcliterals/SignedNatLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcliterals/SignedNatLiteralsTest.java index f55d174d60..178975869f 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcliterals/SignedNatLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcliterals/SignedNatLiteralsTest.java @@ -7,13 +7,14 @@ import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class SignedNatLiteralsTest { @BeforeEach @@ -27,16 +28,16 @@ public void initLog() { private void checkNatLiteral(int i, String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); Optional ast = parser.parse_StringSignedNatLiteral(s); - Assertions.assertTrue(!parser.hasErrors()); - Assertions.assertEquals(i, ast.get().getValue()); + assertFalse(parser.hasErrors()); + assertEquals(i, ast.get().getValue()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private void checkFailingNatLiteral(String s) throws IOException { TestMCCommonLiteralsParser parser = new TestMCCommonLiteralsParser(); parser.parse_StringSignedNatLiteral(s); - Assertions.assertTrue(parser.hasErrors()); + assertTrue(parser.hasErrors()); } @Test @@ -56,7 +57,7 @@ public void testNatLiterals() { } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -67,7 +68,7 @@ public void testFailingNatLiterals() throws IOException { // checkFailingNatLiteral("-5"); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/mcliterals/StringLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/mcliterals/StringLiteralsTest.java index 02e77b5d7b..064051698d 100644 --- a/monticore-grammar/src/test/java/de/monticore/mcliterals/StringLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/mcliterals/StringLiteralsTest.java @@ -8,7 +8,6 @@ import de.monticore.literals.testmccommonliterals._ast.ASTA; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,7 +29,7 @@ public void initLog() { private void checkStringLiteral(String expected, String actual) throws IOException { ASTLiteral lit = MCLiteralsTestHelper.getInstance().parseLiteral(actual); - assertTrue(lit instanceof ASTStringLiteral); + assertInstanceOf(ASTStringLiteral.class, lit); assertEquals(expected, ((ASTStringLiteral) lit).getValue()); assertTrue(Log.getFindings().isEmpty()); @@ -62,7 +61,7 @@ public void testStringLiterals() { checkStringLiteral("\u010000", "\"\\u010000\""); } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/CardinalityPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/CardinalityPrettyPrinterTest.java index 7c499082e7..ee550922ef 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/CardinalityPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/CardinalityPrettyPrinterTest.java @@ -8,7 +8,6 @@ import de.monticore.cardinality._prettyprint.CardinalityFullPrettyPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CardinalityPrettyPrinterTest { @@ -33,59 +32,59 @@ public void init() { public void testCardinality1() throws IOException { TestCardinalityParser parser = new TestCardinalityParser(); Optional result = parser.parseCardinality(new StringReader("[*]")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCardinality cardinality = result.get(); CardinalityFullPrettyPrinter prettyPrinter = new CardinalityFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(cardinality); result = parser.parseCardinality(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(cardinality.deepEquals(result.get())); + assertTrue(cardinality.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCardinality2() throws IOException { TestCardinalityParser parser = new TestCardinalityParser(); Optional result = parser.parseCardinality(new StringReader("[5..9]")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCardinality cardinality = result.get(); CardinalityFullPrettyPrinter prettyPrinter = new CardinalityFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(cardinality); result = parser.parseCardinality(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(cardinality.deepEquals(result.get())); + assertTrue(cardinality.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCardinality3() throws IOException { TestCardinalityParser parser = new TestCardinalityParser(); Optional result = parser.parseCardinality(new StringReader("[6..*]")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCardinality cardinality = result.get(); CardinalityFullPrettyPrinter prettyPrinter = new CardinalityFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(cardinality); result = parser.parseCardinality(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(cardinality.deepEquals(result.get())); + assertTrue(cardinality.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/CompletenessPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/CompletenessPrettyPrinterTest.java index ae4488ef7c..172236ace7 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/CompletenessPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/CompletenessPrettyPrinterTest.java @@ -2,15 +2,11 @@ package de.monticore.prettyprint; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.monticore.testcompleteness.TestCompletenessMill; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import de.monticore.completeness._ast.ASTCompleteness; @@ -19,6 +15,9 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class CompletenessPrettyPrinterTest { @BeforeEach @@ -33,79 +32,79 @@ public void init() { public void testCompleteness() throws IOException { TestCompletenessParser parser = new TestCompletenessParser(); Optional result = parser.parseCompleteness(new StringReader("(c)")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCompleteness completeness = result.get(); CompletenessFullPrettyPrinter prettyPrinter = new CompletenessFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(completeness); result = parser.parseCompleteness(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(completeness.deepEquals(result.get())); + assertTrue(completeness.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIncompleteness() throws IOException { TestCompletenessParser parser = new TestCompletenessParser(); Optional result = parser.parseCompleteness(new StringReader("(...)")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCompleteness completeness = result.get(); CompletenessFullPrettyPrinter prettyPrinter = new CompletenessFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(completeness); result = parser.parseCompleteness(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(completeness.deepEquals(result.get())); + assertTrue(completeness.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testRightCompleteness() throws IOException { TestCompletenessParser parser = new TestCompletenessParser(); Optional result = parser.parseCompleteness(new StringReader("(...,c)")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCompleteness completeness = result.get(); CompletenessFullPrettyPrinter prettyPrinter = new CompletenessFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(completeness); result = parser.parseCompleteness(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(completeness.deepEquals(result.get())); + assertTrue(completeness.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLeftCompleteness() throws IOException { TestCompletenessParser parser = new TestCompletenessParser(); Optional result = parser.parseCompleteness(new StringReader("(c,...)")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCompleteness completeness = result.get(); CompletenessFullPrettyPrinter prettyPrinter = new CompletenessFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(completeness); result = parser.parseCompleteness(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(completeness.deepEquals(result.get())); + assertTrue(completeness.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/GrammarPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/GrammarPrettyPrinterTest.java index ee2d1aab6b..4bf66abff9 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/GrammarPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/GrammarPrettyPrinterTest.java @@ -5,7 +5,6 @@ import de.monticore.grammar.grammar_withconcepts.Grammar_WithConceptsMill; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,6 +15,8 @@ import java.util.Optional; import java.util.stream.Stream; +import static org.junit.jupiter.api.Assertions.*; + /** * This test checks if all (hand-written) MontiCore grammars are print-able using the generated pretty printers */ @@ -59,23 +60,23 @@ public void testPrintGrammar(Path path) throws IOException { System.err.println(path.toAbsolutePath()); Optional astOpt = Grammar_WithConceptsMill.parser().parse(path.toString()); - Assertions.assertTrue(astOpt.isPresent()); + assertTrue(astOpt.isPresent()); String pretty = Grammar_WithConceptsMill.prettyPrint(astOpt.get(), true); - Assertions.assertEquals(0, Log.getFindingsCount(), "Failed to pretty print without findings: " + path); + assertEquals(0, Log.getFindingsCount(), "Failed to pretty print without findings: " + path); Optional parsedAST = Grammar_WithConceptsMill.parser().parse_String(pretty); if (parsedAST.isEmpty()) { - Assertions.assertEquals(Files.readString(path), pretty, "Failed to parse " + path); - Assertions.fail("Failed to parse " + path); + assertEquals(Files.readString(path), pretty, "Failed to parse " + path); + fail("Failed to parse " + path); } if (!Log.getFindings().isEmpty()) { - Assertions.assertEquals(Files.readString(path), pretty, "Failed to parse " + path + " without findings"); - Assertions.fail("Failed to parse " + path + " without findings"); + assertEquals(Files.readString(path), pretty, "Failed to parse " + path + " without findings"); + fail("Failed to parse " + path + " without findings"); } if (!astOpt.get().deepEquals(parsedAST.get())) { - Assertions.assertEquals(Files.readString(path), pretty, "Failed to deep-equals " + path); - Assertions.fail("Failed to deep-equals"); + assertEquals(Files.readString(path), pretty, "Failed to deep-equals " + path); + fail("Failed to deep-equals"); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/JavaLightPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/JavaLightPrettyPrinterTest.java index 25b1d736e0..140581dc91 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/JavaLightPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/JavaLightPrettyPrinterTest.java @@ -7,15 +7,14 @@ import de.monticore.javalight._prettyprint.JavaLightFullPrettyPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class JavaLightPrettyPrinterTest { @@ -35,272 +34,272 @@ public void init() { @Test public void testMethodDeclaration() throws IOException { Optional result = parser.parse_StringMethodDeclaration("private static final int foo(String s[], boolean b)[][][] throws e.Exception { private Integer foo = a; }"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMethodDeclaration ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringMethodDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAbstractInterfaceMethod() throws IOException { Optional result = parser.parse_StringMethodDeclaration("public void foo(String s, boolean b);"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMethodDeclaration ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringMethodDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get()), "Parse pp output: " + output); + assertTrue(ast.deepEquals(result.get()), "Parse pp output: " + output); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDefaultMethod() throws IOException { Optional result = parser.parse_StringMethodDeclaration("default int foo(String s, boolean b)[][] throws e.Exception { return expr; }"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMethodDeclaration ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringMethodDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testConstructorDeclaration() throws IOException { Optional result = parser.parse_StringConstructorDeclaration("public ClassName(String s, boolean b) throws e.Exception { private Integer foo = a;}"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTConstructorDeclaration ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringConstructorDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testConstDeclaration() throws IOException { Optional result = parser.parse_StringConstDeclaration("private static Foo foo [][][] = a;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTConstDeclaration ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringConstDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testThrows() throws IOException { Optional result = parser.parse_StringThrows("a.b.c.D, person.A "); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTThrows ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringThrows(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFormalParameters() throws IOException { Optional result = parser.parse_StringFormalParameters("(public float f, int i, private ASTNode n, Float ... a)"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTFormalParameters ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringFormalParameters(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFormalParameterListing() throws IOException { Optional result = parser.parse_StringFormalParameterListing("public float f, int i, private ASTNode n, Float ... a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTFormalParameterListing ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringFormalParameterListing(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLastFormalParameter() throws IOException { Optional result = parser.parse_StringLastFormalParameter("private String ... a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTLastFormalParameter ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringLastFormalParameter(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAnnotation() throws IOException { Optional result = parser.parse_StringAnnotation("@java.util.List (a = ++a, b = {c, d})"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTAnnotation ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringAnnotation(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testAnnotationPairArguments() throws IOException { Optional result = parser.parse_StringAnnotationPairArguments("a = ++a, b = {c, d}"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTAnnotationPairArguments ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringAnnotationPairArguments(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testElementValueOrExpr() throws IOException { Optional result = parser.parse_StringElementValueOrExpr("++a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTElementValueOrExpr ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringElementValueOrExpr(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testElementValueArrayInitializer() throws IOException { Optional result = parser.parse_StringElementValueArrayInitializer("{c, d}"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTElementValueArrayInitializer ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringElementValueArrayInitializer(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testElementValuePair() throws IOException { Optional result = parser.parse_StringElementValuePair("a = ++a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTElementValuePair ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringElementValuePair(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreatorExpression2() throws IOException { Optional result = parser.parse_StringArrayDimensionByInitializer("[][]{{}}"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTArrayDimensionByInitializer ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringArrayDimensionByInitializer(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/MCCommonLiteralsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/MCCommonLiteralsPrettyPrinterTest.java index b74c299c4d..f6ed383012 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/MCCommonLiteralsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/MCCommonLiteralsPrettyPrinterTest.java @@ -7,15 +7,14 @@ import de.monticore.literals.testmccommonliterals._parser.TestMCCommonLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCCommonLiteralsPrettyPrinterTest { @@ -35,218 +34,218 @@ public void init() { @Test public void testIntLiteral() throws IOException { Optional result = parser.parse_StringNullLiteral("null"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTNullLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringNullLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFalseBooleanLiteral() throws IOException { Optional result = parser.parse_StringBooleanLiteral("true"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBooleanLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringBooleanLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testTrueBooleanLiteral() throws IOException { Optional result = parser.parse_StringBooleanLiteral("false"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBooleanLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringBooleanLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCharLiteral() throws IOException { Optional result = parser.parse_StringCharLiteral("'c'"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCharLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringCharLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testStringLiteral() throws IOException { Optional result = parser.parse_StringStringLiteral("\"something\""); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTStringLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringStringLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSignedNatLiteral() throws IOException { Optional result = parser.parse_StringSignedNatLiteral("-123456789"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTSignedNatLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringSignedNatLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBasicLongLiteral() throws IOException { Optional result = parser.parse_StringBasicLongLiteral("13745934L"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBasicLongLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringBasicLongLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSignedBasicLongLiteral() throws IOException { Optional result = parser.parse_StringSignedBasicLongLiteral("-13745934L"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTSignedBasicLongLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringSignedBasicLongLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBasicFloatLiteral() throws IOException { Optional result = parser.parse_StringBasicFloatLiteral("13745934.73649F"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBasicFloatLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringBasicFloatLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSignedBasicFloatLiteral() throws IOException { Optional result = parser.parse_StringSignedBasicFloatLiteral("-13745934.38462F"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTSignedBasicFloatLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringSignedBasicFloatLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBasicDoubleLiteral() throws IOException { Optional result = parser.parse_StringBasicDoubleLiteral("13745934.73649"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBasicDoubleLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringBasicDoubleLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSignedBasicDoubleLiteral() throws IOException { Optional result = parser.parse_StringSignedBasicDoubleLiteral("-13745934.38462"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTSignedBasicDoubleLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringSignedBasicDoubleLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/MCHexNumbersPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/MCHexNumbersPrettyPrinterTest.java index a5d81ef62a..052b2ce593 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/MCHexNumbersPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/MCHexNumbersPrettyPrinterTest.java @@ -9,7 +9,6 @@ import mchexnumbers._ast.ASTHexInteger; import mchexnumbers._ast.ASTHexadecimal; import mchexnumbers._prettyprint.MCHexNumbersFullPrettyPrinter; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,8 +16,8 @@ import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCHexNumbersPrettyPrinterTest { @@ -34,60 +33,60 @@ public void init() { public void testHexadecimal() throws IOException { TestMCHexNumbersParser parser = new TestMCHexNumbersParser(); Optional result = parser.parseHexadecimal(new StringReader("0X6b90A")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTHexadecimal hexadecimal = result.get(); MCHexNumbersFullPrettyPrinter prettyPrinter = new MCHexNumbersFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(hexadecimal); result = parser.parseHexadecimal(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(hexadecimal.deepEquals(result.get())); + assertTrue(hexadecimal.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testHexIntegerPositiv() throws IOException { TestMCHexNumbersParser parser = new TestMCHexNumbersParser(); Optional result = parser.parseHexInteger(new StringReader("0X6b90A")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTHexInteger hexinteger = result.get(); MCHexNumbersFullPrettyPrinter prettyPrinter = new MCHexNumbersFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(hexinteger); result = parser.parseHexInteger(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(hexinteger.deepEquals(result.get())); + assertTrue(hexinteger.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testHexIntegerNegative() throws IOException { TestMCHexNumbersParser parser = new TestMCHexNumbersParser(); Optional result = parser.parseHexInteger(new StringReader("-0xaf67")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTHexInteger hexinteger = result.get(); MCHexNumbersFullPrettyPrinter prettyPrinter = new MCHexNumbersFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(hexinteger); result = parser.parseHexInteger(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(hexinteger.deepEquals(result.get())); + assertTrue(hexinteger.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/MCJavaLiteralsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/MCJavaLiteralsPrettyPrinterTest.java index b08415bd12..5907a4e65f 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/MCJavaLiteralsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/MCJavaLiteralsPrettyPrinterTest.java @@ -10,15 +10,14 @@ import de.monticore.literals.testmcjavaliterals._parser.TestMCJavaLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCJavaLiteralsPrettyPrinterTest { @@ -37,75 +36,75 @@ public void init() { @Test public void testIntLiteral() throws IOException { Optional result = parser.parse_StringIntLiteral("1110"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTIntLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringIntLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLongLiteral() throws IOException { Optional result = parser.parse_StringLongLiteral("109584763l"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTLongLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringLongLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFloatLiteral() throws IOException { Optional result = parser.parse_StringFloatLiteral("93475.2434356677f"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTFloatLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringFloatLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDoubleLiteral() throws IOException { Optional result = parser.parse_StringDoubleLiteral("1110.45600233"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTDoubleLiteral ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringDoubleLiteral(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/MCNumbersPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/MCNumbersPrettyPrinterTest.java index 120853d0ba..c0302d8731 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/MCNumbersPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/MCNumbersPrettyPrinterTest.java @@ -9,7 +9,6 @@ import mcnumbers._ast.ASTDecimal; import mcnumbers._ast.ASTInteger; import mcnumbers._prettyprint.MCNumbersFullPrettyPrinter; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,8 +16,8 @@ import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCNumbersPrettyPrinterTest { @@ -34,79 +33,79 @@ public void init() { public void testDecimalZero() throws IOException { TestMCNumbersParser parser = new TestMCNumbersParser(); Optional result = parser.parseDecimal(new StringReader("0")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTDecimal decimal = result.get(); MCNumbersFullPrettyPrinter prettyPrinter = new MCNumbersFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(decimal); result = parser.parseDecimal(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(decimal.deepEquals(result.get())); + assertTrue(decimal.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDecimal() throws IOException { TestMCNumbersParser parser = new TestMCNumbersParser(); Optional result = parser.parseDecimal(new StringReader("9702")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTDecimal decimal = result.get(); MCNumbersFullPrettyPrinter prettyPrinter = new MCNumbersFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(decimal); result = parser.parseDecimal(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(decimal.deepEquals(result.get())); + assertTrue(decimal.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIntegerPositive() throws IOException { TestMCNumbersParser parser = new TestMCNumbersParser(); Optional result = parser.parseInteger(new StringReader("780530")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTInteger integer = result.get(); MCNumbersFullPrettyPrinter prettyPrinter = new MCNumbersFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(integer); result = parser.parseInteger(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(integer.deepEquals(result.get())); + assertTrue(integer.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIntegerNegative() throws IOException { TestMCNumbersParser parser = new TestMCNumbersParser(); Optional result = parser.parseInteger(new StringReader("-9702")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTInteger integer = result.get(); MCNumbersFullPrettyPrinter prettyPrinter = new MCNumbersFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(integer); result = parser.parseInteger(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(integer.deepEquals(result.get())); + assertTrue(integer.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/StringLiteralsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/StringLiteralsPrettyPrinterTest.java index 2fb3c47e36..af3334bde4 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/StringLiteralsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/StringLiteralsPrettyPrinterTest.java @@ -6,7 +6,6 @@ import de.monticore.teststringliterals._parser.TestStringLiteralsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import stringliterals._ast.ASTCharLiteral; @@ -17,8 +16,8 @@ import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class StringLiteralsPrettyPrinterTest { @@ -34,8 +33,8 @@ public void init() { public void testCharLiteralEscapeSequenz() throws IOException { TestStringLiteralsParser parser = new TestStringLiteralsParser(); Optional result = parser.parseCharLiteral(new StringReader("'\"'")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCharLiteral cliteral = result.get(); StringLiteralsFullPrettyPrinter prettyPrinter = new StringLiteralsFullPrettyPrinter( @@ -43,20 +42,20 @@ public void testCharLiteralEscapeSequenz() throws IOException { String output = prettyPrinter.prettyprint(cliteral); result = parser.parseCharLiteral(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors(), output); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors(), output); + assertTrue(result.isPresent()); - Assertions.assertTrue(cliteral.deepEquals(result.get())); + assertTrue(cliteral.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCharLiteral() throws IOException { TestStringLiteralsParser parser = new TestStringLiteralsParser(); Optional result = parser.parseCharLiteral(new StringReader("'c'")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCharLiteral cliteral = result.get(); StringLiteralsFullPrettyPrinter prettyPrinter = new StringLiteralsFullPrettyPrinter( @@ -64,12 +63,12 @@ public void testCharLiteral() throws IOException { String output = prettyPrinter.prettyprint(cliteral); result = parser.parseCharLiteral(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors(), output); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors(), output); + assertTrue(result.isPresent()); - Assertions.assertTrue(cliteral.deepEquals(result.get())); + assertTrue(cliteral.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -77,20 +76,20 @@ public void testStringLiteral() throws IOException { TestStringLiteralsParser parser = new TestStringLiteralsParser(); Optional result = parser .parseStringLiteral(new StringReader("\"Text mit 893\"")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTStringLiteral sliteral = result.get(); StringLiteralsFullPrettyPrinter prettyPrinter = new StringLiteralsFullPrettyPrinter( new IndentPrinter()); String output = prettyPrinter.prettyprint(sliteral); result = parser.parseStringLiteral(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors(), output); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors(), output); + assertTrue(result.isPresent()); - Assertions.assertTrue(sliteral.deepEquals(result.get())); + assertTrue(sliteral.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/UMLModifierPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/UMLModifierPrettyPrinterTest.java index 6b27b869e6..423ed61a22 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/UMLModifierPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/UMLModifierPrettyPrinterTest.java @@ -2,15 +2,11 @@ package de.monticore.prettyprint; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.monticore.testumlmodifier.TestUMLModifierMill; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,6 +16,9 @@ import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class UMLModifierPrettyPrinterTest { @BeforeEach @@ -34,39 +33,39 @@ public void init() { public void testModifierWord() throws IOException { TestUMLModifierParser parser = new TestUMLModifierParser(); Optional result = parser.parseModifier(new StringReader("private")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTModifier modifier = result.get(); UMLModifierFullPrettyPrinter prettyPrinter = new UMLModifierFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(modifier); result = parser.parseModifier(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(modifier.deepEquals(result.get())); + assertTrue(modifier.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testModifierSymbol() throws IOException { TestUMLModifierParser parser = new TestUMLModifierParser(); Optional result = parser.parseModifier(new StringReader("-")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTModifier modifier = result.get(); UMLModifierFullPrettyPrinter prettyPrinter = new UMLModifierFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(modifier); result = parser.parseModifier(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(modifier.deepEquals(result.get())); + assertTrue(modifier.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/prettyprint/UMLStereotypePrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/prettyprint/UMLStereotypePrettyPrinterTest.java index 80ca703916..d744bd7bf1 100644 --- a/monticore-grammar/src/test/java/de/monticore/prettyprint/UMLStereotypePrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/prettyprint/UMLStereotypePrettyPrinterTest.java @@ -2,14 +2,11 @@ package de.monticore.prettyprint; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.StringReader; import java.util.Optional; import de.monticore.testumlstereotype.TestUMLStereotypeMill; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import de.monticore.umlstereotype._prettyprint.UMLStereotypeFullPrettyPrinter; import de.monticore.testumlstereotype._parser.TestUMLStereotypeParser; @@ -19,6 +16,9 @@ import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class UMLStereotypePrettyPrinterTest { @BeforeEach @@ -38,39 +38,39 @@ public void setUp() { public void testStereotype() throws IOException { TestUMLStereotypeParser parser = new TestUMLStereotypeParser(); Optional result = parser.parseStereotype(new StringReader("<>")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTStereotype stereotype = result.get(); UMLStereotypeFullPrettyPrinter prettyPrinter = new UMLStereotypeFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(stereotype); result = parser.parseStereotype(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(stereotype.deepEquals(result.get())); + assertTrue(stereotype.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testStereoValue() throws IOException { TestUMLStereotypeParser parser = new TestUMLStereotypeParser(); Optional result = parser.parseStereoValue(new StringReader("s1=\"S1\"")); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTStereoValue stereovalue = result.get(); UMLStereotypeFullPrettyPrinter prettyPrinter = new UMLStereotypeFullPrettyPrinter(new IndentPrinter()); String output = prettyPrinter.prettyprint(stereovalue); result = parser.parseStereoValue(new StringReader(output)); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(stereovalue.deepEquals(result.get())); + assertTrue(stereovalue.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/regex/regularexpressions/cocos/RangeHasLowerOrUpperBoundTest.java b/monticore-grammar/src/test/java/de/monticore/regex/regularexpressions/cocos/RangeHasLowerOrUpperBoundTest.java index 790e11d745..5106b33f26 100644 --- a/monticore-grammar/src/test/java/de/monticore/regex/regularexpressions/cocos/RangeHasLowerOrUpperBoundTest.java +++ b/monticore-grammar/src/test/java/de/monticore/regex/regularexpressions/cocos/RangeHasLowerOrUpperBoundTest.java @@ -8,7 +8,6 @@ import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,8 @@ import java.util.Optional; import java.util.stream.Collectors; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class RangeHasLowerOrUpperBoundTest { @@ -51,10 +50,10 @@ protected void checkValid(String expressionString) throws IOException { CombineExpressionsWithLiteralsParser parser = new CombineExpressionsWithLiteralsParser(); Optional optAST = parser.parse_StringRegExLiteral(expressionString); - Assertions.assertTrue(optAST.isPresent()); + assertTrue(optAST.isPresent()); Log.getFindings().clear(); checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty(), Log.getFindings().stream() + assertTrue(Log.getFindings().isEmpty(), Log.getFindings().stream() .map(Finding::buildMsg) .collect(Collectors.joining(System.lineSeparator()))); } @@ -63,10 +62,10 @@ protected void checkInvalid(String expressionString) throws IOException { CombineExpressionsWithLiteralsParser parser = new CombineExpressionsWithLiteralsParser(); Optional optAST = parser.parse_StringRegExLiteral(expressionString); - Assertions.assertTrue(optAST.isPresent()); + assertTrue(optAST.isPresent()); Log.getFindings().clear(); checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); + assertFalse(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/AssertIsValidTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/AssertIsValidTest.java index c4e42803e3..13b5151547 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/AssertIsValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/AssertIsValidTest.java @@ -5,68 +5,82 @@ import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; import de.monticore.statements.testmcassertstatements.TestMCAssertStatementsMill; import de.monticore.statements.testmcassertstatements._cocos.TestMCAssertStatementsCoCoChecker; -import de.monticore.statements.testmcassertstatements._parser.TestMCAssertStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.FullDeriveFromCombineExpressionsWithLiterals; -import de.monticore.types.check.TypeCalculator; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static de.monticore.statements.testmcassertstatements.TestMCAssertStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +class AssertIsValidTest { -public class AssertIsValidTest { - - protected TestMCAssertStatementsCoCoChecker checker; - @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCAssertStatementsMill.reset(); TestMCAssertStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCAssertStatementsCoCoChecker(); - checker.setTraverser(TestMCAssertStatementsMill.traverser()); - checker.addCoCo(new AssertIsValid(new TypeCalculator(null, new FullDeriveFromCombineExpressionsWithLiterals()))); } - - public void checkValid(String expressionString) throws IOException { - - TestMCAssertStatementsParser parser = new TestMCAssertStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + @ParameterizedTest + @ValueSource(strings = { + "assert 5 >= 0;", + "assert !(true||false)&&(5<6);", + // todo enable after https://git.rwth-aachen.de/monticore/monticore/-/issues/4423 + //"assert 5 >= 0: 1+1;" + }) + void testValid(String expr) throws IOException { + // Given + TestMCAssertStatementsCoCoChecker checker = new TestMCAssertStatementsCoCoChecker(); + checker.addCoCo(new AssertIsValid()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - - public void checkInvalid(String expressionString) throws IOException { - - TestMCAssertStatementsParser parser = new TestMCAssertStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - - } - - @Test - public void testValid() throws IOException { - checkValid("assert 5 >= 0;"); - checkValid("assert !(true||false)&&(5<6);"); - checkValid("assert 5 >= 0: 1+1;"); + + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCAssertStatementsCoCoChecker checker = new TestMCAssertStatementsCoCoChecker(); + checker.addCoCo(new AssertIsValid()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } - - @Test - public void testInvalid() throws IOException { - checkInvalid("assert 4;"); - checkInvalid("assert 'c';"); + + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("assert 4;", AssertIsValid.ERROR_CODE), + arguments("assert 'c';", AssertIsValid.ERROR_CODE), + arguments("assert true + 1; ", "0xB0163") + ); } - -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/CatchIsValidTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/CatchIsValidTest.java index 6072cf9b67..836c808930 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/CatchIsValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/CatchIsValidTest.java @@ -1,4 +1,4 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements.cocos.CatchIsValid; @@ -7,48 +7,53 @@ import de.monticore.statements.testmccommonstatements._symboltable.ITestMCCommonStatementsScope; import de.monticore.statements.testmcexceptionstatements.TestMCExceptionStatementsMill; import de.monticore.statements.testmcexceptionstatements._cocos.TestMCExceptionStatementsCoCoChecker; -import de.monticore.statements.testmcexceptionstatements._parser.TestMCExceptionStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.*; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeOfObject; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.statements.testmcexceptionstatements.TestMCExceptionStatementsMill.*; +import static de.monticore.statements.testmcfulljavastatements.TestMCFullJavaStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; -public class CatchIsValidTest { - - protected TestMCExceptionStatementsCoCoChecker checker; +class CatchIsValidTest { @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCExceptionStatementsMill.reset(); TestMCExceptionStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCExceptionStatementsCoCoChecker(); - checker.setTraverser(TestMCExceptionStatementsMill.traverser()); - checker.addCoCo(new CatchIsValid(new TypeCalculator(null, new FullDeriveFromCombineExpressionsWithLiterals()))); - - SymTypeOfObject sType = SymTypeExpressionFactory.createTypeObject("java.lang.Throwable", TestMCExceptionStatementsMill.globalScope()); - SymTypeOfObject sTypeA = SymTypeExpressionFactory.createTypeObject("A", TestMCExceptionStatementsMill.globalScope()); + // Define Throwable hierarchy (java.lang.Throwable) + SymTypeOfObject throwableType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.lang.Throwable", globalScope()); + SymTypeOfObject aType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("A", globalScope()); - TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill. - oOTypeSymbolBuilder() - .setName("A") - .addSuperTypes(sType) - .build()); + globalScope().add( + oOTypeSymbolBuilder() + .setName("A") + .setSpannedScope(globalScope()) + .addSuperTypes(throwableType) + .build() + ); + // Setup java.lang structure ITestMCCommonStatementsScope javaScope = TestMCCommonStatementsMill.scope(); javaScope.setName("java"); @@ -59,82 +64,94 @@ public void init() { TestMCCommonStatementsMill.globalScope().addSubScope(javaScope); langScope.add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("Throwable") - .build()); - - TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .fieldSymbolBuilder() - .setName("a") - .setType(sTypeA) - .build()); - - SymTypeOfObject symType = SymTypeExpressionFactory.createTypeObject("java.lang.Object", TestMCExceptionStatementsMill.globalScope()); - SymTypeOfObject symTypeB = SymTypeExpressionFactory.createTypeObject("B", TestMCExceptionStatementsMill.globalScope()); - - TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("B") - .addSuperTypes(symType) - .build()); + oOTypeSymbolBuilder() + .setName("Throwable") + .setSpannedScope(globalScope()) + .build() + ); + + // Field of type A + globalScope().add( + fieldSymbolBuilder() + .setName("a") + .setType(aType) + .build() + ); + + // Create Object hierarchy for invalid type + SymTypeOfObject objectType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.lang.Object", globalScope()); + SymTypeOfObject bType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("B", globalScope()); + + globalScope().add( + oOTypeSymbolBuilder() + .setName("B") + .setSpannedScope(globalScope()) + .addSuperTypes(objectType) + .build() + ); langScope.add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("Object") - .build()); - - TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .fieldSymbolBuilder() - .setName("b") - .setType(symTypeB) - .build()); + oOTypeSymbolBuilder() + .setName("Object") + .setSpannedScope(globalScope()) + .build() + ); + + globalScope().add( + fieldSymbolBuilder() + .setName("b") + .setType(bType) + .build() + ); } - public void checkValid(String expressionString) throws IOException { - TestMCExceptionStatementsParser parser = TestMCExceptionStatementsMill.parser(); + @ParameterizedTest + @ValueSource(strings = { "catch(A a) {}" }) + void testValid(String expr) throws IOException { + // Given + TestMCExceptionStatementsCoCoChecker checker = new TestMCExceptionStatementsCoCoChecker(); + checker.addCoCo(new CatchIsValid()); + + ASTCatchClause ast = parser().parse_StringCatchClause(expr).orElseThrow(); - Optional optAST = parser.parse_StringCatchClause(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTCatchClause ast = optAST.get(); + ast.setEnclosingScope(globalScope()); + ast.getCatchTypeList().setEnclosingScope(globalScope()); + ast.getCatchTypeList().forEachMCQualifiedNames(n -> n.setEnclosingScope(globalScope())); - ast.setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - ast.getCatchTypeList().setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - ast.getCatchTypeList().forEachMCQualifiedNames(n -> n.setEnclosingScope(TestMCExceptionStatementsMill.globalScope())); + // When + checker.checkAll(ast); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - public void checkInvalid(String expressionString) throws IOException { - TestMCExceptionStatementsParser parser = new TestMCExceptionStatementsParser(); + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCExceptionStatementsCoCoChecker checker = new TestMCExceptionStatementsCoCoChecker(); + checker.addCoCo(new CatchIsValid()); - Optional optAST = parser.parse_StringCatchClause(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTCatchClause ast = optAST.get(); + ASTCatchClause ast = parser().parse_StringCatchClause(expr).orElseThrow(); - ast.setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - ast.getCatchTypeList().setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - ast.getCatchTypeList().forEachMCQualifiedNames(n -> n.setEnclosingScope(TestMCExceptionStatementsMill.globalScope())); + ast.setEnclosingScope(globalScope()); + ast.getCatchTypeList().setEnclosingScope(globalScope()); + ast.getCatchTypeList().forEachMCQualifiedNames(n -> n.setEnclosingScope(globalScope())); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - } + // When + checker.checkAll(ast); - @Test - public void testValid() throws IOException { - checkValid("catch(A a) {}"); + // Then + assertEquals(List.of(error), Log.getFindings() + .stream() + .map(f -> f.getMsg().substring(0, 7)) + .collect(Collectors.toList()) + ); } - @Test - public void testInvalid() throws IOException { - checkInvalid("catch (B b) {}"); + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("catch(B b) {}", CatchIsValid.ERROR_CODE) + ); } - -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/DoWhileConditionHasBooleanTypeTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/DoWhileConditionHasBooleanTypeTest.java index 1584e9bb28..fa218102aa 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/DoWhileConditionHasBooleanTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/DoWhileConditionHasBooleanTypeTest.java @@ -1,79 +1,87 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.statements.cocos; +import de.monticore.statements.mccommonstatements.cocos.AssertIsValid; import de.monticore.statements.mccommonstatements.cocos.DoWhileConditionHasBooleanType; import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; import de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill; import de.monticore.statements.testmccommonstatements._cocos.TestMCCommonStatementsCoCoChecker; -import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.FullDeriveFromCombineExpressionsWithLiterals; -import de.monticore.types.check.TypeCalculator; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +class DoWhileConditionHasBooleanTypeTest { -public class DoWhileConditionHasBooleanTypeTest { - - protected TestMCCommonStatementsCoCoChecker checker; - @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCCommonStatementsMill.reset(); TestMCCommonStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCCommonStatementsCoCoChecker(); - checker.addCoCo(new DoWhileConditionHasBooleanType(new TypeCalculator(null,new FullDeriveFromCombineExpressionsWithLiterals()))); - } - - public void checkValid(String expressionString) throws IOException { - - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); - } - - public void checkInvalid(String expressionString) throws IOException { - - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - + + @ParameterizedTest + @ValueSource(strings = { + "do{}while(5>6);", + "do{}while(true||false);", + "do{}while(!true&&(5==6));" + }) + void testValid(String expr) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new DoWhileConditionHasBooleanType()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - - @Test - public void testValid() throws IOException { - - checkValid("do{}while(5>6);"); - checkValid("do{}while(true||false);"); - checkValid("do{}while(!true&&(5==6));"); - + + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new DoWhileConditionHasBooleanType()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } - - @Test - public void testInvalid() throws IOException { - - checkInvalid("do{}while(5+5);"); - checkInvalid("do{}while('c');"); - checkInvalid("do{}while(1.2-3.4);"); - + + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("do{}while(5+5);", DoWhileConditionHasBooleanType.ERROR_CODE), + arguments("do{}while('c');", DoWhileConditionHasBooleanType.ERROR_CODE), + arguments("do{}while(1.2-3.4);", DoWhileConditionHasBooleanType.ERROR_CODE), + arguments("do{}while(true + 1);", "0xB0163") + ); } - -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ExpressionStatementIsValidTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ExpressionStatementIsValidTest.java index 2c13a2480c..bc394c8b30 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ExpressionStatementIsValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ExpressionStatementIsValidTest.java @@ -1,88 +1,103 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements.cocos.ExpressionStatementIsValid; import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; import de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill; import de.monticore.statements.testmccommonstatements._cocos.TestMCCommonStatementsCoCoChecker; -import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.monticore.statements.testmccommonstatements._visitor.TestMCCommonStatementsTraverser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.oosymbols._symboltable.FieldSymbol; import de.monticore.types.check.FlatExpressionScopeSetter; -import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -public class ExpressionStatementIsValidTest { +import static de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill.*; +import static de.monticore.types.check.SymTypeExpressionFactory.createPrimitive; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; - protected TestMCCommonStatementsCoCoChecker checker; +class ExpressionStatementIsValidTest { @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCCommonStatementsMill.reset(); TestMCCommonStatementsMill.init(); - TestMCCommonStatementsMill.globalScope().clear(); CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); initSymbols(); - - checker = new TestMCCommonStatementsCoCoChecker(); - checker.addCoCo(new ExpressionStatementIsValid()); } - protected static void initSymbols() { - FieldSymbol anInt = TestMCCommonStatementsMill.fieldSymbolBuilder() - .setName("anInt") - .setType(SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT)) - .setEnclosingScope(TestMCCommonStatementsMill.globalScope()) + private static void initSymbols() { + FieldSymbol anInt = fieldSymbolBuilder().setName("anInt") + .setType(createPrimitive(BasicSymbolsMill.INT)) + .setEnclosingScope(globalScope()) .setAstNodeAbsent() .build(); - TestMCCommonStatementsMill.globalScope().add(anInt); + globalScope().add(anInt); } - public void checkValid(String expressionString) throws IOException { - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional ast = parser.parse_StringMCBlockStatement(expressionString); + @ParameterizedTest + @ValueSource(strings = { + "anInt = 5;" + }) + void testValid(String expr) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new ExpressionStatementIsValid()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); - TestMCCommonStatementsTraverser traverser = TestMCCommonStatementsMill.inheritanceTraverser(); - FlatExpressionScopeSetter scopeSetter = new FlatExpressionScopeSetter(TestMCCommonStatementsMill.globalScope()); - traverser.add4ExpressionsBasis(scopeSetter); - ast.orElseThrow().accept(traverser); + TestMCCommonStatementsTraverser traverser = inheritanceTraverser(); + traverser.add4ExpressionsBasis(new FlatExpressionScopeSetter(globalScope())); + ast.accept(traverser); - checker.checkAll(ast.orElseThrow()); - Assertions.assertTrue(Log.getFindings().isEmpty(), Log.getFindings().toString()); + // When + checker.checkAll(ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - public void checkInvalid(String expressionString) throws IOException { - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional ast = parser.parse_StringMCBlockStatement(expressionString); + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new ExpressionStatementIsValid()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); - TestMCCommonStatementsTraverser traverser = TestMCCommonStatementsMill.inheritanceTraverser(); - FlatExpressionScopeSetter scopeSetter = new FlatExpressionScopeSetter(TestMCCommonStatementsMill.globalScope()); - traverser.add4ExpressionsBasis(scopeSetter); - ast.orElseThrow().accept(traverser); + TestMCCommonStatementsTraverser traverser = inheritanceTraverser(); + traverser.add4ExpressionsBasis(new FlatExpressionScopeSetter(globalScope())); + ast.accept(traverser); - checker.checkAll(ast.orElseThrow()); - Assertions.assertFalse(Log.getFindings().isEmpty(), Log.getFindings().toString()); - } + // When + checker.checkAll(ast); - @Test - public void testIsValid() throws IOException { - checkValid("anInt = 5;"); + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } - @Test - public void testIsInvalid() throws IOException { - checkInvalid("anInt = true;"); + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("anInt = true;", "0xA0179") + ); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ForConditionHasBooleanTypeTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ForConditionHasBooleanTypeTest.java index 9a5d07f474..2020d17e67 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ForConditionHasBooleanTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ForConditionHasBooleanTypeTest.java @@ -1,76 +1,84 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements.cocos.ForConditionHasBooleanType; import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; import de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill; import de.monticore.statements.testmccommonstatements._cocos.TestMCCommonStatementsCoCoChecker; -import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.FullDeriveFromCombineExpressionsWithLiterals; -import de.monticore.types.check.TypeCalculator; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +class ForConditionHasBooleanTypeTest { -public class ForConditionHasBooleanTypeTest { - - protected TestMCCommonStatementsCoCoChecker checker; - @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCCommonStatementsMill.reset(); TestMCCommonStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCCommonStatementsCoCoChecker(); - checker.addCoCo(new ForConditionHasBooleanType(new TypeCalculator(null,new FullDeriveFromCombineExpressionsWithLiterals()))); } - public void checkValid(String expressionString) throws IOException { - - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); - - } - - public void checkInvalid(String expressionString) throws IOException { - - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - + @ParameterizedTest + @ValueSource(strings = { + "for(5; true; 5+1){}", + "for(5; 5<6; 5+1){}", + "for(5; !(false || true) && (6==7); 5+1){}" + }) + void testValid(String expr) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new ForConditionHasBooleanType()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - - @Test - public void testValid() throws IOException { - - checkValid("for(5; true;5+1){}"); - checkValid("for(5; 5<6;5+1){}"); - checkValid("for(5; !(false || true) && (6==7);5+1){}"); - + + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new ForConditionHasBooleanType()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } - - @Test - public void testInvalid() throws IOException { - - checkInvalid("for(1+1;2+2;'x'){}"); - + + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("for(i = 0; 2 + 2; i++){}", ForConditionHasBooleanType.ERROR_CODE), + arguments("for(i = 0; true + 1; i++){}", "0xB0163") + ); } -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ForEachIsValidTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ForEachIsValidTest.java index f87ccdcce8..bcc72b3442 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ForEachIsValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ForEachIsValidTest.java @@ -1,51 +1,61 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements._ast.ASTEnhancedForControl; import de.monticore.statements.mccommonstatements.cocos.ForEachIsValid; import de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill; import de.monticore.statements.testmccommonstatements._cocos.TestMCCommonStatementsCoCoChecker; -import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.monticore.statements.testmccommonstatements._symboltable.ITestMCCommonStatementsScope; import de.monticore.statements.testmccommonstatements._visitor.TestMCCommonStatementsTraverser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.*; +import de.monticore.types.check.FlatExpressionScopeSetter; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeOfObject; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; +import static de.monticore.types3.util.DefsTypesForTests.inScope; +import static de.monticore.types3.util.DefsTypesForTests.oOtype; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; -public class ForEachIsValidTest { - - protected TestMCCommonStatementsCoCoChecker checker; +class ForEachIsValidTest { @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCCommonStatementsMill.reset(); TestMCCommonStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCCommonStatementsCoCoChecker(); - checker.addCoCo(new ForEachIsValid(new TypeCalculator(new FullSynthesizeFromCombineExpressionsWithLiterals(), new FullDeriveFromCombineExpressionsWithLiterals()))); - - SymTypeOfObject iterableType = SymTypeExpressionFactory.createTypeObject("java.lang.Iterable", TestMCCommonStatementsMill.globalScope()); - SymTypeOfObject aObjectType = SymTypeExpressionFactory.createTypeObject("A", TestMCCommonStatementsMill.globalScope()); + // Prepare type and symbol setup + SymTypeOfObject iterableType = + SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.lang.Iterable", TestMCCommonStatementsMill.globalScope()); + SymTypeOfObject aObjectType = + SymTypeExpressionFactory.createTypeObjectViaSurrogate("A", TestMCCommonStatementsMill.globalScope()); TestMCCommonStatementsMill.globalScope().add(TestMCCommonStatementsMill - .oOTypeSymbolBuilder() - .setName("A") - .addSuperTypes(iterableType) - .build()); + .oOTypeSymbolBuilder() + .setName("A") + .setSpannedScope(TestMCCommonStatementsMill.scope()) + .addSuperTypes(iterableType) + .build()); ITestMCCommonStatementsScope javaScope = TestMCCommonStatementsMill.scope(); javaScope.setName("java"); @@ -57,93 +67,99 @@ public void init() { javaScope.addSubScope(langScope); langScope.add(TestMCCommonStatementsMill - .oOTypeSymbolBuilder() - .setName("Iterable") - .build()); + .oOTypeSymbolBuilder() + .setName("Iterable") + .setSpannedScope(TestMCCommonStatementsMill.scope()) + .build()); ITestMCCommonStatementsScope utilScope = TestMCCommonStatementsMill.scope(); utilScope.setName("util"); - javaScope.addSubScope(utilScope); utilScope.add(TestMCCommonStatementsMill - .oOTypeSymbolBuilder().setName("Arrays") - .build()); + .oOTypeSymbolBuilder() + .setName("Arrays") + .setSpannedScope(TestMCCommonStatementsMill.scope()) + .build()); TestMCCommonStatementsMill.globalScope().add(TestMCCommonStatementsMill - .fieldSymbolBuilder() - .setName("a") - .setType(aObjectType) - .build()); + .fieldSymbolBuilder() + .setName("a") + .setType(aObjectType) + .build()); - SymTypeOfObject objectType = SymTypeExpressionFactory.createTypeObject("Object", TestMCCommonStatementsMill.globalScope()); - TestMCCommonStatementsMill.globalScope().add(TestMCCommonStatementsMill - .oOTypeSymbolBuilder() - .setName("Object") - .build()); + SymTypeOfObject objectType = createTypeObject(inScope(TestMCCommonStatementsMill.globalScope(), oOtype("Object"))); TestMCCommonStatementsMill.globalScope().add(TestMCCommonStatementsMill - .fieldSymbolBuilder() - .setName("o") - .setType(objectType) - .build()); + .fieldSymbolBuilder() + .setName("o") + .setType(objectType) + .build()); } private void addToTraverser(TestMCCommonStatementsTraverser traverser, ITestMCCommonStatementsScope enclosingScope) { - FlatExpressionScopeSetter flatExpressionScopeSetter = new FlatExpressionScopeSetter(enclosingScope); - traverser.add4ExpressionsBasis(flatExpressionScopeSetter); - traverser.add4CommonExpressions(flatExpressionScopeSetter); - traverser.add4MCBasicTypes(flatExpressionScopeSetter); - traverser.add4MCCollectionTypes(flatExpressionScopeSetter); - traverser.add4MCArrayTypes(flatExpressionScopeSetter); - traverser.add4MCCommonLiterals(flatExpressionScopeSetter); + FlatExpressionScopeSetter scopeSetter = new FlatExpressionScopeSetter(enclosingScope); + traverser.add4ExpressionsBasis(scopeSetter); + traverser.add4CommonExpressions(scopeSetter); + traverser.add4MCBasicTypes(scopeSetter); + traverser.add4MCCollectionTypes(scopeSetter); + traverser.add4MCArrayTypes(scopeSetter); + traverser.add4MCCommonLiterals(scopeSetter); } - public void checkValid(String expressionString) throws IOException { - TestMCCommonStatementsParser parser = TestMCCommonStatementsMill.parser(); - Optional optAST = parser.parse_StringEnhancedForControl(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTEnhancedForControl ast = optAST.get(); + @ParameterizedTest + @ValueSource(strings = {"Object o : a"}) + void testValid(String expr) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new ForEachIsValid()); + + ASTEnhancedForControl ast = TestMCCommonStatementsMill.parser() + .parse_StringEnhancedForControl(expr) + .orElseThrow(); TestMCCommonStatementsTraverser traverser = TestMCCommonStatementsMill.traverser(); addToTraverser(traverser, TestMCCommonStatementsMill.globalScope()); ast.accept(traverser); ast.setEnclosingScope(TestMCCommonStatementsMill.globalScope()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + // When + checker.checkAll(ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - public void checkInvalid(String expressionString) throws IOException { - TestMCCommonStatementsParser parser = TestMCCommonStatementsMill.parser(); - Optional optAST = parser.parse_StringEnhancedForControl(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTEnhancedForControl ast = optAST.get(); + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new ForEachIsValid()); + + ASTEnhancedForControl ast = TestMCCommonStatementsMill.parser() + .parse_StringEnhancedForControl(expr) + .orElseThrow(); TestMCCommonStatementsTraverser traverser = TestMCCommonStatementsMill.traverser(); addToTraverser(traverser, TestMCCommonStatementsMill.globalScope()); ast.accept(traverser); - ast.setEnclosingScope(TestMCCommonStatementsMill.globalScope()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - } - @Test - public void testValid() throws IOException { - checkValid("Object o : a"); - } + // When + checker.checkAll(ast); - @Test - public void testInvalid() throws IOException { - checkInvalid("Object o : 3"); + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } - @Test - public void testInvalid2() throws IOException { - checkInvalid("Object o : o"); + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("Object o : 3", ForEachIsValid.ERROR_CODE), + arguments("Object o : o", ForEachIsValid.ERROR_CODE), + arguments("Object o : true + 1", "0xB0163") + ); } - -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/IfConditionHasBooleanTypeTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/IfConditionHasBooleanTypeTest.java index 3b6c3c8817..e9edc884e9 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/IfConditionHasBooleanTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/IfConditionHasBooleanTypeTest.java @@ -1,79 +1,87 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements.cocos.IfConditionHasBooleanType; import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; import de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill; import de.monticore.statements.testmccommonstatements._cocos.TestMCCommonStatementsCoCoChecker; -import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.FullDeriveFromCombineExpressionsWithLiterals; -import de.monticore.types.check.TypeCalculator; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +class IfConditionHasBooleanTypeTest { -public class IfConditionHasBooleanTypeTest { - - protected TestMCCommonStatementsCoCoChecker checker; - @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCCommonStatementsMill.reset(); TestMCCommonStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCCommonStatementsCoCoChecker(); - checker.addCoCo(new IfConditionHasBooleanType(new TypeCalculator(null,new FullDeriveFromCombineExpressionsWithLiterals()))); - } - - public void checkValid(String expressionString) throws IOException { - - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); - } - - public void checkInvalid(String expressionString) throws IOException { - - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - + + @ParameterizedTest + @ValueSource(strings = { + "if(true){}", + "if(1<2){}", + "if(!true&&(5==6)){}", + "if((1<2)||(5%2==1)){}" + }) + void testValid(String expr) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new IfConditionHasBooleanType()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - - @Test - public void testValid() throws IOException{ - - checkValid("if(true){}"); - checkValid("if(1<2){}"); - checkValid("if(!true&&(5==6)){}"); - checkValid("if((1<2)||(5%2==1)){}"); - + + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new IfConditionHasBooleanType()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } - - @Test - public void testInvalid()throws IOException{ - - checkInvalid("if(1+1){}"); - checkInvalid("if('c'+10){}"); - checkInvalid("if(1.2-5.5){}"); - + + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("if(1+1){}", IfConditionHasBooleanType.ERROR_CODE), + arguments("if('c'+10){}", IfConditionHasBooleanType.ERROR_CODE), + arguments("if(1.2-5.5){}", IfConditionHasBooleanType.ERROR_CODE), + arguments("if(true + 1){}", "0xB0163") + ); } -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ResourceInTryStatementCloseableTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ResourceInTryStatementCloseableTest.java index 84c78ebb43..cf5f6c7640 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ResourceInTryStatementCloseableTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ResourceInTryStatementCloseableTest.java @@ -1,4 +1,4 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements.cocos.ResourceInTryStatementCloseable; @@ -9,130 +9,151 @@ import de.monticore.statements.testmccommonstatements._symboltable.ITestMCCommonStatementsScope; import de.monticore.statements.testmcexceptionstatements.TestMCExceptionStatementsMill; import de.monticore.statements.testmcexceptionstatements._cocos.TestMCExceptionStatementsCoCoChecker; -import de.monticore.statements.testmcexceptionstatements._parser.TestMCExceptionStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.*; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeOfObject; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.statements.testmcexceptionstatements.TestMCExceptionStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; -public class ResourceInTryStatementCloseableTest { - - protected TestMCExceptionStatementsCoCoChecker checker; +class ResourceInTryStatementCloseableTest { @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCExceptionStatementsMill.reset(); TestMCExceptionStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCExceptionStatementsCoCoChecker(); - checker.setTraverser(TestMCExceptionStatementsMill.traverser()); - checker.addCoCo(new ResourceInTryStatementCloseable(new TypeCalculator(null, new FullDeriveFromCombineExpressionsWithLiterals()))); - - SymTypeOfObject sType = SymTypeExpressionFactory.createTypeObject("java.io.Closeable", TestMCExceptionStatementsMill.globalScope()); - SymTypeOfObject sTypeA = SymTypeExpressionFactory.createTypeObject("A", TestMCExceptionStatementsMill.globalScope()); + // Setup type hierarchy + SymTypeOfObject closeableType = + SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.io.Closeable", TestMCExceptionStatementsMill.globalScope()); + SymTypeOfObject typeA = + SymTypeExpressionFactory.createTypeObjectViaSurrogate("A", TestMCExceptionStatementsMill.globalScope()); + SymTypeOfObject typeB = + SymTypeExpressionFactory.createTypeObjectViaSurrogate("B", TestMCExceptionStatementsMill.globalScope()); + // Define A extending Closeable TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("A") - .addSuperTypes(sType) - .build()); + TestMCExceptionStatementsMill.oOTypeSymbolBuilder() + .setName("A") + .setSpannedScope(TestMCCommonStatementsMill.globalScope()) + .addSuperTypes(closeableType) + .build() + ); + + // Define B not extending Closeable + TestMCExceptionStatementsMill.globalScope().add( + TestMCExceptionStatementsMill.oOTypeSymbolBuilder() + .setName("B") + .setSpannedScope(TestMCCommonStatementsMill.globalScope()) + .build() + ); + // Setup java.io hierarchy ITestMCCommonStatementsScope javaScope = TestMCCommonStatementsMill.scope(); javaScope.setName("java"); - ITestMCCommonStatementsScope ioScope = TestMCCommonStatementsMill.scope(); ioScope.setName("io"); - javaScope.addSubScope(ioScope); TestMCCommonStatementsMill.globalScope().addSubScope(javaScope); ioScope.add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("Closeable") - .build()); + TestMCExceptionStatementsMill.oOTypeSymbolBuilder() + .setName("Closeable") + .setSpannedScope(TestMCCommonStatementsMill.globalScope()) + .build() + ); + // Add fields TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .fieldSymbolBuilder() - .setName("a") - .setType(sTypeA) - .build()); - - SymTypeOfObject sTypeB = SymTypeExpressionFactory.createTypeObject("B", TestMCExceptionStatementsMill.globalScope()); - - TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("B") - .build()); - + TestMCExceptionStatementsMill.fieldSymbolBuilder() + .setName("a") + .setType(typeA) + .build() + ); TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .fieldSymbolBuilder() - .setName("b") - .setType(sTypeB) - .build()); + TestMCExceptionStatementsMill.fieldSymbolBuilder() + .setName("b") + .setType(typeB) + .build() + ); } - public void checkValid(String expressionString) throws IOException { - TestMCExceptionStatementsParser parser = TestMCExceptionStatementsMill.parser(); - - Optional optAST = parser.parse_StringTryStatement3(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTTryStatement3 ast = optAST.get(); + @ParameterizedTest + @ValueSource(strings = { + "try(A c = a){}" + }) + void testValid(String expr) throws IOException { + // Given + TestMCExceptionStatementsCoCoChecker checker = new TestMCExceptionStatementsCoCoChecker(); + checker.setTraverser(TestMCExceptionStatementsMill.traverser()); + checker.addCoCo(new ResourceInTryStatementCloseable()); + ASTTryStatement3 ast = parser().parse_StringTryStatement3(expr).orElseThrow(); ast.setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); for (ASTTryLocalVariableDeclaration dec : ast.getTryLocalVariableDeclarationList()) { dec.getExpression().setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - - Log.getFindings().clear(); - checker.checkAll((ASTMCExceptionStatementsNode) optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); } - } - public void checkInvalid(String expressionString) throws IOException { - TestMCExceptionStatementsParser parser = TestMCExceptionStatementsMill.parser(); + Log.getFindings().clear(); + + // When + checker.checkAll((ASTMCExceptionStatementsNode) ast); - Optional optAST = parser.parse_StringTryStatement3(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTTryStatement3 ast = optAST.get(); + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); + } + + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCExceptionStatementsCoCoChecker checker = new TestMCExceptionStatementsCoCoChecker(); + checker.setTraverser(TestMCExceptionStatementsMill.traverser()); + checker.addCoCo(new ResourceInTryStatementCloseable()); + ASTTryStatement3 ast = parser().parse_StringTryStatement3(expr).orElseThrow(); ast.setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); for (ASTTryLocalVariableDeclaration dec : ast.getTryLocalVariableDeclarationList()) { dec.getExpression().setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - - Log.getFindings().clear(); - checker.checkAll((ASTMCExceptionStatementsNode) optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); } - } - @Test - public void testValid() throws IOException { - checkValid("try(A c = a){}"); - } + Log.getFindings().clear(); - @Test - public void testInvalid() throws IOException { - checkInvalid("try(B c = b){}"); + // When + checker.checkAll((ASTMCExceptionStatementsNode) ast); + + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("try(B c = b){}", ResourceInTryStatementCloseable.ERROR_CODE), + arguments("try(B c = true + 1){}", "0xB0163") + ); + } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/SwitchStatementValidTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/SwitchStatementValidTest.java index a8b082dcee..7fe98e455e 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/SwitchStatementValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/SwitchStatementValidTest.java @@ -1,4 +1,4 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements._symboltable.IMCCommonStatementsArtifactScope; @@ -7,111 +7,154 @@ import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; import de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill; import de.monticore.statements.testmccommonstatements._cocos.TestMCCommonStatementsCoCoChecker; -import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.monticore.statements.testmccommonstatements._visitor.TestMCCommonStatementsTraverser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.types.check.FlatExpressionScopeSetter; -import de.monticore.types.check.FullDeriveFromCombineExpressionsWithLiterals; import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types.check.TypeCalculator; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +class SwitchStatementValidTest { -public class SwitchStatementValidTest { - - protected TestMCCommonStatementsCoCoChecker checker; - @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCCommonStatementsMill.reset(); TestMCCommonStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCCommonStatementsCoCoChecker(); - checker.addCoCo(new SwitchStatementValid(new TypeCalculator(null,new FullDeriveFromCombineExpressionsWithLiterals()))); - } - - public void checkValid(String expressionString) throws IOException { - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); } - - public void checkInvalid(String expressionString) throws IOException { - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); + + @ParameterizedTest + @ValueSource(strings = { + "switch(5){}", + "switch('c'){}" + }) + void testValid(String expr) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new SwitchStatementValid()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - - @Test - public void testValid() throws IOException { - checkValid("switch(5){}"); - checkValid("switch('c'){}"); + + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new SwitchStatementValid()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } - - @Test - public void testInvalid() throws IOException { - checkInvalid("switch(5.5){}"); - checkInvalid("switch(5.5F){}"); - checkInvalid("switch(false){}"); + + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("switch(5.5){}", SwitchStatementValid.ERROR_CODE), + arguments("switch(5.5F){}", SwitchStatementValid.ERROR_CODE), + arguments("switch(false){}", SwitchStatementValid.ERROR_CODE) + ); } - @Test - public void testSwitchEnumConstants() throws IOException { - IMCCommonStatementsArtifactScope imported - = new MCCommonStatementsSymbols2Json().load("src/test/resources/de/monticore/statements/Enum.sym"); + @ParameterizedTest + @ValueSource(strings = {"switch(c){}"}) + void testSwitchEnumConstantsValid(String expr) throws IOException { + // Given + IMCCommonStatementsArtifactScope imported = + new MCCommonStatementsSymbols2Json().load("src/test/resources/de/monticore/statements/Enum.sym"); + TestMCCommonStatementsMill.globalScope().addSubScope(imported); - TestMCCommonStatementsMill - .globalScope() - .addSubScope(imported); + VariableSymbol variable = TestMCCommonStatementsMill.variableSymbolBuilder() + .setName("c") + .setType(SymTypeExpressionFactory.createTypeObject(imported.resolveOOType("A").orElseThrow())) + .build(); - VariableSymbol variable1 = TestMCCommonStatementsMill.variableSymbolBuilder() - .setName("c") - .setType(SymTypeExpressionFactory.createTypeObject(imported.resolveOOType("A").get())) - .build(); - TestMCCommonStatementsMill.globalScope().getVariableSymbols().put(variable1.getName() , variable1); + TestMCCommonStatementsMill.globalScope().add(variable); - VariableSymbol variable2 = TestMCCommonStatementsMill.variableSymbolBuilder() - .setName("d") - .setType(SymTypeExpressionFactory.createTypeObject(imported.resolveOOType("B").get())) - .build(); - TestMCCommonStatementsMill.globalScope().getVariableSymbols().put(variable2.getName() , variable2); + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new SwitchStatementValid()); - TestMCCommonStatementsParser parser = TestMCCommonStatementsMill.parser(); - Optional optAST1 = parser.parse_StringMCBlockStatement("switch(c){}"); - Assertions.assertTrue(optAST1.isPresent()); - ASTMCBlockStatement ast1 = optAST1.get(); + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); TestMCCommonStatementsTraverser traverser = TestMCCommonStatementsMill.traverser(); traverser.add4ExpressionsBasis(new FlatExpressionScopeSetter(TestMCCommonStatementsMill.globalScope())); - ast1.accept(traverser); + ast.accept(traverser); - Log.getFindings().clear(); - checker.checkAll(ast1); - Assertions.assertTrue(Log.getFindings().isEmpty()); + // When + checker.checkAll(ast); - Optional optAST2 = parser.parse_StringMCBlockStatement("switch(d){}"); - Assertions.assertTrue(optAST2.isPresent()); - ASTMCBlockStatement ast2 = optAST2.get(); + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); + } + + @ParameterizedTest + @MethodSource("enumExprAndErrorProvider") + void testSwitchEnumConstantsInvalid(String expr, String error) throws IOException { + // Given + IMCCommonStatementsArtifactScope imported = + new MCCommonStatementsSymbols2Json().load("src/test/resources/de/monticore/statements/Enum.sym"); + TestMCCommonStatementsMill.globalScope().addSubScope(imported); + + VariableSymbol variable = TestMCCommonStatementsMill.variableSymbolBuilder() + .setName("d") + .setType(SymTypeExpressionFactory.createTypeObject(imported.resolveOOType("B").orElseThrow())) + .build(); + + TestMCCommonStatementsMill.globalScope().add(variable); + + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new SwitchStatementValid()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); - ast2.accept(traverser); + TestMCCommonStatementsTraverser traverser = TestMCCommonStatementsMill.traverser(); + traverser.add4ExpressionsBasis(new FlatExpressionScopeSetter(TestMCCommonStatementsMill.globalScope())); + ast.accept(traverser); + + // When + checker.checkAll(ast); + + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); + } - checker.checkAll(ast2); - Assertions.assertEquals(1, Log.getFindings().size()); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith(SwitchStatementValid.ERROR_CODE)); + static Stream enumExprAndErrorProvider() { + return Stream.of( + arguments("switch(d){}", SwitchStatementValid.ERROR_CODE), + arguments("switch(true + 1){}", "0xB0163") + ); } -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/SynchronizedArgIsReftypeTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/SynchronizedArgIsReftypeTest.java index 1ea5805053..373631e7dd 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/SynchronizedArgIsReftypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/SynchronizedArgIsReftypeTest.java @@ -1,4 +1,4 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements.cocos.SynchronizedArgIsReftype; @@ -7,80 +7,103 @@ import de.monticore.statements.testmcexceptionstatements.TestMCExceptionStatementsMill; import de.monticore.statements.testmcsynchronizedstatements.TestMCSynchronizedStatementsMill; import de.monticore.statements.testmcsynchronizedstatements._cocos.TestMCSynchronizedStatementsCoCoChecker; -import de.monticore.statements.testmcsynchronizedstatements._parser.TestMCSynchronizedStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.*; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeOfObject; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.statements.testmcsynchronizedstatements.TestMCSynchronizedStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; -public class SynchronizedArgIsReftypeTest { +class SynchronizedArgIsReftypeTest { - protected TestMCSynchronizedStatementsCoCoChecker checker; - @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCSynchronizedStatementsMill.reset(); TestMCSynchronizedStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCSynchronizedStatementsCoCoChecker(); - checker.addCoCo(new SynchronizedArgIsReftype(new TypeCalculator(null, new FullDeriveFromCombineExpressionsWithLiterals()))); - SymTypeOfObject sType = SymTypeExpressionFactory.createTypeObject("java.lang.Object", TestMCExceptionStatementsMill.globalScope()); - TestMCExceptionStatementsMill.globalScope().add(TestMCExceptionStatementsMill.oOTypeSymbolBuilder().setName("java.lang.Object").build()); - TestMCExceptionStatementsMill.globalScope().add(TestMCExceptionStatementsMill.fieldSymbolBuilder().setName("a1").setType(sType).build()); + SymTypeOfObject objectType = + SymTypeExpressionFactory.createTypeObjectViaSurrogate( + "java.lang.Object", + TestMCExceptionStatementsMill.globalScope() + ); + + TestMCExceptionStatementsMill.globalScope().add( + TestMCExceptionStatementsMill.oOTypeSymbolBuilder() + .setName("java.lang.Object") + .build() + ); + + TestMCExceptionStatementsMill.globalScope().add( + TestMCExceptionStatementsMill.fieldSymbolBuilder() + .setName("a1") + .setType(objectType) + .build() + ); } - public void checkValid(String expressionString) throws IOException { + @ParameterizedTest + @ValueSource(strings = {"synchronized(a1){}"}) + void testValid(String expr) throws IOException { + // Given + TestMCSynchronizedStatementsCoCoChecker checker = new TestMCSynchronizedStatementsCoCoChecker(); + checker.addCoCo(new SynchronizedArgIsReftype()); - TestMCSynchronizedStatementsParser parser = new TestMCSynchronizedStatementsParser(); - Optional optAST = parser.parse_StringSynchronizedStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTSynchronizedStatement ast = optAST.get(); + ASTSynchronizedStatement ast = parser().parse_StringSynchronizedStatement(expr).orElseThrow(); ast.getExpression().setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - Log.getFindings().clear(); - checker.checkAll((ASTMCSynchronizedStatementsNode) optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + // When + checker.checkAll((ASTMCSynchronizedStatementsNode) ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - public void checkInvalid(String expressionString) throws IOException { + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCSynchronizedStatementsCoCoChecker checker = new TestMCSynchronizedStatementsCoCoChecker(); + checker.addCoCo(new SynchronizedArgIsReftype()); - TestMCSynchronizedStatementsParser parser = new TestMCSynchronizedStatementsParser(); - Optional optAST = parser.parse_StringSynchronizedStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTSynchronizedStatement ast = optAST.get(); + ASTSynchronizedStatement ast = parser().parse_StringSynchronizedStatement(expr).orElseThrow(); ast.getExpression().setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - Log.getFindings().clear(); - checker.checkAll((ASTMCSynchronizedStatementsNode) optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - - } - - @Test - public void testValid() throws IOException { - checkValid("synchronized(a1){}"); + // When + checker.checkAll((ASTMCSynchronizedStatementsNode) ast); + // Then + assertEquals(List.of(error), Log.getFindings() + .stream() + .map(f -> f.getMsg().substring(0, 7)) + .collect(Collectors.toList()) + ); } - @Test - public void testInvalid() throws IOException { - - checkInvalid("synchronized('f'){}"); - checkInvalid("synchronized(5.5){}"); - checkInvalid("synchronized(false){}"); - + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("synchronized('f'){}", SynchronizedArgIsReftype.ERROR_CODE), + arguments("synchronized(5.5){}", SynchronizedArgIsReftype.ERROR_CODE), + arguments("synchronized(false){}", SynchronizedArgIsReftype.ERROR_CODE), + arguments("synchronized(true + 1){}", "0xB0163") + ); } - -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ThrowIsValidTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ThrowIsValidTest.java index 2e98ccb366..4f7dc79d0c 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/ThrowIsValidTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/ThrowIsValidTest.java @@ -1,4 +1,4 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements.cocos.ThrowIsValid; @@ -8,121 +8,139 @@ import de.monticore.statements.testmccommonstatements._symboltable.ITestMCCommonStatementsScope; import de.monticore.statements.testmcexceptionstatements.TestMCExceptionStatementsMill; import de.monticore.statements.testmcexceptionstatements._cocos.TestMCExceptionStatementsCoCoChecker; -import de.monticore.statements.testmcexceptionstatements._parser.TestMCExceptionStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.*; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.types.check.SymTypeOfObject; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.statements.testmcexceptionstatements.TestMCExceptionStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; -public class ThrowIsValidTest { - - protected TestMCExceptionStatementsCoCoChecker checker; +class ThrowIsValidTest { @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCExceptionStatementsMill.reset(); TestMCExceptionStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCExceptionStatementsCoCoChecker(); - checker.setTraverser(TestMCExceptionStatementsMill.traverser()); - checker.addCoCo(new ThrowIsValid(new TypeCalculator(null, new FullDeriveFromCombineExpressionsWithLiterals()))); - - SymTypeOfObject sType = SymTypeExpressionFactory.createTypeObject("java.lang.Throwable", TestMCExceptionStatementsMill.globalScope()); - SymTypeOfObject sTypeA = SymTypeExpressionFactory.createTypeObject("A", TestMCExceptionStatementsMill.globalScope()); + // Define basic Throwable and hierarchy + SymTypeOfObject throwableType = + SymTypeExpressionFactory.createTypeObjectViaSurrogate("java.lang.Throwable", TestMCExceptionStatementsMill.globalScope()); + SymTypeOfObject aType = + SymTypeExpressionFactory.createTypeObjectViaSurrogate("A", TestMCExceptionStatementsMill.globalScope()); + SymTypeOfObject bType = + SymTypeExpressionFactory.createTypeObjectViaSurrogate("B", TestMCExceptionStatementsMill.globalScope()); + // A extends Throwable TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("A") - .addSuperTypes(sType) - .build()); + TestMCExceptionStatementsMill.oOTypeSymbolBuilder() + .setName("A") + .setSpannedScope(TestMCCommonStatementsMill.globalScope()) + .addSuperTypes(throwableType) + .build() + ); + + // B does not extend Throwable + TestMCExceptionStatementsMill.globalScope().add( + TestMCExceptionStatementsMill.oOTypeSymbolBuilder() + .setName("B") + .setSpannedScope(TestMCCommonStatementsMill.globalScope()) + .build() + ); ITestMCCommonStatementsScope javaScope = TestMCCommonStatementsMill.scope(); javaScope.setName("java"); - ITestMCCommonStatementsScope langScope = TestMCCommonStatementsMill.scope(); langScope.setName("lang"); TestMCCommonStatementsMill.globalScope().addSubScope(javaScope); javaScope.addSubScope(langScope); - langScope.add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("Throwable") - .build()); - - TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .fieldSymbolBuilder() - .setName("a") - .setType(sTypeA) - .build()); - - SymTypeOfObject sTypeB = SymTypeExpressionFactory.createTypeObject("B", TestMCExceptionStatementsMill.globalScope()); + langScope.add(TestMCExceptionStatementsMill.oOTypeSymbolBuilder() + .setName("Throwable") + .setSpannedScope(TestMCCommonStatementsMill.globalScope()) + .build()); + // Add variables a and b TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .oOTypeSymbolBuilder() - .setName("B") - .build()); + TestMCExceptionStatementsMill.fieldSymbolBuilder() + .setName("a") + .setType(aType) + .build() + ); TestMCExceptionStatementsMill.globalScope().add( - TestMCExceptionStatementsMill - .fieldSymbolBuilder() - .setName("b") - .setType(sTypeB) - .build()); + TestMCExceptionStatementsMill.fieldSymbolBuilder() + .setName("b") + .setType(bType) + .build() + ); } - public void checkValid(String expressionString) throws IOException { + @ParameterizedTest + @ValueSource(strings = {"throw a;"}) + void testValid(String expr) throws IOException { + // Given + TestMCExceptionStatementsCoCoChecker checker = new TestMCExceptionStatementsCoCoChecker(); + checker.setTraverser(TestMCExceptionStatementsMill.traverser()); + checker.addCoCo(new ThrowIsValid()); - TestMCExceptionStatementsParser parser = new TestMCExceptionStatementsParser(); - Optional optAST = parser.parse_StringThrowStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTThrowStatement ast = optAST.get(); + ASTThrowStatement ast = parser().parse_StringThrowStatement(expr).orElseThrow(); ast.setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); ast.getExpression().setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - Log.getFindings().clear(); - checker.checkAll((ASTMCExceptionStatementsNode) optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + // When + checker.checkAll((ASTMCExceptionStatementsNode) ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - public void checkInvalid(String expressionString) throws IOException { + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCExceptionStatementsCoCoChecker checker = new TestMCExceptionStatementsCoCoChecker(); + checker.setTraverser(TestMCExceptionStatementsMill.traverser()); + checker.addCoCo(new ThrowIsValid()); - TestMCExceptionStatementsParser parser = new TestMCExceptionStatementsParser(); - Optional optAST = parser.parse_StringThrowStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - ASTThrowStatement ast = optAST.get(); + ASTThrowStatement ast = parser().parse_StringThrowStatement(expr).orElseThrow(); ast.setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); ast.getExpression().setEnclosingScope(TestMCExceptionStatementsMill.globalScope()); - Log.getFindings().clear(); - checker.checkAll((ASTMCExceptionStatementsNode) optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); - } + // When + checker.checkAll((ASTMCExceptionStatementsNode) ast); - @Test - public void testValid() throws IOException { - checkValid("throw a;"); + // Then + assertEquals(List.of(error), Log.getFindings() + .stream() + .map(f -> f.getMsg().substring(0, 7)) + .collect(Collectors.toList())); } - @Test - public void testInvalid() throws IOException { - checkInvalid("throw b;"); + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("throw b;", ThrowIsValid.ERROR_CODE), + arguments("throw true + 1;", "0xB0163") + ); } -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/VarDeclarationInitializationHasCorrectTypeTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/VarDeclarationInitializationHasCorrectTypeTest.java index 95a6a9aff1..7983623a3c 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/VarDeclarationInitializationHasCorrectTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/VarDeclarationInitializationHasCorrectTypeTest.java @@ -1,53 +1,44 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; -import com.google.common.collect.Lists; import de.monticore.statements.mcvardeclarationstatements._cocos.VarDeclarationInitializationHasCorrectType; import de.monticore.statements.mcvardeclarationstatements._symboltable.MCVarDeclarationStatementsSTCompleteTypes; import de.monticore.statements.testmcvardeclarationstatements.TestMCVarDeclarationStatementsMill; import de.monticore.statements.testmcvardeclarationstatements._ast.ASTRootVarDeclaration; import de.monticore.statements.testmcvardeclarationstatements._cocos.TestMCVarDeclarationStatementsCoCoChecker; -import de.monticore.statements.testmcvardeclarationstatements._parser.TestMCVarDeclarationStatementsParser; import de.monticore.statements.testmcvardeclarationstatements._visitor.TestMCVarDeclarationStatementsTraverser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; -import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; +import static de.monticore.statements.testmcvardeclarationstatements.TestMCVarDeclarationStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; -public class VarDeclarationInitializationHasCorrectTypeTest { - - protected TestMCVarDeclarationStatementsCoCoChecker checker; - protected TestMCVarDeclarationStatementsParser parser; +class VarDeclarationInitializationHasCorrectTypeTest { @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCVarDeclarationStatementsMill.reset(); TestMCVarDeclarationStatementsMill.init(); - - TestMCVarDeclarationStatementsMill.globalScope().clear(); CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); addMyTypeToGlobalScope(); addStringToGlobalScope(); - - checker = new TestMCVarDeclarationStatementsCoCoChecker(); - checker.setTraverser(TestMCVarDeclarationStatementsMill.traverser()); - checker.addCoCo(new VarDeclarationInitializationHasCorrectType()); - parser = new TestMCVarDeclarationStatementsParser(); } protected static void addMyTypeToGlobalScope() { @@ -68,61 +59,62 @@ protected static void addStringToGlobalScope() { TestMCVarDeclarationStatementsMill.globalScope().addSubScope(type.getSpannedScope()); } - protected void checkExpectedErrors(ASTRootVarDeclaration decl, List expectedErrorCodes) { - TestMCVarDeclarationStatementsMill.scopesGenitorDelegator().createFromAST(decl); + protected ASTRootVarDeclaration parseAndBuildAST(String decl) throws IOException { + ASTRootVarDeclaration ast = parser().parse_StringRootVarDeclaration(decl).orElseThrow(); + TestMCVarDeclarationStatementsMill.scopesGenitorDelegator().createFromAST(ast); TestMCVarDeclarationStatementsTraverser completerTraverser = TestMCVarDeclarationStatementsMill.traverser(); completerTraverser.add4MCVarDeclarationStatements(new MCVarDeclarationStatementsSTCompleteTypes()); - decl.accept(completerTraverser); - // We must manually set a name for the ArtifactScope. Else we get an exception. - decl.getEnclosingScope().setName("Foo"); - - // When - checker.checkAll(decl); - - // Then - List actualErrors = Log.getFindings().stream() - .filter(Finding::isError) - .map(err -> err.getMsg().split(" ")[0]) - .collect(Collectors.toList()); - Assertions.assertEquals(expectedErrorCodes, actualErrors); + ast.accept(completerTraverser); + ast.getEnclosingScope().setName("Foo"); + return ast; } @Test - public void testValidMultiVarDeclaration() throws IOException { + void testValidMultiVarDeclaration() throws IOException { // Given - String multiVarDeclaration = "int a = 10, b, c = -12;"; - List expectedErrors = new ArrayList<>(); - ASTRootVarDeclaration astDecl = parser.parse_StringRootVarDeclaration(multiVarDeclaration).get(); + TestMCVarDeclarationStatementsCoCoChecker checker = new TestMCVarDeclarationStatementsCoCoChecker(); + checker.addCoCo(new VarDeclarationInitializationHasCorrectType()); + + ASTRootVarDeclaration ast = parseAndBuildAST("int a = 10, b, c = -12;"); + + // When + checker.checkAll(ast); - // When & Then - checkExpectedErrors(astDecl, expectedErrors); + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - @Test - public void testInvalidMultiVarDeclaration() throws IOException { + @ParameterizedTest + @MethodSource("invalidExpressionAndErrorProvider") + void testInvalidDeclarations(String declaration, List expectedErrors) throws IOException { // Given - String multiVarDeclaration = "int a = \"oh no\", b = 10, c, d = \"no no no\";"; - List expectedErrors = Lists.newArrayList( - VarDeclarationInitializationHasCorrectType.ERROR_CODE, - VarDeclarationInitializationHasCorrectType.ERROR_CODE - ); - ASTRootVarDeclaration astDecl = parser.parse_StringRootVarDeclaration(multiVarDeclaration).get(); + TestMCVarDeclarationStatementsCoCoChecker checker = new TestMCVarDeclarationStatementsCoCoChecker(); + checker.addCoCo(new VarDeclarationInitializationHasCorrectType()); + ASTRootVarDeclaration ast = parseAndBuildAST(declaration); + + // When + checker.checkAll(ast); - // When & Then - checkExpectedErrors(astDecl, expectedErrors); + // Then + List actualErrors = Log.getFindings().stream() + .map(f -> f.getMsg().substring(0, 7)) + .collect(Collectors.toList()); + assertEquals(expectedErrors, actualErrors); } - @Test - public void testInvalidMultiVarDeclarationWithTypeReference() throws IOException { - // Given - String multiVarDeclaration = "int a = 3, b, c = MyType, d = \"no no no\";"; - List expectedErrors = Lists.newArrayList( - "0xFD118", - VarDeclarationInitializationHasCorrectType.ERROR_CODE + static Stream invalidExpressionAndErrorProvider() { + return Stream.of( + arguments( + "int a = \"oh no\", b = 10, c, d = \"no no no\";", + List.of( + VarDeclarationInitializationHasCorrectType.ERROR_CODE, + VarDeclarationInitializationHasCorrectType.ERROR_CODE + ) + ), + arguments( + "int a = 3, b, c = MyType, d = \"no no no\";", + List.of("0xFD118", VarDeclarationInitializationHasCorrectType.ERROR_CODE) + ) ); - ASTRootVarDeclaration astDecl = parser.parse_StringRootVarDeclaration(multiVarDeclaration).get(); - - // When & Then - checkExpectedErrors(astDecl, expectedErrors); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/VarDeclarationNameAlreadyDefinedInScopeTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/VarDeclarationNameAlreadyDefinedInScopeTest.java new file mode 100644 index 0000000000..680f630a0a --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/VarDeclarationNameAlreadyDefinedInScopeTest.java @@ -0,0 +1,104 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.statements.cocos; + +import de.monticore.statements.mcvardeclarationstatements._cocos.VarDeclarationNameAlreadyDefinedInScope; +import de.monticore.statements.mcvardeclarationstatements._symboltable.MCVarDeclarationStatementsSTCompleteTypes; +import de.monticore.statements.testmcvardeclarationstatements.TestMCVarDeclarationStatementsMill; +import de.monticore.statements.testmcvardeclarationstatements._ast.ASTRootVarDeclaration; +import de.monticore.statements.testmcvardeclarationstatements._cocos.TestMCVarDeclarationStatementsCoCoChecker; +import de.monticore.statements.testmcvardeclarationstatements._visitor.TestMCVarDeclarationStatementsTraverser; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; +import static de.monticore.statements.testmcvardeclarationstatements.TestMCVarDeclarationStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class VarDeclarationNameAlreadyDefinedInScopeTest { + + @BeforeEach + void init() { + LogStub.init(); + Log.enableFailQuick(false); + TestMCVarDeclarationStatementsMill.reset(); + TestMCVarDeclarationStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); + BasicSymbolsMill.initializePrimitives(); + } + + protected ASTRootVarDeclaration parseAndBuildAST(String decl) throws IOException { + ASTRootVarDeclaration ast = parser().parse_StringRootVarDeclaration(decl).orElseThrow(); + TestMCVarDeclarationStatementsMill.scopesGenitorDelegator().createFromAST(ast); + TestMCVarDeclarationStatementsTraverser completerTraverser = TestMCVarDeclarationStatementsMill.traverser(); + completerTraverser.add4MCVarDeclarationStatements(new MCVarDeclarationStatementsSTCompleteTypes()); + ast.accept(completerTraverser); + return ast; + } + + @Test + void testValidMultiVarDeclaration() throws IOException { + // Given + TestMCVarDeclarationStatementsCoCoChecker checker = new TestMCVarDeclarationStatementsCoCoChecker(); + checker.addCoCo(new VarDeclarationNameAlreadyDefinedInScope()); + + ASTRootVarDeclaration astDecl = parseAndBuildAST("int a = 10, b, c = -12;"); + + // When + checker.checkAll(astDecl); + + // Then + assertNoFindings(); + } + + @Test + void testInvalidMultiVarDeclarationWithoutValue() throws IOException { + // Given + TestMCVarDeclarationStatementsCoCoChecker checker = new TestMCVarDeclarationStatementsCoCoChecker(); + checker.addCoCo(new VarDeclarationNameAlreadyDefinedInScope()); + + ASTRootVarDeclaration astDecl = parseAndBuildAST("int a = 10, a, a = -12;"); + + List expected = List.of( + VarDeclarationNameAlreadyDefinedInScope.ERROR_CODE, + VarDeclarationNameAlreadyDefinedInScope.ERROR_CODE, + VarDeclarationNameAlreadyDefinedInScope.ERROR_CODE + ); + + // When + checker.checkAll(astDecl); + + // Then + assertEquals(expected, Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); + } + + @Test + void testInvalidVarDeclarationWithSymbolInScope() throws IOException { + // Given + TestMCVarDeclarationStatementsCoCoChecker checker = new TestMCVarDeclarationStatementsCoCoChecker(); + checker.addCoCo(new VarDeclarationNameAlreadyDefinedInScope()); + + ASTRootVarDeclaration astDecl = parseAndBuildAST("int a = 10;"); + astDecl.getEnclosingScope().add(TestMCVarDeclarationStatementsMill.variableSymbolBuilder() + .setName("a") + .setEnclosingScope(astDecl.getEnclosingScope()) + .build()); + + // When + checker.checkAll(astDecl); + + // Then + assertEquals(List.of(VarDeclarationNameAlreadyDefinedInScope.ERROR_CODE), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/cocos/WhileConditionHasBooleanTypeTest.java b/monticore-grammar/src/test/java/de/monticore/statements/cocos/WhileConditionHasBooleanTypeTest.java index cc4fd31ad2..711bf24304 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/cocos/WhileConditionHasBooleanTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/cocos/WhileConditionHasBooleanTypeTest.java @@ -1,72 +1,87 @@ -/* (c) https://github.com/MontiCore/monticore */ +/* (c) [https://github.com/MontiCore/monticore](https://github.com/MontiCore/monticore) */ package de.monticore.statements.cocos; import de.monticore.statements.mccommonstatements.cocos.WhileConditionHasBooleanType; import de.monticore.statements.mcstatementsbasis._ast.ASTMCBlockStatement; import de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill; import de.monticore.statements.testmccommonstatements._cocos.TestMCCommonStatementsCoCoChecker; -import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.types.check.FullDeriveFromCombineExpressionsWithLiterals; -import de.monticore.types.check.TypeCalculator; +import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; -import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static de.monticore.statements.testmccommonstatements.TestMCCommonStatementsMill.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +class WhileConditionHasBooleanTypeTest { -public class WhileConditionHasBooleanTypeTest { - - protected TestMCCommonStatementsCoCoChecker checker; - @BeforeEach - public void init() { + void init() { LogStub.init(); Log.enableFailQuick(false); TestMCCommonStatementsMill.reset(); TestMCCommonStatementsMill.init(); + CombineExpressionsWithLiteralsTypeTraverserFactory.initTypeCheck3(); BasicSymbolsMill.initializePrimitives(); - checker = new TestMCCommonStatementsCoCoChecker(); - checker.addCoCo(new WhileConditionHasBooleanType(new TypeCalculator(null,new FullDeriveFromCombineExpressionsWithLiterals()))); - } - - public void checkValid(String expressionString) throws IOException { - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); } - - public void checkInvalid(String expressionString) throws IOException { - TestMCCommonStatementsParser parser = new TestMCCommonStatementsParser(); - Optional optAST = parser.parse_StringMCBlockStatement(expressionString); - Assertions.assertTrue(optAST.isPresent()); - Log.getFindings().clear(); - checker.checkAll(optAST.get()); - Assertions.assertFalse(Log.getFindings().isEmpty()); + + @ParameterizedTest + @ValueSource(strings = { + "while(true){}", + "while(1<2){}", + "while(!true&&(5==6)){}", + "while((1<2)||(5%2==1)){}" + }) + void testValid(String expr) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new WhileConditionHasBooleanType()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertTrue(Log.getFindings().isEmpty(), () -> Log.getFindings().toString()); } - - @Test - public void testValid() throws IOException{ - checkValid("while(true){}"); - checkValid("while(1<2){}"); - checkValid("while(!true&&(5==6)){}"); - checkValid("while((1<2)||(5%2==1)){}"); + + @ParameterizedTest + @MethodSource("exprAndErrorProvider") + void testInvalid(String expr, String error) throws IOException { + // Given + TestMCCommonStatementsCoCoChecker checker = new TestMCCommonStatementsCoCoChecker(); + checker.addCoCo(new WhileConditionHasBooleanType()); + + ASTMCBlockStatement ast = parser().parse_StringMCBlockStatement(expr).orElseThrow(); + + // When + checker.checkAll(ast); + + // Then + assertEquals(List.of(error), Log.getFindings() + .stream().map(f -> f.getMsg().substring(0, 7)).collect(Collectors.toList()) + ); } - - @Test - public void testInvalid()throws IOException{ - checkInvalid("while(1+1){}"); - checkInvalid("while('c'+10){}"); - checkInvalid("while(1.2-5.5){}"); + + static Stream exprAndErrorProvider() { + return Stream.of( + arguments("while(1+1){}", WhileConditionHasBooleanType.ERROR_CODE), + arguments("while('c'+10){}", WhileConditionHasBooleanType.ERROR_CODE), + arguments("while(1.2-5.5){}", WhileConditionHasBooleanType.ERROR_CODE), + arguments("while(true + 1){}", "0xB0163") + ); } - -} \ No newline at end of file +} diff --git a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCArrayStatementsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCArrayStatementsPrettyPrinterTest.java index fb27b74ed9..d1c45040e5 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCArrayStatementsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCArrayStatementsPrettyPrinterTest.java @@ -9,13 +9,14 @@ import de.monticore.statements.testmcarraystatements._parser.TestMCArrayStatementsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCArrayStatementsPrettyPrinterTest { private TestMCArrayStatementsParser parser = new TestMCArrayStatementsParser(); @@ -36,38 +37,38 @@ public void init() { public void testArrayInit() throws IOException { String input = "{a, b, foo}"; Optional result = parser.parse_StringArrayInit(input); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTArrayInit ast = result.get(); String output = prettyPrinter.prettyprint(ast); - Assertions.assertEquals(input.replaceAll(" ", ""), output.replaceAll(" ", "").replaceAll("\n", "")); + assertEquals(input.replaceAll(" ", ""), output.replaceAll(" ", "").replaceAll("\n", "")); result = parser.parse_StringArrayInit(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testArrayDeclaratorId() throws IOException { Optional result = parser.parse_StringArrayDeclaratorId("a [] []"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTArrayDeclaratorId ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringArrayDeclaratorId(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCCommonStatementsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCCommonStatementsPrettyPrinterTest.java index 280fc5857a..c8e17e10ac 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCCommonStatementsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCCommonStatementsPrettyPrinterTest.java @@ -12,15 +12,14 @@ import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCCommonStatementsPrettyPrinterTest { @@ -40,379 +39,379 @@ public void init() { @Test public void testBlock() throws IOException { Optional result = parser.parse_StringMCJavaBlock("{ private Integer foo = a; }"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCJavaBlock ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringMCJavaBlock(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBlockStatement() throws IOException { Optional result = parser.parse_StringMCBlockStatement("private Integer foo = a;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTMCBlockStatement ast = result.get(); ast.accept(prettyPrinter.getTraverser()); String output = prettyPrinter.getPrinter().getContent(); result = parser.parse_StringMCBlockStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLocalVariableDeclaration() throws IOException { Optional result = parser.parse_StringLocalVariableDeclaration("private Integer foo = a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTLocalVariableDeclaration ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringLocalVariableDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testVariableDeclaration() throws IOException { Optional result = parser.parse_StringVariableDeclarator("foo = a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTVariableDeclarator ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringVariableDeclarator(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDeclaratorId() throws IOException { Optional result = parser.parse_StringDeclaratorId("a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTDeclaratorId ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringDeclaratorId(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIfStatement() throws IOException { Optional result = parser.parse_StringIfStatement("if(a) ; else ;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTIfStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringIfStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testForStatement() throws IOException { Optional result = parser.parse_StringForStatement("for(i; i ; i) a;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTForStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringForStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCommonForControl() throws IOException { Optional result = parser.parse_StringCommonForControl("i; i ; i"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCommonForControl ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringCommonForControl(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testEnhancedForControl() throws IOException { Optional result = parser.parse_StringEnhancedForControl("protected List l : a"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTEnhancedForControl ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringEnhancedForControl(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFormalParameter() throws IOException { Optional result = parser.parse_StringFormalParameter("public float f"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTFormalParameter ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringFormalParameter(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testForInitByExpressions() throws IOException { Optional result = parser.parse_StringForInitByExpressions("i, b, c"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTForInitByExpressions ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringForInitByExpressions(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testWhileStatement() throws IOException { Optional result = parser.parse_StringWhileStatement("while (a) ;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTWhileStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringWhileStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDoWhileStatement() throws IOException { Optional result = parser.parse_StringDoWhileStatement("do ; while (a);"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTDoWhileStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringDoWhileStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSwitchStatement() throws IOException { Optional result = parser.parse_StringSwitchStatement("switch (a) {case b : c; default : d;}"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTSwitchStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringSwitchStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testEmptyStatement() throws IOException { Optional result = parser.parse_StringEmptyStatement(";"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTEmptyStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringEmptyStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testExpressionStatement() throws IOException { Optional result = parser.parse_StringExpressionStatement("a;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTExpressionStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringExpressionStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSwitchBlockStatementGroup() throws IOException { Optional result = parser.parse_StringSwitchBlockStatementGroup("case a: foo;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTSwitchBlockStatementGroup ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringSwitchBlockStatementGroup(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testConstantExpressionSwitchLabel() throws IOException { Optional result = parser.parse_StringConstantExpressionSwitchLabel("case a :"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTConstantExpressionSwitchLabel ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringConstantExpressionSwitchLabel(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testEnumConstantSwitchLabel() throws IOException { Optional result = parser.parse_StringEnumConstantSwitchLabel("case a :"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTEnumConstantSwitchLabel ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringEnumConstantSwitchLabel(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testDefaultSwitchLabel() throws IOException { Optional result = parser.parse_StringDefaultSwitchLabel("default :"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTDefaultSwitchLabel ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringDefaultSwitchLabel(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBreakStatement() throws IOException { Optional result = parser.parse_StringBreakStatement("break ;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTBreakStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringBreakStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCExceptionStatementsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCExceptionStatementsPrettyPrinterTest.java index be268e44ae..1f6c394b2c 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCExceptionStatementsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCExceptionStatementsPrettyPrinterTest.java @@ -8,15 +8,14 @@ import de.monticore.statements.testmcexceptionstatements._parser.TestMCExceptionStatementsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCExceptionStatementsPrettyPrinterTest { @@ -36,37 +35,37 @@ public void init() { @Test public void testTryStatement2() throws IOException { Optional result = parser.parse_StringTryStatement2(" try { Integer foo = a;} finally { Integer foo = a; }"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTTryStatement2 ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringTryStatement2(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testTryStatement1() throws IOException { Optional result = parser.parse_StringTryStatement1(" try { Integer foo = a; } catch (private static a.b.c | d.e.G foo) {Integer foo = a; }"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTTryStatement1 ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringTryStatement1(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -75,94 +74,94 @@ public void testTryStatements() throws IOException { Optional result = parser.parse_StringTryStatement3("try ( public Integer a = foo; ) " + "{ public String foo = a ;} " + "catch (private static a.b.c | d.e.G foo) { public String foo = a ;}"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTTryStatement3 ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringTryStatement3(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testTryvariableDeclaration() throws IOException { Optional result = parser.parse_StringTryLocalVariableDeclaration("public Integer a = foo"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTTryLocalVariableDeclaration ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringTryLocalVariableDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCatchClause() throws IOException { Optional result = parser.parse_StringCatchClause("catch (private static a.b.c | d.e.G foo) { public String foo = a; }"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCatchClause ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringCatchClause(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCatchType() throws IOException { Optional result = parser.parse_StringCatchTypeList(" a.b.c | d.e.G "); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTCatchTypeList ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringCatchTypeList(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testThrowStatement() throws IOException { Optional result = parser.parse_StringThrowStatement("throw Exception;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTThrowStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringThrowStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCLowLevelStatementsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCLowLevelStatementsPrettyPrinterTest.java index ba8ceb53a4..d494e92fb0 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCLowLevelStatementsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCLowLevelStatementsPrettyPrinterTest.java @@ -10,21 +10,18 @@ import de.monticore.statements.testmclowlevelstatements._parser.TestMCLowLevelStatementsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCLowLevelStatementsPrettyPrinterTest { - private TestMCLowLevelStatementsParser parser = new TestMCLowLevelStatementsParser(); - - private MCLowLevelStatementsFullPrettyPrinter prettyPrinter = new MCLowLevelStatementsFullPrettyPrinter(new IndentPrinter()); + private TestMCLowLevelStatementsParser parser; @BeforeEach public void init() { @@ -32,60 +29,60 @@ public void init() { Log.enableFailQuick(false); TestMCLowLevelStatementsMill.reset(); TestMCLowLevelStatementsMill.init(); - prettyPrinter.getPrinter().clearBuffer(); + parser = TestMCLowLevelStatementsMill.parser(); } @Test public void testBreakStatement() throws IOException { Optional result = parser.parse_StringLabelledBreakStatement("break a ;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTLabelledBreakStatement ast = result.get(); - String output = prettyPrinter.prettyprint(ast); + String output = TestMCLowLevelStatementsMill.prettyPrint(ast, true); result = parser.parse_StringLabelledBreakStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testLabeledStatement() throws IOException { Optional result = parser.parse_StringLabel("a : break foo;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTLabel ast = result.get(); - String output = prettyPrinter.prettyprint(ast); + String output = TestMCLowLevelStatementsMill.prettyPrint(ast, true); result = parser.parse_StringLabel(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testContinueStatement() throws IOException { Optional result = parser.parse_StringContinueStatement("continue foo;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTContinueStatement ast = result.get(); - String output = prettyPrinter.prettyprint(ast); + String output = TestMCLowLevelStatementsMill.prettyPrint(ast, true); result = parser.parse_StringContinueStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCReturnStatementsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCReturnStatementsPrettyPrinterTest.java index f4aad7c28c..bc60c49fae 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCReturnStatementsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCReturnStatementsPrettyPrinterTest.java @@ -8,15 +8,14 @@ import de.monticore.statements.testmcreturnstatements._parser.TestMCReturnStatementsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCReturnStatementsPrettyPrinterTest { @@ -36,18 +35,18 @@ public void init() { @Test public void testReturnStatement() throws IOException { Optional result = parser.parse_StringReturnStatement("return a ;"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTReturnStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringReturnStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCSynchronizedStatementsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCSynchronizedStatementsPrettyPrinterTest.java index 3cbb5071b1..ee2dfb3632 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCSynchronizedStatementsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCSynchronizedStatementsPrettyPrinterTest.java @@ -8,15 +8,14 @@ import de.monticore.statements.testmcsynchronizedstatements._parser.TestMCSynchronizedStatementsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCSynchronizedStatementsPrettyPrinterTest { @@ -36,19 +35,19 @@ public void init() { @Test public void testReturnStatement() throws IOException { Optional result = parser.parse_StringSynchronizedStatement("synchronized (foo) { final Integer foo = a ;}"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTSynchronizedStatement ast = result.get(); String output = prettyPrinter.prettyprint(ast); result = parser.parse_StringSynchronizedStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCVarDeclarationStatementsPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCVarDeclarationStatementsPrettyPrinterTest.java index bbf24beea1..4b2367d3e8 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCVarDeclarationStatementsPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/MCVarDeclarationStatementsPrettyPrinterTest.java @@ -8,15 +8,14 @@ import de.monticore.statements.testmcvardeclarationstatements._parser.TestMCVarDeclarationStatementsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCVarDeclarationStatementsPrettyPrinterTest { @@ -36,20 +35,20 @@ public void init() { @Test public void testLocalVariableDeclaration() throws IOException { Optional result = parser.parse_StringLocalVariableDeclaration("List a = b, c = d"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); ASTLocalVariableDeclaration ast = result.get(); ast.accept(prettyPrinter.getTraverser()); String output = prettyPrinter.getPrinter().getContent(); result = parser.parse_StringLocalVariableDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(result.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(result.isPresent()); - Assertions.assertTrue(ast.deepEquals(result.get())); + assertTrue(ast.deepEquals(result.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/TrailingSpacesPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/TrailingSpacesPrettyPrinterTest.java index 2ad2c0fdc3..b29ea4336a 100644 --- a/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/TrailingSpacesPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/statements/prettyprint/TrailingSpacesPrettyPrinterTest.java @@ -9,13 +9,14 @@ import de.monticore.statements.testmccommonstatements._parser.TestMCCommonStatementsParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class TrailingSpacesPrettyPrinterTest { TestMCCommonStatementsParser parser; @@ -34,21 +35,21 @@ public void testSingleLineCommentEOL() throws IOException { // Scenario: An expression is string-concatenated into a statement as the initial value // First, we have to extract the inner AST node with the comment Optional blocks = parser.parse_StringMCJavaBlock("{int i1 = a // single line comment\n; int i2 = b; }"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(blocks.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(blocks.isPresent()); ASTLocalVariableDeclarationStatement setStatement = (ASTLocalVariableDeclarationStatement) blocks.get().getMCBlockStatementList().get(0); ASTExpression initialValueAST = ((ASTSimpleInit) setStatement.getLocalVariableDeclaration().getVariableDeclarator(0).getVariableInit()).getExpression(); - Assertions.assertEquals(1, initialValueAST.get_PostCommentList().size()); + assertEquals(1, initialValueAST.get_PostCommentList().size()); // print the initial value expression String initialValue = TestMCCommonStatementsMill.prettyPrint(initialValueAST, true); // and ensure the pretty printed string ends with a linebreak - Assertions.assertTrue(initialValue.endsWith("\n")); + assertTrue(initialValue.endsWith("\n")); // then test to parse this value inlined - in case no linebreak is present, this will fail Optional statement = parser.parse_StringMCJavaBlock("{int i = " + initialValue + "; int i2 = 0; }"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(statement.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(statement.isPresent()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsSymbols2JsonTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsSymbols2JsonTest.java index 464219be5c..eb12f4c30b 100644 --- a/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsSymbols2JsonTest.java +++ b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/BasicSymbolsSymbols2JsonTest.java @@ -3,17 +3,19 @@ import com.google.common.collect.Lists; +import de.monticore.runtime.junit.MCAssertions; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class BasicSymbolsSymbols2JsonTest { private IBasicSymbolsArtifactScope scope; @@ -42,7 +44,7 @@ public void init() { .setEnclosingScope(scope) .build(); - SymTypeExpression symType1 = SymTypeExpressionFactory.createTypeObject("Type", scope); + SymTypeExpression symType1 = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Type", scope); //put subtype into main scope, test if supertypes are serialized correctly TypeSymbol subtype = BasicSymbolsMill.typeSymbolBuilder() @@ -99,7 +101,7 @@ public void init() { public void testDeSer(){ performRoundTripSerialization(scope); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } public void performRoundTripSerialization(IBasicSymbolsArtifactScope scope){ @@ -108,68 +110,68 @@ public void performRoundTripSerialization(IBasicSymbolsArtifactScope scope){ String serialized = symbols2Json.serialize(scope); // then deserialize it IBasicSymbolsArtifactScope deserialized = symbols2Json.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); // and assert that the deserialized scope equals the one before //check that both can resolve the type "Type" Optional type = scope.resolveType("Type"); Optional deserializedType = deserialized.resolveType("Type"); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(deserializedType.isPresent()); + assertTrue(type.isPresent()); + assertTrue(deserializedType.isPresent()); //check that both can resolve the type "SubType" with the supertype "Type" Optional subtype = scope.resolveType("SubType"); Optional deserializedSubType = deserialized.resolveType("SubType"); - Assertions.assertTrue(subtype.isPresent()); - Assertions.assertTrue(deserializedSubType.isPresent()); - Assertions.assertEquals(1, subtype.get().getSuperTypesList().size()); - Assertions.assertEquals(1, deserializedSubType.get().getSuperTypesList().size()); - Assertions.assertEquals("Type", subtype.get().getSuperTypesList().get(0).print()); - Assertions.assertEquals("Type", deserializedSubType.get().getSuperTypesList().get(0).print()); + assertTrue(subtype.isPresent()); + assertTrue(deserializedSubType.isPresent()); + assertEquals(1, subtype.get().getSuperTypesList().size()); + assertEquals(1, deserializedSubType.get().getSuperTypesList().size()); + assertEquals("Type", subtype.get().getSuperTypesList().get(0).print()); + assertEquals("Type", deserializedSubType.get().getSuperTypesList().get(0).print()); IBasicSymbolsScope typeSpanned = type.get().getSpannedScope(); IBasicSymbolsScope deserTypeSpanned = deserializedType.get().getSpannedScope(); //check that both can resolve the TypeVariable "T" in their "Type" - Assertions.assertTrue(typeSpanned.resolveTypeVar("T").isPresent()); - Assertions.assertTrue(deserTypeSpanned.resolveTypeVar("T").isPresent()); + assertTrue(typeSpanned.resolveTypeVar("T").isPresent()); + assertTrue(deserTypeSpanned.resolveTypeVar("T").isPresent()); //check for Variable variable in Type Optional variable = typeSpanned.resolveVariable("variable"); Optional deserializedVariable = deserTypeSpanned.resolveVariable("variable"); - Assertions.assertTrue(variable.isPresent()); - Assertions.assertTrue(deserializedVariable.isPresent()); - Assertions.assertEquals("double", variable.get().getType().print()); - Assertions.assertEquals("double", deserializedVariable.get().getType().print()); + assertTrue(variable.isPresent()); + assertTrue(deserializedVariable.isPresent()); + assertEquals("double", variable.get().getType().print()); + assertEquals("double", deserializedVariable.get().getType().print()); //check for Variable variable2 in Type Optional variable2 = typeSpanned.resolveVariable("variable2"); Optional deserializedVariable2 = deserTypeSpanned.resolveVariable("variable2"); - Assertions.assertTrue(variable2.isPresent()); - Assertions.assertTrue(deserializedVariable2.isPresent()); - Assertions.assertEquals("T", variable2.get().getType().print()); - Assertions.assertEquals("T", deserializedVariable2.get().getType().print()); - Assertions.assertEquals("Type.T", variable2.get().getType().printFullName()); - Assertions.assertEquals("Type.T", deserializedVariable2.get().getType().printFullName()); - Assertions.assertSame(type.get().getSpannedScope(), variable2.get().getType().asTypeVariable().getTypeVarSymbol().getEnclosingScope()); - Assertions.assertSame(deserializedType.get().getSpannedScope(), deserializedVariable2.get().getType().asTypeVariable().getTypeVarSymbol().getEnclosingScope()); + assertTrue(variable2.isPresent()); + assertTrue(deserializedVariable2.isPresent()); + assertEquals("T", variable2.get().getType().print()); + assertEquals("T", deserializedVariable2.get().getType().print()); + assertEquals("Type.T", variable2.get().getType().printFullName()); + assertEquals("Type.T", deserializedVariable2.get().getType().printFullName()); + assertSame(type.get().getSpannedScope(), variable2.get().getType().asTypeVariable().getTypeVarSymbol().getEnclosingScope()); + assertSame(deserializedType.get().getSpannedScope(), deserializedVariable2.get().getType().asTypeVariable().getTypeVarSymbol().getEnclosingScope()); //check for Function function in Type Optional function = typeSpanned.resolveFunction("function"); Optional deserializedFunction = deserTypeSpanned.resolveFunction("function"); - Assertions.assertTrue(function.isPresent()); - Assertions.assertTrue(deserializedFunction.isPresent()); - Assertions.assertEquals("int", function.get().getType().print()); - Assertions.assertEquals("int", deserializedFunction.get().getType().print()); - - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(function.isPresent()); + assertTrue(deserializedFunction.isPresent()); + assertEquals("int", function.get().getType().print()); + assertEquals("int", deserializedFunction.get().getType().print()); + + MCAssertions.assertNoFindings(); } @Test public void testSerializedUnknownKind() { BasicSymbolsSymbols2Json symbols2Json = new BasicSymbolsSymbols2Json(); symbols2Json.deserialize("{\"symbols\": [{\"kind\":\"unknown\", \"name\":\"test\"}]}"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -180,13 +182,13 @@ public void testInvalidJsonForSerializingReturnsError(){ BasicSymbolsSymbols2Json symbols2Json = new BasicSymbolsSymbols2Json(); symbols2Json.deserialize(invalidJsonForSerializing); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xA1238")); + assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xA1238")); symbols2Json.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(1).getMsg().startsWith("0xA1233")); + assertTrue(Log.getFindings().get(1).getMsg().startsWith("0xA1233")); symbols2Json.deserialize(invalidJsonForSerializing3); - Assertions.assertTrue(Log.getFindings().get(2).getMsg().startsWith("0xA0572")); + assertTrue(Log.getFindings().get(2).getMsg().startsWith("0xA0572")); } diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolSurrogateTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolSurrogateTest.java new file mode 100644 index 0000000000..662dcf3393 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolSurrogateTest.java @@ -0,0 +1,425 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.basicsymbols._symboltable; + +import de.monticore.ast.ASTNode; +import de.monticore.interpreter.Value; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symboltable.IScope; +import de.monticore.symboltable.ISymbol; +import de.monticore.symboltable.modifiers.AccessModifier; +import de.monticore.symboltable.modifiers.BasicAccessModifier; +import de.monticore.symboltable.stereotypes.IStereotypeReference; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypeExpressionFactory; +import de.monticore.visitor.ITraverser; +import de.se_rwth.commons.SourcePosition; +import de.se_rwth.commons.logging.LogStub; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; + +/** Tests {@link TypeSymbolSurrogate} */ +public class TypeSymbolSurrogateTest { + + @BeforeEach + void setUp() { + LogStub.init(); + BasicSymbolsMill.init(); + } + + @Test + public void setSpannedScopeShouldSkipSurrogate() { + // Given + Map.Entry pair = createTypeWithSurrogate("Type"); + TypeSymbol type = pair.getKey(); + TypeSymbolSurrogate surrogate = pair.getValue(); + + IBasicSymbolsScope scopeToSet = BasicSymbolsMill.scope(); + + // When + surrogate.setSpannedScope(scopeToSet); + + // Then + assertSame(scopeToSet, type.getSpannedScope()); + } + + @Test + public void getSpannedScopeShouldSkipSurrogate() { + // Given + Map.Entry pair = createTypeWithSurrogate("Type"); + TypeSymbol type = pair.getKey(); + TypeSymbolSurrogate surrogate = pair.getValue(); + + // When + IBasicSymbolsScope scope = surrogate.getSpannedScope(); + + // Then + assertSame(type.getSpannedScope(), scope); + } + + @Test + void getSuperClassShouldSkipSurrogate() { + // Given + Map.Entry pair = createTypeWithSurrogate("Type"); + TypeSymbol type = pair.getKey(); + TypeSymbolSurrogate surrogate = pair.getValue(); + + TypeSymbol superClass = createTypeWithSurrogate("SuperClass").getKey(); + SymTypeExpression superClassExpr = SymTypeExpressionFactory.createFromSymbol(superClass); + type.setSuperTypesList(Collections.singletonList(superClassExpr)); + + // When + SymTypeExpression superClassCalculated = surrogate.getSuperClass(); + + // Then + assertSame(superClassExpr, superClassCalculated); + } + + + @Test + void setSuperClassShouldSkipSurrogate() { + // Given + Map.Entry pair = createTypeWithSurrogate("Type"); + TypeSymbol type = pair.getKey(); + TypeSymbolSurrogate surrogate = pair.getValue(); + + TypeSymbol superClass = createTypeWithSurrogate("SuperClass").getKey(); + SymTypeExpression superClassExpr = SymTypeExpressionFactory.createFromSymbol(superClass); + + // When + surrogate.setSuperTypesList(Collections.singletonList(superClassExpr)); + + // Then + assertSame(superClassExpr, type.getSuperClass()); + } + + @Test + void getTypeParameterListShouldSkipSurrogate() { + // Given + Map.Entry pair = createTypeWithSurrogate("Type"); + TypeSymbol type = pair.getKey(); + TypeSymbolSurrogate surrogate = pair.getValue(); + + TypeVarSymbol typeParam = addTypeParameterTo(type, "T"); + + // When + List typeParams = surrogate.getTypeParameterList(); + + // Then + assertArrayEquals(new TypeVarSymbol[]{typeParam}, typeParams.toArray()); + } + + @Test @SuppressWarnings({"EqualsWithItself", "ConstantConditions"}) + void equalsShouldEqualSame() { + // Given + TypeSymbolSurrogate surrogate = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type") + .setEnclosingScope(BasicSymbolsMill.scope()) + .build(); + + // When + boolean result = surrogate.equals(surrogate); + + // Then + assertTrue(result); + } + + @Test + void equalsShouldNotEqualDifferent1() { + // Given + TypeSymbolSurrogate surrogate1 = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type1") + .setEnclosingScope(BasicSymbolsMill.scope()) + .build(); + + TypeSymbolSurrogate surrogate2 = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type2") + .setEnclosingScope(BasicSymbolsMill.scope()) + .build(); + + // When + boolean result = surrogate1.equals(surrogate2); + + // Then + assertFalse(result); + } + + @Test + void equalsShouldNotEqualDifferent2() { + // Given + IBasicSymbolsScope scope = BasicSymbolsMill.scope(); + + TypeSymbol symbol1 = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type1") + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); + + scope.add(symbol1); + + TypeSymbolSurrogate surrogate1 = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type1") + .setEnclosingScope(scope) + .build(); + + TypeSymbol symbol2 = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type2") + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); + + scope.add(symbol2); + + TypeSymbolSurrogate surrogate2 = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type2") + .setEnclosingScope(scope) + .build(); + + // When + boolean result = surrogate1.equals(surrogate2); + + // Then + assertFalse(result); + } + + @Test + void equalsShouldEqualSymbol() { + // Given + IBasicSymbolsScope scope = BasicSymbolsMill.scope(); + + TypeSymbol symbol = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type") + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); + + scope.add(symbol); + + TypeSymbolSurrogate surrogate = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type") + .setEnclosingScope(scope) + .build(); + + // When + boolean result = surrogate.equals(symbol); + + // Then + assertTrue(result); + } + + @Test + void equalsShouldNotEqualSymbol() { + // Given + IBasicSymbolsScope scope = BasicSymbolsMill.scope(); + + TypeSymbol symbol = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type1") + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); + + scope.add(symbol); + + TypeSymbolSurrogate surrogate = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type2") + .setEnclosingScope(scope) + .build(); + + // When + boolean result = surrogate.equals(symbol); + + // Then + assertFalse(result); + + // When + boolean resultSymmetric = symbol.equals(surrogate); + + // Then + assertFalse(resultSymmetric); + } + + @Test + public void equalsShouldNotEqualAdapted() { + SymbolMock mock1 = new SymbolMock("Type1"); + SymbolMock mock2 = new SymbolMock("Type2"); + + IBasicSymbolsScope scope = new BasicSymbolsScopeWithAdapted(List.of(mock1, mock2)); + + // we don't use the builder because it automatically loads the delegate + TypeSymbolSurrogate surrogate1 = new TypeSymbolSurrogate("Type1"); + surrogate1.setName("Type1"); + surrogate1.setFullName("Type1"); + surrogate1.setEnclosingScope(scope); + + TypeSymbolSurrogate surrogate2 = new TypeSymbolSurrogate("Type2"); + surrogate2.setName("Type2"); + surrogate2.setFullName("Type2"); + surrogate2.setEnclosingScope(scope); + + + var result = surrogate1.equals(surrogate2); + + assertFalse(result); + } + + @Test + public void equalsShouldEqualAdapted() { + SymbolMock mock = new SymbolMock("Type1"); + + IBasicSymbolsScope scope = new BasicSymbolsScopeWithAdapted(List.of(mock)); + + // we don't use the builder because it automatically loads the delegate + TypeSymbolSurrogate surrogate1 = new TypeSymbolSurrogate("Type1"); + surrogate1.setName("Type1"); + surrogate1.setFullName("Type1"); + surrogate1.setEnclosingScope(scope); + + TypeSymbolSurrogate surrogate2 = new TypeSymbolSurrogate("Type1"); + surrogate2.setName("Type1"); + surrogate2.setFullName("Type1"); + surrogate2.setEnclosingScope(scope); + + + var result = surrogate1.equals(surrogate2); + + assertTrue(result); + } + + private static class SymbolMock implements ISymbol { + private final String name; + + SymbolMock(String name) { + this.name = name; + } + public SymbolMock getThis() { + return this; + } + public boolean equals (Object obj) { + if(!(obj instanceof SymbolMock)) { + return false; + } + SymbolMock s1 = getThis(); + SymbolMock s2 = ((SymbolMock) obj).getThis(); + + return s1 == s2; + } + + @Override + public String getName() { + return name; + } + // Boilerplate + @Override + public String getPackageName() { + return null; + } + @Override + public String getFullName() { + return null; + } + @Override + public IScope getEnclosingScope() { + return null; + } + @Override + public void setAccessModifier(AccessModifier accessModifier) { + } + @Override + public Map> getStereoinfo() { + return null; + } + @Override + public boolean isPresentAstNode() { + return false; + } + @Override + public ASTNode getAstNode() { + return null; + } + @Override + public SourcePosition getSourcePosition() { + return null; + } + @Override + public void accept(ITraverser visitor) { + } + } + + private static class SymbolMock2TypeSymbolAdapter extends TypeSymbol { + private final SymbolMock adaptee; + SymbolMock2TypeSymbolAdapter(SymbolMock adaptee) { + super(adaptee.getName()); + this.adaptee = adaptee; + } + + public SymbolMock getAdaptee() { + return adaptee; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof SymbolMock2TypeSymbolAdapter) { + return getAdaptee().equals(((SymbolMock2TypeSymbolAdapter) obj).getAdaptee()); + } + else { + return super.equals(obj); + } + } + } + + private static class BasicSymbolsScopeWithAdapted extends BasicSymbolsScope { + public BasicSymbolsScopeWithAdapted(List adaptees) { + this.adaptees = adaptees; + } + private final List adaptees; + @Override + public List resolveAdaptedTypeLocallyMany(boolean foundSymbols, String name, AccessModifier modifier, Predicate predicate) { + return adaptees.stream().filter(symbol -> symbol.getName().equals(name)).map(SymbolMock2TypeSymbolAdapter::new).collect(Collectors.toList()); + } + } + + /** + * Adds a type parameter to the type. + * + * @return the created type parameter + */ + protected TypeVarSymbol addTypeParameterTo(@NonNull TypeSymbol type, + @NonNull String typeParamName) { + + TypeVarSymbol typeVar = BasicSymbolsMill + .typeVarSymbolBuilder() + .setName(typeParamName) + .setAccessModifier(BasicAccessModifier.PUBLIC) + .build(); + + type.getSpannedScope().add(typeVar); + + return typeVar; + } + + protected static Map.Entry createTypeWithSurrogate( + @NonNull String compName) { + + IBasicSymbolsScope commonScope = BasicSymbolsMill.scope(); + + TypeSymbol symbol = BasicSymbolsMill.typeSymbolBuilder() + .setName(compName) + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); + + commonScope.add(symbol); + + TypeSymbolSurrogate surrogate = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName(compName) + .setEnclosingScope(commonScope) + .build(); + + return Map.entry(symbol, surrogate); + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolTest.java new file mode 100644 index 0000000000..81c751046b --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/basicsymbols/_symboltable/TypeSymbolTest.java @@ -0,0 +1,101 @@ +package de.monticore.symbols.basicsymbols._symboltable; + +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TypeSymbolTest { + + @BeforeEach + void setUp() { + LogStub.init(); + BasicSymbolsMill.init(); + } + + @Test @SuppressWarnings({"EqualsWithItself", "ConstantConditions"}) + void equalsShouldEqualSame() { + // Given + TypeSymbol symbol = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type") + .setEnclosingScope(BasicSymbolsMill.scope()) + .build(); + + // When + boolean result = symbol.equals(symbol); + + // Then + assertTrue(result); + } + + @Test + void equalsShouldNotEqualDifferent() { + // Given + TypeSymbol symbol1 = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type1") + .setEnclosingScope(BasicSymbolsMill.scope()) + .build(); + + TypeSymbol symbol2 = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type2") + .setEnclosingScope(BasicSymbolsMill.scope()) + .build(); + + // When + boolean result = symbol1.equals(symbol2); + + // Then + assertFalse(result); + } + + @Test + void equalsShouldEqualSurrogate() { + // Given + IBasicSymbolsScope scope = BasicSymbolsMill.scope(); + + TypeSymbol symbol = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type") + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); + + scope.add(symbol); + + TypeSymbolSurrogate surrogate = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type") + .setEnclosingScope(scope) + .build(); + + // When + boolean result = symbol.equals(surrogate); + + // Then + assertTrue(result); + } + + @Test + void equalsShouldNotEqualSurrogate() { + // Given + IBasicSymbolsScope scope = BasicSymbolsMill.scope(); + + TypeSymbol symbol = BasicSymbolsMill.typeSymbolBuilder() + .setName("Type1") + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); + + scope.add(symbol); + + TypeSymbolSurrogate surrogate = BasicSymbolsMill.typeSymbolSurrogateBuilder() + .setName("Type2") + .setEnclosingScope(scope) + .build(); + + // When + boolean result = symbol.equals(surrogate); + + // Then + assertFalse(result); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/CompKindOfComponentTypeTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/CompKindOfComponentTypeTest.java deleted file mode 100644 index fe45c27979..0000000000 --- a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/CompKindOfComponentTypeTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package de.monticore.symbols.compsymbols._symboltable; - -import de.monticore.symbols.compsymbols.CompSymbolsMill; -import de.monticore.types.check.CompKindOfComponentType; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Holds test for {@link CompKindOfComponentType} - */ -public class CompKindOfComponentTypeTest { - - @Test - void testDeepClone() { - // Given - CompKindOfComponentType comp = new CompKindOfComponentType(CompSymbolsMill.componentTypeSymbolBuilder().build()); - - // When - CompKindOfComponentType clone = comp.deepClone().asComponentType(); - - // Then - Assertions.assertEquals(comp.getTypeInfo(), clone.getTypeInfo()); - Assertions.assertNotSame(comp.getArguments(), clone.getArguments()); - Assertions.assertIterableEquals(comp.getArguments(), clone.getArguments()); - Assertions.assertNotSame(comp.getParamBindings(), clone.getParamBindings()); - Assertions.assertIterableEquals(comp.getParamBindingsAsList(), clone.getParamBindingsAsList()); - Assertions.assertEquals(comp.getSourceNode().isPresent(), clone.getSourceNode().isPresent()); - } -} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/CompKindOfGenericComponentTypeTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/CompKindOfGenericComponentTypeTest.java deleted file mode 100644 index 930906fc20..0000000000 --- a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/CompKindOfGenericComponentTypeTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package de.monticore.symbols.compsymbols._symboltable; - -import de.monticore.symbols.compsymbols.CompSymbolsMill; -import de.monticore.types.check.CompKindOfComponentType; -import de.monticore.types.check.CompKindOfGenericComponentType; -import de.monticore.types.check.SymTypeExpressionFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; - -/** - * Holds test for {@link CompKindOfGenericComponentType} - */ -public class CompKindOfGenericComponentTypeTest { - - @Test - void testDeepClone() { - // Given - CompKindOfGenericComponentType comp = new CompKindOfGenericComponentType(CompSymbolsMill.componentTypeSymbolBuilder().build(), List.of(SymTypeExpressionFactory.createPrimitive("int"))); - - // When - CompKindOfGenericComponentType clone = comp.deepClone().asGenericComponentType(); - - // Then - Assertions.assertEquals(comp.getTypeInfo(), clone.getTypeInfo()); - Assertions.assertNotSame(comp.getArguments(), clone.getArguments()); - Assertions.assertIterableEquals(comp.getArguments(), clone.getArguments()); - Assertions.assertNotSame(comp.getParamBindings(), clone.getParamBindings()); - Assertions.assertIterableEquals(comp.getParamBindingsAsList(), clone.getParamBindingsAsList()); - Assertions.assertEquals(comp.getSourceNode().isPresent(), clone.getSourceNode().isPresent()); - Assertions.assertNotSame(comp.getTypeBindingsAsList(), clone.getTypeBindingsAsList()); - } -} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentSymbolDeSerTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentSymbolDeSerTest.java deleted file mode 100644 index 7e47eae964..0000000000 --- a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentSymbolDeSerTest.java +++ /dev/null @@ -1,343 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package de.monticore.symbols.compsymbols._symboltable; - - -import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; -import de.monticore.symbols.compsymbols.CompSymbolsMill; -import de.monticore.types.check.CompKindExpression; -import de.monticore.types.check.CompKindOfComponentType; -import de.monticore.types.check.SymTypeExpressionFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.nio.file.Path; - -import static java.nio.file.Files.readString; - -public class ComponentSymbolDeSerTest { - - protected static final String RELATIVE_DIR = "src/test/resources/de/monticore/symbols/compsymbols/_symboltable/"; - - protected ComponentTypeSymbolDeSer deSer; - protected CompSymbolsSymbols2Json arc2json; - - @BeforeEach - void setup() { - CompSymbolsMill.reset(); - CompSymbolsMill.init(); - BasicSymbolsMill.initializePrimitives(); - - deSer = new ComponentTypeSymbolDeSer(); - CompSymbolsMill.globalScope().putSymbolDeSer(deSer.getSerializedKind(), deSer); - SubcomponentSymbolDeSer subDeSer = new SubcomponentSymbolDeSer(); - CompSymbolsMill.globalScope().putSymbolDeSer(subDeSer.getSerializedKind(), subDeSer); - arc2json = new CompSymbolsSymbols2Json(); - } - - @Test - void shouldSerializeSuperComponentType() throws IOException { - // Given - // create a symbol for the super component type - ComponentTypeSymbol superCType = CompSymbolsMill.componentTypeSymbolBuilder() - .setName("SuperCType") - .setSpannedScope(CompSymbolsMill.scope()) - .build(); - - // create a reference to the super component type - CompKindExpression parentType = new CompKindOfComponentType(superCType) {}; - - // create a symbol for a component type, reference its super type - ComponentTypeSymbol cType = CompSymbolsMill.componentTypeSymbolBuilder() - .setName("CompTypeWithSuper1") - .setSpannedScope(CompSymbolsMill.scope()) - .addSuperComponents(parentType) - .build(); - - // When - String actual = deSer.serialize(cType, arc2json); - - // the expected result - Path json = Path.of(RELATIVE_DIR, "WithSuper1.json"); - String expected = readString(json).replaceAll("\\s+", ""); - - // Then - Assertions.assertEquals(expected, actual); - } - - @Test - void shouldSerializeSuperComponentType2() throws IOException { - // Given - // create symbols for the two super component types - ComponentTypeSymbol superCType1 = CompSymbolsMill.componentTypeSymbolBuilder() - .setName("SuperCType1") - .setSpannedScope(CompSymbolsMill.scope()) - .build(); - ComponentTypeSymbol superCType2 = CompSymbolsMill.componentTypeSymbolBuilder() - .setName("SuperCType2") - .setSpannedScope(CompSymbolsMill.scope()) - .build(); - - // create a reference for to each of the two super component types - CompKindExpression parentType1 = new CompKindOfComponentType(superCType1); - CompKindExpression parentType2 = new CompKindOfComponentType(superCType2); - - // symbol for a component type, reference its super types - ComponentTypeSymbol cType = CompSymbolsMill.componentTypeSymbolBuilder() - .setName("CompTypeWithSuper2") - .setSpannedScope(CompSymbolsMill.scope()) - .addSuperComponents(parentType1) - .addSuperComponents(parentType2) - .build(); - - // When - String actual = deSer.serialize(cType, arc2json); - - // the expected result - Path json = Path.of(RELATIVE_DIR, "WithSuper2.json"); - String expected = readString(json).replaceAll("\\s+", ""); - - // Then - Assertions.assertEquals(expected, actual); - } - - @Test - void shouldNotSerializeAbsent() throws IOException { - // Given - ComponentTypeSymbol comp = createSimpleComp(); - - // When - String createdJson = deSer.serialize(comp, arc2json); - - // the expected result - Path json = Path.of(RELATIVE_DIR, "Simple.json"); - String expected = readString(json).replaceAll("\\s+", ""); - - // Then - Assertions.assertEquals(expected, createdJson); - } - - @Test - void shouldSerializeTypeParameters() throws IOException { - // Given - ComponentTypeSymbol comp = createSimpleComp(); - comp.getSpannedScope().add( - CompSymbolsMill.typeVarSymbolBuilder() - .setName("A") - .setSpannedScope(CompSymbolsMill.scope()) - .build() - ); - comp.getSpannedScope().add( - CompSymbolsMill.typeVarSymbolBuilder() - .setName("B") - .setSpannedScope(CompSymbolsMill.scope()) - .build() - ); - - // When - String createdJson = deSer.serialize(comp, arc2json); - - // the expected result - Path json = Path.of(RELATIVE_DIR, "WithTypeParams.json"); - String expected = readString(json).replaceAll("\\s+", ""); - - // Then - Assertions.assertEquals(expected, createdJson); - } - - @Test - void shouldSerializeParameters() throws IOException { - // Given - ComponentTypeSymbol comp = createSimpleComp(); - VariableSymbol paramA = CompSymbolsMill.variableSymbolBuilder() - .setName("a") - .setType(SymTypeExpressionFactory.createPrimitive("int")) - .build(); - VariableSymbol paramB = CompSymbolsMill.variableSymbolBuilder() - .setName("b") - .setType(SymTypeExpressionFactory.createPrimitive("int")) - .build(); - - comp.getSpannedScope().add(paramA); - comp.getSpannedScope().add(paramB); - comp.addParameter(paramA); - comp.addParameter(paramB); - - // When - String createdJson = deSer.serialize(comp, arc2json); - - // the expected result - Path json = Path.of(RELATIVE_DIR, "WithParams.json"); - String expected = readString(json).replaceAll("\\s+", ""); - - // Then - Assertions.assertEquals(expected, createdJson); - } - - @Test - void shouldSerializePorts() throws IOException { - // Given - ComponentTypeSymbol comp = createSimpleComp(); - PortSymbol portIncoming = CompSymbolsMill.portSymbolBuilder() - .setName("inc") - .setIncoming(true) - .setType(SymTypeExpressionFactory.createPrimitive("int")) - .setTiming(Timing.TIMED) - .setStronglyCausal(false) - .build(); - PortSymbol portOutgoing = CompSymbolsMill.portSymbolBuilder() - .setName("outg") - .setOutgoing(true) - .setType(SymTypeExpressionFactory.createPrimitive("int")) - .setTiming(Timing.TIMED) - .setStronglyCausal(false) - .build(); - - comp.getSpannedScope().add(portIncoming); - comp.getSpannedScope().add(portOutgoing); - - - // When - String createdJson = deSer.serialize(comp, arc2json); - - // the expected result - Path json = Path.of(RELATIVE_DIR, "WithPorts.json"); - String expected = readString(json).replaceAll("\\s+", ""); - - // Then - Assertions.assertEquals(expected, createdJson); - } - - @Test - void shouldDeserializeParent() throws IOException { - // When - Path json = Path.of(RELATIVE_DIR, "WithParent.json"); - String jsonString = readString(json).replaceAll("\\s+", ""); - ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); - - // Then - Assertions.assertFalse(comp.isEmptySuperComponents(), "Parent not present"); - Assertions.assertEquals("Parent", comp.getSuperComponents(0).printName()); - } - - @Test - void shouldNotDeserializeAbsentParent() throws IOException { - // When - Path json = Path.of(RELATIVE_DIR, "Simple.json"); - String jsonString = readString(json).replaceAll("\\s+", ""); - ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); - - // Then - Assertions.assertTrue(comp.isEmptySuperComponents(), "Parent is present"); - } - - @Test - void shouldDeserializeTypeParameters() throws IOException { - // When - Path json = Path.of(RELATIVE_DIR, "WithTypeParams.json"); - String jsonString = readString(json).replaceAll("\\s+", ""); - ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); - - // Then - Assertions.assertEquals(2, comp.getTypeParameters().size()); - Assertions.assertAll( - () -> Assertions.assertEquals("A", comp.getTypeParameters().get(0).getName()), - () -> Assertions.assertEquals("B", comp.getTypeParameters().get(1).getName()) - ); - } - - @Test - void shouldDeserializeParameters() throws IOException { - // When - Path json = Path.of(RELATIVE_DIR, "WithParams.json"); - String jsonString = readString(json).replaceAll("\\s+", ""); - ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); - - // Then - Assertions.assertEquals(2, comp.getParameterList().size()); - Assertions.assertEquals(2, comp.getSpannedScope().getLocalVariableSymbols().size()); - Assertions.assertAll( - () -> Assertions.assertEquals("a", comp.getParameterList().get(0).getName()), - () -> Assertions.assertEquals("b", comp.getParameterList().get(1).getName()), - () -> Assertions.assertTrue(comp.getSpannedScope().resolveVariable("a").isPresent()), - () -> Assertions.assertTrue(comp.getSpannedScope().resolveVariable("b").isPresent()), - () -> Assertions.assertEquals(comp.getSpannedScope().resolveVariable("a").get(), comp.getParameterList().get(0)), - () -> Assertions.assertEquals(comp.getSpannedScope().resolveVariable("b").get(), comp.getParameterList().get(1)) - ); - } - - @Test - void shouldDeserializePorts() throws IOException { - // When - Path json = Path.of(RELATIVE_DIR, "WithPorts.json"); - String jsonString = readString(json).replaceAll("\\s+", ""); - ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); - - // Then - Assertions.assertEquals(2, comp.getPorts().size()); - Assertions.assertEquals(2, comp.getSpannedScope().getLocalPortSymbols().size()); - Assertions.assertAll( - () -> Assertions.assertEquals("inc", comp.getPorts().get(0).getName()), - () -> Assertions.assertEquals("outg", comp.getPorts().get(1).getName()), - () -> Assertions.assertTrue(comp.getSpannedScope().resolvePort("inc").isPresent()), - () -> Assertions.assertTrue(comp.getSpannedScope().resolvePort("outg").isPresent()), - () -> Assertions.assertEquals(comp.getSpannedScope().resolvePort("inc").get(), comp.getPorts().get(0)), - () -> Assertions.assertEquals(comp.getSpannedScope().resolvePort("outg").get(), comp.getPorts().get(1)) - ); - } - - @Test - void shouldSerializeSubComponents() throws IOException { - // Given - ComponentTypeSymbol comp = createParentComp(); - comp.getSpannedScope().add( - CompSymbolsMill.subcomponentSymbolBuilder() - .setName("inst") - .setType(new CompKindOfComponentType(createSimpleComp())) - .build() - ); - - // When - String createdJson = deSer.serialize(comp, arc2json); - - // the expected result - Path json = Path.of(RELATIVE_DIR, "WithSub.json"); - String expected = readString(json).replaceAll("\\s+", ""); - - // Then - Assertions.assertEquals(expected, createdJson); - } - - @Test - void shouldDeserializeSubComponents() throws IOException { - // When - Path json = Path.of(RELATIVE_DIR, "WithSub.json"); - String jsonString = readString(json).replaceAll("\\s+", ""); - ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); - - // Then - Assertions.assertEquals(1, comp.getSubcomponents().size()); - Assertions.assertEquals(1, comp.getSpannedScope().getLocalSubcomponentSymbols().size()); - Assertions.assertAll( - () -> Assertions.assertEquals("inst", comp.getSubcomponents().get(0).getName()), - () -> Assertions.assertTrue(comp.getSpannedScope().resolveSubcomponent("inst").isPresent()), - () -> Assertions.assertEquals(comp.getSpannedScope().resolveSubcomponent("inst").get(), comp.getSubcomponents().get(0)) - ); - } - - protected static ComponentTypeSymbol createSimpleComp() { - return CompSymbolsMill.componentTypeSymbolBuilder() - .setName("Comp") - .setSpannedScope(CompSymbolsMill.scope()) - .build(); - } - - protected static ComponentTypeSymbol createParentComp() { - return CompSymbolsMill.componentTypeSymbolBuilder() - .setName("Parent") - .setSpannedScope(CompSymbolsMill.scope()) - .build(); - } -} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentSymbolTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentSymbolTest.java deleted file mode 100644 index 5ec388fa4d..0000000000 --- a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentSymbolTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* (c) https://github.com/MontiCore/monticore */ -package de.monticore.symbols.compsymbols._symboltable; - - -import de.monticore.symbols.compsymbols.CompSymbolsMill; -import de.monticore.types.check.CompKindOfComponentType; -import de.monticore.types.check.SymTypeExpressionFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.List; -import java.util.Set; - -/** - * Holds tests for the handwritten methods of {@link ComponentTypeSymbol}. - */ -public class ComponentSymbolTest { - - @Test - void shouldGetAllInheritedPortsWithOverlappingName() { - // Given - ComponentTypeSymbol parent = CompSymbolsMill.componentTypeSymbolBuilder() - .setSpannedScope(CompSymbolsMill.scope()) - .setName("sut") - .build(); - - PortSymbol p1 = CompSymbolsMill.portSymbolBuilder().setName("p").setType(SymTypeExpressionFactory.createObscureType()).build(); - PortSymbol p2 = CompSymbolsMill.portSymbolBuilder().setName("p").setType(SymTypeExpressionFactory.createObscureType()).build(); - - parent.getSpannedScope().add(p1); - parent.getSpannedScope().add(p2); - - ComponentTypeSymbol sut = CompSymbolsMill.componentTypeSymbolBuilder() - .setName("sut") - .setSpannedScope(CompSymbolsMill.scope()) - .setSuperComponentsList(Collections.singletonList(new CompKindOfComponentType(parent))) - .build(); - - // When - Set ports = sut.getAllPorts(); - - // Then - Assertions.assertIterableEquals(List.of(p1, p2), ports); - } -} \ No newline at end of file diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentType2TypeSymbolAdapterTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentType2TypeSymbolAdapterTest.java new file mode 100644 index 0000000000..67eaab7a9a --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentType2TypeSymbolAdapterTest.java @@ -0,0 +1,64 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.symboltable.modifiers.BasicAccessModifier; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Holds tests for {@link ComponentType2TypeSymbolAdapter}. + */ +public class ComponentType2TypeSymbolAdapterTest { + + @ParameterizedTest + @MethodSource("componentTypeSymbolProvider") + void shouldAdaptFields(@NonNull ComponentTypeSymbol adaptee) { + // Given + ComponentType2TypeSymbolAdapter adapter = new ComponentType2TypeSymbolAdapter(adaptee); + + // Then + assertAll( + () -> assertEquals(adaptee.getName(), adapter.getName(), + "The adapter's name should match the adaptee's name."), + () -> assertEquals(adaptee.getFullName(), adapter.getFullName(), + "The adapter's full name should match the adaptee's full name."), + () -> assertEquals(adaptee.getSpannedScope(), adapter.getSpannedScope(), + "The adapter's spanned scope should match the adaptee's enclosing scope."), + () -> assertEquals(adaptee.getEnclosingScope(), adapter.getEnclosingScope(), + "The adapter's enclosing scope should match the adaptee's enclosing scope."), + () -> assertEquals(adaptee.getSourcePosition(), adapter.getSourcePosition(), + "The adapter's source position should match the adaptee's source position."), + () -> assertEquals(BasicAccessModifier.PUBLIC, adapter.getAccessModifier(), + "The adapter should have a public access modifier as ports are the public interface of a component.") + ); + } + + protected static Stream componentTypeSymbolProvider() { + ICompSymbolsScope scope = CompSymbolsMill.scope(); + + // incoming port + ComponentTypeSymbol comp1 = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("c1") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + scope.add(comp1); + comp1.setEnclosingScope(scope); + + // outgoing port + ComponentTypeSymbol comp2 = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("c2") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + scope.add(comp2); + comp2.setEnclosingScope(scope); + + return Stream.of(comp1, comp2); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolBuilderTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolBuilderTest.java new file mode 100644 index 0000000000..28442243e4 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolBuilderTest.java @@ -0,0 +1,189 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.types.check.CompKindExpression; +import de.monticore.types.check.CompKindOfComponentType; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +/** + * Holds tests for the handwritten methods of {@link ComponentTypeSymbolBuilder}. + */ +class ComponentTypeSymbolBuilderTest { + + @Test + void shouldBeValid() { + ComponentTypeSymbolBuilder builder = new ComponentTypeSymbolBuilder(); + builder.setName("A").setSpannedScope(CompSymbolsMill.scope()); + assertTrue(builder.isValid()); + } + + @Test + void shouldBeInvalid() { + ComponentTypeSymbolBuilder builder1 = new ComponentTypeSymbolBuilder(); + ComponentTypeSymbolBuilder builder2 = new ComponentTypeSymbolBuilder(); + builder2.setName("Comp"); + ComponentTypeSymbolBuilder builder3 = new ComponentTypeSymbolBuilder(); + builder3.setSpannedScope(CompSymbolsMill.scope()); + assertFalse(builder1.isValid()); + assertFalse(builder2.isValid()); + assertFalse(builder3.isValid()); + } + + @Test + void shouldHaveParent() { + ComponentTypeSymbol parentComp = CompSymbolsMill.componentTypeSymbolBuilder() + .setSpannedScope(CompSymbolsMill.scope()).setName("A").build(); + ComponentTypeSymbol childComp = CompSymbolsMill.componentTypeSymbolBuilder().setName("B") + .setSpannedScope(CompSymbolsMill.scope()).setSuperComponentsList(Collections.singletonList(new CompKindOfComponentType(parentComp))).build(); + assertFalse(childComp.isEmptySuperComponents()); + } + + @Test + void shouldNotHaveParent() { + ComponentTypeSymbol symbol = CompSymbolsMill.componentTypeSymbolBuilder().setName("A") + .setSpannedScope(CompSymbolsMill.scope()).build(); + assertTrue(symbol.isEmptySuperComponents()); + } + + @Test + void shouldHaveSpec() { + // Given + ComponentTypeSymbol parentComp = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("A") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + CompKindExpression parentExpr = new CompKindOfComponentType(parentComp); + ComponentTypeSymbolBuilder childBuilder = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("B") + .setSpannedScope(CompSymbolsMill.scope()) + .setRefinementsList(Collections.singletonList(parentExpr)); + + // When + ComponentTypeSymbol child = childBuilder.build(); + + // Then + assertEquals(1, child.sizeRefinements()); + assertEquals(parentExpr, child.getRefinements(0)); + } + + @Test + void shouldHaveSpecs() { + // Given + ComponentTypeSymbol parentComp1 = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("A1") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + ComponentTypeSymbol parentComp2 = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("A2") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + CompKindExpression parentExpr1 = new CompKindOfComponentType(parentComp1); + CompKindExpression parentExpr2 = new CompKindOfComponentType(parentComp2); + + ComponentTypeSymbolBuilder childBuilder = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("B") + .setSpannedScope(CompSymbolsMill.scope()) + .setRefinementsList(List.of(parentExpr1, parentExpr2)); + + // When + ComponentTypeSymbol child = childBuilder.build(); + + // Then + assertEquals(2, child.sizeRefinements()); + assertAll( + () -> assertEquals(parentExpr1, child.getRefinements(0)), + () -> assertEquals(parentExpr2, child.getRefinements(1)) + ); + } + + @Test + void shouldNotHaveSpecs() { + // Given + ComponentTypeSymbolBuilder childBuilder = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("A") + .setSpannedScope(CompSymbolsMill.scope()); + + // When + ComponentTypeSymbol child = childBuilder.build(); + + // Then + assertTrue(child.isEmptyRefinements()); + } + + @ParameterizedTest + @MethodSource("compNameAndParametersProvider") + void shouldBuildWithExpectedParameters(String name, List parameters) { + ComponentTypeSymbol symbol = CompSymbolsMill.componentTypeSymbolBuilder().setName(name) + .setSpannedScope(CompSymbolsMill.scope()).setParameterList(parameters).build(); + assertEquals(symbol.getName(), name); + assertIterableEquals(parameters, symbol.getParameterList()); + } + + static Stream compNameAndParametersProvider() { + return Stream.of(arguments("Comp1", Collections.emptyList()), + arguments("Comp2", Arrays.asList( + CompSymbolsMill.variableSymbolBuilder().setName("a").build(), + CompSymbolsMill.variableSymbolBuilder().setName("b").build(), + CompSymbolsMill.variableSymbolBuilder().setName("c").build())), + arguments("Comp3", Arrays.asList( + CompSymbolsMill.variableSymbolBuilder().setName("c").build(), + CompSymbolsMill.variableSymbolBuilder().setName("d").build()))); + } + + @Test + void shouldBuildWithExpectedNumberOfOptionalParameters() { + // Given + VariableSymbol symParamA = CompSymbolsMill.variableSymbolBuilder().setName("A").build(); + VariableSymbol symParamB = CompSymbolsMill.variableSymbolBuilder().setName("B").build(); + VariableSymbol symParamC = CompSymbolsMill.variableSymbolBuilder().setName("C").build(); + VariableSymbol symParamD = CompSymbolsMill.variableSymbolBuilder().setName("D").build(); + int numberOfOptionalParameters = 2; + + // When + ComponentTypeSymbol symbol = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("A") + .setParameterList(List.of(symParamA, symParamB, symParamC, symParamD)) + .setNumOptParams(numberOfOptionalParameters) + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + // Then + assertEquals(2, symbol.getNumOptParams()); + } + + @ParameterizedTest + @MethodSource("compNameAndTypeParametersProvider") + void shouldBuildWithExpectedTypeParameters(String name, + List typeParameters) { + ComponentTypeSymbol symbol = CompSymbolsMill.componentTypeSymbolBuilder().setName(name) + .setSpannedScope(CompSymbolsMill.scope()).setTypeParameters(typeParameters).build(); + assertEquals(symbol.getName(), name); + assertIterableEquals(symbol.getTypeParameters(), typeParameters); + } + + static Stream compNameAndTypeParametersProvider() { + return Stream.of( + arguments("Comp1", Collections.emptyList()), + arguments("Comp2", Arrays.asList( + CompSymbolsMill.typeVarSymbolBuilder().setName("A").build(), + CompSymbolsMill.typeVarSymbolBuilder().setName("B").build(), + CompSymbolsMill.typeVarSymbolBuilder().setName("C").build())), + arguments("Comp3", Collections.singletonList( + CompSymbolsMill.typeVarSymbolBuilder().setName("D").build()))); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolDeSerTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolDeSerTest.java new file mode 100644 index 0000000000..d0f89ae124 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolDeSerTest.java @@ -0,0 +1,429 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + + +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.types.check.CompKindExpression; +import de.monticore.types.check.CompKindOfComponentType; +import de.monticore.types.check.SymTypeExpressionFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Collections; + +import static java.nio.file.Files.readString; +import static org.junit.jupiter.api.Assertions.*; + +public class ComponentTypeSymbolDeSerTest { + + protected static final String RELATIVE_DIR = "src/test/resources/de/monticore/symbols/compsymbols/_symboltable/"; + + protected ComponentTypeSymbolDeSer deSer; + protected CompSymbolsSymbols2Json comp2json; + + @BeforeEach + void setup() { + CompSymbolsMill.reset(); + CompSymbolsMill.init(); + BasicSymbolsMill.initializePrimitives(); + + deSer = new ComponentTypeSymbolDeSer(); + CompSymbolsMill.globalScope().putSymbolDeSer(deSer.getSerializedKind(), deSer); + SubcomponentSymbolDeSer subDeSer = new SubcomponentSymbolDeSer(); + CompSymbolsMill.globalScope().putSymbolDeSer(subDeSer.getSerializedKind(), subDeSer); + comp2json = new CompSymbolsSymbols2Json(); + } + + @Test + void shouldSerializeSuperComponentType() throws IOException { + // Given + // create a symbol for the super component type + ComponentTypeSymbol superCType = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("SuperCType") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + // create a reference to the super component type + CompKindExpression parentType = new CompKindOfComponentType(superCType) {}; + + // create a symbol for a component type, reference its super type + ComponentTypeSymbol cType = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("CompTypeWithSuper1") + .setSpannedScope(CompSymbolsMill.scope()) + .addSuperComponents(parentType) + .build(); + + // When + String actual = deSer.serialize(cType, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithSuper1.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, actual); + } + + @Test + void shouldSerializeSuperComponentType2() throws IOException { + // Given + // create symbols for the two super component types + ComponentTypeSymbol superCType1 = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("SuperCType1") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + ComponentTypeSymbol superCType2 = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("SuperCType2") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + // create a reference for to each of the two super component types + CompKindExpression parentType1 = new CompKindOfComponentType(superCType1); + CompKindExpression parentType2 = new CompKindOfComponentType(superCType2); + + // symbol for a component type, reference its super types + ComponentTypeSymbol cType = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("CompTypeWithSuper2") + .setSpannedScope(CompSymbolsMill.scope()) + .addSuperComponents(parentType1) + .addSuperComponents(parentType2) + .build(); + + // When + String actual = deSer.serialize(cType, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithSuper2.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, actual); + } + + @Test + void shouldNotSerializeAbsent() throws IOException { + // Given + ComponentTypeSymbol comp = createSimpleComp("Comp"); + + // When + String createdJson = deSer.serialize(comp, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "Simple.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, createdJson); + } + + @Test + void shouldSerializeTypeParameters() throws IOException { + // Given + ComponentTypeSymbol comp = createSimpleComp("Comp"); + comp.getSpannedScope().add( + CompSymbolsMill.typeVarSymbolBuilder() + .setName("A") + .setSpannedScope(CompSymbolsMill.scope()) + .build() + ); + comp.getSpannedScope().add( + CompSymbolsMill.typeVarSymbolBuilder() + .setName("B") + .setSpannedScope(CompSymbolsMill.scope()) + .build() + ); + + // When + String createdJson = deSer.serialize(comp, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithTypeParams.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, createdJson); + } + + @Test + void shouldSerializeParameters() throws IOException { + // Given + ComponentTypeSymbol comp = createSimpleComp("Comp"); + VariableSymbol paramA = CompSymbolsMill.variableSymbolBuilder() + .setName("a") + .setType(SymTypeExpressionFactory.createPrimitive("int")) + .build(); + VariableSymbol paramB = CompSymbolsMill.variableSymbolBuilder() + .setName("b") + .setType(SymTypeExpressionFactory.createPrimitive("int")) + .build(); + + comp.getSpannedScope().add(paramA); + comp.getSpannedScope().add(paramB); + comp.addParameter(paramA); + comp.addParameter(paramB); + + // When + String createdJson = deSer.serialize(comp, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithParams.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, createdJson); + } + + @Test + void shouldSerializePorts() throws IOException { + // Given + ComponentTypeSymbol comp = createSimpleComp("Comp"); + PortSymbol portIncoming = CompSymbolsMill.portSymbolBuilder() + .setName("inc") + .setIncoming(true) + .setType(SymTypeExpressionFactory.createPrimitive("int")) + .setTiming(Timing.TIMED) + .setStronglyCausal(false) + .build(); + PortSymbol portOutgoing = CompSymbolsMill.portSymbolBuilder() + .setName("outg") + .setOutgoing(true) + .setType(SymTypeExpressionFactory.createPrimitive("int")) + .setTiming(Timing.TIMED) + .setStronglyCausal(false) + .build(); + + comp.getSpannedScope().add(portIncoming); + comp.getSpannedScope().add(portOutgoing); + + + // When + String createdJson = deSer.serialize(comp, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithPorts.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, createdJson); + } + + @Test + void shouldNotDeserializeAbsentParent() throws IOException { + // When + Path json = Path.of(RELATIVE_DIR, "Simple.json"); + String jsonString = readString(json).replaceAll("\\s+", ""); + ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); + + // Then + assertTrue(comp.isEmptySuperComponents(), "Parent is present"); + } + + @Test + void shouldDeserializeTypeParameters() throws IOException { + // When + Path json = Path.of(RELATIVE_DIR, "WithTypeParams.json"); + String jsonString = readString(json).replaceAll("\\s+", ""); + ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); + + // Then + assertEquals(2, comp.getTypeParameters().size()); + assertAll( + () -> assertEquals("A", comp.getTypeParameters().get(0).getName()), + () -> assertEquals("B", comp.getTypeParameters().get(1).getName()) + ); + } + + @Test + void shouldDeserializeParameters() throws IOException { + // When + Path json = Path.of(RELATIVE_DIR, "WithParams.json"); + String jsonString = readString(json).replaceAll("\\s+", ""); + ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); + + // Then + assertEquals(2, comp.getParameterList().size()); + assertEquals(2, comp.getSpannedScope().getLocalVariableSymbols().size()); + assertAll( + () -> assertEquals("a", comp.getParameterList().get(0).getName()), + () -> assertEquals("b", comp.getParameterList().get(1).getName()), + () -> assertTrue(comp.getSpannedScope().resolveVariable("a").isPresent()), + () -> assertTrue(comp.getSpannedScope().resolveVariable("b").isPresent()), + () -> assertEquals(comp.getSpannedScope().resolveVariable("a").get(), comp.getParameterList().get(0)), + () -> assertEquals(comp.getSpannedScope().resolveVariable("b").get(), comp.getParameterList().get(1)) + ); + } + + @Test + void shouldDeserializePorts() throws IOException { + // When + Path json = Path.of(RELATIVE_DIR, "WithPorts.json"); + String jsonString = readString(json).replaceAll("\\s+", ""); + ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); + + // Then + assertEquals(2, comp.getPorts().size()); + assertEquals(2, comp.getSpannedScope().getLocalPortSymbols().size()); + assertAll( + () -> assertEquals("inc", comp.getPorts().get(0).getName()), + () -> assertEquals("outg", comp.getPorts().get(1).getName()), + () -> assertTrue(comp.getSpannedScope().resolvePort("inc").isPresent()), + () -> assertTrue(comp.getSpannedScope().resolvePort("outg").isPresent()), + () -> assertEquals(comp.getSpannedScope().resolvePort("inc").get(), comp.getPorts().get(0)), + () -> assertEquals(comp.getSpannedScope().resolvePort("outg").get(), comp.getPorts().get(1)) + ); + } + + @Test + void shouldSerializeSubComponents() throws IOException { + // Given + ComponentTypeSymbol comp = createSimpleComp("Parent"); + comp.getSpannedScope().add( + CompSymbolsMill.subcomponentSymbolBuilder() + .setName("inst") + .setType(new CompKindOfComponentType(createSimpleComp("Comp"))) + .build() + ); + + // When + String createdJson = deSer.serialize(comp, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithSub.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, createdJson); + } + + @Test + void shouldDeserializeSubComponents() throws IOException { + // When + Path json = Path.of(RELATIVE_DIR, "WithSub.json"); + String jsonString = readString(json).replaceAll("\\s+", ""); + ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); + + // Then + assertEquals(1, comp.getSubcomponents().size()); + assertEquals(1, comp.getSpannedScope().getLocalSubcomponentSymbols().size()); + assertAll( + () -> assertEquals("inst", comp.getSubcomponents().get(0).getName()), + () -> assertTrue(comp.getSpannedScope().resolveSubcomponent("inst").isPresent()), + () -> assertEquals(comp.getSpannedScope().resolveSubcomponent("inst").get(), comp.getSubcomponents().get(0)) + ); + } + + protected static ComponentTypeSymbol createSimpleComp(String name) { + return CompSymbolsMill.componentTypeSymbolBuilder() + .setName(name) + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + } + + @Test + void shouldSerializeSpec() throws IOException { + // Given + ComponentTypeSymbol comp = createSimpleComp("Comp"); + ComponentTypeSymbol refinement = createSimpleComp("RefinementCType"); + CompKindExpression refinementType = new CompKindOfComponentType(refinement); + comp.setRefinementsList(Collections.singletonList(refinementType)); + + // When + String createdJson = deSer.serialize(comp, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithRefinement.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, createdJson); + } + + @Test + void shouldDeserializeSpec() throws IOException { + // When + Path json = Path.of(RELATIVE_DIR, "WithRefinement.json"); + String jsonString = readString(json).replaceAll("\\s+", ""); + ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); + + // Then + assertFalse(comp.isEmptyRefinements(), "Refined component not present"); + assertEquals("RefinementCType", comp.getRefinements(0).printName()); + } + + + @Test + void shouldSerializeInnerComponents() throws IOException { + // Given + ComponentTypeSymbol comp = createSimpleComp("Comp"); + comp.getSpannedScope().add( + CompSymbolsMill.componentTypeSymbolBuilder() + .setName("inst") + .setSpannedScope(CompSymbolsMill.scope()) + .build() + ); + + // When + String createdJson = deSer.serialize(comp, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithInner.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, createdJson); + } + + @Test + void shouldDeserializeInnerComponents() throws IOException { + // When + Path json = Path.of(RELATIVE_DIR, "WithInner.json"); + String jsonString = readString(json).replaceAll("\\s+", ""); + ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); + + // Then + assertEquals(1, comp.getSpannedScope().getLocalComponentTypeSymbols().size()); + assertAll( + () -> assertEquals("inst", comp.getSpannedScope().getLocalComponentTypeSymbols().get(0).getName()) + ); + } + + @Test + void shouldSerializeFields() throws IOException { + // Given + ComponentTypeSymbol comp = createSimpleComp("Comp"); + comp.getSpannedScope().add( + CompSymbolsMill.variableSymbolBuilder() + .setName("inst") + .setType(SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT)) + .build() + ); + + // When + String createdJson = deSer.serialize(comp, comp2json); + + // the expected result + Path json = Path.of(RELATIVE_DIR, "WithField.json"); + String expected = readString(json).replaceAll("\\s+", ""); + + // Then + assertEquals(expected, createdJson); + } + + @Test + void shouldDeserializeFields() throws IOException { + // When + Path json = Path.of(RELATIVE_DIR, "WithField.json"); + String jsonString = readString(json).replaceAll("\\s+", ""); + ComponentTypeSymbol comp = deSer.deserialize(CompSymbolsMill.globalScope(), jsonString); + + // Then + assertEquals(1, comp.getFields().size()); + assertAll( + () -> assertEquals("inst", comp.getFields().get(0).getName()) + ); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolSurrogateTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolSurrogateTest.java new file mode 100644 index 0000000000..eeff2cbe28 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolSurrogateTest.java @@ -0,0 +1,799 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import com.google.common.base.Preconditions; +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.symboltable.modifiers.BasicAccessModifier; +import de.monticore.types.check.CompKindExpression; +import de.monticore.types.check.CompKindOfComponentType; +import de.monticore.types.check.SymTypeExpressionFactory; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; + +public class ComponentTypeSymbolSurrogateTest { + + @Test + public void setSpannedScopeShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ICompSymbolsScope scopeToSet = CompSymbolsMill.scope(); + + // When + surrogate.setSpannedScope(scopeToSet); + + // Then + assertSame(scopeToSet, comp.getSpannedScope()); + } + + @Test + public void getSpannedScopeShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + // When + ICompSymbolsScope scope = surrogate.getSpannedScope(); + + // Then + assertSame(comp.getSpannedScope(), scope); + } + + @Test + public void getPortsShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addIncomingPortTo(comp, "myPort"); + + // When + List ports = surrogate.getPorts(); + + // Then + assertArrayEquals(new PortSymbol[]{port}, ports.toArray()); + } + + @Test + public void getPortByNameShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addIncomingPortTo(comp, "myPort"); + + // When + Optional portOpt = surrogate.getPort("myPort"); + + // Then + assertTrue(portOpt.isPresent(), "Port is not present"); + assertSame(port, portOpt.get()); + } + + @Test + public void getInheritedPortByNameShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol parent = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Parent") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + comp.setSuperComponentsList(Collections.singletonList(new CompKindOfComponentType(parent))); + + PortSymbol port = addIncomingPortTo(parent, "parentPort"); + + // When + Optional portOpt = surrogate.getPort("parentPort", true); + + // Then + assertTrue(portOpt.isPresent(), "Port is not present"); + assertSame(port, portOpt.get()); + } + + @Test + public void getIncomingPortsShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addIncomingPortTo(comp, "myPort"); + + // When + List ports = surrogate.getIncomingPorts(); + + // Then + assertArrayEquals(new PortSymbol[]{port}, ports.toArray()); + } + + @Test + public void getIncomingPortByNameShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addIncomingPortTo(comp, "myPort"); + + // When + Optional portOpt = surrogate.getIncomingPort("myPort"); + + // Then + assertTrue(portOpt.isPresent(), "Port is not present"); + assertSame(port, portOpt.get()); + } + + @Test + public void getInheritedIncomingPortByNameShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol parent = createCompWithSurrogate("Parent").getKey(); + comp.setSuperComponentsList(Collections.singletonList(new CompKindOfComponentType(parent))); + + PortSymbol port = addIncomingPortTo(parent, "parentPort"); + + // When + Optional portOpt = surrogate.getIncomingPort("parentPort", true); + + // Then + assertTrue(portOpt.isPresent(), "Port is not present"); + assertSame(port, portOpt.get()); + } + + @Test + void isPresentParentShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol parent = createCompWithSurrogate("Parent").getKey(); + comp.setSuperComponentsList(Collections.singletonList(new CompKindOfComponentType(parent))); + + // When + boolean parentIsPresent = !surrogate.isEmptySuperComponents(); + + // Then + assertTrue(parentIsPresent, "No parent present"); + } + + + @Test + void getParentShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol parent = createCompWithSurrogate("Parent").getKey(); + CompKindExpression parentExpr = new CompKindOfComponentType(parent); + comp.setSuperComponentsList(Collections.singletonList(parentExpr)); + + // When + CompKindExpression parentCalculated = surrogate.getSuperComponents(0); + + // Then + assertSame(parentExpr, parentCalculated); + } + + + @Test + void setParentShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol parent = createCompWithSurrogate("Parent").getKey(); + CompKindExpression parentExpr = new CompKindOfComponentType(parent); + + // When + surrogate.setSuperComponentsList(Collections.singletonList(parentExpr)); + + // Then + assertSame(parentExpr, comp.getSuperComponents(0)); + } + + @Test + void isPresentRefinementShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol abstraction = createCompWithSurrogate("Abstraction").getKey(); + CompKindExpression abstractionExpr = new CompKindOfComponentType(abstraction); + comp.setRefinementsList(Collections.singletonList(abstractionExpr)); + + // When + boolean refinedCompIsPresent = !surrogate.isEmptyRefinements(); + + // Then + assertTrue(refinedCompIsPresent, "No refined component present"); + } + + + @Test + void getRefinementShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol abstraction = createCompWithSurrogate("Abstraction").getKey(); + CompKindExpression abstractionExpr = new CompKindOfComponentType(abstraction); + comp.setRefinementsList(Collections.singletonList(abstractionExpr)); + + // When + CompKindExpression parentCalculated = surrogate.getRefinements(0); + + // Then + assertSame(abstractionExpr, parentCalculated); + } + + + @Test + void setRefinementShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol abstraction = createCompWithSurrogate("Abstraction").getKey(); + CompKindExpression abstractionExpr = new CompKindOfComponentType(abstraction); + + // When + surrogate.setRefinementsList(Collections.singletonList(abstractionExpr)); + + // Then + assertSame(abstractionExpr, comp.getRefinements(0)); + } + + @Test + void getParameterListShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + VariableSymbol param = addParameterTo(comp, "myParam"); + + // When + List params = surrogate.getParameterList(); + + // Then + assertArrayEquals(new VariableSymbol[]{param}, params.toArray()); + } + + @Test + void getParameterShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + VariableSymbol param = addParameterTo(comp, "myParam"); + + // When + Optional paramOpt = surrogate.getParameter("myParam"); + + // Then + assertTrue(paramOpt.isPresent(), "No parameter"); + assertSame(param, paramOpt.get()); + } + + @Test + void addParameterShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + VariableSymbol param = CompSymbolsMill + .variableSymbolBuilder() + .setName("param") + .setType(SymTypeExpressionFactory.createObscureType()) + .build(); + + // When + surrogate.getSpannedScope().add(param); + surrogate.addParameter(param); + + // Then + assertArrayEquals(new VariableSymbol[]{param}, comp.getParameterList().toArray()); + } + + + @Test + void addParametersShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + VariableSymbol param = CompSymbolsMill + .variableSymbolBuilder() + .setName("param") + .setType(SymTypeExpressionFactory.createObscureType()) + .build(); + + // When + surrogate.getSpannedScope().add(param); + surrogate.addAllParameter(Collections.singletonList(param)); + + // Then + assertArrayEquals(new VariableSymbol[]{param}, comp.getParameterList().toArray()); + } + + @Test + void hasParametersShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + addParameterTo(comp, "param"); + + // When + boolean hasParameters = surrogate.hasParameters(); + + // Then + assertTrue(hasParameters, "No parameters found"); + } + + @Test + void getTypeParametersShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + TypeVarSymbol typeParam = addTypeParameterTo(comp, "T"); + + // When + List typeParams = surrogate.getTypeParameters(); + + // Then + assertArrayEquals(new TypeVarSymbol[]{typeParam}, typeParams.toArray()); + } + + @Test + void hasTypeParameterShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + addTypeParameterTo(comp, "T"); + + // When + boolean hasTypeParams = surrogate.hasTypeParameter(); + + // then + assertTrue(hasTypeParams, "No type parameters found"); + } + + @Test + void getFieldsShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + VariableSymbol field = addFieldTo(comp, "myField"); + + // When + List fields = surrogate.getFields(); + + // Then + assertArrayEquals(new VariableSymbol[]{field}, fields.toArray()); + } + + @Test + void getFieldByNameShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + VariableSymbol field = addFieldTo(comp, "myField"); + + // When + Optional fieldOpt = surrogate.getField("myField"); + + + // Then + assertTrue(fieldOpt.isPresent(), "No field"); + assertSame(field, fieldOpt.get()); + } + + @Test + void getOutgoingPortsShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addOutgoingPortTo(comp, "myPort"); + + // When + List ports = surrogate.getOutgoingPorts(); + + // Then + assertArrayEquals(new PortSymbol[]{port}, ports.toArray()); + } + + @Test + void getOutgoingPortByNameShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addOutgoingPortTo(comp, "myPort"); + + // When + Optional portOpt = surrogate.getOutgoingPort("myPort"); + + // Then + assertTrue(portOpt.isPresent(), "Port is not present"); + assertSame(port, portOpt.get()); + } + + @Test + void getInheritedOutgoingPortByNameShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + ComponentTypeSymbol parent = createCompWithSurrogate("Parent").getKey(); + CompKindExpression parentExpr = new CompKindOfComponentType(parent); + comp.setSuperComponentsList(Collections.singletonList(parentExpr)); + + PortSymbol port = addOutgoingPortTo(parent, "myPort"); + + // When + Optional portOpt = surrogate.getOutgoingPort("myPort", true); + + // Then + assertTrue(portOpt.isPresent(), "Port is not present"); + assertSame(port, portOpt.get()); + } + + @Test + void getPortsWithDirectionShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + + PortSymbol port = addIncomingPortTo(comp, "myPort"); + + // When + List ports = surrogate.getPorts(true, false); + + // Then + assertArrayEquals(new PortSymbol[]{port}, ports.toArray()); + } + + @Test + void getAllIncomingPortsShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addIncomingPortTo(comp, "myPort"); + + // When + Set ports = surrogate.getAllIncomingPorts(); + + // Then + assertArrayEquals(new PortSymbol[]{port}, ports.toArray()); + } + + @Test + void getAllOutgoingPortsShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addOutgoingPortTo(comp, "myPort"); + + // When + List ports = surrogate.getOutgoingPorts(); + + // Then + assertArrayEquals(new PortSymbol[]{port}, ports.toArray()); + } + + @Test + void getAllPortsWithDirectionShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addIncomingPortTo(comp, "myPort"); + + // When + Set ports = surrogate.getAllPorts(true, false); + + // Then + assertArrayEquals(new PortSymbol[]{port}, ports.toArray()); + } + + @Test + void getAllPortsShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + PortSymbol port = addOutgoingPortTo(comp, "myPort"); + + // When + Set ports = surrogate.getAllPorts(); + + // Then + assertArrayEquals(new PortSymbol[]{port}, ports.toArray()); + } + + @Test + void getSubComponentsShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + SubcomponentSymbol sub = addSubComponentTo(comp, "sub"); + + // When + List subs = surrogate.getSubcomponents(); + + // Then + assertArrayEquals(new SubcomponentSymbol[]{sub}, subs.toArray()); + } + + @Test + void getSubComponentShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + SubcomponentSymbol sub = addSubComponentTo(comp, "mySub"); + + // When + Optional subOpt = surrogate.getSubcomponents("mySub"); + + // Then + assertTrue(subOpt.isPresent(), "Sub component is not present"); + assertSame(sub, subOpt.get()); + } + + + @Test + void isDecomposedShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + addSubComponentTo(comp, "sub"); + + // When + boolean isDecomposed = surrogate.isDecomposed(); + + // Then + assertTrue(isDecomposed, "Should be decomposed"); + } + + @Test + void isAtomicShouldSkipSurrogate() { + // Given + Map.Entry pair = createCompWithSurrogate("Comp"); + ComponentTypeSymbol comp = pair.getKey(); + ComponentTypeSymbolSurrogate surrogate = pair.getValue(); + + addSubComponentTo(comp, "sub"); + + // When + boolean isAtomic = surrogate.isAtomic(); + + // Then + assertFalse(isAtomic, "Should not be atomic"); + } + + /** + * Adds an incoming port symbol to the spanned scope of the component. The port type is only mocked. + * + * @return the created Port + */ + protected PortSymbol addIncomingPortTo(@NonNull ComponentTypeSymbol compType, @NonNull String portName) { + return addPortTo(compType, portName, true); + } + + /** + * Adds an outgoing port symbol to the spanned scope of the component. The port type is only mocked. + * + * @return the created Port + */ + protected PortSymbol addOutgoingPortTo(@NonNull ComponentTypeSymbol compType, @NonNull String portName) { + return addPortTo(compType, portName, false); + } + + /** + * Adds a port symbol to the spanned scope of the component. The port type is only mocked. + * + * @return the created Port + */ + protected PortSymbol addPortTo(@NonNull ComponentTypeSymbol compType, @NonNull String portName, boolean isIncoming) { + Preconditions.checkNotNull(compType); + Preconditions.checkNotNull(portName); + + PortSymbol port = CompSymbolsMill + .portSymbolBuilder() + .setName(portName) + .setIncoming(isIncoming) + .setOutgoing(!isIncoming) + .setType(SymTypeExpressionFactory.createObscureType()) + .setAccessModifier(BasicAccessModifier.PUBLIC) + .build(); + + compType.getSpannedScope().add(port); + + return port; + } + + /** + * Adds a subcomponent to the spanned scope of the component. The sub component's type type is only mocked. + * + * @return the created subcomponent + */ + protected SubcomponentSymbol addSubComponentTo(@NonNull ComponentTypeSymbol compType, @NonNull String subCompName) { + Preconditions.checkNotNull(compType); + Preconditions.checkNotNull(subCompName); + + SubcomponentSymbol subComp = CompSymbolsMill + .subcomponentSymbolBuilder() + .setName(subCompName) + .setType(new CompKindOfComponentType(CompSymbolsMill.componentTypeSymbolSurrogateBuilder().setName("empty").setEnclosingScope(compType.getSpannedScope()).build())) + .setAccessModifier(BasicAccessModifier.PUBLIC) + .build(); + + compType.getSpannedScope().add(subComp); + + return subComp; + } + + /** + * Adds an inner component type symbol to the spanned scope of the component. + * + * @return the created inner component type + */ + protected ComponentTypeSymbol addInnerComponentTypeTo(@NonNull ComponentTypeSymbol compType, @NonNull String innerCompTypeName) { + Preconditions.checkNotNull(compType); + Preconditions.checkNotNull(innerCompTypeName); + + ComponentTypeSymbol innerComp = CompSymbolsMill + .componentTypeSymbolBuilder() + .setName(innerCompTypeName) + .setSpannedScope(CompSymbolsMill.scope()) + .setAccessModifier(BasicAccessModifier.PUBLIC) + .build(); + + compType.getSpannedScope().add(innerComp); + + return innerComp; + } + + /** + * Adds a field to the spanned scope of the component. The field type is only mocked. + * + * @return the created field. + */ + protected VariableSymbol addFieldTo(@NonNull ComponentTypeSymbol compType, @NonNull String fieldName) { + Preconditions.checkNotNull(compType); + Preconditions.checkNotNull(fieldName); + + VariableSymbol field = CompSymbolsMill + .variableSymbolBuilder() + .setName(fieldName) + .setType(SymTypeExpressionFactory.createObscureType()) + .setAccessModifier(BasicAccessModifier.PUBLIC) + .build(); + + compType.getSpannedScope().add(field); + + return field; + } + + /** + * Adds a parameter to the spanned scope of the component. The parameter type is only mocked. + * + * @return the created parameter. + */ + protected VariableSymbol addParameterTo(@NonNull ComponentTypeSymbol compType, @NonNull String paramName) { + Preconditions.checkNotNull(compType); + Preconditions.checkNotNull(paramName); + + VariableSymbol param = CompSymbolsMill + .variableSymbolBuilder() + .setName(paramName) + .setType(SymTypeExpressionFactory.createObscureType()) + .setAccessModifier(BasicAccessModifier.PUBLIC) + .build(); + + compType.getSpannedScope().add(param); + compType.addParameter(param); + + return param; + } + + /** + * Adds a type parameter to the component. + * + * @return the created type parameter + */ + protected TypeVarSymbol addTypeParameterTo(@NonNull ComponentTypeSymbol compType, + @NonNull String typeParamName) { + Preconditions.checkNotNull(compType); + Preconditions.checkNotNull(typeParamName); + + TypeVarSymbol typeVar = CompSymbolsMill + .typeVarSymbolBuilder() + .setName(typeParamName) + .setAccessModifier(BasicAccessModifier.PUBLIC) + .build(); + + compType.getSpannedScope().add(typeVar); + + return typeVar; + } + + protected static Map.Entry createCompWithSurrogate( + @NonNull String compName) { + Preconditions.checkNotNull(compName); + + ICompSymbolsScope commonScope = CompSymbolsMill.scope(); + + ComponentTypeSymbol symbol = CompSymbolsMill.componentTypeSymbolBuilder() + .setName(compName) + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + commonScope.add(symbol); + + ComponentTypeSymbolSurrogate surrogate = CompSymbolsMill.componentTypeSymbolSurrogateBuilder() + .setName(compName) + .setEnclosingScope(commonScope) + .build(); + + return Map.entry(symbol, surrogate); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolTest.java new file mode 100644 index 0000000000..36ff1e0fb4 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/ComponentTypeSymbolTest.java @@ -0,0 +1,257 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.types.check.CompKindOfComponentType; +import de.monticore.types.check.SymTypeExpressionFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +/** + * Holds tests for the handwritten methods of {@link ComponentTypeSymbol}. + */ +public class ComponentTypeSymbolTest { + + @Test + void shouldGetAllInheritedPortsWithOverlappingName() { + // Given + ComponentTypeSymbol parent = CompSymbolsMill.componentTypeSymbolBuilder() + .setSpannedScope(CompSymbolsMill.scope()) + .setName("sut") + .build(); + + PortSymbol p1 = CompSymbolsMill.portSymbolBuilder().setName("p").setType(SymTypeExpressionFactory.createObscureType()).build(); + PortSymbol p2 = CompSymbolsMill.portSymbolBuilder().setName("p").setType(SymTypeExpressionFactory.createObscureType()).build(); + + parent.getSpannedScope().add(p1); + parent.getSpannedScope().add(p2); + + ComponentTypeSymbol sut = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("sut") + .setSpannedScope(CompSymbolsMill.scope()) + .setSuperComponentsList(Collections.singletonList(new CompKindOfComponentType(parent))) + .build(); + + // When + Set ports = sut.getAllPorts(); + + // Then + assertIterableEquals(List.of(p1, p2), ports); + } + + @Test + public void shouldStateIfHasParameters() { + // Given + ComponentTypeSymbol compWithoutParameters = CompSymbolsMill.componentTypeSymbolBuilder().setName("Comp1") + .setSpannedScope(CompSymbolsMill.scope()).build(); + ComponentTypeSymbol compWithParameters = CompSymbolsMill.componentTypeSymbolBuilder().setName("Comp2") + .setSpannedScope(CompSymbolsMill.scope()).build(); + List params = Arrays.asList( + CompSymbolsMill.variableSymbolBuilder().setName("first").build(), + CompSymbolsMill.variableSymbolBuilder().setName("second").build(), + CompSymbolsMill.variableSymbolBuilder().setName("third").build() + ); + + // When + params.forEach(compWithParameters.getSpannedScope()::add); + compWithParameters.addAllParameter(params); + + // Then + assertFalse(compWithoutParameters.hasParameters()); + assertTrue(compWithParameters.hasParameters()); + assertEquals(3, compWithParameters.getParameterList().size()); + } + + @Test + public void shouldReturnParametersIfPresent() { + // Given + ComponentTypeSymbol compWithoutParameters = CompSymbolsMill.componentTypeSymbolBuilder().setName("Comp1") + .setSpannedScope(CompSymbolsMill.scope()).build(); + ComponentTypeSymbol compWithParameters = CompSymbolsMill.componentTypeSymbolBuilder().setName("Comp2") + .setSpannedScope(CompSymbolsMill.scope()).build(); + List params = Arrays.asList( + CompSymbolsMill.variableSymbolBuilder().setName("first").build(), + CompSymbolsMill.variableSymbolBuilder().setName("second").build(), + CompSymbolsMill.variableSymbolBuilder().setName("third").build() + ); + + // When + params.forEach(compWithParameters.getSpannedScope()::add); + compWithParameters.addAllParameter(params); + + // Then + for (VariableSymbol param : params) { + assertTrue(compWithParameters.getParameter(param.getName()).isPresent()); + assertFalse(compWithoutParameters.getParameter(param.getName()).isPresent()); + } + } + + @Test + public void shouldStateIfHasTypeParameters() { + // Given + ComponentTypeSymbol compWithoutTypeParameters = CompSymbolsMill.componentTypeSymbolBuilder().setName("Comp1") + .setSpannedScope(CompSymbolsMill.scope()).build(); + ComponentTypeSymbol compWithTypeParameters = CompSymbolsMill.componentTypeSymbolBuilder().setName("Comp2") + .setSpannedScope(CompSymbolsMill.scope()).build(); + List typeParams = Arrays.asList( + CompSymbolsMill.typeVarSymbolBuilder().setName("first").build(), + CompSymbolsMill.typeVarSymbolBuilder().setName("second").build(), + CompSymbolsMill.typeVarSymbolBuilder().setName("third").build() + ); + typeParams.forEach(compWithTypeParameters.getSpannedScope()::add); + + // When & Then + assertFalse(compWithoutTypeParameters.hasTypeParameter()); + assertTrue(compWithTypeParameters.hasTypeParameter()); + } + + @ParameterizedTest + @MethodSource("portNameAndDirectionProvider") + public void shouldReturnIncomingPortsOnly(Map ports) { + ComponentTypeSymbol symbol = buildTestComponentWithPorts(ports); + assertIterableEquals(ports.entrySet().stream() + .filter(p -> p.getValue().equals(true)).map(Map.Entry::getKey).collect(Collectors.toList()), + symbol.getIncomingPorts().stream().map(PortSymbol::getName).collect(Collectors.toList())); + } + + @ParameterizedTest + @MethodSource("portNameAndDirectionProvider") + public void shouldReturnOutgoingPortsOnly(Map ports) { + ComponentTypeSymbol symbol = buildTestComponentWithPorts(ports); + assertIterableEquals(ports.entrySet().stream() + .filter(p -> p.getValue().equals(false)).map(Map.Entry::getKey).collect(Collectors.toList()), + symbol.getOutgoingPorts().stream().map(PortSymbol::getName).collect(Collectors.toList())); + } + + @ParameterizedTest + @MethodSource("portNameAndDirectionProvider") + public void shouldFindPortWithExpectedDirection(Map ports) { + ComponentTypeSymbol symbol = buildTestComponentWithPorts(ports); + for (String port : ports.keySet()) { + if (ports.get(port)) { + assertTrue(symbol.getIncomingPort(port).isPresent()); + assertFalse(symbol.getOutgoingPort(port).isPresent()); + } else { + assertFalse(symbol.getIncomingPort(port).isPresent()); + assertTrue(symbol.getOutgoingPort(port).isPresent()); + } + } + } + + @ParameterizedTest + @MethodSource("portNameAndDirectionProvider") + public void shouldStateCorrectlyIFHasPorts(Map ports) { + ComponentTypeSymbol symbol = buildTestComponentWithPorts(ports); + if (ports.isEmpty()) { + assertFalse(symbol.hasPorts()); + } else { + assertTrue(symbol.hasPorts()); + } + } + + static Stream portNameAndDirectionProvider() { + LinkedHashMap ports1 = new LinkedHashMap<>(); + LinkedHashMap ports2 = new LinkedHashMap<>(); + ports2.put("o1", false); + ports2.put("o2", false); + LinkedHashMap ports3 = new LinkedHashMap<>(); + ports3.put("i1", true); + ports3.put("i2", true); + LinkedHashMap ports4 = new LinkedHashMap<>(); + ports4.put("i1", true); + ports4.put("o1", false); + ports4.put("i2", true); + ports4.put("o2", false); + return Stream.of(arguments(ports1), arguments(ports2), arguments(ports3), arguments(ports4)); + } + + private ComponentTypeSymbol buildTestComponentWithPorts(Map ports) { + ComponentTypeSymbol compSymbol = CompSymbolsMill.componentTypeSymbolBuilder().setName("Comp") + .setSpannedScope(CompSymbolsMill.scope()).build(); + for (String port : ports.keySet()) { + PortSymbol portSymbol = CompSymbolsMill.portSymbolBuilder() + .setName(port).setType(SymTypeExpressionFactory.createObscureType()).setIncoming(ports.get(port)).setOutgoing(!ports.get(port)).build(); + compSymbol.getSpannedScope().add(portSymbol); + } + return compSymbol; + } + + @ParameterizedTest + @MethodSource("instanceNamesProvider") + public void shouldFindSubComponents(List instances) { + ComponentTypeSymbol symbol = builtTestComponentWithInstances(instances); + assertEquals(symbol.getSubcomponents().size(), instances.size()); + assertIterableEquals(symbol.getSubcomponents() + .stream().map(SubcomponentSymbol::getName).collect(Collectors.toList()), instances); + } + + static Stream instanceNamesProvider() { + return Stream.of( + arguments(Collections.emptyList()), + arguments(Arrays.asList("sub1", "sub2", "sub3"))); + } + + @Test + public void shouldFindExpectedSubComponent() { + List instances = Arrays.asList("sub1", "sub2", "sub3"); + ComponentTypeSymbol symbol = this.builtTestComponentWithInstances(instances); + for (String instance : instances) { + assertTrue(symbol.getSubcomponents(instance).isPresent()); + assertEquals(symbol.getSubcomponents(instance).get().getName(), instance); + } + } + + @Test + public void shouldNotFindUnexpectedSubComponent() { + ComponentTypeSymbol symbol1 = this.builtTestComponentWithInstances(Collections.emptyList()); + ComponentTypeSymbol symbol2 = this.builtTestComponentWithInstances( + Arrays.asList("sub1", "sub2", "sub3")); + assertFalse(symbol1.getSubcomponents("sub4").isPresent()); + assertFalse(symbol2.getSubcomponents("sub4").isPresent()); + } + + @Test + void shouldBeAtomicOrDecomposed() { + ComponentTypeSymbol composedComponent = + builtTestComponentWithInstances(Arrays.asList("a", "b", "c")); + ComponentTypeSymbol atomicComponent = + builtTestComponentWithInstances(Collections.emptyList()); + assertTrue(composedComponent.isDecomposed()); + assertFalse(composedComponent.isAtomic()); + assertFalse(atomicComponent.isDecomposed()); + assertTrue(atomicComponent.isAtomic()); + } + + private ComponentTypeSymbol builtTestComponentWithInstances(List instances) { + ComponentTypeSymbol compSymbol = CompSymbolsMill.componentTypeSymbolBuilder().setName("Comp") + .setSpannedScope(CompSymbolsMill.scope()).build(); + for (String instance : instances) { + SubcomponentSymbol subCompSymbol = CompSymbolsMill.subcomponentSymbolBuilder() + .setName(instance) + .setType(new CompKindOfComponentType( + CompSymbolsMill.componentTypeSymbolSurrogateBuilder() + .setName("empty") + .setEnclosingScope(compSymbol.getSpannedScope()) + .build())) + .build(); + compSymbol.getSpannedScope().add(subCompSymbol); + } + return compSymbol; + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/Port2VariableAdapterTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/Port2VariableAdapterTest.java new file mode 100644 index 0000000000..4e638b8356 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/Port2VariableAdapterTest.java @@ -0,0 +1,116 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import com.google.common.base.Preconditions; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.symboltable.modifiers.BasicAccessModifier; +import de.monticore.types.check.SymTypeExpressionFactory; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Port2VariableAdapterTest { + + @BeforeEach + public void setup() { + CompSymbolsMill.reset(); + CompSymbolsMill.init(); + BasicSymbolsMill.initializePrimitives(); + } + + @ParameterizedTest + @CsvSource({ + // name, in, out + "in, true, false", + "out, false, true", + "inout, true, true" + }) + void shouldAdaptFields(@NonNull String name, boolean in, boolean out) { + Preconditions.checkNotNull(name); + + // Given + PortSymbol adaptee = CompSymbolsMill.portSymbolBuilder() + .setName(name) + .setIncoming(in) + .setOutgoing(out) + .setType(SymTypeExpressionFactory + .createPrimitive(BasicSymbolsMill.BOOLEAN)) + .build(); + ICompSymbolsScope scope = CompSymbolsMill.scope(); + scope.add(adaptee); + adaptee.setEnclosingScope(scope); + + Port2VariableAdapter adapter = new Port2VariableAdapter(adaptee); + + // Then + assertAll( + () -> assertEquals(adaptee.getName(), adapter.getName(), + "The adapter's name should match the adaptee's name."), + () -> assertEquals(adaptee.getFullName(), adapter.getFullName(), + "The adapter's full name should match the adaptee's full name."), + () -> assertEquals(adaptee.getType(), adapter.getType(), + "The adapter's type should match the adaptee's type."), + () -> assertEquals(adaptee.isIncoming(), adapter.isIsReadOnly(), + "The adapter should be read only if the adaptee is an incoming port."), + () -> assertEquals(adaptee.getEnclosingScope(), adapter.getEnclosingScope(), + "The adapter's enclosing scope should match the adaptee's enclosing scope."), + () -> assertEquals(adaptee.getSourcePosition(), adapter.getSourcePosition(), + "The adapter's source position should match the adaptee's source position."), + () -> assertEquals(BasicAccessModifier.PUBLIC, adapter.getAccessModifier(), + "The adapter should have a public access modifier as ports are the public interface of a component.") + ); + } + + @ParameterizedTest + @CsvSource({ + // name, in, out + "in, true, false", + "out, false, true", + "inout, true, true" + }) + void shouldDeepClone(@NonNull String name, boolean in, boolean out) { + Preconditions.checkNotNull(name); + + // Given + PortSymbol adaptee = CompSymbolsMill.portSymbolBuilder() + .setName(name) + .setIncoming(in) + .setOutgoing(out) + .setType(SymTypeExpressionFactory + .createPrimitive(BasicSymbolsMill.BOOLEAN)) + .build(); + ICompSymbolsScope scope = CompSymbolsMill.scope(); + scope.add(adaptee); + adaptee.setEnclosingScope(scope); + + Port2VariableAdapter adapter = new Port2VariableAdapter(adaptee); + + // When + Port2VariableAdapter clone = adapter.deepClone(); + + // Then + assertAll( + () -> assertEquals(adapter.getAdaptee(), clone.getAdaptee(), + "The clone's adaptee should match the adapter's adaptee."), + () -> assertEquals(adapter.getName(), clone.getName(), + "The clone's name should match the adapter's name."), + () -> assertEquals(adapter.getFullName(), clone.getFullName(), + "The clone's full name should match the adapter's full name."), + () -> assertEquals(adapter.getType(), clone.getType(), + "The clone's type should match the adapter's type."), + () -> assertEquals(adapter.isIsReadOnly(), clone.isIsReadOnly(), + "The clone should be read only if the adapter is read only."), + () -> assertEquals(adapter.getEnclosingScope(), clone.getEnclosingScope(), + "The clone's enclosing scope should match the adapter's enclosing scope."), + () -> assertEquals(adapter.isPresentAstNode(), clone.isPresentAstNode(), + "The clone should have an ast node if the adapter has an ast node."), + () -> assertEquals(adapter.getAccessModifier(), clone.getAccessModifier(), + "The clone's access modifier should match the adapter's access modifier.") + ); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/Subcomponent2VariableAdapterTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/Subcomponent2VariableAdapterTest.java new file mode 100644 index 0000000000..f3d4d27cfe --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/compsymbols/_symboltable/Subcomponent2VariableAdapterTest.java @@ -0,0 +1,116 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.symbols.compsymbols._symboltable; + +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.symboltable.modifiers.BasicAccessModifier; +import de.monticore.types.check.CompKindOfComponentType; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Holds tests for {@link Subcomponent2VariableAdapter}. + */ +public class Subcomponent2VariableAdapterTest { + + @Test + void shouldAdaptFields() { + // Given + ICompSymbolsScope scope = CompSymbolsMill.scope(); + ComponentTypeSymbol type = CompSymbolsMill.componentTypeSymbolSurrogateBuilder().setName("empty").setEnclosingScope(scope).build(); + type.setSpannedScope(CompSymbolsMill.scope()); + SubcomponentSymbol adaptee = CompSymbolsMill.subcomponentSymbolBuilder() + .setName("sub") + .setType(new CompKindOfComponentType(type)) + .setEnclosingScope(scope) + .build(); + scope.add(adaptee); + + Subcomponent2VariableAdapter adapter = new Subcomponent2VariableAdapter(adaptee); + + // Then + assertAll( + () -> assertEquals(adaptee.getName(), adapter.getName(), + "The adapter's name should match the adaptee's name."), + () -> assertEquals(adaptee.getFullName(), adapter.getFullName(), + "The adapter's full name should match the adaptee's full name."), + () -> assertEquals(adaptee.getType().getTypeInfo(), ((ComponentType2TypeSymbolAdapter) adapter.getType().getTypeInfo()).getAdaptee(), + "The adapter's type should match the adaptee's type."), + () -> assertEquals(adaptee.getEnclosingScope(), adapter.getEnclosingScope(), + "The adapter's enclosing scope should match the adaptee's enclosing scope."), + () -> assertEquals(adaptee.getSourcePosition(), adapter.getSourcePosition(), + "The adapter's source position should match the adaptee's source position."), + () -> assertEquals(BasicAccessModifier.PRIVATE, adapter.getAccessModifier(), + "The adapter should have a public access modifier as ports are the public interface of a component.") + ); + } + + @Test + void shouldDeepClone() { + // Given + ICompSymbolsScope scope = CompSymbolsMill.scope(); + ComponentTypeSymbol type = CompSymbolsMill.componentTypeSymbolSurrogateBuilder().setName("empty").setEnclosingScope(scope).build(); + type.setSpannedScope(CompSymbolsMill.scope()); + SubcomponentSymbol adaptee = CompSymbolsMill.subcomponentSymbolBuilder() + .setName("sub") + .setType(new CompKindOfComponentType(type)) + .setEnclosingScope(scope) + .build(); + scope.add(adaptee); + + Subcomponent2VariableAdapter adapter = new Subcomponent2VariableAdapter(adaptee); + + // When + Subcomponent2VariableAdapter clone = adapter.deepClone(); + + // Then + assertAll( + () -> assertEquals(adapter.getAdaptee(), clone.getAdaptee(), + "The clone's adaptee should match the adapter's adaptee."), + () -> assertEquals(adapter.getName(), clone.getName(), + "The clone's name should match the adapter's name."), + () -> assertEquals(adapter.getFullName(), clone.getFullName(), + "The clone's full name should match the adapter's full name."), + () -> assertEquals(((ComponentType2TypeSymbolAdapter) adapter.getType().getTypeInfo()).getAdaptee(), ((ComponentType2TypeSymbolAdapter) clone.getType().getTypeInfo()).getAdaptee(), + "The clone's type should match the adapter's type."), + () -> assertEquals(adapter.isIsReadOnly(), clone.isIsReadOnly(), + "The clone should be read only if the adapter is read only."), + () -> assertEquals(adapter.getEnclosingScope(), clone.getEnclosingScope(), + "The clone's enclosing scope should match the adapter's enclosing scope."), + () -> assertEquals(adapter.isPresentAstNode(), clone.isPresentAstNode(), + "The clone should have an ast node if the adapter has an ast node."), + () -> assertEquals(adapter.getAccessModifier(), clone.getAccessModifier(), + "The clone's access modifier should match the adapter's access modifier.") + ); + } + + @Test + void shouldNotThrowErrorIfTypeIsMissing() { + // Given + SubcomponentSymbol adaptee = CompSymbolsMill.subcomponentSymbolBuilder() + .setName("sub") + .build(); + ICompSymbolsScope scope = CompSymbolsMill.scope(); + scope.add(adaptee); + adaptee.setEnclosingScope(scope); + + // When + Subcomponent2VariableAdapter adapter = new Subcomponent2VariableAdapter(adaptee); + + // Then + assertAll( + () -> assertEquals(adaptee.getName(), adapter.getName(), + "The adapter's name should match the adaptee's name."), + () -> assertEquals(adaptee.getFullName(), adapter.getFullName(), + "The adapter's full name should match the adaptee's full name."), + () -> assertTrue(adapter.getType().isObscureType(), + "The adapter's type should be obscure."), + () -> assertEquals(adaptee.getEnclosingScope(), adapter.getEnclosingScope(), + "The adapter's enclosing scope should match the adaptee's enclosing scope."), + () -> assertEquals(adaptee.getSourcePosition(), adapter.getSourcePosition(), + "The adapter's source position should match the adaptee's source position."), + () -> assertEquals(BasicAccessModifier.PRIVATE, adapter.getAccessModifier(), + "The adapter should have a public access modifier as ports are the public interface of a component.") + ); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/CloneTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/CloneTest.java index e2c64a11d7..264c7ad22d 100644 --- a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/CloneTest.java +++ b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/CloneTest.java @@ -7,13 +7,12 @@ import de.monticore.types.check.SymTypeExpressionFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class CloneTest { @@ -54,42 +53,43 @@ public void init(){ @Test public void testMethod(){ List methodsAllInclusion = symbolTable.resolveMethodMany("foo"); - Assertions.assertEquals(1, methodsAllInclusion.size()); + assertEquals(1, methodsAllInclusion.size()); MethodSymbol methodSymbol = methodsAllInclusion.get(0); MethodSymbol cloneSymbol = methodSymbol.deepClone(); - Assertions.assertEquals(methodSymbol.getName(), cloneSymbol.getName()); - Assertions.assertEquals(methodSymbol.getParameterList().size(), cloneSymbol.getParameterList().size()); - Assertions.assertEquals(methodSymbol.isIsMethod(), cloneSymbol.isIsMethod()); - Assertions.assertEquals(methodSymbol.isIsPrivate(), cloneSymbol.isIsPrivate()); - Assertions.assertEquals(methodSymbol.isIsPublic(), cloneSymbol.isIsPublic()); - Assertions.assertEquals(methodSymbol.isIsProtected(), cloneSymbol.isIsProtected()); - Assertions.assertEquals(methodSymbol.isIsAbstract(), cloneSymbol.isIsAbstract()); - Assertions.assertEquals(methodSymbol.isIsStatic(), cloneSymbol.isIsStatic()); - Assertions.assertEquals(methodSymbol.isIsFinal(), cloneSymbol.isIsFinal()); - Assertions.assertEquals(methodSymbol.isIsElliptic(), cloneSymbol.isIsElliptic()); - Assertions.assertEquals(methodSymbol.isIsConstructor(), cloneSymbol.isIsConstructor()); - Assertions.assertEquals(methodSymbol.getType().asPrimitive().getPrimitiveName(), cloneSymbol.getType().asPrimitive().getPrimitiveName()); + assertEquals(methodSymbol.getName(), cloneSymbol.getName()); + assertEquals(methodSymbol.getParameterList().size(), cloneSymbol.getParameterList().size()); + assertEquals(methodSymbol.isIsMethod(), cloneSymbol.isIsMethod()); + assertEquals(methodSymbol.isIsPrivate(), cloneSymbol.isIsPrivate()); + assertEquals(methodSymbol.isIsPublic(), cloneSymbol.isIsPublic()); + assertEquals(methodSymbol.isIsProtected(), cloneSymbol.isIsProtected()); + assertEquals(methodSymbol.isIsAbstract(), cloneSymbol.isIsAbstract()); + assertEquals(methodSymbol.isIsStatic(), cloneSymbol.isIsStatic()); + assertEquals(methodSymbol.isIsFinal(), cloneSymbol.isIsFinal()); + assertEquals(methodSymbol.isIsElliptic(), cloneSymbol.isIsElliptic()); + assertEquals(methodSymbol.isIsConstructor(), cloneSymbol.isIsConstructor()); + assertEquals(methodSymbol.getType().asPrimitive().getPrimitiveName(), cloneSymbol.getType().asPrimitive().getPrimitiveName()); } @Test public void testField(){ List fieldsAllInclusion = symbolTable.resolveFieldMany("bar"); - Assertions.assertEquals(1, fieldsAllInclusion.size()); + assertEquals(1, fieldsAllInclusion.size()); FieldSymbol fieldSymbol = fieldsAllInclusion.get(0); FieldSymbol cloneSymbol = fieldSymbol.deepClone(); - Assertions.assertEquals(fieldSymbol.getName(), cloneSymbol.getName()); - Assertions.assertEquals(fieldSymbol.getType().asPrimitive().getPrimitiveName(), cloneSymbol.getType().asPrimitive().getPrimitiveName()); - Assertions.assertEquals(fieldSymbol.isIsFinal(), cloneSymbol.isIsFinal()); - Assertions.assertEquals(fieldSymbol.isIsPrivate(), cloneSymbol.isIsPrivate()); - Assertions.assertEquals(fieldSymbol.isIsProtected(), cloneSymbol.isIsProtected()); - Assertions.assertEquals(fieldSymbol.isIsPublic(), cloneSymbol.isIsPublic()); - Assertions.assertEquals(fieldSymbol.isIsStatic(), cloneSymbol.isIsStatic()); - Assertions.assertEquals(fieldSymbol.isIsDerived(), cloneSymbol.isIsDerived()); - Assertions.assertEquals(fieldSymbol.isIsReadOnly(), cloneSymbol.isIsReadOnly()); + assertEquals(fieldSymbol.getName(), cloneSymbol.getName()); + assertEquals(fieldSymbol.getType().asPrimitive().getPrimitiveName(), cloneSymbol.getType().asPrimitive().getPrimitiveName()); + assertEquals(fieldSymbol.isIsFinal(), cloneSymbol.isIsFinal()); + assertEquals(fieldSymbol.isIsPrivate(), cloneSymbol.isIsPrivate()); + assertEquals(fieldSymbol.isIsProtected(), cloneSymbol.isIsProtected()); + assertEquals(fieldSymbol.isIsPublic(), cloneSymbol.isIsPublic()); + assertEquals(fieldSymbol.isIsStatic(), cloneSymbol.isIsStatic()); + assertEquals(fieldSymbol.isIsEnumConstant(), cloneSymbol.isIsEnumConstant()); + assertEquals(fieldSymbol.isIsDerived(), cloneSymbol.isIsDerived()); + assertEquals(fieldSymbol.isIsReadOnly(), cloneSymbol.isIsReadOnly()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/ModifierTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/ModifierTest.java index 412265c11a..6d93f4fc10 100644 --- a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/ModifierTest.java +++ b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/ModifierTest.java @@ -10,12 +10,13 @@ import de.monticore.types.check.SymTypeExpressionFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class ModifierTest { protected IOOSymbolsScope symbolTable; @@ -98,67 +99,67 @@ public void init(){ @Test public void testType(){ List typesAllInclusion = symbolTable.resolveOOTypeMany("Test"); - Assertions.assertEquals(6, typesAllInclusion.size()); + assertEquals(6, typesAllInclusion.size()); List typesPublic = symbolTable.resolveOOTypeMany("Test", BasicAccessModifier.PUBLIC); - Assertions.assertEquals(1, typesPublic.size()); + assertEquals(1, typesPublic.size()); List typesProtected = symbolTable.resolveOOTypeMany("Test", BasicAccessModifier.PROTECTED); - Assertions.assertEquals(2, typesProtected.size()); + assertEquals(2, typesProtected.size()); List typesPrivate = symbolTable.resolveOOTypeMany("Test", BasicAccessModifier.PRIVATE); - Assertions.assertEquals(6, typesPrivate.size()); + assertEquals(6, typesPrivate.size()); List typesStatic = symbolTable.resolveOOTypeMany("Test", StaticAccessModifier.STATIC); - Assertions.assertEquals(2, typesStatic.size()); + assertEquals(2, typesStatic.size()); List typesPrivateStatic = symbolTable .resolveOOTypeMany("Test", new CompoundAccessModifier(List.of(BasicAccessModifier.PRIVATE, StaticAccessModifier.STATIC))); - Assertions.assertEquals(2, typesPrivateStatic.size()); + assertEquals(2, typesPrivateStatic.size()); } @Test public void testMethod(){ List methodsAllInclusion = symbolTable.resolveMethodMany("foo"); - Assertions.assertEquals(6, methodsAllInclusion.size()); + assertEquals(6, methodsAllInclusion.size()); List methodsPublic = symbolTable.resolveMethodMany("foo", BasicAccessModifier.PUBLIC); - Assertions.assertEquals(1, methodsPublic.size()); + assertEquals(1, methodsPublic.size()); List methodsProtected = symbolTable.resolveMethodMany("foo", BasicAccessModifier.PROTECTED); - Assertions.assertEquals(3, methodsProtected.size()); + assertEquals(3, methodsProtected.size()); List methodsPrivate = symbolTable.resolveMethodMany("foo", BasicAccessModifier.PRIVATE); - Assertions.assertEquals(6, methodsPrivate.size()); + assertEquals(6, methodsPrivate.size()); List methodsStatic = symbolTable.resolveMethodMany("foo", StaticAccessModifier.STATIC); - Assertions.assertEquals(2, methodsStatic.size()); + assertEquals(2, methodsStatic.size()); List methodsProtectedStatic = symbolTable .resolveMethodMany("foo", new CompoundAccessModifier(List.of(BasicAccessModifier.PROTECTED, StaticAccessModifier.STATIC))); - Assertions.assertEquals(1, methodsProtectedStatic.size()); + assertEquals(1, methodsProtectedStatic.size()); } @Test public void testField(){ List fieldsAllInclusion = symbolTable.resolveFieldMany("bar"); - Assertions.assertEquals(6, fieldsAllInclusion.size()); + assertEquals(6, fieldsAllInclusion.size()); List fieldsPublic = symbolTable.resolveFieldMany("bar", BasicAccessModifier.PUBLIC); - Assertions.assertEquals(2, fieldsPublic.size()); + assertEquals(2, fieldsPublic.size()); List fieldsProtected = symbolTable.resolveFieldMany("bar", BasicAccessModifier.PROTECTED); - Assertions.assertEquals(3, fieldsProtected.size()); + assertEquals(3, fieldsProtected.size()); List fieldsPrivate = symbolTable.resolveFieldMany("bar", BasicAccessModifier.PRIVATE); - Assertions.assertEquals(6, fieldsPrivate.size()); + assertEquals(6, fieldsPrivate.size()); List fieldsStatic = symbolTable.resolveFieldMany("bar", StaticAccessModifier.STATIC); - Assertions.assertEquals(2, fieldsStatic.size()); + assertEquals(2, fieldsStatic.size()); List fieldsPublicStatic = symbolTable .resolveFieldMany("bar", new CompoundAccessModifier(BasicAccessModifier.PUBLIC, StaticAccessModifier.STATIC)); - Assertions.assertEquals(1, fieldsPublicStatic.size()); + assertEquals(1, fieldsPublicStatic.size()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/OOSymbolsModifierTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/OOSymbolsModifierTest.java index 8bc77956e1..79888b9d4c 100644 --- a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/OOSymbolsModifierTest.java +++ b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/OOSymbolsModifierTest.java @@ -2,13 +2,11 @@ package de.monticore.symbols.oosymbols._symboltable; import de.monticore.symbols.oosymbols.OOSymbolsMill; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class OOSymbolsModifierTest { @@ -22,105 +20,105 @@ public void setup() { public void testOOTypeSymbolModifier() { OOTypeSymbol symbol = OOSymbolsMill.oOTypeSymbolBuilder().setName("Foo").build(); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsPublic(true); - Assertions.assertTrue(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertTrue(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsPrivate(true); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertTrue(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertTrue(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsProtected(true); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertTrue(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertTrue(symbol.isIsProtected()); symbol.setIsProtected(false); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); } @Test public void testFieldSymbolModifier() { FieldSymbol symbol = OOSymbolsMill.fieldSymbolBuilder().setName("Foo").build(); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsPublic(true); - Assertions.assertTrue(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertTrue(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsPrivate(true); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertTrue(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertTrue(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsProtected(true); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertTrue(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertTrue(symbol.isIsProtected()); symbol.setIsProtected(false); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); } @Test public void testMethodSymbolModifier() { MethodSymbol symbol = OOSymbolsMill.methodSymbolBuilder().setName("Foo").build(); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsPublic(true); - Assertions.assertTrue(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertTrue(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsPrivate(true); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertTrue(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertTrue(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); symbol.setIsProtected(true); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertTrue(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertTrue(symbol.isIsProtected()); symbol.setIsProtected(false); - Assertions.assertFalse(symbol.isIsPublic()); - Assertions.assertFalse(symbol.isIsPrivate()); - Assertions.assertFalse(symbol.isIsProtected()); + assertFalse(symbol.isIsPublic()); + assertFalse(symbol.isIsPrivate()); + assertFalse(symbol.isIsProtected()); - Assertions.assertFalse(symbol.isAbstract); + assertFalse(symbol.isAbstract); symbol.setIsAbstract(true); - Assertions.assertTrue(symbol.isAbstract); + assertTrue(symbol.isAbstract); } diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/OOSymbolsSymbols2JsonTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/OOSymbolsSymbols2JsonTest.java index a0842bf4df..d507d25221 100644 --- a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/OOSymbolsSymbols2JsonTest.java +++ b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/_symboltable/OOSymbolsSymbols2JsonTest.java @@ -8,12 +8,13 @@ import de.monticore.types.check.SymTypeExpressionFactory; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class OOSymbolsSymbols2JsonTest { private IOOSymbolsArtifactScope scope; @@ -43,7 +44,7 @@ public void init() { type.setSpannedScope(typeSpannedScope); - SymTypeExpression symType1 = SymTypeExpressionFactory.createTypeObject("Type", scope); + SymTypeExpression symType1 = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Type", scope); //put subtype into main scope, test if supertypes are serialized correctly OOTypeSymbol subtype = OOSymbolsMill.oOTypeSymbolBuilder() @@ -84,7 +85,7 @@ public void init() { public void testDeSer(){ performRoundTripSerialization(scope); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -95,23 +96,23 @@ public void performRoundTripSerialization(IOOSymbolsScope scope){ // then deserialize it OOSymbolsSymbols2Json symbols2Json = new OOSymbolsSymbols2Json(); IOOSymbolsArtifactScope deserialized = symbols2Json.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); // and assert that the deserialized scope equals the one before Optional type = scope.resolveOOType("Type"); Optional deserializedType = deserialized.resolveOOType("Type"); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(deserializedType.isPresent()); + assertTrue(type.isPresent()); + assertTrue(deserializedType.isPresent()); //check that both can resolve the type "SubType" with the supertype "Type" Optional subtype = scope.resolveOOType("SubType"); Optional deserializedSubType = deserialized.resolveOOType("SubType"); - Assertions.assertTrue(subtype.isPresent()); - Assertions.assertTrue(deserializedSubType.isPresent()); - Assertions.assertEquals(1, subtype.get().getSuperTypesList().size()); - Assertions.assertEquals(1, deserializedSubType.get().getSuperTypesList().size()); - Assertions.assertEquals("Type", subtype.get().getSuperTypesList().get(0).print()); - Assertions.assertEquals("Type", deserializedSubType.get().getSuperTypesList().get(0).print()); + assertTrue(subtype.isPresent()); + assertTrue(deserializedSubType.isPresent()); + assertEquals(1, subtype.get().getSuperTypesList().size()); + assertEquals(1, deserializedSubType.get().getSuperTypesList().size()); + assertEquals("Type", subtype.get().getSuperTypesList().get(0).print()); + assertEquals("Type", deserializedSubType.get().getSuperTypesList().get(0).print()); IOOSymbolsScope typeSpanned = type.get().getSpannedScope(); IOOSymbolsScope deserializedTypeSpanned = deserializedType.get().getSpannedScope(); @@ -119,27 +120,27 @@ public void performRoundTripSerialization(IOOSymbolsScope scope){ //check for Variable variable in Type Optional variable = typeSpanned.resolveField("variable"); Optional deserializedVariable = deserializedTypeSpanned.resolveField("variable"); - Assertions.assertTrue(variable.isPresent()); - Assertions.assertTrue(deserializedVariable.isPresent()); - Assertions.assertEquals("double", variable.get().getType().print()); - Assertions.assertEquals("double", deserializedVariable.get().getType().print()); + assertTrue(variable.isPresent()); + assertTrue(deserializedVariable.isPresent()); + assertEquals("double", variable.get().getType().print()); + assertEquals("double", deserializedVariable.get().getType().print()); //check for Function function in Type Optional function = typeSpanned.resolveMethod("function"); Optional deserializedFunction = deserializedTypeSpanned.resolveMethod("function"); - Assertions.assertTrue(function.isPresent()); - Assertions.assertTrue(deserializedFunction.isPresent()); - Assertions.assertEquals("int", function.get().getType().print()); - Assertions.assertEquals("int", deserializedFunction.get().getType().print()); + assertTrue(function.isPresent()); + assertTrue(deserializedFunction.isPresent()); + assertEquals("int", function.get().getType().print()); + assertEquals("int", deserializedFunction.get().getType().print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSerializedUnknownKind() { OOSymbolsSymbols2Json symbols2Json = new OOSymbolsSymbols2Json(); symbols2Json.deserialize("{\"symbols\": [{\"kind\":\"unknown\", \"name\":\"test\"}]}"); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -150,13 +151,13 @@ public void testInvalidJsonForSerializingReturnsError(){ OOSymbolsSymbols2Json symbols2Json = new OOSymbolsSymbols2Json(); symbols2Json.deserialize(invalidJsonForSerializing); - Assertions.assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xA1238")); + assertTrue(Log.getFindings().get(0).getMsg().startsWith("0xA1238")); symbols2Json.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(1).getMsg().startsWith("0xA1233")); + assertTrue(Log.getFindings().get(1).getMsg().startsWith("0xA1233")); symbols2Json.deserialize(invalidJsonForSerializing3); - Assertions.assertTrue(Log.getFindings().get(2).getMsg().startsWith("0xA0572")); + assertTrue(Log.getFindings().get(2).getMsg().startsWith("0xA0572")); } } diff --git a/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/types3/OOSymbolsSymTypeRelationsTest.java b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/types3/OOSymbolsSymTypeRelationsTest.java new file mode 100644 index 0000000000..02022af8d0 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/symbols/oosymbols/types3/OOSymbolsSymTypeRelationsTest.java @@ -0,0 +1,239 @@ +// (c) https://github.com/MontiCore/monticore +package de.monticore.symbols.oosymbols.types3; + +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.oosymbols.OOSymbolsMill; +import de.monticore.symbols.oosymbols._symboltable.FieldSymbol; +import de.monticore.symbols.oosymbols._symboltable.IOOSymbolsScope; +import de.monticore.symbols.oosymbols._symboltable.MethodSymbol; +import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types.check.SymTypeOfFunction; +import de.monticore.types3.AbstractTypeVisitorTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.List; +import java.util.Optional; + +import static de.monticore.types.check.SymTypeExpressionFactory.createFunction; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; +import static de.monticore.types3.util.DefsTypesForTests._intSymType; +import static de.monticore.types3.util.DefsTypesForTests._unboxedString; +import static de.monticore.types3.util.DefsTypesForTests.field; +import static de.monticore.types3.util.DefsTypesForTests.inScope; +import static de.monticore.types3.util.DefsTypesForTests.method; +import static de.monticore.types3.util.DefsTypesForTests.oOtype; +import static de.monticore.types3.util.DefsTypesForTests.variable; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class OOSymbolsSymTypeRelationsTest extends AbstractTypeVisitorTest { + + protected SymTypeExpression myClassType; + protected SymTypeExpression myClassConstructorType; + protected SymTypeExpression myClassGetNameType; + protected SymTypeExpression myInterfaceType; + protected SymTypeExpression myFunctionalInterfaceType; + protected SymTypeExpression myFunctionalInterfaceApplyType; + protected SymTypeExpression myFunctionalInterfaceSubType; + protected SymTypeExpression myNonFunctionalInterfaceSubType; + protected SymTypeExpression myEnumType; + protected SymTypeExpression myEnumVal1Type; + protected SymTypeExpression myEnumVal2Type; + protected SymTypeExpression myEnumDefaultType; + + @BeforeEach + public void init() throws IOException { + OOSymbolsSymTypeRelations.init(); + initTypes(); + } + + protected void initTypes() throws IOException { + IOOSymbolsScope gs = OOSymbolsMill.globalScope(); + + OOTypeSymbol myClassSym = inScope(gs, oOtype("MyClass")); + myClassSym.setIsClass(true); + VariableSymbol myClassVar = inScope(gs, + variable("myClass", createTypeObject(myClassSym)) + ); + MethodSymbol myClassGetNameSym = inScope(myClassSym.getSpannedScope(), + method("getName", _unboxedString) + ); + myClassGetNameSym.setIsMethod(true); + MethodSymbol myClassConstructorSym = inScope(myClassSym.getSpannedScope(), + method("MyClass", createTypeObject(myClassSym)) + ); + myClassConstructorSym.setIsConstructor(true); + + OOTypeSymbol myInterfaceSym = inScope(gs, oOtype("MyInterface")); + myInterfaceSym.setIsInterface(true); + + OOTypeSymbol myFunctionalInterfaceSym = inScope(gs, + oOtype("MyFunctionalInterface") + ); + myFunctionalInterfaceSym.setIsInterface(true); + MethodSymbol myFunctionalInterfaceApplySym = + inScope(myFunctionalInterfaceSym.getSpannedScope(), + method("apply", _intSymType) + ); + myFunctionalInterfaceApplySym.setIsAbstract(true); + MethodSymbol myFunctionalInterfaceGetNameSym = + inScope(myFunctionalInterfaceSym.getSpannedScope(), + method("getName", _unboxedString) + ); + + OOTypeSymbol myFunctionalInterfaceSub = inScope(gs, oOtype( + "MyFunctionalInterfaceSub", + List.of(createTypeObject(myFunctionalInterfaceSym)) + )); + myFunctionalInterfaceSub.setIsInterface(true); + + OOTypeSymbol myNonFunctionalInterfaceSub = inScope(gs, oOtype( + "MyNonFunctionalInterfaceSub", + List.of(createTypeObject(myFunctionalInterfaceSym)) + )); + myNonFunctionalInterfaceSub.setIsInterface(true); + MethodSymbol myNonFunctionalInterfaceApply = inScope( + myNonFunctionalInterfaceSub.getSpannedScope(), + method("apply", _intSymType) + ); + + OOTypeSymbol myEnumSym = inScope(gs, oOtype("MyEnum")); + myEnumSym.setIsEnum(true); + FieldSymbol enumVal1Sym = inScope(myEnumSym.getSpannedScope(), + field("ENUM_VAL1", createTypeObject(myEnumSym)) + ); + enumVal1Sym.setIsStatic(true); + enumVal1Sym.setIsFinal(true); + enumVal1Sym.setIsEnumConstant(true); + FieldSymbol enumVal2Sym = inScope(myEnumSym.getSpannedScope(), + field("ENUM_VAL2", createTypeObject(myEnumSym)) + ); + enumVal2Sym.setIsStatic(true); + enumVal2Sym.setIsFinal(true); + enumVal2Sym.setIsEnumConstant(true); + FieldSymbol enumDefaultSym = inScope(myEnumSym.getSpannedScope(), + field("ENUM_DEFAULT", createTypeObject(myEnumSym)) + ); + enumDefaultSym.setIsStatic(true); + enumDefaultSym.setIsFinal(true); + + myClassType = getTypeOfMCType("MyClass"); + myClassConstructorType = createFunction(myClassConstructorSym); + myClassGetNameType = createFunction(myClassGetNameSym); + myInterfaceType = getTypeOfMCType("MyInterface"); + myFunctionalInterfaceType = createTypeObject(myFunctionalInterfaceSym); + myFunctionalInterfaceApplyType = createFunction(myFunctionalInterfaceApplySym); + myFunctionalInterfaceSubType = getTypeOfMCType("MyFunctionalInterfaceSub"); + myNonFunctionalInterfaceSubType = getTypeOfMCType("MyNonFunctionalInterfaceSub"); + myEnumType = getTypeOfMCType("MyEnum"); + myEnumVal1Type = getTypeOfExpr("MyEnum.ENUM_VAL1"); + myEnumVal2Type = getTypeOfExpr("MyEnum.ENUM_VAL2"); + myEnumDefaultType = getTypeOfExpr("MyEnum.ENUM_DEFAULT"); + MCAssertions.assertNoFindings(); + } + + @Test + public void recognizeClasses() { + assertFalse(OOSymbolsSymTypeRelations.isClass(_intSymType)); + assertFalse(OOSymbolsSymTypeRelations.isClass(_unboxedString)); + assertTrue(OOSymbolsSymTypeRelations.isClass(myClassType)); + assertFalse(OOSymbolsSymTypeRelations.isClass(myInterfaceType)); + assertFalse(OOSymbolsSymTypeRelations.isClass(myEnumType)); + } + + @Test + public void recognizeInterfaces() { + assertFalse(OOSymbolsSymTypeRelations.isInterface(_intSymType)); + assertFalse(OOSymbolsSymTypeRelations.isInterface(_unboxedString)); + assertFalse(OOSymbolsSymTypeRelations.isInterface(myClassType)); + assertTrue(OOSymbolsSymTypeRelations.isInterface(myInterfaceType)); + assertFalse(OOSymbolsSymTypeRelations.isInterface(myEnumType)); + } + + @Test + public void recognizeEnums() { + assertFalse(OOSymbolsSymTypeRelations.isEnum(_intSymType)); + assertFalse(OOSymbolsSymTypeRelations.isEnum(_unboxedString)); + assertFalse(OOSymbolsSymTypeRelations.isEnum(myClassType)); + assertFalse(OOSymbolsSymTypeRelations.isEnum(myInterfaceType)); + assertTrue(OOSymbolsSymTypeRelations.isEnum(myEnumType)); + } + + @Test + public void recognizeMethods() { + assertFalse(OOSymbolsSymTypeRelations.isMethod(_intSymType)); + assertFalse(OOSymbolsSymTypeRelations.isMethod(_unboxedString)); + assertFalse(OOSymbolsSymTypeRelations.isMethod(myFunctionalInterfaceType)); + assertFalse(OOSymbolsSymTypeRelations.isMethod( + createFunction(_intSymType) + )); + assertTrue(OOSymbolsSymTypeRelations.isMethod(myClassGetNameType)); + assertFalse(OOSymbolsSymTypeRelations.isMethod(myClassConstructorType)); + } + + @Test + public void recognizeConstructor() { + assertFalse(OOSymbolsSymTypeRelations.isConstructor(_intSymType)); + assertFalse(OOSymbolsSymTypeRelations.isConstructor(_unboxedString)); + assertFalse(OOSymbolsSymTypeRelations.isConstructor(myFunctionalInterfaceType)); + assertFalse(OOSymbolsSymTypeRelations.isConstructor( + createFunction(_intSymType) + )); + assertFalse(OOSymbolsSymTypeRelations.isConstructor(myClassGetNameType)); + assertTrue(OOSymbolsSymTypeRelations.isConstructor(myClassConstructorType)); + } + + @Test + public void recognizeEnumConstant() { + assertFalse(OOSymbolsSymTypeRelations.sourceIsEnumConstant(_intSymType)); + assertFalse(OOSymbolsSymTypeRelations.sourceIsEnumConstant(_unboxedString)); + assertFalse(OOSymbolsSymTypeRelations.sourceIsEnumConstant(myEnumType)); + assertTrue(OOSymbolsSymTypeRelations.sourceIsEnumConstant(myEnumVal1Type)); + assertFalse(OOSymbolsSymTypeRelations.sourceIsEnumConstant(myEnumDefaultType)); + } + + @Test + public void recognizeFunctionalInterface() { + Optional abstractMethod; + assertFalse(OOSymbolsSymTypeRelations + .getAbstractFunctionOfFunctionalInterFace(_intSymType) + .isPresent() + ); + assertFalse(OOSymbolsSymTypeRelations + .getAbstractFunctionOfFunctionalInterFace(_unboxedString) + .isPresent() + ); + assertFalse(OOSymbolsSymTypeRelations + .getAbstractFunctionOfFunctionalInterFace(myInterfaceType) + .isPresent() + ); + assertFalse(OOSymbolsSymTypeRelations + .getAbstractFunctionOfFunctionalInterFace(myFunctionalInterfaceApplyType) + .isPresent() + ); + abstractMethod = OOSymbolsSymTypeRelations + .getAbstractFunctionOfFunctionalInterFace(myFunctionalInterfaceType); + assertTrue(abstractMethod.isPresent()); + assertSame( + abstractMethod.get().getSymbol(), + myFunctionalInterfaceApplyType.asFunctionType().getSymbol() + ); + abstractMethod = OOSymbolsSymTypeRelations + .getAbstractFunctionOfFunctionalInterFace(myFunctionalInterfaceSubType); + assertTrue(abstractMethod.isPresent()); + assertSame( + abstractMethod.get().getSymbol(), + myFunctionalInterfaceApplyType.asFunctionType().getSymbol() + ); + assertFalse(OOSymbolsSymTypeRelations + .getAbstractFunctionOfFunctionalInterFace(myNonFunctionalInterfaceSubType) + .isPresent() + ); + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/testsymtabmill/MillTest.java b/monticore-grammar/src/test/java/de/monticore/testsymtabmill/MillTest.java index b309436cf6..f1702ecfbc 100644 --- a/monticore-grammar/src/test/java/de/monticore/testsymtabmill/MillTest.java +++ b/monticore-grammar/src/test/java/de/monticore/testsymtabmill/MillTest.java @@ -6,12 +6,10 @@ import de.monticore.testsymtabmill.testsymtabmill._symboltable.*; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MillTest { @@ -36,10 +34,10 @@ public void testMill(){ TestSymTabMillScopesGenitorDelegator symbolTableCreatorDelegator = TestSymTabMillMill.scopesGenitorDelegator(); - Assertions.assertFalse(scope.isShadowing()); - Assertions.assertTrue(symbolTableCreator.getCurrentScope().get().equals(scope)); + assertFalse(scope.isShadowing()); + assertEquals(symbolTableCreator.getCurrentScope().get(), scope); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/typepersistence/TypePersistenceTest.java b/monticore-grammar/src/test/java/de/monticore/typepersistence/TypePersistenceTest.java index df28e0db16..d91d49f99c 100644 --- a/monticore-grammar/src/test/java/de/monticore/typepersistence/TypePersistenceTest.java +++ b/monticore-grammar/src/test/java/de/monticore/typepersistence/TypePersistenceTest.java @@ -10,14 +10,13 @@ import de.monticore.typepersistence.variable._symboltable.VariableScopesGenitorDelegator; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TypePersistenceTest { @@ -52,8 +51,8 @@ public void test() throws IOException { Optional varModel = blahParser.parse_String("var String a"); VariableScopesGenitorDelegator varSymbolTableCreator = VariableMill.scopesGenitorDelegator(); IVariableScope blahSymbolTable = varSymbolTableCreator.createFromAST(varModel.get()); - Assertions.assertTrue(varModel.isPresent()); + assertTrue(varModel.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/AlwaysTheSameASTTest.java b/monticore-grammar/src/test/java/de/monticore/types/AlwaysTheSameASTTest.java index 599e0ad82e..2bf5a29430 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/AlwaysTheSameASTTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/AlwaysTheSameASTTest.java @@ -15,13 +15,14 @@ import de.monticore.types.mcsimplegenerictypestest._parser.MCSimpleGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class AlwaysTheSameASTTest { private MCBasicTypesTestParser basicTypesTestParser; @@ -58,41 +59,41 @@ public void testMCListType() throws IOException { String list = "List"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCGenericType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCListType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCGenericType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCListType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCGenericType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCListType.class, genericAST.get()); ASTMCListType basicGenericList = (ASTMCListType) basicGenericAst.get(); ASTMCListType customList = (ASTMCListType) customAst.get(); ASTMCListType genericList = (ASTMCListType) genericAST.get(); - Assertions.assertTrue(basicGenericList.deepEquals(customList)); - Assertions.assertTrue(basicGenericList.deepEquals(genericList)); - Assertions.assertTrue(genericList.deepEquals(customList)); + assertTrue(basicGenericList.deepEquals(customList)); + assertTrue(basicGenericList.deepEquals(genericList)); + assertTrue(genericList.deepEquals(customList)); - Assertions.assertEquals(basicGenericAst.get().printType().split("\\.").length, 1); + assertEquals(1, basicGenericAst.get().printType().split("\\.").length); - Assertions.assertEquals(basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0], "List"); + assertEquals("List", basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0]); - Assertions.assertEquals(basicGenericAst.get().getMCTypeArgumentList().size(), 1); + assertEquals(1, basicGenericAst.get().getMCTypeArgumentList().size()); ASTMCTypeArgument argument = basicGenericAst.get().getMCTypeArgumentList().get(0); Optional argument2 = mcCollectionTypesTestParser.parse_StringMCTypeArgument("String"); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(argument2.isPresent()); - Assertions.assertTrue(argument.deepEquals(argument2.get())); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(argument2.isPresent()); + assertTrue(argument.deepEquals(argument2.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -101,33 +102,33 @@ public void testMCListTypeWithCollectionTypeParser() throws IOException { String list = "List"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCGenericType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCListType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCGenericType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCListType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCGenericType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCListType.class, genericAST.get()); ASTMCListType basicGenericList = (ASTMCListType) basicGenericAst.get(); ASTMCListType customList = (ASTMCListType) customAst.get(); ASTMCListType genericList = (ASTMCListType) genericAST.get(); - Assertions.assertTrue(basicGenericList.deepEquals(customList)); - Assertions.assertTrue(basicGenericList.deepEquals(genericList)); - Assertions.assertTrue(genericList.deepEquals(customList)); + assertTrue(basicGenericList.deepEquals(customList)); + assertTrue(basicGenericList.deepEquals(genericList)); + assertTrue(genericList.deepEquals(customList)); - Assertions.assertEquals(basicGenericAst.get().printType().split("\\.").length, 1); + assertEquals(1, basicGenericAst.get().printType().split("\\.").length); - Assertions.assertEquals(basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0], "List"); + assertEquals("List", basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0]); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -135,29 +136,29 @@ public void testMCListTypeWithTypeParser() throws IOException { String list = "List"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCListType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCListType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCType(list); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCListType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCListType.class, genericAST.get()); ASTMCListType basicGenericList = (ASTMCListType) basicGenericAst.get(); ASTMCListType customList = (ASTMCListType) customAst.get(); ASTMCListType genericList = (ASTMCListType) genericAST.get(); - Assertions.assertTrue(basicGenericList.deepEquals(customList)); - Assertions.assertTrue(basicGenericList.deepEquals(genericList)); - Assertions.assertTrue(genericList.deepEquals(customList)); + assertTrue(basicGenericList.deepEquals(customList)); + assertTrue(basicGenericList.deepEquals(genericList)); + assertTrue(genericList.deepEquals(customList)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -165,37 +166,37 @@ public void testMCMapTypeWithGenericCollectionTypeParser() throws IOException { String map = "Map"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCGenericType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCMapType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCGenericType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCMapType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCGenericType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCMapType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertEquals(basicGenericAst.get().printType().split("\\.").length, 1); + assertEquals(1, basicGenericAst.get().printType().split("\\.").length); - Assertions.assertEquals(basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0], "Map"); + assertEquals("Map", basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0]); - Assertions.assertEquals(basicGenericAst.get().getMCTypeArgumentList().size(), 2); + assertEquals(2, basicGenericAst.get().getMCTypeArgumentList().size()); ASTMCTypeArgument argument = basicGenericAst.get().getMCTypeArgumentList().get(0); Optional argument2 = mcCollectionTypesTestParser.parse_StringMCTypeArgument("Integer"); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(argument2.isPresent()); - Assertions.assertTrue(argument.deepEquals(argument2.get())); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(argument2.isPresent()); + assertTrue(argument.deepEquals(argument2.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -203,25 +204,25 @@ public void testMCMapTypeWithTypeParser() throws IOException { String map = "Map"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCMapType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCMapType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCMapType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -229,29 +230,29 @@ public void testMCMapTypeWithCollectionTypeParser() throws IOException { String map = "Map"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCGenericType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCMapType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCGenericType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCMapType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCGenericType(map); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCMapType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCMapType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertEquals(basicGenericAst.get().printType().split("\\.").length, 1); + assertEquals(1, basicGenericAst.get().printType().split("\\.").length); - Assertions.assertEquals(basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0], "Map"); + assertEquals("Map", basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0]); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -259,38 +260,38 @@ public void testMCOptionalType() throws IOException { String optional = "Optional"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCGenericType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCGenericType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCGenericType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertEquals(basicGenericAst.get().printType().split("\\.").length, 1); + assertEquals(1, basicGenericAst.get().printType().split("\\.").length); - Assertions.assertEquals(basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0], "Optional"); + assertEquals("Optional", basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0]); - Assertions.assertEquals(basicGenericAst.get().getMCTypeArgumentList().size(), 1); + assertEquals(1, basicGenericAst.get().getMCTypeArgumentList().size()); ASTMCTypeArgument argument = basicGenericAst.get().getMCTypeArgumentList().get(0); Optional argument2 = mcCollectionTypesTestParser.parse_StringMCTypeArgument("String"); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(argument2.isPresent()); - Assertions.assertTrue(argument.deepEquals(argument2.get())); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(argument2.isPresent()); + assertTrue(argument.deepEquals(argument2.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -298,26 +299,26 @@ public void testMCOptionalTypeWithTypeParser() throws IOException { String optional = "Optional"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -325,30 +326,30 @@ public void testMCOptionalTypeWithCollectionTypeParser() throws IOException { String optional = "Optional"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCGenericType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCGenericType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCGenericType(optional); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCOptionalType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertEquals(basicGenericAst.get().printType().split("\\.").length, 1); + assertEquals(1, basicGenericAst.get().printType().split("\\.").length); - Assertions.assertEquals(basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0], "Optional"); + assertEquals("Optional", basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0]); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -356,38 +357,38 @@ public void testMCSetTypeWithGenericCollectionTypeParser() throws IOException { String set = "Set"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCGenericType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCSetType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCGenericType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCSetType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCGenericType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCSetType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertEquals(basicGenericAst.get().printType().split("\\.").length, 1); + assertEquals(1, basicGenericAst.get().printType().split("\\.").length); - Assertions.assertEquals(basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0], "Set"); + assertEquals("Set", basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0]); - Assertions.assertEquals(basicGenericAst.get().getMCTypeArgumentList().size(), 1); + assertEquals(1, basicGenericAst.get().getMCTypeArgumentList().size()); ASTMCTypeArgument argument = basicGenericAst.get().getMCTypeArgumentList().get(0); Optional argument2 = mcCollectionTypesTestParser.parse_StringMCTypeArgument("String"); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(argument2.isPresent()); - Assertions.assertTrue(argument.deepEquals(argument2.get())); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(argument2.isPresent()); + assertTrue(argument.deepEquals(argument2.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -395,26 +396,26 @@ public void testMCSetTypeWithTypeParser() throws IOException { String set = "Set"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCSetType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCSetType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCSetType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -422,30 +423,30 @@ public void testMCSetTypeWithCollectionTypeParser() throws IOException { String set = "Set"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCGenericType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCSetType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCGenericType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCSetType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCGenericType(set); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCSetType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCSetType.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertEquals(basicGenericAst.get().printType().split("\\.").length, 1); + assertEquals(1, basicGenericAst.get().printType().split("\\.").length); - Assertions.assertEquals(basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0], "Set"); + assertEquals("Set", basicGenericAst.get().printWithoutTypeArguments().split("\\.")[0]); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -453,25 +454,25 @@ public void testMCBasicTypeArgument() throws IOException { String type = "de.monticore.ASTNode"; Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCTypeArgument(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCBasicTypeArgument); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCBasicTypeArgument.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCTypeArgument(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCBasicTypeArgument); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCBasicTypeArgument.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCTypeArgument(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCBasicTypeArgument); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCBasicTypeArgument.class, genericAST.get()); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -479,18 +480,18 @@ public void testMCCustomTypeArgument() throws IOException { String type = "List"; Optional customAst = customGenericTypesTestParser.parse_StringMCTypeArgument(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCCustomTypeArgument); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCCustomTypeArgument.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCTypeArgument(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCCustomTypeArgument); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCCustomTypeArgument.class, genericAST.get()); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -498,32 +499,32 @@ public void testMCQualifiedType() throws IOException { String type = "de.monticore.ASTNode"; Optional basicAST = basicTypesTestParser.parse_StringMCType(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicAST.isPresent()); - Assertions.assertTrue(basicAST.get() instanceof ASTMCQualifiedType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicAST.isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, basicAST.get()); Optional basicGenericAst = mcCollectionTypesTestParser.parse_StringMCType(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(basicGenericAst.isPresent()); - Assertions.assertTrue(basicGenericAst.get() instanceof ASTMCQualifiedType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(basicGenericAst.isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, basicGenericAst.get()); Optional customAst = customGenericTypesTestParser.parse_StringMCType(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(customAst.isPresent()); - Assertions.assertTrue(customAst.get() instanceof ASTMCQualifiedType); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(customAst.isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, customAst.get()); Optional genericAST = genericTypesTestParser.parse_StringMCType(type); - Assertions.assertFalse(mcCollectionTypesTestParser.hasErrors()); - Assertions.assertTrue(genericAST.isPresent()); - Assertions.assertTrue(genericAST.get() instanceof ASTMCQualifiedType); - - Assertions.assertTrue(basicAST.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicAST.get().deepEquals(basicGenericAst.get())); - Assertions.assertTrue(basicAST.get().deepEquals(genericAST.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(customAst.get())); - Assertions.assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); - Assertions.assertTrue(genericAST.get().deepEquals(customAst.get())); + assertFalse(mcCollectionTypesTestParser.hasErrors()); + assertTrue(genericAST.isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, genericAST.get()); + + assertTrue(basicAST.get().deepEquals(customAst.get())); + assertTrue(basicAST.get().deepEquals(basicGenericAst.get())); + assertTrue(basicAST.get().deepEquals(genericAST.get())); + assertTrue(basicGenericAst.get().deepEquals(customAst.get())); + assertTrue(basicGenericAst.get().deepEquals(genericAST.get())); + assertTrue(genericAST.get().deepEquals(customAst.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/MCBasicTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/MCBasicTypesTest.java index 4b3b10f88a..c722bfda73 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/MCBasicTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/MCBasicTypesTest.java @@ -6,13 +6,14 @@ import de.monticore.types.mcbasictypestest._parser.MCBasicTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCBasicTypesTest { @BeforeEach @@ -28,28 +29,28 @@ public void init() { public void testPrimitiveTypesAPI() throws IOException { MCBasicTypesTestParser mcBasicTypesParser = new MCBasicTypesTestParser(); Optional boolOpt = mcBasicTypesParser.parse_StringMCPrimitiveType("boolean"); - Assertions.assertTrue(boolOpt.isPresent()); + assertTrue(boolOpt.isPresent()); ASTMCPrimitiveType bool = boolOpt.get(); boolean isBool = bool.isBoolean(); - Assertions.assertTrue(isBool); + assertTrue(isBool); boolean isByte = bool.isByte(); - Assertions.assertFalse(isByte); + assertFalse(isByte); boolean isChar = bool.isChar(); - Assertions.assertFalse(isChar); + assertFalse(isChar); boolean isDouble = bool.isDouble(); - Assertions.assertFalse(isDouble); + assertFalse(isDouble); boolean isFloat = bool.isFloat(); - Assertions.assertFalse(isFloat); + assertFalse(isFloat); boolean isInt = bool.isInt(); - Assertions.assertFalse(isInt); + assertFalse(isInt); boolean isShort = bool.isShort(); - Assertions.assertFalse(isShort); + assertFalse(isShort); - Assertions.assertEquals(bool.toString(), "boolean"); + assertEquals("boolean", bool.toString()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -67,15 +68,15 @@ public void testPrimitiveTypes() { Optional type = mcBasicTypesParser.parse_String(primitive); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCPrimitiveType); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCPrimitiveType.class, type.get()); } } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -84,12 +85,12 @@ public void testMCQualifiedType() throws IOException { for (String type : types) { MCBasicTypesTestParser mcBasicTypesParser = new MCBasicTypesTestParser(); Optional astType = mcBasicTypesParser.parse_String(type); - Assertions.assertNotNull(astType); - Assertions.assertTrue(astType.isPresent()); - Assertions.assertTrue(astType.get() instanceof ASTMCQualifiedType); + assertNotNull(astType); + assertTrue(astType.isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, astType.get()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -98,13 +99,13 @@ public void testMCQualifiedName() throws IOException { for (String type : types) { MCBasicTypesTestParser mcBasicTypesParser = new MCBasicTypesTestParser(); Optional astType = mcBasicTypesParser.parse_StringMCQualifiedName(type); - Assertions.assertNotNull(astType); - Assertions.assertTrue(astType.isPresent()); + assertNotNull(astType); + assertTrue(astType.isPresent()); //test toString - Assertions.assertEquals(astType.get().toString(), type); + assertEquals(astType.get().toString(), type); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -113,11 +114,11 @@ public void testMCImportStatement() throws IOException { String type = "import socnet.Person.*;"; MCBasicTypesTestParser mcBasicTypesParser = new MCBasicTypesTestParser(); Optional astType = mcBasicTypesParser.parse_StringMCImportStatement(type); - Assertions.assertNotNull(astType); - Assertions.assertTrue(astType.isPresent()); + assertNotNull(astType); + assertTrue(astType.isPresent()); //test getQName method - Assertions.assertEquals(astType.get().getQName(), "socnet.Person"); + assertEquals("socnet.Person", astType.get().getQName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/MCCollectionTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/MCCollectionTypesTest.java index 8b5d2dcf4d..96b30bcb4d 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/MCCollectionTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/MCCollectionTypesTest.java @@ -14,13 +14,14 @@ import de.monticore.types.mccollectiontypeswithoutprimitivestest._parser.MCCollectionTypesWithoutPrimitivesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCCollectionTypesTest { @BeforeEach @@ -43,9 +44,9 @@ public void testBasicGenericsTypes() throws IOException { // .parseType(primitive); Optional type = mcBasicTypesParser.parse_StringMCType(testType); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCObjectType); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCObjectType.class, type.get()); ASTMCObjectType t = (ASTMCObjectType) type.get(); MCCollectionTypesTraverser traverser = MCCollectionTypesMill.traverser(); @@ -53,13 +54,13 @@ public void testBasicGenericsTypes() throws IOException { t.accept(traverser); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } private class CheckTypeVisitor implements MCCollectionTypesVisitor2 { public void visit(ASTMCType node) { if (!(node instanceof ASTMCQualifiedType)) { - Assertions.fail("Found not String"); + fail("Found not String"); } } } @@ -68,68 +69,68 @@ public void visit(ASTMCType node) { public void testMCListTypeValid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("List"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCListType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCListType.class, type.get()); //test specific methods ASTMCListType listType = (ASTMCListType) type.get(); - Assertions.assertEquals(listType.getNameList().size(), 1); + assertEquals(1, listType.getNameList().size()); - Assertions.assertEquals(listType.getNameList().get(0), "List"); + assertEquals("List", listType.getNameList().get(0)); - Assertions.assertEquals(listType.getMCTypeArgumentList().size(), 1); + assertEquals(1, listType.getMCTypeArgumentList().size()); ASTMCTypeArgument argument = listType.getMCTypeArgumentList().get(0); Optional argument2 = parser.parse_StringMCTypeArgument("String"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(argument2.isPresent()); - Assertions.assertTrue(argument.deepEquals(argument2.get())); + assertFalse(parser.hasErrors()); + assertTrue(argument2.isPresent()); + assertTrue(argument.deepEquals(argument2.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCListTypeInvalid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.List"); - Assertions.assertTrue(parser.hasErrors()); - Assertions.assertFalse(type.isPresent()); + assertTrue(parser.hasErrors()); + assertFalse(type.isPresent()); } @Test public void testMCMapTypeValid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("Map"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCMapType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCMapType.class, type.get()); //test specific methods ASTMCMapType mapType = (ASTMCMapType) type.get(); - Assertions.assertEquals(mapType.getNameList().size(), 1); + assertEquals(1, mapType.getNameList().size()); - Assertions.assertEquals(mapType.getNameList().get(0), "Map"); + assertEquals("Map", mapType.getNameList().get(0)); - Assertions.assertEquals(mapType.getMCTypeArgumentList().size(), 2); + assertEquals(2, mapType.getMCTypeArgumentList().size()); ASTMCTypeArgument argument = mapType.getMCTypeArgumentList().get(0); Optional argument2 = parser.parse_StringMCTypeArgument("Integer"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(argument2.isPresent()); - Assertions.assertTrue(argument.deepEquals(argument2.get())); + assertFalse(parser.hasErrors()); + assertTrue(argument2.isPresent()); + assertTrue(argument.deepEquals(argument2.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCMapTypeInvalid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.Map"); - Assertions.assertTrue(parser.hasErrors()); - Assertions.assertFalse(type.isPresent()); + assertTrue(parser.hasErrors()); + assertFalse(type.isPresent()); } @@ -137,34 +138,34 @@ public void testMCMapTypeInvalid() throws IOException { public void testMCOptionalTypeValid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("Optional"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCOptionalType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, type.get()); //test specific methods ASTMCOptionalType optionalType = (ASTMCOptionalType) type.get(); - Assertions.assertEquals(optionalType.getNameList().size(), 1); + assertEquals(1, optionalType.getNameList().size()); - Assertions.assertEquals(optionalType.getNameList().get(0), "Optional"); + assertEquals("Optional", optionalType.getNameList().get(0)); - Assertions.assertEquals(optionalType.getMCTypeArgumentList().size(), 1); + assertEquals(1, optionalType.getMCTypeArgumentList().size()); ASTMCTypeArgument argument = optionalType.getMCTypeArgumentList().get(0); Optional argument2 = parser.parse_StringMCTypeArgument("String"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(argument2.isPresent()); - Assertions.assertTrue(argument.deepEquals(argument2.get())); + assertFalse(parser.hasErrors()); + assertTrue(argument2.isPresent()); + assertTrue(argument.deepEquals(argument2.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCOptionalTypeInvalid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.Optional"); - Assertions.assertTrue(parser.hasErrors()); - Assertions.assertFalse(type.isPresent()); + assertTrue(parser.hasErrors()); + assertFalse(type.isPresent()); } @@ -172,54 +173,54 @@ public void testMCOptionalTypeInvalid() throws IOException { public void testMCSetTypeValid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("Set"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCSetType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCSetType.class, type.get()); //test specific methods ASTMCSetType setType = (ASTMCSetType) type.get(); - Assertions.assertEquals(setType.getNameList().size(), 1); + assertEquals(1, setType.getNameList().size()); - Assertions.assertEquals(setType.getNameList().get(0), "Set"); + assertEquals("Set", setType.getNameList().get(0)); - Assertions.assertEquals(setType.getMCTypeArgumentList().size(), 1); + assertEquals(1, setType.getMCTypeArgumentList().size()); ASTMCTypeArgument argument = setType.getMCTypeArgumentList().get(0); Optional argument2 = parser.parse_StringMCTypeArgument("String"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(argument2.isPresent()); - Assertions.assertTrue(argument.deepEquals(argument2.get())); + assertFalse(parser.hasErrors()); + assertTrue(argument2.isPresent()); + assertTrue(argument.deepEquals(argument2.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCSetTypeInvalid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.Set"); - Assertions.assertTrue(parser.hasErrors()); - Assertions.assertFalse(type.isPresent()); + assertTrue(parser.hasErrors()); + assertFalse(type.isPresent()); } @Test public void testMCTypeArgumentValid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCTypeArgument("a.b.c"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCBasicTypeArgument); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCBasicTypeArgument.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCTypeArgumentInvalid() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCTypeArgument("List"); - Assertions.assertTrue(parser.hasErrors()); - Assertions.assertFalse(type.isPresent()); + assertTrue(parser.hasErrors()); + assertFalse(type.isPresent()); } @@ -227,11 +228,11 @@ public void testMCTypeArgumentInvalid() throws IOException { public void collectionTypeWithInt() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional type = parser.parse_StringMCGenericType("List"); - Assertions.assertTrue(type.isPresent()); - Assertions.assertEquals("List", type.get().printWithoutTypeArguments()); - Assertions.assertTrue(type.get().getMCTypeArgumentList().get(0) instanceof ASTMCPrimitiveTypeArgument); + assertTrue(type.isPresent()); + assertEquals("List", type.get().printWithoutTypeArguments()); + assertInstanceOf(ASTMCPrimitiveTypeArgument.class, type.get().getMCTypeArgumentList().get(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -239,8 +240,8 @@ public void collectionTypeWithInt() throws IOException { public void collectionTypeWithIntFail() throws IOException { MCCollectionTypesWithoutPrimitivesTestParser parser = new MCCollectionTypesWithoutPrimitivesTestParser(); Optional type = parser.parse_StringMCGenericType("List"); - Assertions.assertTrue(parser.hasErrors()); - Assertions.assertFalse(type.isPresent()); + assertTrue(parser.hasErrors()); + assertFalse(type.isPresent()); } @Test @@ -251,18 +252,18 @@ public void testPrintTypeWithoutTypeArguments() throws IOException { Optional setType = parser.parse_StringMCSetType("Set"); Optional mapType = parser.parse_StringMCMapType("Map"); Optional genericType = parser.parse_StringMCGenericType("Map"); - Assertions.assertTrue(listType.isPresent()); - Assertions.assertTrue(optionalType.isPresent()); - Assertions.assertTrue(setType.isPresent()); - Assertions.assertTrue(mapType.isPresent()); - Assertions.assertTrue(genericType.isPresent()); - Assertions.assertEquals("List", listType.get().printWithoutTypeArguments()); - Assertions.assertEquals("Optional", optionalType.get().printWithoutTypeArguments()); - Assertions.assertEquals("Set", setType.get().printWithoutTypeArguments()); - Assertions.assertEquals("Map", genericType.get().printWithoutTypeArguments()); - Assertions.assertEquals("Map", genericType.get().printWithoutTypeArguments()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(listType.isPresent()); + assertTrue(optionalType.isPresent()); + assertTrue(setType.isPresent()); + assertTrue(mapType.isPresent()); + assertTrue(genericType.isPresent()); + assertEquals("List", listType.get().printWithoutTypeArguments()); + assertEquals("Optional", optionalType.get().printWithoutTypeArguments()); + assertEquals("Set", setType.get().printWithoutTypeArguments()); + assertEquals("Map", genericType.get().printWithoutTypeArguments()); + assertEquals("Map", genericType.get().printWithoutTypeArguments()); + assertFalse(parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/MCFullGenericTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/MCFullGenericTypesTest.java index e666a96512..72b8317ad6 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/MCFullGenericTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/MCFullGenericTypesTest.java @@ -7,13 +7,14 @@ import de.monticore.types.mcfullgenerictypestest._parser.MCFullGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCFullGenericTypesTest { @BeforeEach @@ -29,13 +30,13 @@ public void testPrintTypeWithoutTypeArguments() throws IOException { MCFullGenericTypesTestParser parser = new MCFullGenericTypesTestParser(); Optional multipleGenericType = parser.parse_StringMCMultipleGenericType("a.B.D.E.G"); Optional genericType = parser.parse_StringMCGenericType("a.B.D.E.G"); - Assertions.assertTrue(genericType.isPresent()); - Assertions.assertTrue(multipleGenericType.isPresent()); - Assertions.assertEquals("a.B.D.E.G", multipleGenericType.get().printWithoutTypeArguments()); - Assertions.assertEquals("a.B.D.E.G", genericType.get().printWithoutTypeArguments()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(genericType.isPresent()); + assertTrue(multipleGenericType.isPresent()); + assertEquals("a.B.D.E.G", multipleGenericType.get().printWithoutTypeArguments()); + assertEquals("a.B.D.E.G", genericType.get().printWithoutTypeArguments()); + assertFalse(parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/MCFunctionTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/MCFunctionTypesTest.java index d24f6fe9f5..0069d2f9f3 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/MCFunctionTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/MCFunctionTypesTest.java @@ -8,17 +8,13 @@ import de.monticore.types.mcfunctiontypestest._parser.MCFunctionTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MCFunctionTypesTest { @@ -33,108 +29,108 @@ public void init() { @Test public void testRunnableFunctionType() throws IOException { ASTMCFunctionType type = parseMCFunctionType("() -> void"); - Assertions.assertEquals("void", type.getMCReturnType() + assertEquals("void", type.getMCReturnType() .printType()); - Assertions.assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); - Assertions.assertEquals(0, type.getMCFunctionParTypes().getMCTypeList().size()); + assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); + assertEquals(0, type.getMCFunctionParTypes().getMCTypeList().size()); } @Test public void testSupplierFunctionType() throws IOException { ASTMCFunctionType type = parseMCFunctionType("() -> int"); - Assertions.assertEquals("int", type.getMCReturnType() + assertEquals("int", type.getMCReturnType() .printType()); - Assertions.assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); - Assertions.assertEquals(0, type.getMCFunctionParTypes().getMCTypeList().size()); + assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); + assertEquals(0, type.getMCFunctionParTypes().getMCTypeList().size()); } @Test public void testWithInputFunctionType1() throws IOException { ASTMCUnaryFunctionType type = parseMCFunctionTypeNoParentheses("int -> void"); - Assertions.assertEquals("void", type.getMCReturnType().printType()); - Assertions.assertEquals("int", type.getMCType().printType()); + assertEquals("void", type.getMCReturnType().printType()); + assertEquals("int", type.getMCType().printType()); } @Test public void testWithInputFunctionType2() throws IOException { ASTMCFunctionType type = parseMCFunctionType("(int, long) -> void"); - Assertions.assertEquals("void", type.getMCReturnType().printType()); - Assertions.assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); - Assertions.assertEquals(2, type.getMCFunctionParTypes().getMCTypeList().size()); - Assertions.assertEquals("int", type.getMCFunctionParTypes().getMCType(0).printType()); - Assertions.assertEquals("long", type.getMCFunctionParTypes().getMCType(1).printType()); + assertEquals("void", type.getMCReturnType().printType()); + assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); + assertEquals(2, type.getMCFunctionParTypes().getMCTypeList().size()); + assertEquals("int", type.getMCFunctionParTypes().getMCType(0).printType()); + assertEquals("long", type.getMCFunctionParTypes().getMCType(1).printType()); } @Test public void testEllipticFunctionType1() throws IOException { ASTMCFunctionType type = parseMCFunctionType("(long...) -> void"); - Assertions.assertEquals("void", type.getMCReturnType() + assertEquals("void", type.getMCReturnType() .printType()); - Assertions.assertTrue(type.getMCFunctionParTypes().isPresentIsElliptic()); - Assertions.assertEquals(1, type.getMCFunctionParTypes().getMCTypeList().size()); - Assertions.assertEquals("long", type.getMCFunctionParTypes().getMCType(0) + assertTrue(type.getMCFunctionParTypes().isPresentIsElliptic()); + assertEquals(1, type.getMCFunctionParTypes().getMCTypeList().size()); + assertEquals("long", type.getMCFunctionParTypes().getMCType(0) .printType()); } @Test public void testEllipticFunctionType2() throws IOException { ASTMCFunctionType type = parseMCFunctionType("(int, long...) -> long"); - Assertions.assertEquals("long", type.getMCReturnType() + assertEquals("long", type.getMCReturnType() .printType()); - Assertions.assertTrue(type.getMCFunctionParTypes().isPresentIsElliptic()); - Assertions.assertEquals(2, type.getMCFunctionParTypes().getMCTypeList().size()); - Assertions.assertEquals("int", type.getMCFunctionParTypes().getMCType(0) + assertTrue(type.getMCFunctionParTypes().isPresentIsElliptic()); + assertEquals(2, type.getMCFunctionParTypes().getMCTypeList().size()); + assertEquals("int", type.getMCFunctionParTypes().getMCType(0) .printType()); - Assertions.assertEquals("long", type.getMCFunctionParTypes().getMCType(1) + assertEquals("long", type.getMCFunctionParTypes().getMCType(1) .printType()); } @Test public void testHigherOrderFunctionType1() throws IOException { ASTMCFunctionType type = parseMCFunctionType("() -> () -> void"); - Assertions.assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); - Assertions.assertEquals(0, type.getMCFunctionParTypes().getMCTypeList().size()); + assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); + assertEquals(0, type.getMCFunctionParTypes().getMCTypeList().size()); } @Test public void testHigherOrderFunctionType2() throws IOException { ASTMCFunctionType type = parseMCFunctionType("((long) -> void) -> (int) -> long"); - Assertions.assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); - Assertions.assertEquals(1, type.getMCFunctionParTypes().getMCTypeList().size()); + assertFalse(type.getMCFunctionParTypes().isPresentIsElliptic()); + assertEquals(1, type.getMCFunctionParTypes().getMCTypeList().size()); } @Test public void testHigherOrderFunctionType3() throws IOException { ASTMCUnaryFunctionType type = parseMCFunctionTypeNoParentheses("int -> long -> void"); - Assertions.assertEquals("int", type.getMCType().printType()); - Assertions.assertTrue(type.getMCReturnType().isPresentMCType()); + assertEquals("int", type.getMCType().printType()); + assertTrue(type.getMCReturnType().isPresentMCType()); ASTMCType returnType = type.getMCReturnType().getMCType(); - Assertions.assertTrue(returnType instanceof ASTMCUnaryFunctionType); + assertInstanceOf(ASTMCUnaryFunctionType.class, returnType); ASTMCUnaryFunctionType returnFuncType = (ASTMCUnaryFunctionType) returnType; - Assertions.assertEquals("long", returnFuncType.getMCType().printType()); - Assertions.assertEquals("void", returnFuncType.getMCReturnType().printType()); + assertEquals("long", returnFuncType.getMCType().printType()); + assertEquals("void", returnFuncType.getMCReturnType().printType()); } @Test public void testHigherOrderFunctionType5() throws IOException { ASTMCUnaryFunctionType type = parseMCFunctionTypeNoParentheses("int -> (long -> void) -> long"); - Assertions.assertEquals("int", type.getMCType().printType()); - Assertions.assertEquals("(long->void)->long", type.getMCReturnType().printType()); + assertEquals("int", type.getMCType().printType()); + assertEquals("(long->void)->long", type.getMCReturnType().printType()); } protected ASTMCFunctionType parseMCFunctionType(String mcTypeStr) throws IOException { MCFunctionTypesTestParser parser = new MCFunctionTypesTestParser(); Optional typeOpt = parser.parse_StringMCType(mcTypeStr); - Assertions.assertNotNull(typeOpt); - Assertions.assertTrue(typeOpt.isPresent()); - Assertions.assertTrue(typeOpt.get() instanceof ASTMCFunctionType); + assertNotNull(typeOpt); + assertTrue(typeOpt.isPresent()); + assertInstanceOf(ASTMCFunctionType.class, typeOpt.get()); ASTMCFunctionType type = (ASTMCFunctionType) typeOpt.get(); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); return type; } @@ -143,12 +139,12 @@ protected ASTMCUnaryFunctionType parseMCFunctionTypeNoParentheses( ) throws IOException { MCFunctionTypesTestParser parser = new MCFunctionTypesTestParser(); Optional typeOpt = parser.parse_StringMCType(mcTypeStr); - Assertions.assertNotNull(typeOpt); - Assertions.assertTrue(typeOpt.isPresent()); - Assertions.assertTrue(typeOpt.get() instanceof ASTMCUnaryFunctionType); + assertNotNull(typeOpt); + assertTrue(typeOpt.isPresent()); + assertInstanceOf(ASTMCUnaryFunctionType.class, typeOpt.get()); ASTMCUnaryFunctionType type = (ASTMCUnaryFunctionType) typeOpt.get(); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); return type; } diff --git a/monticore-grammar/src/test/java/de/monticore/types/MCGenericsTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/MCGenericsTypesTest.java index 3ea790ccbf..ced4284409 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/MCGenericsTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/MCGenericsTypesTest.java @@ -13,14 +13,15 @@ import de.monticore.types.mcfullgenerictypestest._parser.MCFullGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCGenericsTypesTest { @BeforeEach @@ -45,14 +46,14 @@ public void testBasicGenericsTypes() throws IOException { // .parseType(primitive); Optional type = mcBasicTypesParser.parse_StringMCType(testType); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCObjectType); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCObjectType.class, type.get()); System.out.println(type.get().getClass()); ASTMCObjectType t = (ASTMCObjectType) type.get(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -70,14 +71,14 @@ public void testArrayTypes() throws IOException { Optional type = genericTypesTestParser.parse_StringMCType(testType); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCArrayType); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCArrayType.class, type.get()); ASTMCArrayType t = (ASTMCArrayType) type.get(); - Assertions.assertEquals(2, t.getDimensions()); + assertEquals(2, t.getDimensions()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -86,12 +87,12 @@ public void testMCComplexReferenceTypeValid() throws IOException { MCFullGenericTypesTestMill.init(); MCFullGenericTypesTestParser parser = new MCFullGenericTypesTestParser(); Optional type = parser.parse_StringMCType("java.util.List.Set.some.Collection"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCMultipleGenericType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCMultipleGenericType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -100,12 +101,12 @@ public void testMcWildcardTypeArgument() throws IOException { MCFullGenericTypesTestMill.init(); MCFullGenericTypesTestParser parser = new MCFullGenericTypesTestParser(); Optional type = parser.parse_StringMCTypeArgument("? extends java.util.Set"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCWildcardTypeArgument); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCWildcardTypeArgument.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -115,7 +116,7 @@ public void testOldComplexArrayTypes() { GenericTypesTestParser parser = new GenericTypesTestParser(); try { // test-data - HashMap testdata = new HashMap(); + LinkedHashMap testdata = new LinkedHashMap(); testdata.put("Collection[]", 1); testdata.put("L[]", 1); testdata.put("C>[]", 1); @@ -126,19 +127,19 @@ public void testOldComplexArrayTypes() { // checks for (String teststring : testdata.keySet()) { Optional type = parser.parse_StringMCType(teststring); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); // check typing and dimension: - Assertions.assertTrue(type.get() instanceof ASTMCArrayType); + assertInstanceOf(ASTMCArrayType.class, type.get()); ASTMCArrayType arrayType = (ASTMCArrayType) type.get(); - Assertions.assertEquals(testdata.get(teststring).intValue(), arrayType.getDimensions()); - Assertions.assertTrue(arrayType.getMCType() instanceof ASTMCObjectType); + assertEquals(testdata.get(teststring).intValue(), arrayType.getDimensions()); + assertInstanceOf(ASTMCObjectType.class, arrayType.getMCType()); } } catch (IOException e) { - Assertions.fail(e.getMessage()); + fail(e.getMessage()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -184,13 +185,13 @@ public void testOldComplexTypes() throws IOException { Optional type = genericTypesTestParser.parse_StringMCType(testType); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); + assertNotNull(type); + assertTrue(type.isPresent()); //assertTrue(type.get() instanceof ASTMCMultipleGenericType); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/MCSimpleGenericsTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/MCSimpleGenericsTypesTest.java index 86406f2aaa..e75b66af7a 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/MCSimpleGenericsTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/MCSimpleGenericsTypesTest.java @@ -9,13 +9,14 @@ import de.monticore.types.mcsimplegenerictypestest._parser.MCSimpleGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCSimpleGenericsTypesTest { @BeforeEach @@ -36,99 +37,99 @@ public void testCustomGenericsTypes() throws IOException { Optional type = mcBasicTypesParser.parse_StringMCType(testType); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCObjectType); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCObjectType.class, type.get()); System.out.println(type.get().getClass()); ASTMCObjectType t = (ASTMCObjectType) type.get(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCListTypeValid() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("List"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCListType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCListType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCListTypeValid2() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.List"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCBasicGenericType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCBasicGenericType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCMapTypeValid() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("Map"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCMapType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCMapType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCMapTypeValid2() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.Map, String>"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCBasicGenericType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCBasicGenericType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCMapTypeValid3() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.HashMap>"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCBasicGenericType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCBasicGenericType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCOptionalTypeValid() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("Optional"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCOptionalType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCOptionalType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCOptionalTypeValid2() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.Optional>"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCBasicGenericType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCBasicGenericType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -136,48 +137,48 @@ public void testMCOptionalTypeValid2() throws IOException { public void testMCSetTypeValid() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("Set"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCSetType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCSetType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCSetTypeValid2() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("java.util.Set>"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCBasicGenericType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCBasicGenericType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCTypeArgumentValid() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCTypeArgument("a.b.c"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCBasicTypeArgument); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCBasicTypeArgument.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCTypeArgumentValid2() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCGenericType("List"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertNotNull(type); - Assertions.assertTrue(type.isPresent()); - Assertions.assertTrue(type.get() instanceof ASTMCListType); + assertFalse(parser.hasErrors()); + assertNotNull(type); + assertTrue(type.isPresent()); + assertInstanceOf(ASTMCListType.class, type.get()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -185,8 +186,8 @@ public void testMCComplexReferenceTypeInvalid() throws IOException { //not defined in that grammar, only in MCGenericsTypes MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional type = parser.parse_StringMCType("java.util.List.Set.some.Collection"); - Assertions.assertTrue(parser.hasErrors()); - Assertions.assertFalse(type.isPresent()); + assertTrue(parser.hasErrors()); + assertFalse(type.isPresent()); } @Test @@ -194,12 +195,12 @@ public void testPrintTypeWithoutTypeArguments() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional basicGenericType = parser.parse_StringMCBasicGenericType("a.B"); Optional genericType = parser.parse_StringMCGenericType("a.B"); - Assertions.assertTrue(genericType.isPresent()); - Assertions.assertTrue(basicGenericType.isPresent()); - Assertions.assertEquals("a.B", basicGenericType.get().printWithoutTypeArguments()); - Assertions.assertEquals("a.B", genericType.get().printWithoutTypeArguments()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(genericType.isPresent()); + assertTrue(basicGenericType.isPresent()); + assertEquals("a.B", basicGenericType.get().printWithoutTypeArguments()); + assertEquals("a.B", genericType.get().printWithoutTypeArguments()); + assertFalse(parser.hasErrors()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/MCTypeFacadeTest.java b/monticore-grammar/src/test/java/de/monticore/types/MCTypeFacadeTest.java index 732c1783b1..31bb0fd8a6 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/MCTypeFacadeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/MCTypeFacadeTest.java @@ -12,10 +12,11 @@ import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class MCTypeFacadeTest { private MCTypeFacade mcTypeFacade; @@ -30,339 +31,339 @@ public void init() { @Test public void testCreateQualifiedTypeName() { ASTMCQualifiedType qualifiedType = mcTypeFacade.createQualifiedType("a.b.c.Foo"); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), qualifiedType.getNameList()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), qualifiedType.getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateQualifiedTypeClass() { ASTMCQualifiedType qualifiedType = mcTypeFacade.createQualifiedType(java.lang.String.class); - Assertions.assertEquals(Lists.newArrayList("String"), qualifiedType.getNameList()); + assertEquals(Lists.newArrayList("String"), qualifiedType.getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateBasicTypeArgumentOf() { ASTMCBasicTypeArgument type = mcTypeFacade.createBasicTypeArgumentOf("a.b.c.Foo"); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), type.getMCQualifiedType().getNameList()); - Assertions.assertTrue(type.getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeOpt().get()).getNameList()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), type.getMCQualifiedType().getNameList()); + assertTrue(type.getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateWildCardWithNoBounds() { ASTMCWildcardTypeArgument type = mcTypeFacade.createWildCardWithNoBounds(); - Assertions.assertFalse(type.isPresentLowerBound()); - Assertions.assertFalse(type.isPresentUpperBound()); + assertFalse(type.isPresentLowerBound()); + assertFalse(type.isPresentUpperBound()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateWildCardWithUpperBoundTypeClass() { ASTMCWildcardTypeArgument type = mcTypeFacade.createWildCardWithUpperBoundType(String.class); - Assertions.assertFalse(type.isPresentLowerBound()); - Assertions.assertTrue(type.isPresentUpperBound()); - Assertions.assertTrue(type.getUpperBound() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getUpperBound()).getNameList()); + assertFalse(type.isPresentLowerBound()); + assertTrue(type.isPresentUpperBound()); + assertInstanceOf(ASTMCQualifiedType.class, type.getUpperBound()); + assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getUpperBound()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateWildCardWithUpperBoundTypeName() { ASTMCWildcardTypeArgument type = mcTypeFacade.createWildCardWithUpperBoundType("a.b.c.Foo"); - Assertions.assertFalse(type.isPresentLowerBound()); - Assertions.assertTrue(type.isPresentUpperBound()); - Assertions.assertTrue(type.getUpperBound() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getUpperBound()).getNameList()); + assertFalse(type.isPresentLowerBound()); + assertTrue(type.isPresentUpperBound()); + assertInstanceOf(ASTMCQualifiedType.class, type.getUpperBound()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getUpperBound()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateWildCardWithUpperBoundTypeType() { ASTMCWildcardTypeArgument type = mcTypeFacade.createWildCardWithUpperBoundType(mcTypeFacade.createQualifiedType("a.b.c.Foo")); - Assertions.assertFalse(type.isPresentLowerBound()); - Assertions.assertTrue(type.isPresentUpperBound()); - Assertions.assertTrue(type.getUpperBound() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getUpperBound()).getNameList()); + assertFalse(type.isPresentLowerBound()); + assertTrue(type.isPresentUpperBound()); + assertInstanceOf(ASTMCQualifiedType.class, type.getUpperBound()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getUpperBound()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateOptionalTypeOfClass() { ASTMCOptionalType type = mcTypeFacade.createOptionalTypeOf(String.class); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Optional", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Optional", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateOptionalTypeOfName() { ASTMCOptionalType type = mcTypeFacade.createOptionalTypeOf("a.b.c.Foo"); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Optional", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Optional", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateOptionalTypeOfType() { ASTMCOptionalType type = mcTypeFacade.createOptionalTypeOf(mcTypeFacade.createQualifiedType("a.b.c.Foo")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Optional", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Optional", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateOptionalTypeOfTypeArgument() { ASTMCOptionalType type = mcTypeFacade.createOptionalTypeOf(mcTypeFacade.createBasicTypeArgumentOf("a.b.c.Foo")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Optional", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Optional", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateListTypeOfClass() { ASTMCListType type = mcTypeFacade.createListTypeOf(String.class); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("List", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("List", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateListTypeOfName() { ASTMCListType type = mcTypeFacade.createListTypeOf("a.b.c.Foo"); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("List", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("List", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateListTypeOfType() { ASTMCListType type = mcTypeFacade.createListTypeOf(mcTypeFacade.createQualifiedType("a.b.c.Foo")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("List", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("List", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateListTypeOfTypeArgument() { ASTMCListType type = mcTypeFacade.createListTypeOf(mcTypeFacade.createBasicTypeArgumentOf("a.b.c.Foo")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("List", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("List", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateSetTypeOfClass() { ASTMCSetType type = mcTypeFacade.createSetTypeOf(String.class); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Set", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Set", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateSetTypeOfName() { ASTMCSetType type = mcTypeFacade.createSetTypeOf("a.b.c.Foo"); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Set", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Set", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateSetTypeOfType() { ASTMCSetType type = mcTypeFacade.createSetTypeOf(mcTypeFacade.createQualifiedType("a.b.c.Foo")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Set", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Set", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateSetTypeOfTypeArgument() { ASTMCSetType type = mcTypeFacade.createSetTypeOf(mcTypeFacade.createBasicTypeArgumentOf("a.b.c.Foo")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Set", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Set", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateCollectionTypeOfClass() { ASTMCGenericType type = mcTypeFacade.createCollectionTypeOf(String.class); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Collection", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Collection", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(0).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateCollectionTypeOfName() { ASTMCGenericType type = mcTypeFacade.createCollectionTypeOf("a.b.c.Foo"); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Collection", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Collection", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(0).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateCollectionTypeOfType() { ASTMCGenericType type = mcTypeFacade.createCollectionTypeOf(mcTypeFacade.createQualifiedType("a.b.c.Foo")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Collection", type.getName(0)); - Assertions.assertEquals(1, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Collection", type.getName(0)); + assertEquals(1, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(0).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateMapTypeOfClass() { ASTMCMapType type = mcTypeFacade.createMapTypeOf(String.class, Integer.class); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Map", type.getName(0)); - Assertions.assertEquals(2, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getKey().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getKey().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getKey().getMCTypeOpt().get()).getNameList()); - - Assertions.assertTrue(type.getValue().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getValue().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("Integer"), ((ASTMCQualifiedType) type.getValue().getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Map", type.getName(0)); + assertEquals(2, type.sizeMCTypeArguments()); + assertTrue(type.getKey().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getKey().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type.getKey().getMCTypeOpt().get()).getNameList()); + + assertTrue(type.getValue().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getValue().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("Integer"), ((ASTMCQualifiedType) type.getValue().getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateMapTypeOfName() { ASTMCMapType type = mcTypeFacade.createMapTypeOf("a.b.c.Foo", "d.e.f.Bla"); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Map", type.getName(0)); - Assertions.assertEquals(2, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getKey().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getKey().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getKey().getMCTypeOpt().get()).getNameList()); - - Assertions.assertTrue(type.getValue().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getValue().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getValue().getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Map", type.getName(0)); + assertEquals(2, type.sizeMCTypeArguments()); + assertTrue(type.getKey().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getKey().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getKey().getMCTypeOpt().get()).getNameList()); + + assertTrue(type.getValue().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getValue().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getValue().getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateMapTypeOfType() { ASTMCMapType type = mcTypeFacade.createMapTypeOf(mcTypeFacade.createQualifiedType("a.b.c.Foo"), mcTypeFacade.createQualifiedType("d.e.f.Bla")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Map", type.getName(0)); - Assertions.assertEquals(2, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getKey().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getKey().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getKey().getMCTypeOpt().get()).getNameList()); - - Assertions.assertTrue(type.getValue().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getValue().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getValue().getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Map", type.getName(0)); + assertEquals(2, type.sizeMCTypeArguments()); + assertTrue(type.getKey().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getKey().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getKey().getMCTypeOpt().get()).getNameList()); + + assertTrue(type.getValue().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getValue().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getValue().getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateMapTypeOfTypeArgument() { ASTMCMapType type = mcTypeFacade.createMapTypeOf(mcTypeFacade.createBasicTypeArgumentOf("a.b.c.Foo"), mcTypeFacade.createBasicTypeArgumentOf("d.e.f.Bla")); - Assertions.assertEquals(1, type.sizeNames()); - Assertions.assertEquals("Map", type.getName(0)); - Assertions.assertEquals(2, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getKey().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getKey().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getKey().getMCTypeOpt().get()).getNameList()); - - Assertions.assertTrue(type.getValue().getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getValue().getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getValue().getMCTypeOpt().get()).getNameList()); + assertEquals(1, type.sizeNames()); + assertEquals("Map", type.getName(0)); + assertEquals(2, type.sizeMCTypeArguments()); + assertTrue(type.getKey().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getKey().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getKey().getMCTypeOpt().get()).getNameList()); + + assertTrue(type.getValue().getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getValue().getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getValue().getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -373,18 +374,18 @@ public void testCreateBasicGenericTypeOfNameList() { ASTMCBasicGenericType type = mcTypeFacade.createBasicGenericTypeOf( Lists.newArrayList("my", "special", "GenericType"), Lists.newArrayList(basicTypeArgumentOfFoo, basicTypeArgumentOfBla)); - Assertions.assertEquals(3, type.sizeNames()); - Assertions.assertEquals(Lists.newArrayList("my","special","GenericType"), type.getNameList()); - Assertions.assertEquals(2, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - - Assertions.assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getMCTypeArgument(1).getMCTypeOpt().get()).getNameList()); + assertEquals(3, type.sizeNames()); + assertEquals(Lists.newArrayList("my","special","GenericType"), type.getNameList()); + assertEquals(2, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(0).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + + assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(1).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getMCTypeArgument(1).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -395,18 +396,18 @@ public void testCreateBasicGenericTypeOfArgumentList() { ASTMCBasicGenericType type = mcTypeFacade.createBasicGenericTypeOf( "my.special.GenericType", Lists.newArrayList(basicTypeArgumentOfFoo, basicTypeArgumentOfBla)); - Assertions.assertEquals(3, type.sizeNames()); - Assertions.assertEquals(Lists.newArrayList("my","special","GenericType"), type.getNameList()); - Assertions.assertEquals(2, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - - Assertions.assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getMCTypeArgument(1).getMCTypeOpt().get()).getNameList()); + assertEquals(3, type.sizeNames()); + assertEquals(Lists.newArrayList("my","special","GenericType"), type.getNameList()); + assertEquals(2, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(0).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + + assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(1).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getMCTypeArgument(1).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -416,108 +417,108 @@ public void testCreateBasicGenericTypeOfArgumentVarArgs() { ASTMCBasicGenericType type = mcTypeFacade.createBasicGenericTypeOf( "my.special.GenericType", basicTypeArgumentOfFoo, basicTypeArgumentOfBla); - Assertions.assertEquals(3, type.sizeNames()); - Assertions.assertEquals(Lists.newArrayList("my","special","GenericType"), type.getNameList()); - Assertions.assertEquals(2, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - - Assertions.assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getMCTypeArgument(1).getMCTypeOpt().get()).getNameList()); + assertEquals(3, type.sizeNames()); + assertEquals(Lists.newArrayList("my","special","GenericType"), type.getNameList()); + assertEquals(2, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(0).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + + assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(1).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getMCTypeArgument(1).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateBasicGenericTypeOfArgumentString() { ASTMCBasicGenericType type = mcTypeFacade.createBasicGenericTypeOf( "my.special.GenericType", "a.b.c.Foo", "d.e.f.Bla"); - Assertions.assertEquals(3, type.sizeNames()); - Assertions.assertEquals(Lists.newArrayList("my","special","GenericType"), type.getNameList()); - Assertions.assertEquals(2, type.sizeMCTypeArguments()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); - - Assertions.assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().isPresent()); - Assertions.assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().get() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getMCTypeArgument(1).getMCTypeOpt().get()).getNameList()); + assertEquals(3, type.sizeNames()); + assertEquals(Lists.newArrayList("my","special","GenericType"), type.getNameList()); + assertEquals(2, type.sizeMCTypeArguments()); + assertTrue(type.getMCTypeArgument(0).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(0).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("a", "b", "c", "Foo"), ((ASTMCQualifiedType) type.getMCTypeArgument(0).getMCTypeOpt().get()).getNameList()); + + assertTrue(type.getMCTypeArgument(1).getMCTypeOpt().isPresent()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCTypeArgument(1).getMCTypeOpt().get()); + assertEquals(Lists.newArrayList("d", "e", "f", "Bla"), ((ASTMCQualifiedType) type.getMCTypeArgument(1).getMCTypeOpt().get()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateArrayTypeString() { ASTMCArrayType type = mcTypeFacade.createArrayType("int", 3); - Assertions.assertEquals(3, type.getDimensions()); - Assertions.assertTrue(type.getMCType() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("int"), ((ASTMCQualifiedType) type.getMCType()).getNameList()); + assertEquals(3, type.getDimensions()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCType()); + assertEquals(Lists.newArrayList("int"), ((ASTMCQualifiedType) type.getMCType()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateArrayTypeClass() { ASTMCArrayType type = mcTypeFacade.createArrayType(Integer.class, 3); - Assertions.assertEquals(3, type.getDimensions()); - Assertions.assertTrue(type.getMCType() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("Integer"), ((ASTMCQualifiedType) type.getMCType()).getNameList()); + assertEquals(3, type.getDimensions()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCType()); + assertEquals(Lists.newArrayList("Integer"), ((ASTMCQualifiedType) type.getMCType()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateArrayTypeType() { ASTMCArrayType type = mcTypeFacade.createArrayType(mcTypeFacade.createQualifiedType("int"), 3); - Assertions.assertEquals(3, type.getDimensions()); - Assertions.assertTrue(type.getMCType() instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("int"), ((ASTMCQualifiedType) type.getMCType()).getNameList()); + assertEquals(3, type.getDimensions()); + assertInstanceOf(ASTMCQualifiedType.class, type.getMCType()); + assertEquals(Lists.newArrayList("int"), ((ASTMCQualifiedType) type.getMCType()).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateVoidType() { ASTMCVoidType type = mcTypeFacade.createVoidType(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateBooleanType() { ASTMCPrimitiveType type = mcTypeFacade.createBooleanType(); - Assertions.assertTrue(type.isBoolean()); + assertTrue(type.isBoolean()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testIsBooleanType() { ASTMCPrimitiveType booleanType = mcTypeFacade.createBooleanType(); - Assertions.assertTrue(mcTypeFacade.isBooleanType(booleanType)); + assertTrue(mcTypeFacade.isBooleanType(booleanType)); ASTMCType stringType = mcTypeFacade.createStringType(); - Assertions.assertFalse(mcTypeFacade.isBooleanType(stringType)); + assertFalse(mcTypeFacade.isBooleanType(stringType)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreateIntType() { ASTMCPrimitiveType type = mcTypeFacade.createIntType(); - Assertions.assertTrue(type.isInt()); + assertTrue(type.isInt()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCreatePrimitiveType() { ASTMCType type = mcTypeFacade.createStringType(); - Assertions.assertTrue(type instanceof ASTMCQualifiedType); - Assertions.assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type).getNameList()); + assertInstanceOf(ASTMCQualifiedType.class, type); + assertEquals(Lists.newArrayList("String"), ((ASTMCQualifiedType) type).getNameList()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/MCollectionTypesCorrectStateTest.java b/monticore-grammar/src/test/java/de/monticore/types/MCollectionTypesCorrectStateTest.java index ab70981f2a..c565f07a44 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/MCollectionTypesCorrectStateTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/MCollectionTypesCorrectStateTest.java @@ -9,13 +9,14 @@ import de.monticore.types.mccollectiontypeswithoutprimitivestest._parser.MCCollectionTypesWithoutPrimitivesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCollectionTypesCorrectStateTest { private ASTMCListType listTypeParser; @@ -40,23 +41,23 @@ public void init() { public void setUp() throws IOException { MCCollectionTypesWithoutPrimitivesTestParser parser = new MCCollectionTypesWithoutPrimitivesTestParser(); Optional listTypeParser = parser.parse_StringMCListType("List"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(listTypeParser.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(listTypeParser.isPresent()); this.listTypeParser = listTypeParser.get(); Optional optionalTypeParser = parser.parse_StringMCOptionalType("Optional"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(optionalTypeParser.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(optionalTypeParser.isPresent()); this.optTypeParser = optionalTypeParser.get(); Optional setType = parser.parse_StringMCSetType("Set"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(setType.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(setType.isPresent()); this.setTypeParser = setType.get(); Optional mapType = parser.parse_StringMCMapType("Map"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(mapType.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(mapType.isPresent()); this.mapTypeParser = mapType.get(); @@ -68,64 +69,64 @@ public void setUp() throws IOException { ASTMCQualifiedType stringType = MCCollectionTypesMill.mCQualifiedTypeBuilder().setMCQualifiedName(stringName).build(); typeArgumentString = MCCollectionTypesMill.mCBasicTypeArgumentBuilder().setMCQualifiedType(stringType).build(); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void mCListTypeNameListFinal() { // test that MCListType only contains one element 'List' - Assertions.assertEquals(1, listTypeParser.getNameList().size()); - Assertions.assertEquals("List", listTypeParser.getName(0)); + assertEquals(1, listTypeParser.getNameList().size()); + assertEquals("List", listTypeParser.getName(0)); // set name over getter listTypeParser.getNameList().set(0, "Foo"); - Assertions.assertEquals(1, listTypeParser.getNameList().size()); - Assertions.assertEquals("List", listTypeParser.getName(0)); + assertEquals(1, listTypeParser.getNameList().size()); + assertEquals("List", listTypeParser.getName(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void mCOptionalTypeNameListFinal() { // test that MCListType only contains one element 'Optional' - Assertions.assertEquals(1, optTypeParser.getNameList().size()); - Assertions.assertEquals("Optional", optTypeParser.getName(0)); + assertEquals(1, optTypeParser.getNameList().size()); + assertEquals("Optional", optTypeParser.getName(0)); // set name over getter optTypeParser.getNameList().set(0, "Foo"); - Assertions.assertEquals(1, optTypeParser.getNameList().size()); - Assertions.assertEquals("Optional", optTypeParser.getName(0)); + assertEquals(1, optTypeParser.getNameList().size()); + assertEquals("Optional", optTypeParser.getName(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void mCSetTypeNameListFinal() { // test that MCListType only contains one element 'Set' - Assertions.assertEquals(1, setTypeParser.getNameList().size()); - Assertions.assertEquals("Set", setTypeParser.getName(0)); + assertEquals(1, setTypeParser.getNameList().size()); + assertEquals("Set", setTypeParser.getName(0)); // set name over getter setTypeParser.getNameList().set(0, "Foo"); - Assertions.assertEquals(1, setTypeParser.getNameList().size()); - Assertions.assertEquals("Set", setTypeParser.getName(0)); + assertEquals(1, setTypeParser.getNameList().size()); + assertEquals("Set", setTypeParser.getName(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void mCMapTypeNameListFinal() throws IOException { // test that MCListType only contains one element 'Map' - Assertions.assertEquals(1, mapTypeParser.getNameList().size()); - Assertions.assertEquals("Map", mapTypeParser.getName(0)); + assertEquals(1, mapTypeParser.getNameList().size()); + assertEquals("Map", mapTypeParser.getName(0)); // set name over getter mapTypeParser.getNameList().set(0, "Foo"); - Assertions.assertEquals(1, mapTypeParser.getNameList().size()); - Assertions.assertEquals("Map", mapTypeParser.getName(0)); + assertEquals(1, mapTypeParser.getNameList().size()); + assertEquals("Map", mapTypeParser.getName(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -134,10 +135,10 @@ public void mCListTypeNameListFinalFromBuilder() { ASTMCListType listBuild = MCCollectionTypesMill.mCListTypeBuilder() .setMCTypeArgument(typeArgumentInt) .build(); - Assertions.assertEquals(1, listBuild.getNameList().size()); - Assertions.assertEquals("List", listBuild.getName(0)); + assertEquals(1, listBuild.getNameList().size()); + assertEquals("List", listBuild.getName(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -146,10 +147,10 @@ public void mCOptionalTypeNameListFinalFromBuilder() { ASTMCOptionalType optBuild = MCCollectionTypesMill.mCOptionalTypeBuilder() .setMCTypeArgument(typeArgumentInt) .build(); - Assertions.assertEquals(1, optBuild.getNameList().size()); - Assertions.assertEquals("Optional", optBuild.getName(0)); + assertEquals(1, optBuild.getNameList().size()); + assertEquals("Optional", optBuild.getName(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -158,10 +159,10 @@ public void mCSetTypeNameListFinalFromBuilder() { ASTMCSetType setBuild = MCCollectionTypesMill.mCSetTypeBuilder() .setMCTypeArgument(typeArgumentInt) .build(); - Assertions.assertEquals(1, setBuild.getNameList().size()); - Assertions.assertEquals("Set", setBuild.getName(0)); + assertEquals(1, setBuild.getNameList().size()); + assertEquals("Set", setBuild.getName(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -171,40 +172,40 @@ public void mCMapTypeNameListFinalFromBuilder() { .setKey(typeArgumentInt) .setValue(typeArgumentString) .build(); - Assertions.assertEquals(1, mapBuildNoName.getNameList().size()); - Assertions.assertEquals("Map", mapBuildNoName.getName(0)); + assertEquals(1, mapBuildNoName.getNameList().size()); + assertEquals("Map", mapBuildNoName.getName(0)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void mCListTypeSetTypeArgument() { listTypeParser.setMCTypeArgument(typeArgumentString); - Assertions.assertEquals(1, listTypeParser.getMCTypeArgumentList().size()); - Assertions.assertEquals("String", listTypeParser.getMCTypeArgument().printType()); + assertEquals(1, listTypeParser.getMCTypeArgumentList().size()); + assertEquals("String", listTypeParser.getMCTypeArgument().printType()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void mcOptionalTypeSetTypeArgument() { optTypeParser.setMCTypeArgument(typeArgumentString); - Assertions.assertEquals(1, optTypeParser.getMCTypeArgumentList().size()); - Assertions.assertEquals("String", optTypeParser.getMCTypeArgument().printType()); + assertEquals(1, optTypeParser.getMCTypeArgumentList().size()); + assertEquals("String", optTypeParser.getMCTypeArgument().printType()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void mcMapTypeSetKey() { mapTypeParser.setKey(typeArgumentString); - Assertions.assertEquals(2, mapTypeParser.getMCTypeArgumentList().size()); - Assertions.assertEquals("String", mapTypeParser.getKey().printType()); - Assertions.assertEquals("Integer", mapTypeParser.getValue().printType()); + assertEquals(2, mapTypeParser.getMCTypeArgumentList().size()); + assertEquals("String", mapTypeParser.getKey().printType()); + assertEquals("Integer", mapTypeParser.getValue().printType()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/AbstractDeriveTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/AbstractDeriveTest.java index c5cdab7d9d..30756f853a 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/AbstractDeriveTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/AbstractDeriveTest.java @@ -14,7 +14,6 @@ import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,8 +21,8 @@ import java.util.Optional; import static de.monticore.types.check.DefsTypeBasic.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AbstractDeriveTest { @@ -33,15 +32,15 @@ public class AbstractDeriveTest { // Parser used for convenience: // (may be any other Parser that understands CommonExpressions) - AbstractTypeCheckTestParser p = new AbstractTypeCheckTestParser(); + protected AbstractTypeCheckTestParser p; // This is an auxiliary - FullDeriveFromCombineExpressionsWithLiteralsAbstract derLit = new FullDeriveFromCombineExpressionsWithLiteralsAbstract(); + protected FullDeriveFromCombineExpressionsWithLiteralsAbstract derLit; // other arguments not used (and therefore deliberately null) // This is the TypeChecker under Test: - TypeCalculator tc = new TypeCalculator(null, derLit); + protected TypeCalculator tc; @BeforeEach @@ -69,7 +68,7 @@ public void init(){ TypeSymbol student = AbstractTypeCheckTestMill.typeSymbolBuilder() .setName("Student") .setSpannedScope(AbstractTypeCheckTestMill.scope()) - .setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObject("Person",scope))) + .setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person",scope))) .setEnclosingScope(scope) .build(); add2scope(scope, student); @@ -77,7 +76,7 @@ public void init(){ TypeSymbol firstsemesterstudent = AbstractTypeCheckTestMill.typeSymbolBuilder() .setName("FirstSemesterStudent") .setSpannedScope(AbstractTypeCheckTestMill.scope()) - .setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObject("Student",scope))) + .setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student",scope))) .setEnclosingScope(scope) .build(); firstsemesterstudent.setSpannedScope(AbstractTypeCheckTestMill.scope()); @@ -91,12 +90,17 @@ public void init(){ add2scope(person.getSpannedScope(), method("foo", SymTypeExpressionFactory.createTypeVoid())); add2scope(person.getSpannedScope(), field("bar", SymTypeExpressionFactory.createPrimitive("int"))); add2scope(scope, firstsemesterstudent); - add2scope(scope, field("person1", SymTypeExpressionFactory.createTypeObject("Person", scope))); + add2scope(scope, field("person1", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person", scope))); add2scope(scope, field("firstsemester", SymTypeExpressionFactory. - createTypeObject("FirstSemesterStudent", scope))); + createTypeObjectViaSurrogate("FirstSemesterStudent", scope))); tc = new TypeCalculator(null, derLit); flatExpressionScopeSetter = new FlatExpressionScopeSetter(scope); traverser = getTraverser(flatExpressionScopeSetter); + + derLit = new FullDeriveFromCombineExpressionsWithLiteralsAbstract(); + p = AbstractTypeCheckTestMill.parser(); + tc = new TypeCalculator(null, derLit); + } public void add2scope(IBasicSymbolsScope scope, TypeSymbol type){ @@ -125,56 +129,56 @@ public AbstractTypeCheckTestTraverser getTraverser(FlatExpressionScopeSetter fla @Test public void testFieldAccessInnerVariables() throws IOException { Optional expr = p.parse_StringExpression("person1.bar"); - Assertions.assertTrue(expr.isPresent()); + assertTrue(expr.isPresent()); expr.get().accept(traverser); - Assertions.assertEquals("int", tc.typeOf(expr.get()).print()); + assertEquals("int", tc.typeOf(expr.get()).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testFieldAccessInnerTypes() throws IOException { Optional expr = p.parse_StringExpression("person1.Address"); - Assertions.assertTrue(expr.isPresent()); + assertTrue(expr.isPresent()); expr.get().accept(traverser); - Assertions.assertEquals("Address", tc.typeOf(expr.get()).print()); + assertEquals("Address", tc.typeOf(expr.get()).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testCallInnerMethods() throws IOException { Optional expr = p.parse_StringExpression("person1.foo()"); - Assertions.assertTrue(expr.isPresent()); + assertTrue(expr.isPresent()); expr.get().accept(traverser); - Assertions.assertEquals("void", tc.typeOf(expr.get()).print()); + assertEquals("void", tc.typeOf(expr.get()).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInheritanceVariables() throws IOException { Optional expr = p.parse_StringExpression("firstsemester.bar"); - Assertions.assertTrue(expr.isPresent()); + assertTrue(expr.isPresent()); expr.get().accept(traverser); - Assertions.assertEquals("int", tc.typeOf(expr.get()).print()); + assertEquals("int", tc.typeOf(expr.get()).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testInheritanceMethods() throws IOException { Optional expr = p.parse_StringExpression("firstsemester.foo()"); - Assertions.assertTrue(expr.isPresent()); + assertTrue(expr.isPresent()); expr.get().accept(traverser); - Assertions.assertEquals("void", tc.typeOf(expr.get()).print()); + assertEquals("void", tc.typeOf(expr.get()).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/CompKindOfComponentTypeTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/CompKindOfComponentTypeTest.java new file mode 100644 index 0000000000..aef2fbcce6 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/types/check/CompKindOfComponentTypeTest.java @@ -0,0 +1,212 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.types.check; + +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; +import de.monticore.symbols.compsymbols._symboltable.PortSymbol; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Holds test for {@link CompKindOfComponentType} + */ +public class CompKindOfComponentTypeTest { + + @BeforeEach + public void setup() { + CompSymbolsMill.reset(); + CompSymbolsMill.init(); + BasicSymbolsMill.initializePrimitives(); + } + + @Test + void testDeepClone() { + // Given + CompKindOfComponentType comp = new CompKindOfComponentType(CompSymbolsMill.componentTypeSymbolBuilder() + .setName("A") + .setSpannedScope(CompSymbolsMill.scope()) + .build()); + + // When + CompKindOfComponentType clone = comp.deepClone().asComponentType(); + + // Then + assertEquals(comp.getTypeInfo(), clone.getTypeInfo()); + assertNotSame(comp.getArguments(), clone.getArguments()); + assertIterableEquals(comp.getArguments(), clone.getArguments()); + assertNotSame(comp.getParamBindings(), clone.getParamBindings()); + assertIterableEquals(comp.getParamBindingsAsList(), clone.getParamBindingsAsList()); + assertEquals(comp.getSourceNode().isPresent(), clone.getSourceNode().isPresent()); + } + + /** + * Method under test {@link CompKindOfComponentType#getSuperComponents()} + */ + @Test + public void getParentShouldReturnExpected() { + // Given + ComponentTypeSymbol symbolWithDefinitions = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Comp") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + ComponentTypeSymbol symbolVersionForTypeExpr = CompSymbolsMill + .componentTypeSymbolSurrogateBuilder() + .setName(symbolWithDefinitions.getFullName()) + .setEnclosingScope(CompSymbolsMill.globalScope()) + .build(); + + // Given + CompSymbolsMill.globalScope().add(symbolWithDefinitions); + symbolWithDefinitions.setEnclosingScope(CompSymbolsMill.globalScope()); + + ComponentTypeSymbol parent = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Parent") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + CompKindOfComponentType parentTypeExpr = new CompKindOfComponentType(parent); + + symbolWithDefinitions.setSuperComponentsList(Collections.singletonList(parentTypeExpr)); + CompKindOfComponentType compTypeExpr = new CompKindOfComponentType(symbolVersionForTypeExpr); + + // When + List parentOfTypeExpr = compTypeExpr.getSuperComponents(); + + // Then + assertFalse(parentOfTypeExpr.isEmpty(), "Parent not present."); + assertEquals(parentTypeExpr, parentOfTypeExpr.get(0)); + } + + /** + * Method under test {@link CompKindOfComponentType#getSuperComponents()} + */ + @Test + public void getParentShouldReturnOptionalEmpty() { + // Given + ComponentTypeSymbol component = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Comp") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + CompKindOfComponentType compTypeExpr = new CompKindOfComponentType(component); + + // When + List parentOfTypeExpr = compTypeExpr.getSuperComponents(); + + // Then + assertTrue(parentOfTypeExpr.isEmpty()); + } + + @Test + public void shouldGetTypeExprOfPort() { + // Given + ComponentTypeSymbol symbolWithDefinitions = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Comp") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + ComponentTypeSymbol symbolVersionForTypeExpr = CompSymbolsMill + .componentTypeSymbolSurrogateBuilder() + .setName(symbolWithDefinitions.getFullName()) + .setEnclosingScope(CompSymbolsMill.globalScope()) + .build(); + + // Given + CompSymbolsMill.globalScope().add(symbolWithDefinitions); + symbolWithDefinitions.setEnclosingScope(CompSymbolsMill.globalScope()); + + String portName = "port"; + PortSymbol port = CompSymbolsMill.portSymbolBuilder() + .setName(portName) + .setType(SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT)) + .setIncoming(true) + .build(); + symbolWithDefinitions.getSpannedScope().add(port); + + CompKindOfComponentType compTypeExpr = new CompKindOfComponentType(symbolVersionForTypeExpr); + + // When + Optional portsType = compTypeExpr.getTypeOfPort(portName); + + // Then + assertTrue(portsType.isPresent(), "Port not present"); + assertInstanceOf(SymTypePrimitive.class, portsType.get()); + assertEquals(BasicSymbolsMill.INT, portsType.get().print()); + } + + @Test + public void shouldGetTypeExprOfInheritedPort() { + // Given + ComponentTypeSymbol parent = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Parent") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + String portName = "port"; + PortSymbol port = CompSymbolsMill.portSymbolBuilder() + .setName(portName) + .setType(SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT)) + .setIncoming(true) + .build(); + parent.getSpannedScope().add(port); + + ComponentTypeSymbol component = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Comp") + .setSuperComponentsList(Collections.singletonList(new CompKindOfComponentType(parent))) + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + CompKindOfComponentType compTypeExpr = new CompKindOfComponentType(component); + + // When + Optional portsType = compTypeExpr.getTypeOfPort(portName); + + // Then + assertTrue(portsType.isPresent()); + assertTrue(portsType.get() instanceof SymTypePrimitive); + assertEquals(BasicSymbolsMill.INT, portsType.get().print()); + } + + @Test + public void shouldGetTypeExprOfParameter() { + // Given + ComponentTypeSymbol symbolWithDefinitions = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Comp") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + ComponentTypeSymbol symbolVersionForTypeExpr = CompSymbolsMill + .componentTypeSymbolSurrogateBuilder() + .setName(symbolWithDefinitions.getFullName()) + .setEnclosingScope(CompSymbolsMill.globalScope()) + .build(); + + // Given + CompSymbolsMill.globalScope().add(symbolWithDefinitions); + symbolWithDefinitions.setEnclosingScope(CompSymbolsMill.globalScope()); + + String paramName = "para"; + VariableSymbol param = CompSymbolsMill.variableSymbolBuilder() + .setName(paramName) + .setType(SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT)) + .build(); + symbolWithDefinitions.getSpannedScope().add(param); + symbolWithDefinitions.addParameter(param); + + CompKindOfComponentType compTypeExpr = new CompKindOfComponentType(symbolVersionForTypeExpr); + + // When + Optional paramType = compTypeExpr.getTypeOfParameter(paramName); + + // Then + assertTrue(paramType.isPresent(), "Param not present"); + assertInstanceOf(SymTypePrimitive.class, paramType.get()); + assertEquals(BasicSymbolsMill.INT, paramType.get().print()); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/CompKindOfGenericComponentTypeTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/CompKindOfGenericComponentTypeTest.java new file mode 100644 index 0000000000..4c72123b65 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/types/check/CompKindOfGenericComponentTypeTest.java @@ -0,0 +1,445 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.types.check; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; +import de.monticore.symbols.compsymbols.CompSymbolsMill; +import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; +import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbolSurrogate; +import de.monticore.symbols.compsymbols._symboltable.PortSymbol; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Holds test for {@link CompKindOfGenericComponentType} + */ +public class CompKindOfGenericComponentTypeTest { + + @BeforeEach + public void setup() { + CompSymbolsMill.reset(); + CompSymbolsMill.init(); + BasicSymbolsMill.initializePrimitives(); + } + + @Test + void testDeepClone() { + // Given + CompKindOfGenericComponentType comp = new CompKindOfGenericComponentType(CompSymbolsMill.componentTypeSymbolBuilder() + .setName("A") + .setSpannedScope(CompSymbolsMill.scope()) + .build(), + List.of(SymTypeExpressionFactory.createPrimitive("int"))); + + // When + CompKindOfGenericComponentType clone = comp.deepClone().asGenericComponentType(); + + // Then + assertEquals(comp.getTypeInfo(), clone.getTypeInfo()); + assertNotSame(comp.getArguments(), clone.getArguments()); + assertIterableEquals(comp.getArguments(), clone.getArguments()); + assertNotSame(comp.getParamBindings(), clone.getParamBindings()); + assertIterableEquals(comp.getParamBindingsAsList(), clone.getParamBindingsAsList()); + assertEquals(comp.getSourceNode().isPresent(), clone.getSourceNode().isPresent()); + assertNotSame(comp.getTypeBindingsAsList(), clone.getTypeBindingsAsList()); + } + + @Test + public void shouldGetParentComponent() { + // Given + ComponentTypeSymbol parent = createComponentWithTypeVar("Parent", "S"); + ComponentTypeSymbol component = CompSymbolsMill.componentTypeSymbolBuilder() + .setName("Comp") + .setSpannedScope(CompSymbolsMill.scope()) + .build(); + + // Creating a typeExpr representing Parent that is then set to be the parent of comp + CompKindExpression parentTypeExpr = new CompKindOfGenericComponentType(parent, + Lists.newArrayList(SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT))); + component.setSuperComponentsList(Collections.singletonList(parentTypeExpr)); + + CompKindOfComponentType compTypeExpr = new CompKindOfComponentType(component); + + // When && Then + assertFalse(compTypeExpr.getSuperComponents().isEmpty()); + assertEquals(parentTypeExpr, compTypeExpr.getSuperComponents().get(0)); + } + + @Test + public void shouldGetParentWithTypeVarPrimitive() { + // Given + ComponentTypeSymbol parent = createComponentWithTypeVar("Parent", "S"); + ComponentTypeSymbol child = createComponentWithTypeVar("Child", "T"); + + SymTypeVariable typeVar = SymTypeExpressionFactory.createTypeVariable(child.getTypeParameters().get(0)); + child.setSuperComponentsList(Collections.singletonList(new CompKindOfGenericComponentType(parent, Lists.newArrayList(typeVar)))); + + SymTypeExpression typeArg = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT); + CompKindExpression bChild = new CompKindOfGenericComponentType(child, Lists.newArrayList(typeArg)); + + // When + CompKindOfGenericComponentType bParent = ((CompKindOfGenericComponentType) bChild.getSuperComponents().get(0)); + + // Then + assertSame(parent, bParent.getTypeInfo()); + assertInstanceOf(CompKindOfGenericComponentType.class, bParent); + assertTrue(bParent.getTypeBindingFor(parent.getTypeParameters().get(0)).isPresent()); + assertEquals(typeArg, bParent.getTypeBindingFor(parent.getTypeParameters().get(0)).get()); + } + + @Test + public void shouldGetParentWithTypeVarObject() { + // Given + ComponentTypeSymbol parent = createComponentWithTypeVar("Parent", "S"); + ComponentTypeSymbol child = createComponentWithTypeVar("Child", "T"); + + SymTypeVariable typeVar = SymTypeExpressionFactory.createTypeVariable(child.getTypeParameters().get(0)); + child.setSuperComponentsList(Collections.singletonList(new CompKindOfGenericComponentType(parent, Lists.newArrayList(typeVar)))); + + SymTypeExpression typeArg = SymTypeExpressionFactory + .createTypeObject(CompSymbolsMill.typeSymbolBuilder() + .setName("First") + .setSpannedScope(CompSymbolsMill.scope()) + .build() + ); + CompKindExpression bChild = new CompKindOfGenericComponentType(child, Lists.newArrayList(typeArg)); + + // When + CompKindOfGenericComponentType bParent = ((CompKindOfGenericComponentType) bChild.getSuperComponents().get(0)); + + // Then + assertSame(parent, bParent.getTypeInfo()); + assertInstanceOf(CompKindOfGenericComponentType.class, bParent); + assertTrue(bParent.getTypeBindingFor(parent.getTypeParameters().get(0)).isPresent()); + assertEquals(typeArg, bParent.getTypeBindingFor(parent.getTypeParameters().get(0)).get()); + } + + @Test + public void shouldGetParentWithTypeVarObjects() { + // Given + ComponentTypeSymbol parent = createComponentWithTypeVar("Parent", "S", "T"); + ComponentTypeSymbol child = createComponentWithTypeVar("Child", "U", "V"); + + SymTypeVariable typeVar1 = SymTypeExpressionFactory.createTypeVariable(child.getTypeParameters().get(0)); + SymTypeVariable typeVar2 = SymTypeExpressionFactory.createTypeVariable(child.getTypeParameters().get(1)); + child.setSuperComponentsList(Collections.singletonList(new CompKindOfGenericComponentType(parent, Lists.newArrayList(typeVar1, typeVar2)))); + + SymTypeExpression typeArg1 = SymTypeExpressionFactory + .createTypeObject(CompSymbolsMill.typeSymbolBuilder() + .setName("First") + .setSpannedScope(CompSymbolsMill.scope()) + .build()); + SymTypeExpression typeArg2 = SymTypeExpressionFactory + .createTypeObject(CompSymbolsMill.typeSymbolBuilder() + .setName("Second") + .setSpannedScope(CompSymbolsMill.scope()) + .build()); + CompKindExpression bChild = new CompKindOfGenericComponentType(child, Lists.newArrayList(typeArg1, typeArg2)); + + // When + CompKindOfGenericComponentType bParent = ((CompKindOfGenericComponentType) bChild.getSuperComponents().get(0)); + + // Then + assertSame(parent, bParent.getTypeInfo()); + assertInstanceOf(CompKindOfGenericComponentType.class, bParent); + assertTrue(bParent.getTypeBindingFor(parent.getTypeParameters().get(0)).isPresent()); + assertEquals(typeArg1, bParent.getTypeBindingFor(parent.getTypeParameters().get(0)).get()); + assertTrue(bParent.getTypeBindingFor(parent.getTypeParameters().get(1)).isPresent()); + assertEquals(typeArg2, bParent.getTypeBindingFor(parent.getTypeParameters().get(1)).get()); + } + + @Test + public void shouldGetParentWithTypeVar() { + // Given + ComponentTypeSymbol parent = createComponentWithTypeVar("Parent", "S"); + ComponentTypeSymbol child = createComponentWithTypeVar("Child", "T"); + + SymTypeVariable typeVar = SymTypeExpressionFactory.createTypeVariable(child.getTypeParameters().get(0)); + child.setSuperComponentsList(Collections.singletonList(new CompKindOfGenericComponentType(parent, Lists.newArrayList(typeVar)))); + + TypeVarSymbol symbol = CompSymbolsMill.typeVarSymbolBuilder().setName("A").build(); + SymTypeExpression typeArg = SymTypeExpressionFactory.createTypeVariable(symbol); + CompKindExpression bChild = new CompKindOfGenericComponentType(child, Lists.newArrayList(typeArg)); + + // When + CompKindOfGenericComponentType bParent = ((CompKindOfGenericComponentType) bChild.getSuperComponents().get(0)); + + // Then + assertSame(parent, bParent.getTypeInfo()); + assertInstanceOf(CompKindOfGenericComponentType.class, bParent); + assertTrue(bParent.getTypeBindingFor(parent.getTypeParameters().get(0)).isPresent()); + assertEquals(typeArg, bParent.getTypeBindingFor(parent.getTypeParameters().get(0)).get()); + } + + protected static Stream compWithTypeParamAndOptionallySurrogateProvider() { + Named original = Named.of( + "CompSymbol", + createComponentWithTypeVar("Comp", "T") + ); + Named surrogate = Named.of( + "CompSurrogate", + createSurrogateInGlobalScopeFor(original.getPayload()) + ); + + return Stream.of( + Arguments.of(original, original), + Arguments.of(original, surrogate) + ); + } + + /** + * @param symbolWithDefinitions Provide a component type symbol in which ports will be added in this test. + * @param symbolVersionForTypeExpr Set this to {@code symbolWithDefinitions}, or to a surrogate pointing to that + * symbol. This object will be used to create The ComponentTypeExpression. + */ + @ParameterizedTest + @MethodSource("compWithTypeParamAndOptionallySurrogateProvider") + public void shouldGetTypeExprOfPortWithOwnTypeVarReplaced(@NonNull ComponentTypeSymbol symbolWithDefinitions, + @NonNull ComponentTypeSymbol symbolVersionForTypeExpr) { + Preconditions.checkNotNull(symbolWithDefinitions); + Preconditions.checkNotNull(symbolVersionForTypeExpr); + + // Given + CompSymbolsMill.globalScope().add(symbolWithDefinitions); + symbolWithDefinitions.setEnclosingScope(CompSymbolsMill.globalScope()); + symbolVersionForTypeExpr.setEnclosingScope(CompSymbolsMill.globalScope()); + + TypeVarSymbol typeVar = symbolWithDefinitions.getTypeParameters().get(0); + + String portName = "port"; + PortSymbol port = CompSymbolsMill.portSymbolBuilder() + .setName(portName) + .setType(SymTypeExpressionFactory.createTypeVariable(typeVar)) + .setIncoming(true) + .build(); + symbolWithDefinitions.getSpannedScope().add(port); + + SymTypeExpression intTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT); + CompKindOfGenericComponentType boundCompTypeExpr = + new CompKindOfGenericComponentType(symbolVersionForTypeExpr, Lists.newArrayList(intTypeExpr)); + + // When + Optional portsType = boundCompTypeExpr.getTypeOfPort(portName); + + // Then + assertTrue(portsType.isPresent(), "Port missing"); + assertInstanceOf(SymTypePrimitive.class, portsType.get()); + assertEquals(BasicSymbolsMill.INT, portsType.get().print()); + } + + @Test + public void shouldGetTypeExprOfPortWithParentTypeVarReplaced() { + // Given + ComponentTypeSymbol parentCompDefinition = createComponentWithTypeVar("Parent", "S"); + TypeVarSymbol parentTypeVar = parentCompDefinition.getTypeParameters().get(0); + String portName = "porr"; + PortSymbol port = CompSymbolsMill.portSymbolBuilder() + .setName(portName) + .setType(SymTypeExpressionFactory.createTypeVariable(parentTypeVar)) + .setIncoming(true) + .build(); + parentCompDefinition.getSpannedScope().add(port); + + ComponentTypeSymbol compDefinition = createComponentWithTypeVar("Comp", "T"); + // bind parent's S with child's T to declare: Comp extends Parent + TypeVarSymbol childTypeVar = compDefinition.getTypeParameters().get(0); + SymTypeExpression childTypeVarExpr = SymTypeExpressionFactory.createTypeVariable(childTypeVar); + CompKindExpression boundParentTypeExpr = + new CompKindOfGenericComponentType(parentCompDefinition, Lists.newArrayList(childTypeVarExpr)); + compDefinition.setSuperComponentsList(Collections.singletonList(boundParentTypeExpr)); + + // create CompTypeExpr representing Comp + SymTypeExpression intTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT); + CompKindOfGenericComponentType boundCompTypeExpr = + new CompKindOfGenericComponentType(compDefinition, Lists.newArrayList(intTypeExpr)); + + // When + Optional portsType = boundCompTypeExpr.getTypeOfPort(portName); + + // Then + assertTrue(portsType.isPresent()); + assertTrue(portsType.get() instanceof SymTypePrimitive); + assertEquals(BasicSymbolsMill.INT, portsType.get().print()); + } + + /** + * @param symbolWithDefinitions Provide a component type symbol in which parameters will be added in this test. + * @param symbolVersionForTypeExpr Set this to {@code symbolWithDefinitions}, or to a surrogate pointing to that + * symbol. This object will be used to create The ComponentTypeExpression. + */ + @ParameterizedTest + @MethodSource("compWithTypeParamAndOptionallySurrogateProvider") + public void shouldGetTypeExprOfParameterWithOwnTypeVarReplaced(@NonNull ComponentTypeSymbol symbolWithDefinitions, + @NonNull ComponentTypeSymbol symbolVersionForTypeExpr) { + Preconditions.checkNotNull(symbolWithDefinitions); + Preconditions.checkNotNull(symbolVersionForTypeExpr); + + // Given + CompSymbolsMill.globalScope().add(symbolWithDefinitions); + symbolWithDefinitions.setEnclosingScope(CompSymbolsMill.globalScope()); + symbolVersionForTypeExpr.setEnclosingScope(CompSymbolsMill.globalScope()); + + TypeVarSymbol typeVar = symbolWithDefinitions.getTypeParameters().get(0); + + String paramName = "parr"; + VariableSymbol param = CompSymbolsMill.variableSymbolBuilder() + .setName(paramName) + .setType(SymTypeExpressionFactory.createTypeVariable(typeVar)) + .build(); + symbolWithDefinitions.getSpannedScope().add(param); + symbolWithDefinitions.addParameter(param); + + SymTypeExpression intTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT); + CompKindOfGenericComponentType boundCompTypeExpr = + new CompKindOfGenericComponentType(symbolVersionForTypeExpr, Lists.newArrayList(intTypeExpr)); + + // When + Optional paramTypeExpr = boundCompTypeExpr.getTypeOfParameter(paramName); + + // Then + assertTrue(paramTypeExpr.isPresent(), "param missing"); + assertInstanceOf(SymTypePrimitive.class, paramTypeExpr.get()); + assertEquals(BasicSymbolsMill.INT, paramTypeExpr.get().print()); + } + + @Test + public void shouldGetTypeExprOfParameterWithParentTypeVarReplaced() { + // Given + ComponentTypeSymbol parentCompDefinition = createComponentWithTypeVar("Parent", "S"); + TypeVarSymbol parentTypeVar = parentCompDefinition.getTypeParameters().get(0); + String name = "parr"; + VariableSymbol paramOfParent = CompSymbolsMill.variableSymbolBuilder() + .setName(name) + .setType(SymTypeExpressionFactory.createTypeVariable(parentTypeVar)) + .build(); + parentCompDefinition.getSpannedScope().add(paramOfParent); + parentCompDefinition.addParameter(paramOfParent); + + ComponentTypeSymbol compDefinition = createComponentWithTypeVar("Comp", "T"); + TypeVarSymbol childTypeVar = compDefinition.getTypeParameters().get(0); + VariableSymbol paramOfComp = CompSymbolsMill.variableSymbolBuilder() + .setName(name) + .setType(SymTypeExpressionFactory.createTypeVariable(childTypeVar)) + .build(); + compDefinition.getSpannedScope().add(paramOfComp); + compDefinition.addParameter(paramOfComp); + // bind parent's S with child's T to declare: Comp extends Parent + SymTypeExpression childTypeVarExpr = SymTypeExpressionFactory.createTypeVariable(childTypeVar); + CompKindExpression boundParentTypeExpr = + new CompKindOfGenericComponentType(parentCompDefinition, Lists.newArrayList(childTypeVarExpr)); + compDefinition.setSuperComponentsList(Collections.singletonList(boundParentTypeExpr)); + + // create CompTypeExpr representing Comp + SymTypeExpression intTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT); + CompKindOfGenericComponentType boundCompTypeExpr = + new CompKindOfGenericComponentType(compDefinition, Lists.newArrayList(intTypeExpr)); + + // When + Optional paramTypeExpr = boundCompTypeExpr.getTypeOfParameter(name); + + // Then + assertTrue(paramTypeExpr.isPresent()); + assertTrue(paramTypeExpr.get() instanceof SymTypePrimitive); + assertEquals(BasicSymbolsMill.INT, paramTypeExpr.get().print()); + } + + @Test + public void shouldGetBindingsAsListInCorrectOrder() { + // Given + ComponentTypeSymbol comp = createComponentWithTypeVar("Comp", "A", "B", "C"); + + SymTypeExpression floatTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.FLOAT); + SymTypeExpression intTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT); + SymTypeExpression boolTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.BOOLEAN); + List typeExprList = Lists.newArrayList(floatTypeExpr, intTypeExpr, boolTypeExpr); + + // When + CompKindOfGenericComponentType compTypeExpr = new CompKindOfGenericComponentType(comp, typeExprList); + + // Then + List returnedBindings = compTypeExpr.getTypeBindingsAsList(); + assertEquals(typeExprList, returnedBindings); + } + + @Test + public void shouldGetTypeParamBindingsSkippingSurrogate() { + // Given + ComponentTypeSymbol comp = createComponentWithTypeVar("Comp", "A", "B", "C"); + ComponentTypeSymbolSurrogate compSurrogate = CompSymbolsMill + .componentTypeSymbolSurrogateBuilder() + .setName("Comp") + .setEnclosingScope(CompSymbolsMill.globalScope()).build(); + CompSymbolsMill.globalScope().add(comp); + comp.setEnclosingScope(CompSymbolsMill.globalScope()); + + + SymTypeExpression floatTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.FLOAT); + SymTypeExpression intTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.INT); + SymTypeExpression boolTypeExpr = SymTypeExpressionFactory.createPrimitive(BasicSymbolsMill.BOOLEAN); + List typeExprList = Lists.newArrayList(floatTypeExpr, intTypeExpr, boolTypeExpr); + + // When + CompKindOfGenericComponentType compTypeExpr = new CompKindOfGenericComponentType(compSurrogate, typeExprList); + + // Then + assertAll( + () -> assertEquals(floatTypeExpr, compTypeExpr.getTypeBindingFor("A").orElseThrow()), + () -> assertEquals(intTypeExpr, compTypeExpr.getTypeBindingFor("B").orElseThrow()), + () -> assertEquals(boolTypeExpr, compTypeExpr.getTypeBindingFor("C").orElseThrow()), + () -> assertEquals(3, compTypeExpr.getTypeVarBindings().size()) + ); + + } + + /** + * Beware that the created symbol is not enclosed by any scope yet. + */ + protected static ComponentTypeSymbol createComponentWithTypeVar(@NonNull String compName, + @NonNull String... typeVarNames) { + Preconditions.checkNotNull(compName); + Preconditions.checkNotNull(typeVarNames); + + List typeVars = new ArrayList<>(typeVarNames.length); + for (String typeVarName : typeVarNames) { + TypeVarSymbol typeVar = CompSymbolsMill.typeVarSymbolBuilder() + .setName(typeVarName) + .build(); + typeVars.add(typeVar); + } + + return CompSymbolsMill.componentTypeSymbolBuilder() + .setName(compName) + .setSpannedScope(CompSymbolsMill.scope()) + .setTypeParameters(typeVars) + .build(); + } + + /** + * Beware that the created surrogate is not enclosed by any scope yet. + */ + protected static ComponentTypeSymbol createSurrogateInGlobalScopeFor(@NonNull ComponentTypeSymbol original) { + Preconditions.checkNotNull(original); + + return CompSymbolsMill + .componentTypeSymbolSurrogateBuilder() + .setName(original.getFullName()) + .setEnclosingScope(CompSymbolsMill.globalScope()) + .build(); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/DefiningSymbolsTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/DefiningSymbolsTest.java index 0ac3108de5..bd3183d824 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/DefiningSymbolsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/DefiningSymbolsTest.java @@ -21,15 +21,13 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class DefiningSymbolsTest { @@ -73,99 +71,100 @@ public void init() { @Test public void testQualified() throws IOException { Optional expr = p.parse_StringExpression("ListOfInt.e"); - Assertions.assertTrue(expr.isPresent()); - Assertions.assertTrue(expr.get() instanceof ASTFieldAccessExpression); + assertTrue(expr.isPresent()); + assertInstanceOf(ASTFieldAccessExpression.class, expr.get()); ASTFieldAccessExpression e = (ASTFieldAccessExpression) expr.get(); e.accept(getFlatExpressionScopeSetter(as)); TypeCalculator tc = new TypeCalculator(null, deriver); tc.typeOf(e); - Assertions.assertTrue(e.getDefiningSymbol().isPresent()); + assertTrue(e.getDefiningSymbol().isPresent()); ISymbol definingSymbol = e.getDefiningSymbol().get(); - Assertions.assertTrue(definingSymbol instanceof FieldSymbol); - Assertions.assertEquals("e", definingSymbol.getName()); - - Assertions.assertTrue(e.getExpression() instanceof ASTNameExpression); + assertInstanceOf(FieldSymbol.class, definingSymbol); + assertEquals("e", definingSymbol.getName()); + + assertInstanceOf(ASTNameExpression.class, e.getExpression()); ASTNameExpression listOfInt = (ASTNameExpression) e.getExpression(); - Assertions.assertTrue(listOfInt.getDefiningSymbol().isPresent()); - Assertions.assertEquals(listOfInt.getDefiningSymbol().get(), this.listOfInt); + assertTrue(listOfInt.getDefiningSymbol().isPresent()); + assertEquals(listOfInt.getDefiningSymbol().get(), this.listOfInt); expr = p.parse_StringExpression("ListOfInt.add(3)"); - Assertions.assertTrue(expr.isPresent()); - Assertions.assertTrue(expr.get() instanceof ASTCallExpression); + assertTrue(expr.isPresent()); + assertInstanceOf(ASTCallExpression.class, expr.get()); ASTCallExpression add = (ASTCallExpression) expr.get(); add.accept(getFlatExpressionScopeSetter(as)); tc.typeOf(add); - Assertions.assertTrue(add.getDefiningSymbol().isPresent()); + assertTrue(add.getDefiningSymbol().isPresent()); definingSymbol = add.getDefiningSymbol().get(); - Assertions.assertTrue(definingSymbol instanceof MethodSymbol); - Assertions.assertEquals("add", definingSymbol.getName()); - - Assertions.assertTrue(add.getExpression() instanceof ASTFieldAccessExpression); - Assertions.assertTrue(((ASTFieldAccessExpression) add.getExpression()).getExpression() instanceof ASTNameExpression); + assertInstanceOf(MethodSymbol.class, definingSymbol); + assertEquals("add", definingSymbol.getName()); + + assertInstanceOf(ASTFieldAccessExpression.class, add.getExpression()); + assertInstanceOf(ASTNameExpression.class, + ((ASTFieldAccessExpression) add.getExpression()).getExpression()); listOfInt = (ASTNameExpression) ((ASTFieldAccessExpression) add.getExpression()).getExpression(); - Assertions.assertTrue(listOfInt.getDefiningSymbol().isPresent()); - Assertions.assertEquals(listOfInt.getDefiningSymbol().get(), this.listOfInt); + assertTrue(listOfInt.getDefiningSymbol().isPresent()); + assertEquals(listOfInt.getDefiningSymbol().get(), this.listOfInt); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testUnqualified() throws IOException { Optional expr = p.parse_StringExpression("e"); - Assertions.assertTrue(expr.isPresent()); - Assertions.assertTrue(expr.get() instanceof ASTNameExpression); + assertTrue(expr.isPresent()); + assertInstanceOf(ASTNameExpression.class, expr.get()); ASTNameExpression e = (ASTNameExpression) expr.get(); e.accept(getFlatExpressionScopeSetter(typeScope)); TypeCalculator tc = new TypeCalculator(null, deriver); tc.typeOf(e); - Assertions.assertTrue(e.getDefiningSymbol().isPresent()); + assertTrue(e.getDefiningSymbol().isPresent()); ISymbol definingSymbol = e.getDefiningSymbol().get(); - Assertions.assertTrue(definingSymbol instanceof FieldSymbol); - Assertions.assertEquals("e", definingSymbol.getName()); + assertInstanceOf(FieldSymbol.class, definingSymbol); + assertEquals("e", definingSymbol.getName()); expr = p.parse_StringExpression("add(3)"); - Assertions.assertTrue(expr.isPresent()); - Assertions.assertTrue(expr.get() instanceof ASTCallExpression); + assertTrue(expr.isPresent()); + assertInstanceOf(ASTCallExpression.class, expr.get()); ASTCallExpression add = (ASTCallExpression) expr.get(); add.accept(getFlatExpressionScopeSetter(typeScope)); tc.typeOf(add); - Assertions.assertTrue(add.getDefiningSymbol().isPresent()); + assertTrue(add.getDefiningSymbol().isPresent()); definingSymbol = add.getDefiningSymbol().get(); - Assertions.assertTrue(definingSymbol instanceof MethodSymbol); - Assertions.assertEquals("add", definingSymbol.getName()); + assertInstanceOf(MethodSymbol.class, definingSymbol); + assertEquals("add", definingSymbol.getName()); expr = p.parse_StringExpression("ListOfInt"); - Assertions.assertTrue(expr.isPresent()); - Assertions.assertTrue(expr.get() instanceof ASTNameExpression); + assertTrue(expr.isPresent()); + assertInstanceOf(ASTNameExpression.class, expr.get()); ASTNameExpression listOfInt = (ASTNameExpression) expr.get(); listOfInt.accept(getFlatExpressionScopeSetter(as)); tc.typeOf(listOfInt); - Assertions.assertTrue(listOfInt.getDefiningSymbol().isPresent()); - Assertions.assertEquals(listOfInt.getDefiningSymbol().get(), this.listOfInt); + assertTrue(listOfInt.getDefiningSymbol().isPresent()); + assertEquals(listOfInt.getDefiningSymbol().get(), this.listOfInt); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testTypes() throws IOException { Optional type = as.resolveType("int"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); Optional intType = p.parse_StringMCType("int"); - Assertions.assertTrue(intType.isPresent()); + assertTrue(intType.isPresent()); intType.get().accept(getFlatExpressionScopeSetter(as)); TypeCalculator tc = new TypeCalculator(synthesizer, null); tc.symTypeFromAST(intType.get()); - Assertions.assertTrue(intType.get().getDefiningSymbol().isPresent()); - Assertions.assertEquals(intType.get().getDefiningSymbol().get(), type.get()); + assertTrue(intType.get().getDefiningSymbol().isPresent()); + assertEquals(intType.get().getDefiningSymbol().get(), type.get()); Optional listOfIntType = p.parse_StringMCType("ListOfInt"); - Assertions.assertTrue(listOfIntType.isPresent()); + assertTrue(listOfIntType.isPresent()); listOfIntType.get().accept(getFlatExpressionScopeSetter(as)); tc.symTypeFromAST(listOfIntType.get()); - Assertions.assertTrue(listOfIntType.get().getDefiningSymbol().isPresent()); - Assertions.assertEquals(listOfIntType.get().getDefiningSymbol().get(), this.listOfInt); + assertTrue(listOfIntType.get().getDefiningSymbol().isPresent()); + assertEquals(listOfIntType.get().getDefiningSymbol().get(), this.listOfInt); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } protected CombineExpressionsWithLiteralsTraverser getFlatExpressionScopeSetter(IExpressionsBasisScope scope){ diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeAbstractTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeAbstractTest.java index 98f25697f0..ccd1c9f744 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeAbstractTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeAbstractTest.java @@ -17,7 +17,6 @@ import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import java.io.IOException; @@ -26,6 +25,8 @@ import java.util.Optional; import java.util.stream.Collectors; +import static org.junit.jupiter.api.Assertions.*; + public abstract class DeriveSymTypeAbstractTest { @BeforeEach @@ -55,7 +56,7 @@ protected TypeCalculator getTypeCalculator() { protected ASTExpression parseExpression(String expression) throws IOException { Optional astExpression = parseStringExpression(expression); - Assertions.assertTrue(astExpression.isPresent()); + assertTrue(astExpression.isPresent()); return astExpression.get(); } @@ -77,7 +78,7 @@ protected final void check(String expression, String expectedType) throws IOExce ASTExpression astex = parseExpression(expression); setFlatExpressionScope(astex); - Assertions.assertEquals(expectedType, tc.typeOf(astex).print(), "Wrong return type for expression " + expression); + assertEquals(expectedType, tc.typeOf(astex).print(), "Wrong return type for expression " + expression); } protected final void checkError(String expression, String expectedError) throws IOException { @@ -88,10 +89,10 @@ protected final void checkError(String expression, String expectedError) throws Log.getFindings().clear(); try { SymTypeExpression result = tc.typeOf(astex); - Assertions.assertTrue(result.isObscureType()); - Assertions.assertEquals(expectedError, getFirstErrorCode()); + assertTrue(result.isObscureType()); + assertEquals(expectedError, getFirstErrorCode()); } catch (RuntimeException e) { - Assertions.assertEquals(expectedError, getFirstErrorCode()); + assertEquals(expectedError, getFirstErrorCode()); } } @@ -104,10 +105,10 @@ protected final void checkErrors(String expression, List expectedErrors) try { tc.typeOf(astex); } catch (RuntimeException e) { - Assertions.assertEquals(expectedErrors, getAllErrorCodes()); + assertEquals(expectedErrors, getAllErrorCodes()); return; } - Assertions.fail(); + fail(); } protected final void checkErrors(String expression, String... expectedErrors) throws IOException { @@ -125,14 +126,14 @@ protected final void checkErrorsAndFailOnException(String expression, List sType = p.parse_StringExpression("C.D"); - Assertions.assertTrue(sType.isPresent()); + assertTrue(sType.isPresent()); //TODO ND: complete when inner types are added } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfExpressionTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfExpressionTest.java index 65198b183b..39fec6c078 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfExpressionTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfExpressionTest.java @@ -12,6 +12,7 @@ import de.monticore.symbols.oosymbols.OOSymbolsMill; import de.monticore.symbols.oosymbols._symboltable.FieldSymbol; import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; +import de.monticore.types3.util.DefsTypesForTests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -19,7 +20,6 @@ import java.util.Optional; import static de.monticore.types.check.DefsTypeBasic.*; -import static org.junit.Assert.assertEquals; public class DeriveSymTypeOfExpressionTest extends DeriveSymTypeAbstractTest { @@ -45,21 +45,21 @@ public void init() { add2scope(scope, DefsTypeBasic._String); // some FieldSymbols (ie. Variables, Attributes) - OOTypeSymbol p = new OOTypeSymbol("Person"); + OOTypeSymbol p = DefsTypesForTests.oOtype("Person"); add2scope(scope,p); - OOTypeSymbol s = new OOTypeSymbol("Student"); + OOTypeSymbol s = DefsTypesForTests.oOtype("Student"); add2scope(scope,s); - s.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObject("Person", scope))); - OOTypeSymbol f = new OOTypeSymbol("FirstSemesterStudent"); + s.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person", scope))); + OOTypeSymbol f = DefsTypesForTests.oOtype("FirstSemesterStudent"); add2scope(scope,f); - f.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObject("Student", scope))); + f.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student", scope))); add2scope(scope, field("foo", _intSymType)); add2scope(scope, field("bar2", _booleanSymType)); - add2scope(scope, field("person1",SymTypeExpressionFactory.createTypeObject("Person",scope))); - add2scope(scope, field("person2",SymTypeExpressionFactory.createTypeObject("Person",scope))); - add2scope(scope, field("student1",SymTypeExpressionFactory.createTypeObject("Student",scope))); - add2scope(scope,field("student2",SymTypeExpressionFactory.createTypeObject("Student",scope))); - add2scope(scope,field("firstsemester",SymTypeExpressionFactory.createTypeObject("FirstSemesterStudent",scope))); + add2scope(scope, field("person1",SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person",scope))); + add2scope(scope, field("person2",SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person",scope))); + add2scope(scope, field("student1",SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student",scope))); + add2scope(scope,field("student2",SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student",scope))); + add2scope(scope,field("firstsemester",SymTypeExpressionFactory.createTypeObjectViaSurrogate("FirstSemesterStudent",scope))); //testing for generics TypeVarSymbol genArgs = typeVariable("GenArg"); diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfJavaClassExpressionsTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfJavaClassExpressionsTest.java index 3c39d75cd0..06bc7776a4 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfJavaClassExpressionsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfJavaClassExpressionsTest.java @@ -13,7 +13,6 @@ import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; import de.monticore.symbols.oosymbols.OOSymbolsMill; import de.monticore.symbols.oosymbols._symboltable.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,6 +20,7 @@ import java.util.Optional; import static de.monticore.types.check.DefsTypeBasic.*; +import static org.junit.jupiter.api.Assertions.assertFalse; public class DeriveSymTypeOfJavaClassExpressionsTest extends DeriveSymTypeAbstractTest { @@ -61,10 +61,10 @@ public void init() { add2scope(scope,p); OOTypeSymbol s = new OOTypeSymbol("Student"); add2scope(scope,s); - s.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObject("Person", scope))); + s.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person", scope))); OOTypeSymbol f = new OOTypeSymbol("FirstSemesterStudent"); add2scope(scope,f); - f.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObject("Student", scope))); + f.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student", scope))); add2scope(scope, field("foo", _intSymType)); add2scope(scope, field("bar2", _booleanSymType)); add2scope(scope, field("vardouble", _doubleSymType)); @@ -72,12 +72,12 @@ public void init() { add2scope(scope, field("varfloat", _floatSymType)); add2scope(scope, field("varlong", _longSymType)); add2scope(scope, field("varint", _intSymType)); - add2scope(scope, field("varString", SymTypeExpressionFactory.createTypeObject("String", scope))); - add2scope(scope, field("person1", SymTypeExpressionFactory.createTypeObject("Person", scope))); - add2scope(scope, field("person2", SymTypeExpressionFactory.createTypeObject("Person", scope))); - add2scope(scope, field("student1", SymTypeExpressionFactory.createTypeObject("Student", scope))); - add2scope(scope, field("student2", SymTypeExpressionFactory.createTypeObject("Student", scope))); - add2scope(scope, field("firstsemester", SymTypeExpressionFactory.createTypeObject("FirstSemesterStudent", scope))); + add2scope(scope, field("varString", SymTypeExpressionFactory.createTypeObjectViaSurrogate("String", scope))); + add2scope(scope, field("person1", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person", scope))); + add2scope(scope, field("person2", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person", scope))); + add2scope(scope, field("student1", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student", scope))); + add2scope(scope, field("student2", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student", scope))); + add2scope(scope, field("firstsemester", SymTypeExpressionFactory.createTypeObjectViaSurrogate("FirstSemesterStudent", scope))); setFlatExpressionScopeSetter(scope); } @@ -114,7 +114,7 @@ public void deriveFromPrimarySuperExpression() throws IOException { .setName("A") .setEnclosingScope(scope) .build(); - SymTypeExpression sup = SymTypeExpressionFactory.createTypeObject("A",scope); + SymTypeExpression sup = SymTypeExpressionFactory.createTypeObjectViaSurrogate("A",scope); supType.setIsClass(true); add2scope(scope,supType); @@ -362,10 +362,10 @@ public void failDeriveSymTypeOfClassExpression() throws IOException{ //test that types must have a name Optional class1 = p.parse_StringExpression("3.class"); - Assertions.assertFalse(class1.isPresent()); + assertFalse(class1.isPresent()); Optional class2 = p.parse_StringExpression("\"Hallo\".class"); - Assertions.assertFalse(class2.isPresent()); + assertFalse(class2.isPresent()); } @Test @@ -455,7 +455,7 @@ public void deriveSymTypeOfSuperExpression() throws IOException { superOuter.getSpannedScope().setEnclosingScope(superOuter.getEnclosingScope()); test.getSpannedScope().setEnclosingScope(superOuter.getSpannedScope()); superOuter.setIsClass(true); - SymTypeExpression superOuterType = SymTypeExpressionFactory.createTypeObject("SuperOuter",scope); + SymTypeExpression superOuterType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("SuperOuter",scope); add2scope(scope,superOuter); //class Outer @@ -549,7 +549,7 @@ public void failDeriveFromSuperExpression3() throws IOException{ superOuter.getSpannedScope().setEnclosingScope(superOuter.getEnclosingScope()); test.getSpannedScope().setEnclosingScope(superOuter.getSpannedScope()); superOuter.setIsClass(true); - SymTypeExpression superOuterType = SymTypeExpressionFactory.createTypeObject("SuperOuter",scope); + SymTypeExpression superOuterType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("SuperOuter",scope); add2scope(scope,superOuter); //second super type @@ -560,7 +560,7 @@ public void failDeriveFromSuperExpression3() throws IOException{ .build(); superOuterTwo.getSpannedScope().setEnclosingScope(superOuterTwo.getEnclosingScope()); superOuterTwo.setIsClass(true); - SymTypeExpression superOuterTwoType = SymTypeExpressionFactory.createTypeObject("SuperOuterTwo",scope); + SymTypeExpression superOuterTwoType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("SuperOuterTwo",scope); add2scope(scope,superOuterTwo); //class Outer @@ -643,7 +643,7 @@ public void failDeriveFromSuperExpression5() throws IOException{ superOuter.getSpannedScope().setEnclosingScope(superOuter.getEnclosingScope()); test.getSpannedScope().setEnclosingScope(superOuter.getSpannedScope()); superOuter.setIsClass(true); - SymTypeExpression superOuterType = SymTypeExpressionFactory.createTypeObject("SuperOuter",scope); + SymTypeExpression superOuterType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("SuperOuter",scope); add2scope(scope,superOuter); //class Outer @@ -687,7 +687,7 @@ public void deriveSymTypeOfPrimaryGenericInvocationExpression() throws IOExcepti aSuper.setIsClass(true); aSuper.getSpannedScope().setEnclosingScope(aSuper.getEnclosingScope()); asuperconstr.getSpannedScope().setEnclosingScope(aSuper.getSpannedScope()); - SymTypeExpression aSuperType = SymTypeExpressionFactory.createTypeObject("ASuper",scope); + SymTypeExpression aSuperType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("ASuper",scope); asuperconstr.setType(aSuperType); add2scope(scope,aSuper); @@ -733,7 +733,7 @@ public void deriveSymTypeOfPrimaryGenericInvocationExpression() throws IOExcepti get.getSpannedScope().setEnclosingScope(a.getSpannedScope()); aconstr.getSpannedScope().setEnclosingScope(a.getSpannedScope()); set.getSpannedScope().setEnclosingScope(a.getSpannedScope()); - SymTypeExpression aType = SymTypeExpressionFactory.createTypeObject("A",scope); + SymTypeExpression aType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("A",scope); aconstr.setType(aType); add2scope(scope, a); @@ -775,7 +775,7 @@ public void failDeriveSymTypeOfPrimaryGenericInvocationExpression() throws IOExc sup.getSpannedScope().setEnclosingScope(sup.getEnclosingScope()); help.getSpannedScope().setEnclosingScope(sup.getSpannedScope()); add2scope(scope,sup); - SymTypeExpression supType = SymTypeExpressionFactory.createTypeObject("Sup",scope); + SymTypeExpression supType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Sup",scope); OOTypeSymbol sub = OOSymbolsMill.oOTypeSymbolBuilder() .setSpannedScope(CombineExpressionsWithLiteralsMill.scope()) .setName("Sub") @@ -810,7 +810,7 @@ public void failDeriveSymTypeOfPrimaryGenericInvocationExpression2() throws IOEx sup.getSpannedScope().setEnclosingScope(sup.getEnclosingScope()); help.getSpannedScope().setEnclosingScope(sup.getSpannedScope()); add2scope(scope,sup); - SymTypeExpression supType = SymTypeExpressionFactory.createTypeObject("Sup",scope); + SymTypeExpression supType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Sup",scope); OOTypeSymbol sub = OOSymbolsMill.oOTypeSymbolBuilder() .setSpannedScope(CombineExpressionsWithLiteralsMill.scope()) .setName("Sub") @@ -837,7 +837,7 @@ public void failDeriveSymTypeOfPrimaryGenericInvocationExpression3() throws IOEx sup.setIsClass(true); sup.getSpannedScope().setEnclosingScope(sup.getEnclosingScope()); add2scope(scope,sup); - SymTypeExpression supType = SymTypeExpressionFactory.createTypeObject("Sup",scope); + SymTypeExpression supType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Sup",scope); OOTypeSymbol sub = OOSymbolsMill.oOTypeSymbolBuilder() .setSpannedScope(CombineExpressionsWithLiteralsMill.scope()) .setName("Sub") @@ -870,7 +870,7 @@ public void deriveSymTypeOfGenericInvocationExpression() throws IOException { a.addMethodSymbol(test); a.getSpannedScope().setEnclosingScope(a.getEnclosingScope()); test.getSpannedScope().setEnclosingScope(a.getSpannedScope()); - SymTypeExpression aType = SymTypeExpressionFactory.createTypeObject("A",scope); + SymTypeExpression aType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("A",scope); FieldSymbol aField = field("a",aType); add2scope(scope,aField); add2scope(scope,a); @@ -897,7 +897,7 @@ public void failDeriveSymTypeOfGenericInvocationExpression() throws IOException{ a.addMethodSymbol(constr); a.getSpannedScope().setEnclosingScope(a.getEnclosingScope()); constr.getSpannedScope().setEnclosingScope(a.getSpannedScope()); - SymTypeExpression aType = SymTypeExpressionFactory.createTypeObject("A",scope); + SymTypeExpression aType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("A",scope); constr.setType(aType); FieldSymbol aField = field("a",aType); add2scope(scope,aField); @@ -925,7 +925,7 @@ public void failDeriveSymTypeOfGenericInvocationExpression2() throws IOException aSuper.addMethodSymbol(constr); aSuper.getSpannedScope().setEnclosingScope(aSuper.getEnclosingScope()); constr.getSpannedScope().setEnclosingScope(aSuper.getSpannedScope()); - SymTypeExpression asupertype = SymTypeExpressionFactory.createTypeObject("ASuper",scope); + SymTypeExpression asupertype = SymTypeExpressionFactory.createTypeObjectViaSurrogate("ASuper",scope); constr.setType(asupertype); add2scope(scope,aSuper); OOTypeSymbol a = OOSymbolsMill.oOTypeSymbolBuilder() @@ -934,7 +934,7 @@ public void failDeriveSymTypeOfGenericInvocationExpression2() throws IOException .setEnclosingScope(scope) .build(); a.getSpannedScope().setEnclosingScope(a.getEnclosingScope()); - SymTypeExpression aType = SymTypeExpressionFactory.createTypeObject("A",scope); + SymTypeExpression aType = SymTypeExpressionFactory.createTypeObjectViaSurrogate("A",scope); FieldSymbol aField = field("a",aType); add2scope(scope,aField); add2scope(scope,a); @@ -1027,7 +1027,7 @@ public void testDeriveFromCreatorExpressionAnonymousClass() throws IOException { .build(); bsp2.addMethodSymbol(bsp2constr); - SymTypeExpression bsp2Sym = SymTypeExpressionFactory.createTypeObject("Bsp2",scope); + SymTypeExpression bsp2Sym = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Bsp2",scope); bsp2constr.setType(bsp2Sym); bsp2constr.setEnclosingScope(bsp2.getSpannedScope()); @@ -1070,7 +1070,7 @@ public void testDeriveFromCreatorExpressionAnonymousClass() throws IOException { .build(); bsp3.addMethodSymbol(bsp3constr2); - SymTypeExpression bsp3Sym = SymTypeExpressionFactory.createTypeObject("Bsp3", scope); + SymTypeExpression bsp3Sym = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Bsp3", scope); bsp3constr.setType(bsp3Sym); bsp3constr2.setType(bsp3Sym); @@ -1138,7 +1138,7 @@ public void failDeriveFromCreatorExpressionAnonymousClass3() throws IOException .build(); bsp3.addMethodSymbol(bsp3constr); - SymTypeExpression bsp3Sym = SymTypeExpressionFactory.createTypeObject("Bsp3", scope); + SymTypeExpression bsp3Sym = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Bsp3", scope); bsp3constr.setType(bsp3Sym); bsp3constr.setEnclosingScope(bsp3.getSpannedScope()); @@ -1180,7 +1180,7 @@ public void failDeriveFromCreatorExpressionAnonymousClass4() throws IOException bsp4constr.setSpannedScope(CombineExpressionsWithLiteralsMill.scope()); add2scope(bsp4constr.getSpannedScope(),field1); add2scope(bsp4constr.getSpannedScope(),field2); - SymTypeExpression bsp4Sym = SymTypeExpressionFactory.createTypeObject("Bsp4",scope); + SymTypeExpression bsp4Sym = SymTypeExpressionFactory.createTypeObjectViaSurrogate("Bsp4",scope); bsp4constr.setType(bsp4Sym); add2scope(bsp4.getSpannedScope(), bsp4constr); add2scope(scope,bsp4); diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfLambdaExpressionsTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfLambdaExpressionsTest.java index e3825475ba..5e81ebf180 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfLambdaExpressionsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfLambdaExpressionsTest.java @@ -12,17 +12,17 @@ import de.monticore.grammar.grammar_withconcepts.FullSynthesizeFromMCSGT4Grammar; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import de.se_rwth.commons.logging.Log; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class DeriveSymTypeOfLambdaExpressionsTest extends DeriveSymTypeAbstractTest { /** @@ -88,9 +88,9 @@ protected void checkWithST(String expression, String expectedType) throws IOExce setupTypeCheck(); ASTExpression astex = parseAndGenerateSymbolTable(expression); - Assertions.assertEquals(expectedType, getTypeCalculator().typeOf(astex).print()); + assertEquals(expectedType, getTypeCalculator().typeOf(astex).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /*--------------------------------------------------- TESTS ---------------------------------------------------------*/ diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfLiteralsTest.java index 369137d38f..25d83a360c 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfLiteralsTest.java @@ -7,12 +7,11 @@ import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DeriveSymTypeOfLiteralsTest { @@ -45,9 +44,9 @@ public void before() { @Test public void deriveTFromLiteral1(){ ASTLiteral lit = MCCommonLiteralsMill.natLiteralBuilder().setDigits("17").build(); - Assertions.assertEquals("int", tc.typeOf(lit).print()); + assertEquals("int", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfMCCommonLiteralsTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfMCCommonLiteralsTest.java index a1dcd637eb..2e4f617ed1 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfMCCommonLiteralsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/DeriveSymTypeOfMCCommonLiteralsTest.java @@ -8,14 +8,13 @@ import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.se_rwth.commons.logging.*; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DeriveSymTypeOfMCCommonLiteralsTest { @@ -47,25 +46,25 @@ public void before() { @Test public void deriveTFromLiteral1Null() throws IOException { ASTLiteral lit = MCCommonLiteralsMill.nullLiteralBuilder().build(); - Assertions.assertEquals("null", tc.typeOf(lit).print()); + assertEquals("null", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void deriveTFromLiteral1Boolean() throws IOException { ASTLiteral lit = MCCommonLiteralsMill.booleanLiteralBuilder().setSource(0).build(); - Assertions.assertEquals("boolean", tc.typeOf(lit).print()); + assertEquals("boolean", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void deriveTFromLiteral1Char() throws IOException { ASTLiteral lit = MCCommonLiteralsMill.charLiteralBuilder().setSource("c").build(); - Assertions.assertEquals("char", tc.typeOf(lit).print()); + assertEquals("char", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -79,43 +78,43 @@ public void deriveTFromLiteral1String() throws IOException { gs.add(str); ASTLiteral lit = MCCommonLiteralsMill.stringLiteralBuilder().setSource("hjasdk").build(); lit.setEnclosingScope(gs); - Assertions.assertEquals("String", tc.typeOf(lit).print()); + assertEquals("String", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void deriveTFromLiteral1Int() throws IOException { ASTLiteral lit = MCCommonLiteralsMill.natLiteralBuilder().setDigits("17").build(); - Assertions.assertEquals("int", tc.typeOf(lit).print()); + assertEquals("int", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void deriveTFromLiteral1BasicLong() throws IOException { ASTLiteral lit = MCCommonLiteralsMill.basicLongLiteralBuilder().setDigits("17").build(); - Assertions.assertEquals("long", tc.typeOf(lit).print()); + assertEquals("long", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void deriveTFromLiteral1BasicFloat() throws IOException { ASTLiteral lit = MCCommonLiteralsMill.basicFloatLiteralBuilder().setPre("10").setPost("03").build(); - Assertions.assertEquals("float", tc.typeOf(lit).print()); + assertEquals("float", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void deriveTFromLiteral1BasicDouble() throws IOException { ASTLiteral lit = MCCommonLiteralsMill.basicDoubleLiteralBuilder().setPre("710").setPost("93").build(); - Assertions.assertEquals("double", tc.typeOf(lit).print()); + assertEquals("double", tc.typeOf(lit).print()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/FullSynthesizeCompKindFromMCBasicTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/FullSynthesizeCompKindFromMCBasicTypesTest.java new file mode 100644 index 0000000000..fca627a2a6 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/types/check/FullSynthesizeCompKindFromMCBasicTypesTest.java @@ -0,0 +1,69 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.types.check; + +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; +import de.monticore.types.MCTypeFacade; +import de.monticore.types.componentsymbolswithmcbasictypestest.ComponentSymbolsWithMCBasicTypesTestMill; +import de.monticore.types.mcbasictypes._ast.ASTMCType; +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class FullSynthesizeCompKindFromMCBasicTypesTest extends AbstractMCTest { + + @BeforeEach + public void setup() { + LogStub.init(); + Log.enableFailQuick(false); + Log.clearFindings(); + + ComponentSymbolsWithMCBasicTypesTestMill.reset(); + ComponentSymbolsWithMCBasicTypesTestMill.init(); + } + + @Test + public void synthesizesCompKind_forResolvableComponentTypeSymbol() { + // Given + ComponentTypeSymbol typeA = ComponentSymbolsWithMCBasicTypesTestMill.componentTypeSymbolBuilder() + .setName("A") + .setSpannedScope(ComponentSymbolsWithMCBasicTypesTestMill.scope()) + .build(); + ComponentSymbolsWithMCBasicTypesTestMill.globalScope().add(typeA); + typeA.setEnclosingScope(ComponentSymbolsWithMCBasicTypesTestMill.globalScope()); + + ASTMCType ast = MCTypeFacade.getInstance().createQualifiedType("A"); + ast.setEnclosingScope(ComponentSymbolsWithMCBasicTypesTestMill.globalScope()); + + FullSynthesizeCompKindFromMCBasicTypes synth = new FullSynthesizeCompKindFromMCBasicTypes(); + + // When + Optional res = synth.synthesize(ast); + + // Then + assertTrue(res.isPresent()); + assertTrue(res.get().isComponentType()); + assertEquals(typeA, res.get().getTypeInfo()); + } + + @Test + public void shouldLogErrorOnPrimitive() { + // Given + ASTMCType ast = MCTypeFacade.getInstance().createIntType(); + FullSynthesizeCompKindFromMCBasicTypes synth = new FullSynthesizeCompKindFromMCBasicTypes(); + + // When + Optional result = synth.synthesize(ast); + + // Then + assertTrue(result.isEmpty(), "Expected no CompKindExpression for primitive 'int'"); + MCAssertions.assertHasFindingStartingWith("0xD0104 Cannot resolve component 'int'"); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SymTypeExpressionDeSerTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SymTypeExpressionDeSerTest.java index b2a26c609f..84f791f63a 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/SymTypeExpressionDeSerTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SymTypeExpressionDeSerTest.java @@ -13,7 +13,6 @@ import de.monticore.symboltable.serialization.json.JsonObject; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,6 +21,7 @@ import java.util.Optional; import static de.monticore.types.check.SymTypeExpressionFactory.*; +import static org.junit.jupiter.api.Assertions.*; public class SymTypeExpressionDeSerTest { // setup of objects (unchanged during tests) @@ -120,9 +120,9 @@ public void init() { teVarB = SymTypeExpressionFactory.createTypeVariable("B", scope); - teP = createTypeObject("de.x.Person", scope); + teP = createTypeObjectViaSurrogate("de.x.Person", scope); - teH = createTypeObject("Human", scope); // on purpose: package missing + teH = createTypeObjectViaSurrogate("Human", scope); // on purpose: package missing teVoid = createTypeVoid(); @@ -252,10 +252,10 @@ protected void performRoundTripSerialization(SymTypeExpression expr) { String serialized = deser.serialize(expr); // then deserialize it SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); // and assert that the serialized and deserialized symtype expression equals the one before - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); if (!deserialized.isWildcard() && !deserialized.isRegExType() && !deserialized.isSIUnitType() && @@ -263,7 +263,7 @@ protected void performRoundTripSerialization(SymTypeExpression expr) { ) { TypeSymbol expectedTS = deserialized.getTypeInfo(); TypeSymbol actualTS = expr.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); } } @@ -273,13 +273,13 @@ protected void performRoundTripSerializationSymTypeOfGenerics(SymTypeOfGenerics String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); TypeSymbol expectedTS = deserialized.getTypeInfo(); TypeSymbol actualTS = deserialized.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); } protected void performRoundTripSerializationSymTypeOfFunction(SymTypeOfFunction expr) { @@ -288,13 +288,13 @@ protected void performRoundTripSerializationSymTypeOfFunction(SymTypeOfFunction String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); TypeSymbol expectedTS = deserialized.getTypeInfo(); TypeSymbol actualTS = deserialized.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); } protected void performRoundTripSerializationSymTypeOfObject(SymTypeOfObject expr) { @@ -303,13 +303,13 @@ protected void performRoundTripSerializationSymTypeOfObject(SymTypeOfObject expr String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); TypeSymbol expectedTS = deserialized.getTypeInfo(); TypeSymbol actualTS = deserialized.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); } protected void performRoundTripSerializationSymTypeVariable(SymTypeVariable expr) { @@ -318,13 +318,13 @@ protected void performRoundTripSerializationSymTypeVariable(SymTypeVariable expr String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); TypeSymbol expectedTS = deserialized.getTypeInfo(); TypeSymbol actualTS = deserialized.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); } protected void performRoundTripSerializationSymTypeArray(SymTypeArray expr) { @@ -333,13 +333,13 @@ protected void performRoundTripSerializationSymTypeArray(SymTypeArray expr) { String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); TypeSymbol expectedTS = deserialized.getTypeInfo(); TypeSymbol actualTS = deserialized.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); //assertTrue(Log.getFindings().isEmpty()); } @@ -350,13 +350,13 @@ protected void performRoundTripSerializationSymTypePrimitive(SymTypePrimitive ex String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); TypeSymbol expectedTS = deserialized.getTypeInfo(); TypeSymbol actualTS = deserialized.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); } protected void performRoundTripSerializationSymTypeOfSIUnit(SymTypeOfSIUnit expr) { @@ -365,10 +365,10 @@ protected void performRoundTripSerializationSymTypeOfSIUnit(SymTypeOfSIUnit expr String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); } protected void performRoundTripSerializationSymTypeOfNumericWithSIUnit( @@ -379,10 +379,10 @@ protected void performRoundTripSerializationSymTypeOfNumericWithSIUnit( String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertEquals(expr.print(), deserialized.print()); - Assertions.assertEquals(expr.printAsJson(), deserialized.printAsJson()); + assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.printAsJson(), deserialized.printAsJson()); } protected void performRoundTripSerializationSymTypeOfUnion(SymTypeOfUnion expr) { @@ -391,13 +391,13 @@ protected void performRoundTripSerializationSymTypeOfUnion(SymTypeOfUnion expr) String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertTrue(expr.deepEquals(deserialized)); - Assertions.assertEquals(deser.serialize(expr), deser.serialize((SymTypeOfUnion) deserialized)); + assertTrue(expr.deepEquals(deserialized)); + assertEquals(deser.serialize(expr), deser.serialize((SymTypeOfUnion) deserialized)); TypeSymbol expectedTS = deserialized.getTypeInfo(); TypeSymbol actualTS = deserialized.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); } protected void performRoundTripSerializationSymTypeOfRegEx(SymTypeOfRegEx expr) { @@ -406,10 +406,10 @@ protected void performRoundTripSerializationSymTypeOfRegEx(SymTypeOfRegEx expr) String serialized = deser.serialize(expr); SymTypeExpression deserialized = deser.deserialize(serialized); - Assertions.assertNotNull(deserialized); + assertNotNull(deserialized); - Assertions.assertTrue(expr.deepEquals(deserialized)); - Assertions.assertEquals(deser.serialize(expr), deser.serialize((SymTypeOfRegEx) deserialized)); + assertTrue(expr.deepEquals(deserialized)); + assertEquals(deser.serialize(expr), deser.serialize((SymTypeOfRegEx) deserialized)); } @Test @@ -453,10 +453,10 @@ protected void performRoundtrip2(SymTypeExpression expr) { // then deserialize it SymTypeExpression loaded = deser.deserialize(serialized); - Assertions.assertNotNull(loaded); + assertNotNull(loaded); // and assert that the serialized and deserialized symtype expression equals the one before - Assertions.assertEquals(expr.print(), loaded.print()); - Assertions.assertEquals(expr.printAsJson(), loaded.printAsJson()); + assertEquals(expr.print(), loaded.print()); + assertEquals(expr.printAsJson(), loaded.printAsJson()); if (!loaded.isWildcard() && !loaded.isRegExType() && !loaded.isSIUnitType() && @@ -464,7 +464,7 @@ protected void performRoundtrip2(SymTypeExpression expr) { ) { TypeSymbol expectedTS = loaded.getTypeInfo(); TypeSymbol actualTS = expr.getTypeInfo(); - Assertions.assertEquals(expectedTS.getName(), actualTS.getName()); + assertEquals(expectedTS.getName(), actualTS.getName()); } // usual member @@ -475,7 +475,7 @@ protected void performRoundtrip2(SymTypeExpression expr) { //produce a fake JSON object from the serialized member and parse this JsonObject json = JsonParser.parseJsonObject(printer.getContent()); SymTypeExpression deserialized = SymTypeExpressionDeSer.deserializeMember("foo", json); - Assertions.assertEquals(expr.print(), deserialized.print()); + assertEquals(expr.print(), deserialized.print()); // optional member that is present printer = new JsonPrinter(); @@ -485,8 +485,8 @@ protected void performRoundtrip2(SymTypeExpression expr) { json = JsonParser.parseJsonObject(printer.getContent()); Optional deserializedOpt = SymTypeExpressionDeSer .deserializeOptionalMember("foo", json); - Assertions.assertTrue(deserializedOpt.isPresent()); - Assertions.assertEquals(expr.print(), deserializedOpt.get().print()); + assertTrue(deserializedOpt.isPresent()); + assertEquals(expr.print(), deserializedOpt.get().print()); // optional member that is empty printer = new JsonPrinter(true); @@ -495,7 +495,7 @@ protected void performRoundtrip2(SymTypeExpression expr) { printer.endObject(); json = JsonParser.parseJsonObject(printer.getContent()); deserializedOpt = SymTypeExpressionDeSer.deserializeOptionalMember("foo", json); - Assertions.assertTrue(!deserializedOpt.isPresent()); + assertTrue(!deserializedOpt.isPresent()); // list member that is empty printer = new JsonPrinter(true); @@ -505,7 +505,7 @@ protected void performRoundtrip2(SymTypeExpression expr) { json = JsonParser.parseJsonObject(printer.getContent()); List deserializedList = SymTypeExpressionDeSer .deserializeListMember("foo", json); - Assertions.assertEquals(0, deserializedList.size()); + assertEquals(0, deserializedList.size()); // list member with single element printer = new JsonPrinter(); @@ -514,8 +514,8 @@ protected void performRoundtrip2(SymTypeExpression expr) { printer.endObject(); json = JsonParser.parseJsonObject(printer.getContent()); deserializedList = SymTypeExpressionDeSer.deserializeListMember("foo", json); - Assertions.assertEquals(1, deserializedList.size()); - Assertions.assertEquals(expr.print(), deserializedList.get(0).print()); + assertEquals(1, deserializedList.size()); + assertEquals(expr.print(), deserializedList.get(0).print()); // list member with two elements printer = new JsonPrinter(); @@ -524,9 +524,9 @@ protected void performRoundtrip2(SymTypeExpression expr) { printer.endObject(); json = JsonParser.parseJsonObject(printer.getContent()); deserializedList = SymTypeExpressionDeSer.deserializeListMember("foo", json); - Assertions.assertEquals(2, deserializedList.size()); - Assertions.assertEquals(expr.print(), deserializedList.get(0).print()); - Assertions.assertEquals(expr.print(), deserializedList.get(1).print()); + assertEquals(2, deserializedList.size()); + assertEquals(expr.print(), deserializedList.get(0).print()); + assertEquals(expr.print(), deserializedList.get(1).print()); } @Test @@ -535,38 +535,38 @@ public void testInvalidJsonForSerializingReturnsError() { String invalidJsonForSerializing2 = "{\n\t\"symTypeExpression\": {\n\t\t\"foo\":\"bar\", \n\t\t\"foo2\":\"bar2\"\n\t}\n}"; SymTypeExpressionDeSer.getInstance().deserialize(invalidJsonForSerializing); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823FE")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823FE")); SymTypeExpressionDeSer.getInstance().deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823FE")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823FE")); SymTypeOfGenericsDeSer symTypeOfGenericsDeSer = new SymTypeOfGenericsDeSer(); symTypeOfGenericsDeSer.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F6")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F6")); SymTypeArrayDeSer symTypeArrayDeSer = new SymTypeArrayDeSer(); symTypeArrayDeSer.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F2")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F2")); SymTypeOfObjectDeSer symTypeOfObjectDeSer = new SymTypeOfObjectDeSer(); symTypeOfObjectDeSer.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F4")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F4")); SymTypeVariableDeSer symTypeVariableDeSer = new SymTypeVariableDeSer(); symTypeVariableDeSer.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F5")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F5")); SymTypePrimitiveDeSer symTypePrimitiveDeser = new SymTypePrimitiveDeSer(); symTypePrimitiveDeser.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F1")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x823F1")); SymTypeOfUnionDeSer symTypeOfUnionDeser = new SymTypeOfUnionDeSer(); symTypeOfUnionDeser.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x9E2F7")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x9E2F7")); SymTypeOfRegExDeSer symTypeOfRegExDeSer = new SymTypeOfRegExDeSer(); symTypeOfRegExDeSer.deserialize(invalidJsonForSerializing2); - Assertions.assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x9E2F9")); + assertTrue(Log.getFindings().get(Log.getFindings().size() - 1).getMsg().startsWith("0x9E2F9")); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SymTypeExpressionTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SymTypeExpressionTest.java index 4de0096201..c6e4c4c290 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/SymTypeExpressionTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SymTypeExpressionTest.java @@ -3,7 +3,6 @@ import com.google.common.collect.Lists; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; -import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.oosymbols.OOSymbolsMill; import de.monticore.symbols.oosymbols._symboltable.IOOSymbolsScope; import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; @@ -13,7 +12,6 @@ import de.monticore.types3.util.DefsTypesForTests; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,8 +24,7 @@ import static de.monticore.types.check.DefsTypeBasic._intSymType; import static de.monticore.types.check.SymTypeExpressionFactory.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SymTypeExpressionTest { @@ -134,7 +131,7 @@ public void init(){ teVarA = SymTypeExpressionFactory.createTypeVariable("A", scope); - teIntA = createTypeObject("java.lang.Integer",scope); + teIntA = createTypeObjectViaSurrogate("java.lang.Integer",scope); teVarB = SymTypeExpressionFactory.createTypeVariable("B", scope); @@ -142,9 +139,9 @@ public void init(){ teVarLower = SymTypeExpressionFactory.createInferenceVariable(createTopType(), teIntA); - teP = createTypeObject("de.x.Person", scope); + teP = createTypeObjectViaSurrogate("de.x.Person", scope); - teH = createTypeObject("Human", + teH = createTypeObjectViaSurrogate("Human", scope); // on purpose: package missing teVoid = createTypeVoid(); @@ -216,569 +213,547 @@ public void init(){ @Test public void subTypeTest() { - Assertions.assertTrue(teInt.isPrimitive()); - Assertions.assertTrue(teInt.isValidType()); - Assertions.assertFalse(teInt.isGenericType()); - Assertions.assertFalse(teInt.isTypeVariable()); - Assertions.assertFalse(teInt.isArrayType()); - Assertions.assertFalse(teInt.isVoidType()); - Assertions.assertFalse(teInt.isNullType()); - Assertions.assertFalse(teInt.isObjectType()); - Assertions.assertFalse(teInt.isFunctionType()); - Assertions.assertFalse(teInt.isObscureType()); - Assertions.assertFalse(teInt.isWildcard()); - Assertions.assertFalse(teInt.isUnionType()); - - Assertions.assertTrue(teVarA.isTypeVariable()); - Assertions.assertFalse(teVarA.isValidType()); - Assertions.assertTrue(teP.isObjectType()); - Assertions.assertTrue(teP.isValidType()); - Assertions.assertTrue(teVoid.isVoidType()); - Assertions.assertTrue(teVoid.isValidType()); - Assertions.assertTrue(teNull.isNullType()); - Assertions.assertTrue(teNull.isValidType()); - Assertions.assertTrue(teArr1.isArrayType()); - Assertions.assertTrue(teArr1.isValidType()); - Assertions.assertTrue(teSet.isGenericType()); - Assertions.assertTrue(teSet.isValidType()); - Assertions.assertTrue(teUpperBound.isWildcard()); - Assertions.assertFalse(teUpperBound.isValidType()); - Assertions.assertTrue(teFunc1.isFunctionType()); - Assertions.assertTrue(teFunc1.isValidType()); - Assertions.assertTrue(teSIUnit1.isSIUnitType()); - Assertions.assertTrue(teNumWithSIUnit1.isNumericWithSIUnitType()); - Assertions.assertTrue(teUnion1.isUnionType()); - Assertions.assertTrue(teUnion1.isValidType()); - Assertions.assertTrue(teInter1.isIntersectionType()); - Assertions.assertTrue(teInter1.isValidType()); - Assertions.assertTrue(teTuple1.isTupleType()); - Assertions.assertTrue(teRegEx1.isRegExType()); - Assertions.assertTrue(teObscure.isObscureType()); - Assertions.assertFalse(teObscure.isValidType()); + assertTrue(teInt.isPrimitive()); + assertFalse(teInt.isGenericType()); + assertFalse(teInt.isTypeVariable()); + assertFalse(teInt.isArrayType()); + assertFalse(teInt.isVoidType()); + assertFalse(teInt.isNullType()); + assertFalse(teInt.isObjectType()); + assertFalse(teInt.isFunctionType()); + assertFalse(teInt.isObscureType()); + assertFalse(teInt.isWildcard()); + assertFalse(teInt.isUnionType()); + + assertTrue(teVarA.isTypeVariable()); + assertTrue(teP.isObjectType()); + assertTrue(teVoid.isVoidType()); + assertTrue(teNull.isNullType()); + assertTrue(teArr1.isArrayType()); + assertTrue(teSet.isGenericType()); + assertTrue(teUpperBound.isWildcard()); + assertTrue(teFunc1.isFunctionType()); + assertTrue(teSIUnit1.isSIUnitType()); + assertTrue(teNumWithSIUnit1.isNumericWithSIUnitType()); + assertTrue(teUnion1.isUnionType()); + assertTrue(teInter1.isIntersectionType()); + assertTrue(teTuple1.isTupleType()); + assertTrue(teRegEx1.isRegExType()); + assertTrue(teObscure.isObscureType()); } @Test public void printTest() { - Assertions.assertEquals("double", teDouble.print()); - Assertions.assertEquals("int", teInt.print()); - Assertions.assertEquals("A", teVarA.print()); - Assertions.assertEquals("de.x.Person", teP.print()); - Assertions.assertEquals("void", teVoid.print()); - Assertions.assertEquals("null", teNull.print()); - Assertions.assertEquals("Human[]", teArr1.print()); - Assertions.assertEquals("int[][][]", teArr3.print()); - Assertions.assertEquals("java.util.Set", teSet.printFullName()); - Assertions.assertEquals("java.util.Set", teSetA.printFullName()); - Assertions.assertEquals("Map", teMap.printFullName()); - Assertions.assertEquals("x.Foo", teFoo.printFullName()); - Assertions.assertEquals("java.util.Set>", teDeep1.printFullName()); - Assertions.assertEquals("java.util.Map2>>", teDeep2.printFullName()); - Assertions.assertEquals("? extends int", teUpperBound.print()); - Assertions.assertEquals("? super Human", teLowerBound.print()); - Assertions.assertEquals("?", teWildcard.print()); - Assertions.assertEquals("java.util.Map", teMap3.printFullName()); - Assertions.assertEquals("() -> void", teFunc1.print()); - Assertions.assertEquals("(double, int) -> int", teFunc2.print()); - Assertions.assertEquals("((double, int) -> int) -> () -> void", teFunc3.print()); - Assertions.assertEquals("(double, int...) -> void", teFunc4.print()); - Assertions.assertEquals("[m/ms^2]", teSIUnit1.print()); - Assertions.assertEquals("[1]", teSIUnit2.print()); - Assertions.assertEquals("[m/ms^2]", teNumWithSIUnit1.print()); - Assertions.assertEquals("double | int", teUnion1.print()); - Assertions.assertEquals("double & int", teInter1.print()); - Assertions.assertEquals("(int, double)", teTuple1.print()); - Assertions.assertEquals("R\"gr(a|e)y\"", teRegEx1.print()); + assertEquals("double", teDouble.print()); + assertEquals("int", teInt.print()); + assertEquals("A", teVarA.print()); + assertEquals("de.x.Person", teP.print()); + assertEquals("void", teVoid.print()); + assertEquals("null", teNull.print()); + assertEquals("Human[]", teArr1.print()); + assertEquals("int[][][]", teArr3.print()); + assertEquals("java.util.Set", teSet.printFullName()); + assertEquals("java.util.Set", teSetA.printFullName()); + assertEquals("Map", teMap.printFullName()); + assertEquals("x.Foo", teFoo.printFullName()); + assertEquals("java.util.Set>", teDeep1.printFullName()); + assertEquals("java.util.Map2>>", teDeep2.printFullName()); + assertEquals("? extends int", teUpperBound.print()); + assertEquals("? super Human", teLowerBound.print()); + assertEquals("?", teWildcard.print()); + assertEquals("java.util.Map", teMap3.printFullName()); + assertEquals("() -> void", teFunc1.print()); + assertEquals("(double, int) -> int", teFunc2.print()); + assertEquals("((double, int) -> int) -> () -> void", teFunc3.print()); + assertEquals("(double, int...) -> void", teFunc4.print()); + assertEquals("[m/ms^2]", teSIUnit1.print()); + assertEquals("[1]", teSIUnit2.print()); + assertEquals("[m/ms^2]", teNumWithSIUnit1.print()); + assertEquals("double | int", teUnion1.print()); + assertEquals("double & int", teInter1.print()); + assertEquals("(int, double)", teTuple1.print()); + assertEquals("R\"gr(a|e)y\"", teRegEx1.print()); } @Test public void printAsJsonTest() { JsonElement result = JsonParser.parse(teDouble.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teDoubleJson = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teDoubleJson.getStringMember("kind")); - Assertions.assertEquals("double", teDoubleJson.getStringMember("primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", teDoubleJson.getStringMember("kind")); + assertEquals("double", teDoubleJson.getStringMember("primitiveName")); result = JsonParser.parse(teInt.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teIntJson = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teIntJson.getStringMember("kind")); - Assertions.assertEquals("int", teIntJson.getStringMember("primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", teIntJson.getStringMember("kind")); + assertEquals("int", teIntJson.getStringMember("primitiveName")); result = JsonParser.parse(teVarA.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teVarAJson = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeVariable", teVarAJson.getStringMember("kind")); - Assertions.assertEquals("A", teVarAJson.getStringMember("varName")); + assertEquals("de.monticore.types.check.SymTypeVariable", teVarAJson.getStringMember("kind")); + assertEquals("A", teVarAJson.getStringMember("varName")); result = JsonParser.parse(teP.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject tePJson = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfObject", tePJson.getStringMember("kind")); - Assertions.assertEquals("de.x.Person", tePJson.getStringMember("objName")); + assertEquals("de.monticore.types.check.SymTypeOfObject", tePJson.getStringMember("kind")); + assertEquals("de.x.Person", tePJson.getStringMember("objName")); result = JsonParser.parse(teVoid.printAsJson()); - Assertions.assertTrue(result.isJsonString()); - Assertions.assertEquals("void", result.getAsJsonString().getValue()); + assertTrue(result.isJsonString()); + assertEquals("void", result.getAsJsonString().getValue()); result = JsonParser.parse(teNull.printAsJson()); - Assertions.assertTrue(result.isJsonString()); - Assertions.assertEquals("null", result.getAsJsonString().getValue()); + assertTrue(result.isJsonString()); + assertEquals("null", result.getAsJsonString().getValue()); result = JsonParser.parse(teArr1.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teArr1Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeArray", teArr1Json.getStringMember("kind")); - Assertions.assertEquals(1, teArr1Json.getIntegerMember("dim"), 0.01); + assertEquals("de.monticore.types.check.SymTypeArray", teArr1Json.getStringMember("kind")); + assertEquals(1, teArr1Json.getIntegerMember("dim"), 0.01); JsonObject teArr1ArgJson = teArr1Json.getObjectMember("argument"); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfObject", teArr1ArgJson.getStringMember("kind")); - Assertions.assertEquals("Human", teArr1ArgJson.getStringMember("objName")); + assertEquals("de.monticore.types.check.SymTypeOfObject", teArr1ArgJson.getStringMember("kind")); + assertEquals("Human", teArr1ArgJson.getStringMember("objName")); result = JsonParser.parse(teArr3.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teArr3Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeArray", teArr3Json.getStringMember("kind")); - Assertions.assertEquals(3, teArr3Json.getIntegerMember("dim"), 0.01); + assertEquals("de.monticore.types.check.SymTypeArray", teArr3Json.getStringMember("kind")); + assertEquals(3, teArr3Json.getIntegerMember("dim"), 0.01); JsonObject teArr3ArgJson = teArr3Json.getObjectMember("argument"); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teArr3ArgJson.getStringMember("kind")); - Assertions.assertEquals("int", teArr3ArgJson.getStringMember("primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", teArr3ArgJson.getStringMember("kind")); + assertEquals("int", teArr3ArgJson.getStringMember("primitiveName")); result = JsonParser.parse(teSet.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teSetJson = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teSetJson.getStringMember("kind")); - Assertions.assertEquals("java.util.Set", teSetJson.getStringMember("typeConstructorFullName")); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teSetJson.getStringMember("kind")); + assertEquals("java.util.Set", teSetJson.getStringMember("typeConstructorFullName")); List teSetArgsJson = teSetJson.getArrayMember("arguments"); - Assertions.assertEquals(1, teSetArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfObject", teSetArgsJson.get(0).getAsJsonObject().getStringMember("kind")); - Assertions.assertEquals("de.x.Person", teSetArgsJson.get(0).getAsJsonObject().getStringMember("objName")); + assertEquals(1, teSetArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypeOfObject", teSetArgsJson.get(0).getAsJsonObject().getStringMember("kind")); + assertEquals("de.x.Person", teSetArgsJson.get(0).getAsJsonObject().getStringMember("objName")); result = JsonParser.parse(teSetA.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teSetAJson = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teSetAJson.getStringMember("kind")); - Assertions.assertEquals("java.util.Set", teSetAJson.getStringMember("typeConstructorFullName")); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teSetAJson.getStringMember("kind")); + assertEquals("java.util.Set", teSetAJson.getStringMember("typeConstructorFullName")); List teSetAArgsJson = teSetAJson.getArrayMember("arguments"); - Assertions.assertEquals(1, teSetAArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypeVariable", teSetAArgsJson.get(0).getAsJsonObject().getStringMember("kind")); - Assertions.assertEquals("A", teSetAArgsJson.get(0).getAsJsonObject().getStringMember("varName")); + assertEquals(1, teSetAArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypeVariable", teSetAArgsJson.get(0).getAsJsonObject().getStringMember("kind")); + assertEquals("A", teSetAArgsJson.get(0).getAsJsonObject().getStringMember("varName")); result = JsonParser.parse(teMap.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teMapJson = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teMapJson.getStringMember("kind")); - Assertions.assertEquals("Map", teMapJson.getStringMember("typeConstructorFullName")); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teMapJson.getStringMember("kind")); + assertEquals("Map", teMapJson.getStringMember("typeConstructorFullName")); List teMapArgsJson = teMapJson.getArrayMember("arguments"); - Assertions.assertEquals(2, teMapArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teMapArgsJson.get(0).getAsJsonObject().getStringMember("kind")); - Assertions.assertEquals("int", teMapArgsJson.get(0).getAsJsonObject().getStringMember("primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfObject", teMapArgsJson.get(1).getAsJsonObject().getStringMember("kind")); - Assertions.assertEquals("de.x.Person", teMapArgsJson.get(1).getAsJsonObject().getStringMember("objName")); + assertEquals(2, teMapArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypePrimitive", teMapArgsJson.get(0).getAsJsonObject().getStringMember("kind")); + assertEquals("int", teMapArgsJson.get(0).getAsJsonObject().getStringMember("primitiveName")); + assertEquals("de.monticore.types.check.SymTypeOfObject", teMapArgsJson.get(1).getAsJsonObject().getStringMember("kind")); + assertEquals("de.x.Person", teMapArgsJson.get(1).getAsJsonObject().getStringMember("objName")); result = JsonParser.parse(teFoo.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teFooJson = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teFooJson.getStringMember("kind")); - Assertions.assertEquals("x.Foo", teFooJson.getStringMember("typeConstructorFullName")); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teFooJson.getStringMember("kind")); + assertEquals("x.Foo", teFooJson.getStringMember("typeConstructorFullName")); List teFooArgsJson = teFooJson.getArrayMember("arguments"); - Assertions.assertEquals(4, teFooArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfObject", teFooArgsJson.get(0).getAsJsonObject().getStringMember("kind")); - Assertions.assertEquals("de.x.Person", teFooArgsJson.get(0).getAsJsonObject().getStringMember("objName")); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teFooArgsJson.get(1).getAsJsonObject().getStringMember("kind")); - Assertions.assertEquals("double", teFooArgsJson.get(1).getAsJsonObject().getStringMember("primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teFooArgsJson.get(2).getAsJsonObject().getStringMember("kind")); - Assertions.assertEquals("int", teFooArgsJson.get(2).getAsJsonObject().getStringMember("primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfObject", teFooArgsJson.get(3).getAsJsonObject().getStringMember("kind")); - Assertions.assertEquals("Human", teFooArgsJson.get(3).getAsJsonObject().getStringMember("objName")); + assertEquals(4, teFooArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypeOfObject", teFooArgsJson.get(0).getAsJsonObject().getStringMember("kind")); + assertEquals("de.x.Person", teFooArgsJson.get(0).getAsJsonObject().getStringMember("objName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", teFooArgsJson.get(1).getAsJsonObject().getStringMember("kind")); + assertEquals("double", teFooArgsJson.get(1).getAsJsonObject().getStringMember("primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", teFooArgsJson.get(2).getAsJsonObject().getStringMember("kind")); + assertEquals("int", teFooArgsJson.get(2).getAsJsonObject().getStringMember("primitiveName")); + assertEquals("de.monticore.types.check.SymTypeOfObject", teFooArgsJson.get(3).getAsJsonObject().getStringMember("kind")); + assertEquals("Human", teFooArgsJson.get(3).getAsJsonObject().getStringMember("objName")); result = JsonParser.parse(teDeep1.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teDeep1Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep1Json.getStringMember("kind")); - Assertions.assertEquals("java.util.Set", teDeep1Json.getStringMember("typeConstructorFullName")); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep1Json.getStringMember("kind")); + assertEquals("java.util.Set", teDeep1Json.getStringMember("typeConstructorFullName")); List teDeep1ArgsJson = teDeep1Json.getArrayMember("arguments"); - Assertions.assertEquals(1, teDeep1ArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep1ArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("Map", teDeep1ArgsJson.get(0).getAsJsonObject().getStringMember( "typeConstructorFullName")); + assertEquals(1, teDeep1ArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep1ArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("Map", teDeep1ArgsJson.get(0).getAsJsonObject().getStringMember( "typeConstructorFullName")); List teDeep1teMapArgsJson = teDeep1ArgsJson.get(0).getAsJsonObject() .getArrayMember("arguments"); - Assertions.assertEquals(2, teDeep1teMapArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teDeep1teMapArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("int", teDeep1teMapArgsJson.get(0).getAsJsonObject().getStringMember("primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfObject", teDeep1teMapArgsJson.get(1).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("de.x.Person", teDeep1teMapArgsJson.get(1).getAsJsonObject().getStringMember( "objName")); + assertEquals(2, teDeep1teMapArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypePrimitive", teDeep1teMapArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("int", teDeep1teMapArgsJson.get(0).getAsJsonObject().getStringMember("primitiveName")); + assertEquals("de.monticore.types.check.SymTypeOfObject", teDeep1teMapArgsJson.get(1).getAsJsonObject().getStringMember( "kind")); + assertEquals("de.x.Person", teDeep1teMapArgsJson.get(1).getAsJsonObject().getStringMember( "objName")); result = JsonParser.parse(teDeep2.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teDeep2Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep2Json.getStringMember("kind")); - Assertions.assertEquals("java.util.Map2", teDeep2Json.getStringMember("typeConstructorFullName")); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep2Json.getStringMember("kind")); + assertEquals("java.util.Map2", teDeep2Json.getStringMember("typeConstructorFullName")); List teDeep2ArgsJson = teDeep2Json.getArrayMember("arguments"); - Assertions.assertEquals(2, teDeep2ArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teDeep2ArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("int", teDeep2ArgsJson.get(0).getAsJsonObject().getStringMember( "primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep2ArgsJson.get(1).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("java.util.Set", teDeep2ArgsJson.get(1).getAsJsonObject().getStringMember( "typeConstructorFullName")); + assertEquals(2, teDeep2ArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypePrimitive", teDeep2ArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("int", teDeep2ArgsJson.get(0).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep2ArgsJson.get(1).getAsJsonObject().getStringMember( "kind")); + assertEquals("java.util.Set", teDeep2ArgsJson.get(1).getAsJsonObject().getStringMember( "typeConstructorFullName")); List teDeep2SetArgsJson = teDeep2ArgsJson.get(1).getAsJsonObject() .getArrayMember("arguments"); - Assertions.assertEquals(1, teDeep2SetArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep2SetArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("Map", teDeep2SetArgsJson.get(0).getAsJsonObject().getStringMember( "typeConstructorFullName")); + assertEquals(1, teDeep2SetArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypeOfGenerics", teDeep2SetArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("Map", teDeep2SetArgsJson.get(0).getAsJsonObject().getStringMember( "typeConstructorFullName")); List teDeep2SetMapArgsJson = teDeep2SetArgsJson.get(0).getAsJsonObject() .getArrayMember("arguments"); - Assertions.assertEquals(2, teDeep2SetMapArgsJson.size(), 0.01); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", teDeep2SetMapArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("int", teDeep2SetMapArgsJson.get(0).getAsJsonObject().getStringMember( "primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfObject", teDeep2SetMapArgsJson.get(1).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("de.x.Person", teDeep2SetMapArgsJson.get(1).getAsJsonObject().getStringMember( "objName")); + assertEquals(2, teDeep2SetMapArgsJson.size(), 0.01); + assertEquals("de.monticore.types.check.SymTypePrimitive", teDeep2SetMapArgsJson.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("int", teDeep2SetMapArgsJson.get(0).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypeOfObject", teDeep2SetMapArgsJson.get(1).getAsJsonObject().getStringMember( "kind")); + assertEquals("de.x.Person", teDeep2SetMapArgsJson.get(1).getAsJsonObject().getStringMember( "objName")); result = JsonParser.parse(teUpperBound.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teUpperBound2Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfWildcard", teUpperBound2Json.getStringMember("kind")); - Assertions.assertTrue(teUpperBound2Json.getBooleanMember("isUpper")); + assertEquals("de.monticore.types.check.SymTypeOfWildcard", teUpperBound2Json.getStringMember("kind")); + assertTrue(teUpperBound2Json.getBooleanMember("isUpper")); JsonObject bound = teUpperBound2Json.getObjectMember("bound"); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", bound.getStringMember("kind")); - Assertions.assertEquals("int", bound.getStringMember("primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", bound.getStringMember("kind")); + assertEquals("int", bound.getStringMember("primitiveName")); result = JsonParser.parse(teFunc2.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teFunc2Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfFunction", teFunc2Json.getStringMember("kind")); + assertEquals("de.monticore.types.check.SymTypeOfFunction", teFunc2Json.getStringMember("kind")); JsonObject func2returnType = teFunc2Json.getObjectMember("returnType"); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", func2returnType.getStringMember( "kind")); - Assertions.assertEquals("int", func2returnType.getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", func2returnType.getStringMember( "kind")); + assertEquals("int", func2returnType.getStringMember( "primitiveName")); List func2Arguments = teFunc2Json.getArrayMember("argumentTypes"); - Assertions.assertEquals(2, func2Arguments.size()); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", func2Arguments.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("double", func2Arguments.get(0).getAsJsonObject().getStringMember( "primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", func2Arguments.get(1).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("int", func2Arguments.get(1).getAsJsonObject().getStringMember( "primitiveName")); - Assertions.assertFalse(teFunc2Json.getBooleanMember("elliptic")); + assertEquals(2, func2Arguments.size()); + assertEquals("de.monticore.types.check.SymTypePrimitive", func2Arguments.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("double", func2Arguments.get(0).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", func2Arguments.get(1).getAsJsonObject().getStringMember( "kind")); + assertEquals("int", func2Arguments.get(1).getAsJsonObject().getStringMember( "primitiveName")); + assertFalse(teFunc2Json.getBooleanMember("elliptic")); result = JsonParser.parse(teFunc4.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teFunc4Json = result.getAsJsonObject(); - Assertions.assertTrue(teFunc4Json.getBooleanMember("elliptic")); + assertTrue(teFunc4Json.getBooleanMember("elliptic")); result = JsonParser.parse(teUnion1.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teUnion1Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfUnion", teUnion1Json.getStringMember("kind")); - Assertions.assertEquals(2, teUnion1Json.getArrayMember("unionizedTypes").size()); + assertEquals("de.monticore.types.check.SymTypeOfUnion", teUnion1Json.getStringMember("kind")); + assertEquals(2, teUnion1Json.getArrayMember("unionizedTypes").size()); List union1Types = teUnion1Json.getArrayMember("unionizedTypes"); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", union1Types.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("double", union1Types.get(0).getAsJsonObject().getStringMember( "primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", union1Types.get(1).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("int", union1Types.get(1).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", union1Types.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("double", union1Types.get(0).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", union1Types.get(1).getAsJsonObject().getStringMember( "kind")); + assertEquals("int", union1Types.get(1).getAsJsonObject().getStringMember( "primitiveName")); result = JsonParser.parse(teInter1.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teInter1Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfIntersection", teInter1Json.getStringMember("kind")); - Assertions.assertEquals(2, teInter1Json.getArrayMember("intersectedTypes").size()); + assertEquals("de.monticore.types.check.SymTypeOfIntersection", teInter1Json.getStringMember("kind")); + assertEquals(2, teInter1Json.getArrayMember("intersectedTypes").size()); List intersected1Types = teInter1Json.getArrayMember("intersectedTypes"); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", intersected1Types.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("double", intersected1Types.get(0).getAsJsonObject().getStringMember( "primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", intersected1Types.get(1).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("int", intersected1Types.get(1).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", intersected1Types.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("double", intersected1Types.get(0).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", intersected1Types.get(1).getAsJsonObject().getStringMember( "kind")); + assertEquals("int", intersected1Types.get(1).getAsJsonObject().getStringMember( "primitiveName")); result = JsonParser.parse(teTuple1.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teTuple1Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfTuple", teTuple1Json.getStringMember("kind")); - Assertions.assertEquals(2, teTuple1Json.getArrayMember("listedTypes").size()); + assertEquals("de.monticore.types.check.SymTypeOfTuple", teTuple1Json.getStringMember("kind")); + assertEquals(2, teTuple1Json.getArrayMember("listedTypes").size()); List tuple1types = teTuple1Json.getArrayMember("listedTypes"); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", tuple1types.get(0).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("int", tuple1types.get(0).getAsJsonObject().getStringMember( "primitiveName")); - Assertions.assertEquals("de.monticore.types.check.SymTypePrimitive", tuple1types.get(1).getAsJsonObject().getStringMember( "kind")); - Assertions.assertEquals("double", tuple1types.get(1).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", tuple1types.get(0).getAsJsonObject().getStringMember( "kind")); + assertEquals("int", tuple1types.get(0).getAsJsonObject().getStringMember( "primitiveName")); + assertEquals("de.monticore.types.check.SymTypePrimitive", tuple1types.get(1).getAsJsonObject().getStringMember( "kind")); + assertEquals("double", tuple1types.get(1).getAsJsonObject().getStringMember( "primitiveName")); result = JsonParser.parse(teRegEx1.printAsJson()); - Assertions.assertTrue(result.isJsonObject()); + assertTrue(result.isJsonObject()); JsonObject teRegEx1Json = result.getAsJsonObject(); - Assertions.assertEquals("de.monticore.types.check.SymTypeOfRegEx", teRegEx1Json.getStringMember("kind")); - Assertions.assertEquals("gr(a|e)y", teRegEx1Json.getStringMember("regex")); - } - - @Test - public void baseNameTest() { - Assertions.assertEquals("Person", ((SymTypeOfObject) (teP)).getBaseName()); - Assertions.assertEquals("Human", ((SymTypeOfObject) (teH)).getBaseName()); - Assertions.assertEquals("Map", ((SymTypeOfGenerics) (teMap)).getBaseName()); - Assertions.assertEquals("Set", ((SymTypeOfGenerics) (teSet)).getBaseName()); + assertEquals("de.monticore.types.check.SymTypeOfRegEx", teRegEx1Json.getStringMember("kind")); + assertEquals("gr(a|e)y", teRegEx1Json.getStringMember("regex")); } @Test public void unboxTest(){ - Assertions.assertEquals("Set>", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teSetB)); - Assertions.assertEquals("Set", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teSet)); - Assertions.assertEquals("Set", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teSetA)); - Assertions.assertEquals("Map", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teMap)); - Assertions.assertEquals("Map,x.Foo>", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teMap2)); + assertEquals("Set>", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teSetB)); + assertEquals("Set", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teSet)); + assertEquals("Set", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teSetA)); + assertEquals("Map", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teMap)); + assertEquals("Map,x.Foo>", SymTypeOfGenerics.unbox((SymTypeOfGenerics)teMap2)); } @Test public void boxTest() { - Assertions.assertEquals("java.util.Set>", SymTypeOfGenerics.box((SymTypeOfGenerics) teSetB)); - Assertions.assertEquals("java.util.Set", SymTypeOfGenerics.box((SymTypeOfGenerics) teSet)); - Assertions.assertEquals("java.util.Set", SymTypeOfGenerics.box((SymTypeOfGenerics) teSetA)); - Assertions.assertEquals("java.util.Map", SymTypeOfGenerics.box((SymTypeOfGenerics)teMap)); - Assertions.assertEquals("java.util.Map,x.Foo>", SymTypeOfGenerics.box((SymTypeOfGenerics)teMap2)); + assertEquals("java.util.Set>", SymTypeOfGenerics.box((SymTypeOfGenerics) teSetB)); + assertEquals("java.util.Set", SymTypeOfGenerics.box((SymTypeOfGenerics) teSet)); + assertEquals("java.util.Set", SymTypeOfGenerics.box((SymTypeOfGenerics) teSetA)); + assertEquals("java.util.Map", SymTypeOfGenerics.box((SymTypeOfGenerics)teMap)); + assertEquals("java.util.Map,x.Foo>", SymTypeOfGenerics.box((SymTypeOfGenerics)teMap2)); } @Test public void testHasTypeInfo() { - Assertions.assertTrue(teInt.hasTypeInfo()); - Assertions.assertFalse(createPrimitive((TypeSymbol) null).hasTypeInfo()); - Assertions.assertFalse(teVarA.hasTypeInfo()); - Assertions.assertFalse(teVarB.hasTypeInfo()); - Assertions.assertFalse(teVarUpper.hasTypeInfo()); - Assertions.assertFalse(teVarLower.hasTypeInfo()); - Assertions.assertTrue(teIntA.hasTypeInfo()); - Assertions.assertFalse(createTypeObject(null).hasTypeInfo()); - Assertions.assertTrue(teP.hasTypeInfo()); - Assertions.assertTrue(teH.hasTypeInfo()); - Assertions.assertFalse(teVoid.hasTypeInfo()); - Assertions.assertFalse(teNull.hasTypeInfo()); - Assertions.assertFalse(teArr1.hasTypeInfo()); - Assertions.assertFalse(teArr3.hasTypeInfo()); - Assertions.assertTrue(teSetA.hasTypeInfo()); - Assertions.assertTrue(teSetB.hasTypeInfo()); - Assertions.assertTrue(teSetC.hasTypeInfo()); - Assertions.assertTrue(teMap.hasTypeInfo()); - Assertions.assertTrue(teMapA.hasTypeInfo()); - Assertions.assertTrue(teMap3.hasTypeInfo()); - Assertions.assertTrue(teFoo.hasTypeInfo()); - Assertions.assertTrue(teDeep1.hasTypeInfo()); - Assertions.assertTrue(teDeep2.hasTypeInfo()); - Assertions.assertFalse(teUpperBound.hasTypeInfo()); - Assertions.assertFalse(teLowerBound.hasTypeInfo()); - Assertions.assertFalse(teWildcard.hasTypeInfo()); - Assertions.assertFalse(teFunc1.hasTypeInfo()); - Assertions.assertFalse(teFunc2.hasTypeInfo()); - Assertions.assertFalse(teFunc3.hasTypeInfo()); - Assertions.assertFalse(teFunc4.hasTypeInfo()); - Assertions.assertFalse(teSIUnit1.hasTypeInfo()); - Assertions.assertFalse(teNumWithSIUnit1.hasTypeInfo()); - Assertions.assertFalse(teUnion1.hasTypeInfo()); - Assertions.assertFalse(teTuple1.hasTypeInfo()); - Assertions.assertFalse(teRegEx1.hasTypeInfo()); - Assertions.assertFalse(teObscure.hasTypeInfo()); + assertTrue(teInt.hasTypeInfo()); + assertFalse(teVarA.hasTypeInfo()); + assertFalse(teVarB.hasTypeInfo()); + assertFalse(teVarUpper.hasTypeInfo()); + assertFalse(teVarLower.hasTypeInfo()); + assertTrue(teIntA.hasTypeInfo()); + assertTrue(teP.hasTypeInfo()); + assertTrue(teH.hasTypeInfo()); + assertFalse(teVoid.hasTypeInfo()); + assertFalse(teNull.hasTypeInfo()); + assertFalse(teArr1.hasTypeInfo()); + assertFalse(teArr3.hasTypeInfo()); + assertTrue(teSetA.hasTypeInfo()); + assertTrue(teSetB.hasTypeInfo()); + assertTrue(teSetC.hasTypeInfo()); + assertTrue(teMap.hasTypeInfo()); + assertTrue(teMapA.hasTypeInfo()); + assertTrue(teMap3.hasTypeInfo()); + assertTrue(teFoo.hasTypeInfo()); + assertTrue(teDeep1.hasTypeInfo()); + assertTrue(teDeep2.hasTypeInfo()); + assertFalse(teUpperBound.hasTypeInfo()); + assertFalse(teLowerBound.hasTypeInfo()); + assertFalse(teWildcard.hasTypeInfo()); + assertFalse(teFunc1.hasTypeInfo()); + assertFalse(teFunc2.hasTypeInfo()); + assertFalse(teFunc3.hasTypeInfo()); + assertFalse(teFunc4.hasTypeInfo()); + assertFalse(teSIUnit1.hasTypeInfo()); + assertFalse(teNumWithSIUnit1.hasTypeInfo()); + assertFalse(teUnion1.hasTypeInfo()); + assertFalse(teTuple1.hasTypeInfo()); + assertFalse(teRegEx1.hasTypeInfo()); + assertFalse(teObscure.hasTypeInfo()); } @Test public void deepCloneTest(){ //SymTypeVoid - Assertions.assertTrue(teVoid.deepClone() instanceof SymTypeVoid); - Assertions.assertEquals(teVoid.getTypeInfo().getName(), teVoid.deepClone().getTypeInfo().getName()); - Assertions.assertEquals(teVoid.print(), teVoid.deepClone().print()); + assertTrue(teVoid.deepClone() instanceof SymTypeVoid); + assertEquals(teVoid.getTypeInfo().getName(), teVoid.deepClone().getTypeInfo().getName()); + assertEquals(teVoid.print(), teVoid.deepClone().print()); //SymTypeOfNull - Assertions.assertTrue(teNull.deepClone() instanceof SymTypeOfNull); - Assertions.assertEquals(teNull.getTypeInfo().getName(), teNull.deepClone().getTypeInfo().getName()); - Assertions.assertEquals(teNull.print(), teNull.deepClone().print()); + assertTrue(teNull.deepClone() instanceof SymTypeOfNull); + assertEquals(teNull.getTypeInfo().getName(), teNull.deepClone().getTypeInfo().getName()); + assertEquals(teNull.print(), teNull.deepClone().print()); //SymTypeVariable - Assertions.assertTrue(teVarA.deepClone() instanceof SymTypeVariable); - Assertions.assertFalse(teVarA.deepClone().isPrimitive()); - Assertions.assertTrue(teVarA.deepClone().isTypeVariable()); - Assertions.assertEquals(teVarA.print(), teVarA.deepClone().print()); + assertTrue(teVarA.deepClone() instanceof SymTypeVariable); + assertFalse(teVarA.deepClone().isPrimitive()); + assertTrue(teVarA.deepClone().isTypeVariable()); + assertEquals(teVarA.print(), teVarA.deepClone().print()); - Assertions.assertTrue(teVarUpper.deepClone() instanceof SymTypeInferenceVariable); - Assertions.assertFalse(teVarUpper.deepClone().isPrimitive()); - Assertions.assertTrue(teVarUpper.deepClone().isInferenceVariable()); - Assertions.assertEquals(teVarUpper.print(), teVarUpper.deepClone().print()); + assertTrue(teVarUpper.deepClone() instanceof SymTypeInferenceVariable); + assertFalse(teVarUpper.deepClone().isPrimitive()); + assertTrue(teVarUpper.deepClone().isInferenceVariable()); + assertEquals(teVarUpper.print(), teVarUpper.deepClone().print()); - Assertions.assertTrue(teVarLower.deepClone() instanceof SymTypeInferenceVariable); - Assertions.assertFalse(teVarLower.deepClone().isPrimitive()); - Assertions.assertTrue(teVarLower.deepClone().isInferenceVariable()); - Assertions.assertEquals(teVarLower.print(), teVarLower.deepClone().print()); + assertTrue(teVarLower.deepClone() instanceof SymTypeInferenceVariable); + assertFalse(teVarLower.deepClone().isPrimitive()); + assertTrue(teVarLower.deepClone().isInferenceVariable()); + assertEquals(teVarLower.print(), teVarLower.deepClone().print()); //SymTypePrimitive - Assertions.assertTrue(teInt.deepClone() instanceof SymTypePrimitive); - Assertions.assertEquals(teInt.getTypeInfo().getName(), teInt.deepClone().getTypeInfo().getName()); - Assertions.assertTrue(teInt.deepClone().isPrimitive()); - Assertions.assertEquals(teInt.print(), teInt.deepClone().print()); + assertTrue(teInt.deepClone() instanceof SymTypePrimitive); + assertEquals(teInt.getTypeInfo().getName(), teInt.deepClone().getTypeInfo().getName()); + assertTrue(teInt.deepClone().isPrimitive()); + assertEquals(teInt.print(), teInt.deepClone().print()); //SymTypeOfObject - Assertions.assertTrue(teH.deepClone() instanceof SymTypeOfObject); - Assertions.assertEquals(teH.print(), teH.deepClone().print()); + assertTrue(teH.deepClone() instanceof SymTypeOfObject); + assertEquals(teH.print(), teH.deepClone().print()); //SymTypeArray - Assertions.assertTrue(teArr1.deepClone() instanceof SymTypeArray); - Assertions.assertEquals(teArr1.print(), teArr1.deepClone().print()); - Assertions.assertEquals(((SymTypeArray)teArr1).getDim(), ((SymTypeArray)teArr1.deepClone()).getDim()); - Assertions.assertEquals(((SymTypeArray)teArr1).getArgument().print(), ((SymTypeArray)teArr1.deepClone()).getArgument().print()); + assertTrue(teArr1.deepClone() instanceof SymTypeArray); + assertEquals(teArr1.print(), teArr1.deepClone().print()); + assertEquals(((SymTypeArray)teArr1).getDim(), ((SymTypeArray)teArr1.deepClone()).getDim()); + assertEquals(((SymTypeArray)teArr1).getArgument().print(), ((SymTypeArray)teArr1.deepClone()).getArgument().print()); //SymTypeOfGenerics - Assertions.assertTrue(teDeep1.deepClone() instanceof SymTypeOfGenerics); - Assertions.assertTrue(teDeep1.deepClone().isGenericType()); - Assertions.assertEquals(teDeep1.print(), teDeep1.deepClone().print()); + assertTrue(teDeep1.deepClone() instanceof SymTypeOfGenerics); + assertTrue(teDeep1.deepClone().isGenericType()); + assertEquals(teDeep1.print(), teDeep1.deepClone().print()); //SymTypeOfWildcard - Assertions.assertTrue(teUpperBound.deepClone() instanceof SymTypeOfWildcard); - Assertions.assertEquals(((SymTypeOfWildcard) teUpperBound).getBound().print(), ((SymTypeOfWildcard) teUpperBound.deepClone()).getBound().print()); - Assertions.assertEquals(teUpperBound.print(), teUpperBound.deepClone().print()); + assertTrue(teUpperBound.deepClone() instanceof SymTypeOfWildcard); + assertEquals(((SymTypeOfWildcard) teUpperBound).getBound().print(), ((SymTypeOfWildcard) teUpperBound.deepClone()).getBound().print()); + assertEquals(teUpperBound.print(), teUpperBound.deepClone().print()); //SymTypeOfFunction - Assertions.assertTrue(teFunc3.deepClone() instanceof SymTypeOfFunction); - Assertions.assertTrue(teFunc3.deepClone().isFunctionType()); - Assertions.assertEquals(teFunc3.print(), teFunc3.deepClone().print()); + assertTrue(teFunc3.deepClone() instanceof SymTypeOfFunction); + assertTrue(teFunc3.deepClone().isFunctionType()); + assertEquals(teFunc3.print(), teFunc3.deepClone().print()); // SymTypeOfSIUnit - Assertions.assertTrue(teSIUnit1.deepClone() instanceof SymTypeOfSIUnit); - Assertions.assertTrue(teSIUnit1.deepClone().isSIUnitType()); - Assertions.assertEquals(teSIUnit1.print(), teSIUnit1.deepClone().print()); + assertTrue(teSIUnit1.deepClone() instanceof SymTypeOfSIUnit); + assertTrue(teSIUnit1.deepClone().isSIUnitType()); + assertEquals(teSIUnit1.print(), teSIUnit1.deepClone().print()); // SymTypeOfNumericWithSIUnit - Assertions.assertTrue(teNumWithSIUnit1.deepClone() instanceof SymTypeOfNumericWithSIUnit); - Assertions.assertTrue(teNumWithSIUnit1.deepClone().isNumericWithSIUnitType()); - Assertions.assertEquals(teNumWithSIUnit1.print(), teNumWithSIUnit1.deepClone().print()); + assertTrue(teNumWithSIUnit1.deepClone() instanceof SymTypeOfNumericWithSIUnit); + assertTrue(teNumWithSIUnit1.deepClone().isNumericWithSIUnitType()); + assertEquals(teNumWithSIUnit1.print(), teNumWithSIUnit1.deepClone().print()); //SymTypeOfUnion - Assertions.assertTrue(teUnion1.deepClone() instanceof SymTypeOfUnion); - Assertions.assertTrue(teUnion1.deepClone().isUnionType()); - Assertions.assertEquals(teUnion1.print(), teUnion1.deepClone().print()); + assertTrue(teUnion1.deepClone() instanceof SymTypeOfUnion); + assertTrue(teUnion1.deepClone().isUnionType()); + assertEquals(teUnion1.print(), teUnion1.deepClone().print()); //SymTypeOfIntersection - Assertions.assertTrue(teInter1.deepClone() instanceof SymTypeOfIntersection); - Assertions.assertTrue(teInter1.deepClone().isIntersectionType()); - Assertions.assertEquals(teInter1.print(), teInter1.deepClone().print()); + assertTrue(teInter1.deepClone() instanceof SymTypeOfIntersection); + assertTrue(teInter1.deepClone().isIntersectionType()); + assertEquals(teInter1.print(), teInter1.deepClone().print()); //SymTypeOfTuple - Assertions.assertTrue(teTuple1.deepClone() instanceof SymTypeOfTuple); - Assertions.assertTrue(teTuple1.deepClone().isTupleType()); - Assertions.assertEquals(teTuple1.print(), teTuple1.deepClone().print()); + assertTrue(teTuple1.deepClone() instanceof SymTypeOfTuple); + assertTrue(teTuple1.deepClone().isTupleType()); + assertEquals(teTuple1.print(), teTuple1.deepClone().print()); - Assertions.assertTrue(teRegEx1.deepClone() instanceof SymTypeOfRegEx); - Assertions.assertTrue(teRegEx1.deepClone().isRegExType()); - Assertions.assertEquals(teRegEx1.print(), teRegEx1.deepClone().print()); + assertTrue(teRegEx1.deepClone() instanceof SymTypeOfRegEx); + assertTrue(teRegEx1.deepClone().isRegExType()); + assertEquals(teRegEx1.print(), teRegEx1.deepClone().print()); } @Test public void testSymTypeExpressionFactory(){ SymTypeVoid tVoid = SymTypeExpressionFactory.createTypeVoid(); - Assertions.assertEquals("void", tVoid.print()); + assertEquals("void", tVoid.print()); SymTypeOfNull tNull = SymTypeExpressionFactory.createTypeOfNull(); - Assertions.assertEquals("null", tNull.print()); + assertEquals("null", tNull.print()); SymTypePrimitive tInt = SymTypeExpressionFactory.createPrimitive("int"); - Assertions.assertEquals("int", tInt.print()); - Assertions.assertTrue(tInt.isIntegralType()); + assertEquals("int", tInt.print()); + assertTrue(tInt.isIntegralType()); SymTypeOfGenerics tA = SymTypeExpressionFactory.createGenerics("A",scope); - Assertions.assertEquals("A<>", tA.print()); - Assertions.assertTrue(tA.isEmptyArguments()); + assertEquals("A<>", tA.print()); + assertTrue(tA.isEmptyArguments()); SymTypeOfGenerics tB = SymTypeExpressionFactory.createGenerics("B",scope,Lists.newArrayList(teArr1,teIntA)); - Assertions.assertEquals("B", tB.printFullName()); - Assertions.assertEquals(2, tB.sizeArguments()); + assertEquals("B", tB.printFullName()); + assertEquals(2, tB.sizeArguments()); SymTypeOfGenerics tC = SymTypeExpressionFactory.createGenerics("C",scope,teDeep1,teDeep2); - Assertions.assertEquals("C>,java.util.Map2>>>", tC.printFullName()); - Assertions.assertEquals(2, tC.sizeArguments()); + assertEquals("C>,java.util.Map2>>>", tC.printFullName()); + assertEquals(2, tC.sizeArguments()); SymTypeOfGenerics tD = SymTypeExpressionFactory.createGenerics("D",scope); - Assertions.assertEquals("D<>", tD.printFullName()); - Assertions.assertTrue(tD.isEmptyArguments()); + assertEquals("D<>", tD.printFullName()); + assertTrue(tD.isEmptyArguments()); SymTypeOfGenerics tE = SymTypeExpressionFactory.createGenerics("E",scope,Lists.newArrayList(teDouble,teMap)); - Assertions.assertEquals("E>", tE.printFullName()); - Assertions.assertEquals(2, tE.sizeArguments()); + assertEquals("E>", tE.printFullName()); + assertEquals(2, tE.sizeArguments()); SymTypeOfGenerics tF = SymTypeExpressionFactory.createGenerics("F",scope,teH,teP); - Assertions.assertEquals("F", tF.printFullName()); - Assertions.assertEquals(2, tF.sizeArguments()); + assertEquals("F", tF.printFullName()); + assertEquals(2, tF.sizeArguments()); SymTypeArray tHuman = SymTypeExpressionFactory.createTypeArray("Human",scope,1,teH); - Assertions.assertEquals("Human[]", tHuman.print()); - Assertions.assertEquals(1, tHuman.getDim()); - Assertions.assertEquals("Human", tHuman.getArgument().print()); + assertEquals("Human[]", tHuman.print()); + assertEquals(1, tHuman.getDim()); + assertEquals("Human", tHuman.getArgument().print()); SymTypeArray tPerson = SymTypeExpressionFactory.createTypeArray("de.x.Person",scope,2,teP); - Assertions.assertEquals("de.x.Person[][]", tPerson.print()); - Assertions.assertEquals(2, tPerson.getDim()); - Assertions.assertEquals("de.x.Person", tPerson.getArgument().print()); + assertEquals("de.x.Person[][]", tPerson.print()); + assertEquals(2, tPerson.getDim()); + assertEquals("de.x.Person", tPerson.getArgument().print()); - SymTypeOfObject tG = SymTypeExpressionFactory.createTypeObject("G",scope); - Assertions.assertEquals("G", tG.print()); + SymTypeOfObject tG = SymTypeExpressionFactory.createTypeObjectViaSurrogate("G",scope); + assertEquals("G", tG.print()); - SymTypeOfObject tH = SymTypeExpressionFactory.createTypeObject("H",scope); - Assertions.assertEquals("H", tH.print()); + SymTypeOfObject tH = SymTypeExpressionFactory.createTypeObjectViaSurrogate("H",scope); + assertEquals("H", tH.print()); SymTypeVariable tT = SymTypeExpressionFactory.createTypeVariable("T",scope); - Assertions.assertEquals("T", tT.print()); + assertEquals("T", tT.print()); SymTypeVariable tS = SymTypeExpressionFactory.createTypeVariable("S",scope); - Assertions.assertEquals("S", tS.print()); + assertEquals("S", tS.print()); SymTypeExpression tExpr = SymTypeExpressionFactory.createTypeExpression("void",scope); - Assertions.assertTrue(tExpr instanceof SymTypeVoid); - Assertions.assertEquals("void", tExpr.print()); + assertInstanceOf(SymTypeVoid.class, tExpr); + assertEquals("void", tExpr.print()); SymTypeOfFunction tFunc1 = SymTypeExpressionFactory.createFunction(tVoid); - Assertions.assertEquals("() -> void", tFunc1.print()); + assertEquals("() -> void", tFunc1.print()); SymTypeOfFunction tFunc2 = SymTypeExpressionFactory.createFunction(tVoid, Lists.newArrayList(tFunc1, tFunc1)); - Assertions.assertEquals("((() -> void), (() -> void)) -> void", tFunc2.print()); + assertEquals("((() -> void), (() -> void)) -> void", tFunc2.print()); SymTypeOfFunction tFunc3 = SymTypeExpressionFactory.createFunction(tVoid, tFunc1, tFunc1); - Assertions.assertEquals("((() -> void), (() -> void)) -> void", tFunc3.print()); + assertEquals("((() -> void), (() -> void)) -> void", tFunc3.print()); SymTypeOfFunction tFunc4 = SymTypeExpressionFactory.createFunction(tVoid, Lists.newArrayList(teDouble, teInt), true); - Assertions.assertEquals("(double, int...) -> void", tFunc4.print()); + assertEquals("(double, int...) -> void", tFunc4.print()); SIUnitBasic tSIUnitBasic1 = createSIUnitBasic("m"); - Assertions.assertEquals("m", tSIUnitBasic1.print()); + assertEquals("m", tSIUnitBasic1.print()); SIUnitBasic tSIUnitBasic2 = createSIUnitBasic("s", 2); - Assertions.assertEquals("s^2", tSIUnitBasic2.print()); + assertEquals("s^2", tSIUnitBasic2.print()); SIUnitBasic tSIUnitBasic3 = createSIUnitBasic("g", "m", -2); - Assertions.assertEquals("mg^-2", tSIUnitBasic3.print()); + assertEquals("mg^-2", tSIUnitBasic3.print()); SymTypeOfSIUnit tSIUnit1 = createSIUnit(List.of(tSIUnitBasic1), List.of()); - Assertions.assertEquals("[m]", tSIUnit1.print()); + assertEquals("[m]", tSIUnit1.print()); SymTypeOfSIUnit tSIUnit2 = createSIUnit(List.of(), List.of(tSIUnitBasic2)); - Assertions.assertEquals("[1/s^2]", tSIUnit2.print()); + assertEquals("[1/s^2]", tSIUnit2.print()); SymTypeOfSIUnit tSIUnit3 = createSIUnit( List.of(tSIUnitBasic1), List.of(tSIUnitBasic2, tSIUnitBasic3) ); - Assertions.assertEquals("[m/s^2mg^-2]", tSIUnit3.print()); + assertEquals("[m/s^2mg^-2]", tSIUnit3.print()); SymTypeOfNumericWithSIUnit tNumSIUnit1 = createNumericWithSIUnit(tSIUnit1, teInt); - Assertions.assertEquals("[m]", tNumSIUnit1.print()); + assertEquals("[m]", tNumSIUnit1.print()); SymTypeOfNumericWithSIUnit tNumSIUnit2 = createNumericWithSIUnit( List.of(tSIUnitBasic1), List.of(tSIUnitBasic2, tSIUnitBasic3), teInt ); - Assertions.assertEquals("[m/s^2mg^-2]", tNumSIUnit2.print()); + assertEquals("[m/s^2mg^-2]", tNumSIUnit2.print()); SymTypeOfUnion tUnion1 = createUnion(teInt, teDouble); - Assertions.assertEquals("double | int", tUnion1.print()); + assertEquals("double | int", tUnion1.print()); SymTypeOfUnion tUnion2 = createUnion(Set.of(teInt, teDouble, teArr1)); - Assertions.assertEquals("Human[] | double | int", tUnion2.print()); + assertEquals("Human[] | double | int", tUnion2.print()); SymTypeOfIntersection tInter1 = createIntersection(teInt, teDouble); - Assertions.assertEquals("double & int", tInter1.print()); + assertEquals("double & int", tInter1.print()); SymTypeOfIntersection tInter2 = createIntersection(Set.of(teInt, teDouble, teArr1)); - Assertions.assertEquals("Human[] & double & int", tInter2.print()); + assertEquals("Human[] & double & int", tInter2.print()); SymTypeOfTuple tTuple1 = createTuple(teInt, teDouble); - Assertions.assertEquals("(int, double)", tTuple1.print()); + assertEquals("(int, double)", tTuple1.print()); SymTypeOfTuple tTuple2 = createTuple(List.of(teInt, teDouble)); - Assertions.assertEquals("(int, double)", tTuple2.print()); + assertEquals("(int, double)", tTuple2.print()); SymTypeOfRegEx tRegEx1 = createTypeRegEx("rege(x(es)?|xps?)"); - Assertions.assertEquals("R\"rege(x(es)?|xps?)\"", tRegEx1.print()); + assertEquals("R\"rege(x(es)?|xps?)\"", tRegEx1.print()); } @Test @@ -801,406 +776,402 @@ public void testSymTypeExpressionFactoryString() { @Test public void testGenericArguments(){ SymTypeExpression teFoo = createGenerics("x.Foo", scope, Lists.newArrayList(teP, teDouble, teInt, teH)); - Assertions.assertTrue(teFoo.isGenericType()); + assertTrue(teFoo.isGenericType()); SymTypeOfGenerics teFoo2 = (SymTypeOfGenerics) teFoo; //getArgumentList & getArgument - Assertions.assertEquals(4, teFoo2.getArgumentList().size()); - Assertions.assertEquals(teP, teFoo2.getArgument(0)); - Assertions.assertEquals(teDouble, teFoo2.getArgument(1)); - Assertions.assertEquals(teInt, teFoo2.getArgument(2)); - Assertions.assertEquals(teH, teFoo2.getArgument(3)); + assertEquals(4, teFoo2.getArgumentList().size()); + assertEquals(teP, teFoo2.getArgument(0)); + assertEquals(teDouble, teFoo2.getArgument(1)); + assertEquals(teInt, teFoo2.getArgument(2)); + assertEquals(teH, teFoo2.getArgument(3)); List arguments = teFoo2.getArgumentList(); //toArrayArguments Object[] args = teFoo2.toArrayArguments(); - Assertions.assertEquals(teP, args[0]); - Assertions.assertEquals(teDouble, args[1]); - Assertions.assertEquals(teInt, args[2]); - Assertions.assertEquals(teH, args[3]); + assertEquals(teP, args[0]); + assertEquals(teDouble, args[1]); + assertEquals(teInt, args[2]); + assertEquals(teH, args[3]); //toArrayArguments2 SymTypeExpression[] symArgs = teFoo2.toArrayArguments(new SymTypeExpression[4]); - Assertions.assertEquals(teP, symArgs[0]); - Assertions.assertEquals(teDouble, symArgs[1]); - Assertions.assertEquals(teInt, symArgs[2]); - Assertions.assertEquals(teH, symArgs[3]); + assertEquals(teP, symArgs[0]); + assertEquals(teDouble, symArgs[1]); + assertEquals(teInt, symArgs[2]); + assertEquals(teH, symArgs[3]); //subListArguments List subList = teFoo2.subListArguments(1,3); - Assertions.assertEquals(2, subList.size()); - Assertions.assertEquals(teDouble, subList.get(0)); - Assertions.assertEquals(teInt, subList.get(1)); + assertEquals(2, subList.size()); + assertEquals(teDouble, subList.get(0)); + assertEquals(teInt, subList.get(1)); //containsArgument - Assertions.assertTrue(teFoo2.containsArgument(teDouble)); - Assertions.assertFalse(teFoo2.containsArgument(teDeep1)); + assertTrue(teFoo2.containsArgument(teDouble)); + assertFalse(teFoo2.containsArgument(teDeep1)); //containsAllArguments - Assertions.assertTrue(teFoo2.containsAllArguments(subList)); + assertTrue(teFoo2.containsAllArguments(subList)); //indexOfArgument - Assertions.assertEquals(0, teFoo2.indexOfArgument(teP)); + assertEquals(0, teFoo2.indexOfArgument(teP)); //lastIndexOfArgument - Assertions.assertEquals(0, teFoo2.lastIndexOfArgument(teP)); + assertEquals(0, teFoo2.lastIndexOfArgument(teP)); //equalsArguments - Assertions.assertTrue(teFoo2.equalsArguments(teFoo2.getArgumentList())); - Assertions.assertFalse(teFoo2.equalsArguments(subList)); + assertTrue(teFoo2.equalsArguments(teFoo2.getArgumentList())); + assertFalse(teFoo2.equalsArguments(subList)); //listIteratorArguments Iterator it = teFoo2.listIteratorArguments(); int i = 0; while(it.hasNext()){ - Assertions.assertEquals(symArgs[i], it.next()); + assertEquals(symArgs[i], it.next()); ++i; } - Assertions.assertEquals(4, i); + assertEquals(4, i); //listIteratorArguments Iterator it3 = teFoo2.listIteratorArguments(1); i=0; while(it3.hasNext()){ - Assertions.assertEquals(symArgs[i+1], it3.next()); + assertEquals(symArgs[i+1], it3.next()); ++i; } - Assertions.assertEquals(3, i); + assertEquals(3, i); //iteratorArguments Iterator it2 = teFoo2.iteratorArguments(); i = 0; while(it2.hasNext()){ - Assertions.assertEquals(symArgs[i], it2.next()); + assertEquals(symArgs[i], it2.next()); ++i; } - Assertions.assertEquals(4, i); + assertEquals(4, i); //spliteratorArguments Spliterator split = teFoo2.spliteratorArguments(); - Assertions.assertEquals(4, split.getExactSizeIfKnown()); + assertEquals(4, split.getExactSizeIfKnown()); split.forEachRemaining(SymTypeExpression::print); //sizeArguments - Assertions.assertEquals(4, teFoo2.sizeArguments()); + assertEquals(4, teFoo2.sizeArguments()); //streamArguments Stream stream =teFoo2.streamArguments(); List list = stream.filter(SymTypeExpression::isPrimitive) .collect(Collectors.toList()); - Assertions.assertEquals(2, list.size()); - Assertions.assertEquals(teDouble, list.get(0)); - Assertions.assertEquals(teInt, list.get(1)); + assertEquals(2, list.size()); + assertEquals(teDouble, list.get(0)); + assertEquals(teInt, list.get(1)); //parallelStreamArguments Stream parStream = teFoo2.parallelStreamArguments(); List parList = parStream.filter(SymTypeExpression::isPrimitive) .collect(Collectors.toList()); - Assertions.assertEquals(2, parList.size()); - Assertions.assertEquals(teDouble, parList.get(0)); - Assertions.assertEquals(teInt, parList.get(1)); + assertEquals(2, parList.size()); + assertEquals(teDouble, parList.get(0)); + assertEquals(teInt, parList.get(1)); //hashCodeArguments - Assertions.assertEquals(teFoo2.getArgumentList().hashCode(), teFoo2.hashCodeArguments()); + assertEquals(teFoo2.getArgumentList().hashCode(), teFoo2.hashCodeArguments()); //forEachArguments teFoo2.forEachArguments(SymTypeExpression::deepClone); - Assertions.assertEquals(teP, teFoo2.getArgument(0)); + assertEquals(teP, teFoo2.getArgument(0)); //setArgument teFoo2.setArgument(2,teDeep2); - Assertions.assertEquals(teDeep2, teFoo2.getArgument(2)); + assertEquals(teDeep2, teFoo2.getArgument(2)); //addArgument teFoo2.addArgument(teSetA); - Assertions.assertEquals(5, teFoo2.sizeArguments()); - Assertions.assertEquals(teSetA, teFoo2.getArgument(4)); + assertEquals(5, teFoo2.sizeArguments()); + assertEquals(teSetA, teFoo2.getArgument(4)); teFoo2.addArgument(3,teArr3); - Assertions.assertEquals(6, teFoo2.sizeArguments()); - Assertions.assertEquals(teArr3, teFoo2.getArgument(3)); + assertEquals(6, teFoo2.sizeArguments()); + assertEquals(teArr3, teFoo2.getArgument(3)); //removeArgument teFoo2.removeArgument(teArr3); - Assertions.assertFalse(teFoo2.containsArgument(teArr3)); - Assertions.assertEquals(5, teFoo2.sizeArguments()); + assertFalse(teFoo2.containsArgument(teArr3)); + assertEquals(5, teFoo2.sizeArguments()); teFoo2.removeArgument(4); - Assertions.assertFalse(teFoo2.containsArgument(teSetA)); - Assertions.assertEquals(4, teFoo2.sizeArguments()); + assertFalse(teFoo2.containsArgument(teSetA)); + assertEquals(4, teFoo2.sizeArguments()); //clearArguments, isEmptyArguments - Assertions.assertFalse(teFoo2.isEmptyArguments()); + assertFalse(teFoo2.isEmptyArguments()); teFoo2.clearArguments(); - Assertions.assertEquals(0, teFoo2.sizeArguments()); - Assertions.assertTrue(teFoo2.isEmptyArguments()); + assertEquals(0, teFoo2.sizeArguments()); + assertTrue(teFoo2.isEmptyArguments()); //setArgumentList arguments = Lists.newArrayList(teP,teDouble,teInt,teH); teFoo2.setArgumentList(arguments); - Assertions.assertEquals(4, teFoo2.sizeArguments()); - Assertions.assertEquals(teP, teFoo2.getArgument(0)); - Assertions.assertEquals(teDouble, teFoo2.getArgument(1)); - Assertions.assertEquals(teInt, teFoo2.getArgument(2)); - Assertions.assertEquals(teH, teFoo2.getArgument(3)); + assertEquals(4, teFoo2.sizeArguments()); + assertEquals(teP, teFoo2.getArgument(0)); + assertEquals(teDouble, teFoo2.getArgument(1)); + assertEquals(teInt, teFoo2.getArgument(2)); + assertEquals(teH, teFoo2.getArgument(3)); //sortArguments teFoo2.sortArguments((arg1,arg2) -> arg1.hashCode()+arg2.hashCode()); - Assertions.assertEquals(4, teFoo2.sizeArguments()); + assertEquals(4, teFoo2.sizeArguments()); //addAllArguments teFoo2.setArgumentList(Lists.newArrayList()); - Assertions.assertTrue(teFoo2.isEmptyArguments()); + assertTrue(teFoo2.isEmptyArguments()); arguments = Lists.newArrayList(teP,teDouble,teInt,teH); teFoo2.addAllArguments(arguments); - Assertions.assertEquals(4, teFoo2.getArgumentList().size()); - Assertions.assertEquals(teP, teFoo2.getArgument(0)); - Assertions.assertEquals(teDouble, teFoo2.getArgument(1)); - Assertions.assertEquals(teInt, teFoo2.getArgument(2)); - Assertions.assertEquals(teH, teFoo2.getArgument(3)); + assertEquals(4, teFoo2.getArgumentList().size()); + assertEquals(teP, teFoo2.getArgument(0)); + assertEquals(teDouble, teFoo2.getArgument(1)); + assertEquals(teInt, teFoo2.getArgument(2)); + assertEquals(teH, teFoo2.getArgument(3)); //retainAllArguments subList = Lists.newArrayList(teP,teH); teFoo2.retainAllArguments(subList); - Assertions.assertEquals(2, teFoo2.sizeArguments()); - Assertions.assertEquals(teP, teFoo2.getArgument(0)); - Assertions.assertEquals(teH, teFoo2.getArgument(1)); + assertEquals(2, teFoo2.sizeArguments()); + assertEquals(teP, teFoo2.getArgument(0)); + assertEquals(teH, teFoo2.getArgument(1)); //removeAllArguments teFoo2.removeAllArguments(subList); - Assertions.assertTrue(teFoo2.isEmptyArguments()); + assertTrue(teFoo2.isEmptyArguments()); //replaceAllArguments arguments = Lists.newArrayList(teP,teDouble,teInt,teH); teFoo2.setArgumentList(arguments); teFoo2.replaceAllArguments(SymTypeExpression::deepClone); - Assertions.assertEquals(4, teFoo2.sizeArguments()); - Assertions.assertTrue(teFoo2.equalsArguments(arguments)); + assertEquals(4, teFoo2.sizeArguments()); + assertTrue(teFoo2.equalsArguments(arguments)); //removeIfArgument teFoo2.removeIfArgument(SymTypeExpression::isPrimitive); - Assertions.assertEquals(2, teFoo2.sizeArguments()); + assertEquals(2, teFoo2.sizeArguments()); } @Test public void symTypeArrayTest(){ SymTypeArray array = SymTypeExpressionFactory.createTypeArray("int",scope,1,_intSymType); - Assertions.assertEquals("int[]", array.print()); + assertEquals("int[]", array.print()); array.setDim(2); - Assertions.assertEquals("int[][]", array.print()); + assertEquals("int[][]", array.print()); } @Test public void symTypeArrayCloneWithLessDimTest() { SymTypeArray arr3 = (SymTypeArray) teArr3; - Assertions.assertEquals("int[][][][]", arr3.cloneWithLessDim(-1).print()); - Assertions.assertEquals("int[][][]", arr3.cloneWithLessDim(0).print()); - Assertions.assertEquals("int[][]", arr3.cloneWithLessDim(1).print()); - Assertions.assertEquals("int[]", arr3.cloneWithLessDim(2).print()); - Assertions.assertEquals("int", arr3.cloneWithLessDim(3).print()); - Assertions.assertFalse(arr3.cloneWithLessDim(3).isArrayType()); + assertEquals("int[][][][]", arr3.cloneWithLessDim(-1).print()); + assertEquals("int[][][]", arr3.cloneWithLessDim(0).print()); + assertEquals("int[][]", arr3.cloneWithLessDim(1).print()); + assertEquals("int[]", arr3.cloneWithLessDim(2).print()); + assertEquals("int", arr3.cloneWithLessDim(3).print()); + assertFalse(arr3.cloneWithLessDim(3).isArrayType()); } @Test public void symTypePrimitiveTest(){ SymTypePrimitive intType = SymTypeExpressionFactory.createPrimitive("int"); - Assertions.assertEquals("int", intType.print()); - intType.setPrimitiveName("double"); - Assertions.assertEquals("double", intType.print()); - intType.setPrimitiveName("int"); - - Assertions.assertEquals("java.lang.Integer", intType.getBoxedPrimitiveName()); - Assertions.assertEquals("Integer", intType.getBaseOfBoxedName()); - Assertions.assertTrue(intType.isIntegralType()); - Assertions.assertTrue(intType.isNumericType()); + assertEquals("int", intType.print()); + + assertEquals("java.lang.Integer", intType.getBoxedPrimitiveName()); + assertTrue(intType.isIntegralType()); + assertTrue(intType.isNumericType()); } @Test public void symTypeOfWildcardTest(){ SymTypeOfWildcard upperBoundInt = (SymTypeOfWildcard) teUpperBound; - Assertions.assertEquals("? extends int", upperBoundInt.print()); - Assertions.assertEquals("int", upperBoundInt.getBound().print()); - Assertions.assertTrue(upperBoundInt.isUpper()); + assertEquals("? extends int", upperBoundInt.print()); + assertEquals("int", upperBoundInt.getBound().print()); + assertTrue(upperBoundInt.isUpper()); } @Test public void testFunctionArguments() { SymTypeExpression teFunExp = createFunction(teVoid, Lists.newArrayList(teP, teDouble, teInt, teH)); - Assertions.assertTrue(teFunExp.isFunctionType()); + assertTrue(teFunExp.isFunctionType()); SymTypeOfFunction teFun = (SymTypeOfFunction) teFunExp; //getArgumentTypeList & getArgumentType - Assertions.assertEquals(4, teFun.getArgumentTypeList().size()); - Assertions.assertEquals(teP, teFun.getArgumentType(0)); - Assertions.assertEquals(teDouble, teFun.getArgumentType(1)); - Assertions.assertEquals(teInt, teFun.getArgumentType(2)); - Assertions.assertEquals(teH, teFun.getArgumentType(3)); + assertEquals(4, teFun.getArgumentTypeList().size()); + assertEquals(teP, teFun.getArgumentType(0)); + assertEquals(teDouble, teFun.getArgumentType(1)); + assertEquals(teInt, teFun.getArgumentType(2)); + assertEquals(teH, teFun.getArgumentType(3)); List arguments = teFun.getArgumentTypeList(); //toArrayArguments Object[] args = teFun.toArrayArgumentTypes(); - Assertions.assertEquals(teP, args[0]); - Assertions.assertEquals(teDouble, args[1]); - Assertions.assertEquals(teInt, args[2]); - Assertions.assertEquals(teH, args[3]); + assertEquals(teP, args[0]); + assertEquals(teDouble, args[1]); + assertEquals(teInt, args[2]); + assertEquals(teH, args[3]); //toArrayArguments2 SymTypeExpression[] symArgs = teFun.toArrayArgumentTypes(new SymTypeExpression[4]); - Assertions.assertEquals(teP, symArgs[0]); - Assertions.assertEquals(teDouble, symArgs[1]); - Assertions.assertEquals(teInt, symArgs[2]); - Assertions.assertEquals(teH, symArgs[3]); + assertEquals(teP, symArgs[0]); + assertEquals(teDouble, symArgs[1]); + assertEquals(teInt, symArgs[2]); + assertEquals(teH, symArgs[3]); //subListArguments List subList = teFun.subListArgumentTypes(1, 3); - Assertions.assertEquals(2, subList.size()); - Assertions.assertEquals(teDouble, subList.get(0)); - Assertions.assertEquals(teInt, subList.get(1)); + assertEquals(2, subList.size()); + assertEquals(teDouble, subList.get(0)); + assertEquals(teInt, subList.get(1)); //containsArgument - Assertions.assertTrue(teFun.containsArgumentType(teDouble)); - Assertions.assertFalse(teFun.containsArgumentType(teDeep1)); + assertTrue(teFun.containsArgumentType(teDouble)); + assertFalse(teFun.containsArgumentType(teDeep1)); //containsAllArgumentTypes - Assertions.assertTrue(teFun.containsAllArgumentTypes(subList)); + assertTrue(teFun.containsAllArgumentTypes(subList)); //indexOfArgument - Assertions.assertEquals(0, teFun.indexOfArgumentType(teP)); + assertEquals(0, teFun.indexOfArgumentType(teP)); //lastIndexOfArgument - Assertions.assertEquals(0, teFun.lastIndexOfArgumentType(teP)); + assertEquals(0, teFun.lastIndexOfArgumentType(teP)); //equalsArgumentTypes - Assertions.assertTrue(teFun.equalsArgumentTypeTypes(teFun.getArgumentTypeList())); - Assertions.assertFalse(teFun.equalsArgumentTypeTypes(subList)); + assertTrue(teFun.equalsArgumentTypeTypes(teFun.getArgumentTypeList())); + assertFalse(teFun.equalsArgumentTypeTypes(subList)); //listIteratorArgumentTypes Iterator it = teFun.listIteratorArgumentTypes(); int i = 0; while (it.hasNext()) { - Assertions.assertEquals(symArgs[i], it.next()); + assertEquals(symArgs[i], it.next()); ++i; } - Assertions.assertEquals(4, i); + assertEquals(4, i); //listIteratorArgumentTypes Iterator it3 = teFun.listIteratorArgumentTypes(1); i = 0; while (it3.hasNext()) { - Assertions.assertEquals(symArgs[i + 1], it3.next()); + assertEquals(symArgs[i + 1], it3.next()); ++i; } - Assertions.assertEquals(3, i); + assertEquals(3, i); //iteratorArgumentTypes Iterator it2 = teFun.iteratorArgumentTypes(); i = 0; while (it2.hasNext()) { - Assertions.assertEquals(symArgs[i], it2.next()); + assertEquals(symArgs[i], it2.next()); ++i; } - Assertions.assertEquals(4, i); + assertEquals(4, i); //spliteratorArgumentTypes Spliterator split = teFun.spliteratorArgumentTypes(); - Assertions.assertEquals(4, split.getExactSizeIfKnown()); + assertEquals(4, split.getExactSizeIfKnown()); split.forEachRemaining(SymTypeExpression::print); //sizeArgumentTypes - Assertions.assertEquals(4, teFun.sizeArgumentTypes()); + assertEquals(4, teFun.sizeArgumentTypes()); //streamArgumentTypes Stream stream = teFun.streamArgumentTypes(); List list = stream.filter(SymTypeExpression::isPrimitive) .collect(Collectors.toList()); - Assertions.assertEquals(2, list.size()); - Assertions.assertEquals(teDouble, list.get(0)); - Assertions.assertEquals(teInt, list.get(1)); + assertEquals(2, list.size()); + assertEquals(teDouble, list.get(0)); + assertEquals(teInt, list.get(1)); //parallelStreamArgumentTypes Stream parStream = teFun.parallelStreamArgumentTypes(); List parList = parStream.filter(SymTypeExpression::isPrimitive) .collect(Collectors.toList()); - Assertions.assertEquals(2, parList.size()); - Assertions.assertEquals(teDouble, parList.get(0)); - Assertions.assertEquals(teInt, parList.get(1)); + assertEquals(2, parList.size()); + assertEquals(teDouble, parList.get(0)); + assertEquals(teInt, parList.get(1)); //hashCodeArgumentTypes - Assertions.assertEquals(teFun.getArgumentTypeList().hashCode(), teFun.hashCodeArgumentTypes()); + assertEquals(teFun.getArgumentTypeList().hashCode(), teFun.hashCodeArgumentTypes()); //forEachArgumentTypes teFun.forEachArgumentTypes(SymTypeExpression::deepClone); - Assertions.assertEquals(teP, teFun.getArgumentType(0)); + assertEquals(teP, teFun.getArgumentType(0)); //setArgument teFun.setArgumentType(2, teDeep2); - Assertions.assertEquals(teDeep2, teFun.getArgumentType(2)); + assertEquals(teDeep2, teFun.getArgumentType(2)); //addArgument teFun.addArgumentType(teSetA); - Assertions.assertEquals(5, teFun.sizeArgumentTypes()); - Assertions.assertEquals(teSetA, teFun.getArgumentType(4)); + assertEquals(5, teFun.sizeArgumentTypes()); + assertEquals(teSetA, teFun.getArgumentType(4)); teFun.addArgumentType(3, teArr3); - Assertions.assertEquals(6, teFun.sizeArgumentTypes()); - Assertions.assertEquals(teArr3, teFun.getArgumentType(3)); + assertEquals(6, teFun.sizeArgumentTypes()); + assertEquals(teArr3, teFun.getArgumentType(3)); //removeArgument teFun.removeArgumentType(teArr3); - Assertions.assertFalse(teFun.containsArgumentType(teArr3)); - Assertions.assertEquals(5, teFun.sizeArgumentTypes()); + assertFalse(teFun.containsArgumentType(teArr3)); + assertEquals(5, teFun.sizeArgumentTypes()); teFun.removeArgumentType(4); - Assertions.assertFalse(teFun.containsArgumentType(teSetA)); - Assertions.assertEquals(4, teFun.sizeArgumentTypes()); + assertFalse(teFun.containsArgumentType(teSetA)); + assertEquals(4, teFun.sizeArgumentTypes()); //clearArgumentTypes, isEmptyArgumentTypes - Assertions.assertFalse(teFun.isEmptyArgumentTypes()); + assertFalse(teFun.isEmptyArgumentTypes()); teFun.clearArgumentTypes(); - Assertions.assertEquals(0, teFun.sizeArgumentTypes()); - Assertions.assertTrue(teFun.isEmptyArgumentTypes()); + assertEquals(0, teFun.sizeArgumentTypes()); + assertTrue(teFun.isEmptyArgumentTypes()); //setArgumentList arguments = Lists.newArrayList(teP, teDouble, teInt, teH); teFun.setArgumentTypeList(arguments); - Assertions.assertEquals(4, teFun.sizeArgumentTypes()); - Assertions.assertEquals(teP, teFun.getArgumentType(0)); - Assertions.assertEquals(teDouble, teFun.getArgumentType(1)); - Assertions.assertEquals(teInt, teFun.getArgumentType(2)); - Assertions.assertEquals(teH, teFun.getArgumentType(3)); + assertEquals(4, teFun.sizeArgumentTypes()); + assertEquals(teP, teFun.getArgumentType(0)); + assertEquals(teDouble, teFun.getArgumentType(1)); + assertEquals(teInt, teFun.getArgumentType(2)); + assertEquals(teH, teFun.getArgumentType(3)); //sortArgumentTypes teFun.sortArgumentTypes((arg1, arg2) -> arg1.hashCode() + arg2.hashCode()); - Assertions.assertEquals(4, teFun.sizeArgumentTypes()); + assertEquals(4, teFun.sizeArgumentTypes()); //addAllArgumentTypes teFun.setArgumentTypeList(Lists.newArrayList()); - Assertions.assertTrue(teFun.isEmptyArgumentTypes()); + assertTrue(teFun.isEmptyArgumentTypes()); arguments = Lists.newArrayList(teP, teDouble, teInt, teH); teFun.addAllArgumentTypes(arguments); - Assertions.assertEquals(4, teFun.getArgumentTypeList().size()); - Assertions.assertEquals(teP, teFun.getArgumentType(0)); - Assertions.assertEquals(teDouble, teFun.getArgumentType(1)); - Assertions.assertEquals(teInt, teFun.getArgumentType(2)); - Assertions.assertEquals(teH, teFun.getArgumentType(3)); + assertEquals(4, teFun.getArgumentTypeList().size()); + assertEquals(teP, teFun.getArgumentType(0)); + assertEquals(teDouble, teFun.getArgumentType(1)); + assertEquals(teInt, teFun.getArgumentType(2)); + assertEquals(teH, teFun.getArgumentType(3)); //retainAllArgumentTypes subList = Lists.newArrayList(teP, teH); teFun.retainAllArgumentTypes(subList); - Assertions.assertEquals(2, teFun.sizeArgumentTypes()); - Assertions.assertEquals(teP, teFun.getArgumentType(0)); - Assertions.assertEquals(teH, teFun.getArgumentType(1)); + assertEquals(2, teFun.sizeArgumentTypes()); + assertEquals(teP, teFun.getArgumentType(0)); + assertEquals(teH, teFun.getArgumentType(1)); //removeAllArgumentTypes teFun.removeAllArgumentTypes(subList); - Assertions.assertTrue(teFun.isEmptyArgumentTypes()); + assertTrue(teFun.isEmptyArgumentTypes()); //replaceAllArgumentTypes arguments = Lists.newArrayList(teP, teDouble, teInt, teH); teFun.setArgumentTypeList(arguments); teFun.replaceAllArgumentTypes(SymTypeExpression::deepClone); - Assertions.assertEquals(4, teFun.sizeArgumentTypes()); - Assertions.assertTrue(teFun.equalsArgumentTypeTypes(arguments)); + assertEquals(4, teFun.sizeArgumentTypes()); + assertTrue(teFun.equalsArgumentTypeTypes(arguments)); //removeIfArgument teFun.removeIfArgumentType(SymTypeExpression::isPrimitive); - Assertions.assertEquals(2, teFun.sizeArgumentTypes()); + assertEquals(2, teFun.sizeArgumentTypes()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeComponentFromMCBasicTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeComponentFromMCBasicTypesTest.java new file mode 100644 index 0000000000..1643297797 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeComponentFromMCBasicTypesTest.java @@ -0,0 +1,140 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.types.check; + +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; +import de.monticore.types.MCTypeFacade; +import de.monticore.types.componentsymbolswithmcbasictypestest.ComponentSymbolsWithMCBasicTypesTestMill; +import de.monticore.types.componentsymbolswithmcbasictypestest._visitor.ComponentSymbolsWithMCBasicTypesTestTraverser; +import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; +import de.monticore.types.mcbasictypes._ast.ASTMCVoidType; +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +public class SynthesizeComponentFromMCBasicTypesTest extends AbstractMCTest { + + @BeforeEach + public void setup() { + LogStub.init(); + Log.enableFailQuick(false); + Log.clearFindings(); + + ComponentSymbolsWithMCBasicTypesTestMill.reset(); + ComponentSymbolsWithMCBasicTypesTestMill.init(); + } + + @ParameterizedTest + @ValueSource(strings = {"Foo", "qual.Foo"}) + public void shouldHandleMCQualifiedType(String qualifiedCompName) { + var globalScope = ComponentSymbolsWithMCBasicTypesTestMill.globalScope(); + + ASTMCQualifiedType ast = MCTypeFacade.getInstance().createQualifiedType(qualifiedCompName); + ast.setEnclosingScope(globalScope); + + ComponentTypeSymbol symbol = ComponentSymbolsWithMCBasicTypesTestMill.componentTypeSymbolBuilder() + .setName(ast.getMCQualifiedName().getBaseName()) + .setSpannedScope(ComponentSymbolsWithMCBasicTypesTestMill.scope()) + .build(); + + if (qualifiedCompName.equals("qual.Foo")) { + var qualScope = ComponentSymbolsWithMCBasicTypesTestMill.scope(); + qualScope.setName("qual"); + qualScope.add(symbol); + qualScope.addSubScope(symbol.getSpannedScope()); + globalScope.addSubScope(qualScope); + } else { + globalScope.add(symbol); + globalScope.addSubScope(symbol.getSpannedScope()); + } + + CompKindCheckResult result = new CompKindCheckResult(); + SynthesizeCompKindFromMCBasicTypes synth = + new SynthesizeCompKindFromMCBasicTypes(result); + + // When + synth.handle(ast); + + // Then + assertTrue(result.getResult().isPresent()); + assertTrue(result.getResult().get().isComponentType()); + assertEquals(symbol, result.getResult().get().getTypeInfo()); + } + + @Test + public void shouldLogErrorForDuplicateSymbols() { + // Given + ASTMCQualifiedType ast = MCTypeFacade.getInstance().createQualifiedType("Foo"); + ast.setEnclosingScope(ComponentSymbolsWithMCBasicTypesTestMill.globalScope()); + + + ComponentTypeSymbol compSymbol1 = ComponentSymbolsWithMCBasicTypesTestMill.componentTypeSymbolBuilder() + .setName(ast.getMCQualifiedName().getBaseName()) + .setSpannedScope(ComponentSymbolsWithMCBasicTypesTestMill.scope()) + .build(); + ComponentSymbolsWithMCBasicTypesTestMill.globalScope().add(compSymbol1); + ComponentSymbolsWithMCBasicTypesTestMill.globalScope().addSubScope(compSymbol1.getSpannedScope()); + + ComponentTypeSymbol compSymbol2 = ComponentSymbolsWithMCBasicTypesTestMill.componentTypeSymbolBuilder() + .setName(ast.getMCQualifiedName().getBaseName()) + .setSpannedScope(ComponentSymbolsWithMCBasicTypesTestMill.scope()) + .build(); + ComponentSymbolsWithMCBasicTypesTestMill.globalScope().add(compSymbol2); + ComponentSymbolsWithMCBasicTypesTestMill.globalScope().addSubScope(compSymbol2.getSpannedScope()); + + CompKindCheckResult result = new CompKindCheckResult(); + SynthesizeCompKindFromMCBasicTypes synth = new SynthesizeCompKindFromMCBasicTypes(result); + + // When + synth.handle(ast); + + // Then + assertTrue(result.getResult().isPresent()); + assertTrue(result.getResult().get().isComponentType()); + assertEquals(compSymbol1, result.getResult().get().getTypeInfo()); + MCAssertions.assertHasFindingStartingWith("0xD0105"); + } + + @ParameterizedTest + @ValueSource(strings = {"Foo", "qual.Foo"}) + public void shouldNotLogErrorForMissingSymbol(String qualifiedName) { + // Given + ASTMCQualifiedType astNormalComp = MCTypeFacade.getInstance().createQualifiedType(qualifiedName); + astNormalComp.setEnclosingScope(ComponentSymbolsWithMCBasicTypesTestMill.globalScope()); + + CompKindCheckResult result = new CompKindCheckResult(); + SynthesizeCompKindFromMCBasicTypes synth4normal = new SynthesizeCompKindFromMCBasicTypes(result); + + // When + synth4normal.handle(astNormalComp); + + // Then + assertFalse(result.getResult().isPresent()); + } + + @Test + public void shouldNotHandleVoidType() { + // Given + ASTMCVoidType voidType = ComponentSymbolsWithMCBasicTypesTestMill.mCVoidTypeBuilder().build(); + CompKindCheckResult resultWrapper = new CompKindCheckResult(); + SynthesizeCompKindFromMCBasicTypes synth = new SynthesizeCompKindFromMCBasicTypes(resultWrapper); + + // Attach a traverser to the synth, as we do not override the handle method and thus the synth tries to traverse the + // AST. In the end this should result in an empty synth result, however, if we do not attach a traverser, this will + // Result in an error instead. + ComponentSymbolsWithMCBasicTypesTestTraverser traverser = ComponentSymbolsWithMCBasicTypesTestMill.traverser(); + traverser.setMCBasicTypesHandler(synth); + + // When + synth.handle(voidType); + + // Then + assertFalse(resultWrapper.getResult().isPresent()); + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeComponentFromMCSimpleGenericTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeComponentFromMCSimpleGenericTypesTest.java new file mode 100644 index 0000000000..3be25b332d --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeComponentFromMCSimpleGenericTypesTest.java @@ -0,0 +1,287 @@ +/* (c) https://github.com/MontiCore/monticore */ +package de.monticore.types.check; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.runtime.junit.MCAssertions; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; +import de.monticore.symbols.compsymbols._symboltable.ComponentTypeSymbol; +import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; +import de.monticore.types.MCTypeFacade; +import de.monticore.types.componentsymbolswithmcbasictypestest.ComponentSymbolsWithMCBasicTypesTestMill; +import de.monticore.types.componentsymbolswithmcbasictypestest._symboltable.IComponentSymbolsWithMCBasicTypesTestScope; +import de.monticore.types.mcbasictypes._ast.ASTMCPrimitiveType; +import de.monticore.types.mcbasictypes._ast.ASTMCQualifiedType; +import de.monticore.types.mcbasictypes._ast.ASTMCType; +import de.monticore.types.mcbasictypes.types3.MCBasicTypesTypeVisitor; +import de.monticore.types.mccollectiontypes._ast.ASTMCBasicTypeArgument; +import de.monticore.types.mccollectiontypes._ast.ASTMCPrimitiveTypeArgument; +import de.monticore.types.mccollectiontypes.types3.MCCollectionTypesTypeVisitor; +import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericType; +import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericTypeBuilder; +import de.monticore.types.mcsimplegenerictypes._ast.ASTMCCustomTypeArgument; +import de.monticore.types.mcsimplegenerictypes.types3.MCSimpleGenericTypesTypeVisitor; +import de.monticore.types3.Type4Ast; +import de.monticore.types3.generics.context.InferenceContext4Ast; +import de.monticore.types3.util.MapBasedTypeCheck3; +import de.se_rwth.commons.logging.Log; +import de.se_rwth.commons.logging.LogStub; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.ValueSource; + +import javax.annotation.Nonnull; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.*; + +public class SynthesizeComponentFromMCSimpleGenericTypesTest extends AbstractMCTest { + + @BeforeEach + public void setup() { + Log.clearFindings(); + LogStub.init(); + Log.enableFailQuick(false); + Log.clearFindings(); + + ComponentSymbolsWithMCBasicTypesTestMill.reset(); + ComponentSymbolsWithMCBasicTypesTestMill.init(); + BasicSymbolsMill.initializePrimitives(); + BasicSymbolsMill.initializeString(); + + Type4Ast type4Ast = new Type4Ast(); + InferenceContext4Ast ctx4Ast = new InferenceContext4Ast(); + + var traverser = ComponentSymbolsWithMCBasicTypesTestMill.traverser(); + + MCBasicTypesTypeVisitor basicTypesVisitor = new MCBasicTypesTypeVisitor(); + basicTypesVisitor.setType4Ast(type4Ast); + traverser.add4MCBasicTypes(basicTypesVisitor); + + MCCollectionTypesTypeVisitor collVisitor = new MCCollectionTypesTypeVisitor(); + collVisitor.setType4Ast(type4Ast); + traverser.add4MCCollectionTypes(collVisitor); + + MCSimpleGenericTypesTypeVisitor simpleGenVisitor = new MCSimpleGenericTypesTypeVisitor(); + simpleGenVisitor.setType4Ast(type4Ast); + traverser.add4MCSimpleGenericTypes(simpleGenVisitor); + + new MapBasedTypeCheck3(traverser, type4Ast, ctx4Ast).setThisAsDelegate(); + } + + @ParameterizedTest + @ValueSource(strings = {"Comp", "scoop.Comp"}) + public void shouldHandleMCBasicGenericType(String qualifiedCompName) { + // Given + var globalScope = ComponentSymbolsWithMCBasicTypesTestMill.globalScope(); + + IComponentSymbolsWithMCBasicTypesTestScope localScope = ComponentSymbolsWithMCBasicTypesTestMill.scope(); + localScope.setName("scoop"); + globalScope.addSubScope(localScope); + + ComponentTypeSymbol compSym = createComponentType("Comp", "K", "V"); + addWithSpannedScope(localScope, compSym); + + TypeSymbol stringSym = BasicSymbolsMill.globalScope() + .resolveType(BasicSymbolsMill.STRING) + .orElseThrow(); + + OOTypeSymbol listSym = ComponentSymbolsWithMCBasicTypesTestMill.oOTypeSymbolBuilder() + .setName("List") + .setSpannedScope(ComponentSymbolsWithMCBasicTypesTestMill.scope()) + .build(); + listSym.addTypeVarSymbol(ComponentSymbolsWithMCBasicTypesTestMill.typeVarSymbolBuilder().setName("T").build()); + addWithSpannedScope(localScope, listSym); + + ASTMCQualifiedType astStringLocal = createQualifiedType( + ImmutableList.of("String"), + localScope, + localScope + ); + + ASTMCType astListOfStringLocal = createGenericType( + ImmutableList.of("List"), + localScope, + astStringLocal + ); + + ASTMCQualifiedType compNameAst = MCTypeFacade.getInstance().createQualifiedType(qualifiedCompName); + List compNameParts = compNameAst.getMCQualifiedName().getPartsList(); + boolean qualified = compNameParts.size() > 1; + + IComponentSymbolsWithMCBasicTypesTestScope enclScope = qualified ? globalScope : localScope; + + ASTMCBasicGenericType astComp = createGenericType( + compNameParts, + enclScope, + astStringLocal, + astListOfStringLocal + ); + + // When + CompKindCheckResult wrapper = new CompKindCheckResult(); + new SynthesizeCompKindFromMCSimpleGenericTypes(wrapper).handle(astComp); + + // Then + assertTrue(wrapper.getResult().isPresent(), "Expected synthesis result to be present"); + assertInstanceOf(CompKindOfGenericComponentType.class, wrapper.getResult().get()); + CompKindOfGenericComponentType result = (CompKindOfGenericComponentType) wrapper.getResult().get(); + + assertEquals(compSym, result.getTypeInfo()); + assertEquals(astComp, result.getSourceNode().orElseThrow()); + + assertEquals(stringSym, result.getTypeBindingFor("K").orElseThrow().getTypeInfo()); + + SymTypeExpression v = result.getTypeBindingFor("V").orElseThrow(); + assertInstanceOf(SymTypeOfGenerics.class, v); + SymTypeOfGenerics vGen = (SymTypeOfGenerics) v; + assertEquals(listSym, vGen.getTypeInfo()); + assertEquals(stringSym, vGen.getArgument(0).getTypeInfo()); + + MCAssertions.assertNoFindings(); + } + + @Test + public void shouldNotHandleMCBasicGenericTypeBecauseCompTypeUnresolvable() { + // Given + ASTMCQualifiedType astString = createQualifiedType( + ImmutableList.of("String"), + ComponentSymbolsWithMCBasicTypesTestMill.globalScope(), + ComponentSymbolsWithMCBasicTypesTestMill.globalScope() + ); + + ASTMCBasicGenericType astComp = createGenericType( + ImmutableList.of("Unresolvable"), + ComponentSymbolsWithMCBasicTypesTestMill.globalScope(), + astString + ); + + // When + CompKindCheckResult wrapper = new CompKindCheckResult(); + new SynthesizeCompKindFromMCSimpleGenericTypes(wrapper).handle(astComp); + + // Then + assertTrue(wrapper.getResult().isEmpty()); + } + + @Test + public void shouldLogErrorForDuplicateSymbols() { + // Given + IComponentSymbolsWithMCBasicTypesTestScope localScope = ComponentSymbolsWithMCBasicTypesTestMill.scope(); + localScope.setName("scoop"); + ComponentSymbolsWithMCBasicTypesTestMill.globalScope().addSubScope(localScope); + + ComponentTypeSymbol comp1 = createComponentType("Comp", "T"); + ComponentTypeSymbol comp2 = createComponentType("Comp", "T"); + addWithSpannedScope(localScope, comp1); + addWithSpannedScope(localScope, comp2); + + ASTMCQualifiedType astString = createQualifiedType( + ImmutableList.of("String"), + localScope, + localScope + ); + + ASTMCBasicGenericType astComp = createGenericType( + ImmutableList.of("Comp"), + localScope, + astString + ); + + // When + CompKindCheckResult wrapper = new CompKindCheckResult(); + new SynthesizeCompKindFromMCSimpleGenericTypes(wrapper).handle(astComp); + + // Then + MCAssertions.assertHasFindingStartingWith("0xD0105"); + assertTrue(wrapper.getResult().isPresent()); + assertInstanceOf(CompKindOfGenericComponentType.class, wrapper.getResult().get()); + assertEquals(astComp, wrapper.getResult().get().getSourceNode().orElseThrow()); + } + + private static void addWithSpannedScope(IComponentSymbolsWithMCBasicTypesTestScope scope, ComponentTypeSymbol sym) { + scope.add(sym); + scope.addSubScope(sym.getSpannedScope()); + } + + private static void addWithSpannedScope(IComponentSymbolsWithMCBasicTypesTestScope scope, OOTypeSymbol sym) { + scope.add(sym); + scope.addSubScope(sym.getSpannedScope()); + } + + private static ComponentTypeSymbol createComponentType(String name, String... typeParams) { + var builder = ComponentSymbolsWithMCBasicTypesTestMill.componentTypeSymbolBuilder() + .setName(name) + .setSpannedScope(ComponentSymbolsWithMCBasicTypesTestMill.scope()); + + builder.setTypeParameters( + Arrays.stream(typeParams) + .map(tp -> ComponentSymbolsWithMCBasicTypesTestMill.typeVarSymbolBuilder().setName(tp).build()) + .collect(ImmutableList.toImmutableList()) + ); + + return builder.build(); + } + + private static ASTMCQualifiedType createQualifiedType( + List nameParts, + IComponentSymbolsWithMCBasicTypesTestScope typeEnclosingScope, + IComponentSymbolsWithMCBasicTypesTestScope nameEnclosingScope + ) { + ASTMCQualifiedType type = ComponentSymbolsWithMCBasicTypesTestMill.mCQualifiedTypeBuilder() + .setMCQualifiedName(ComponentSymbolsWithMCBasicTypesTestMill.mCQualifiedNameBuilder() + .addAllParts(nameParts) + .build()) + .build(); + + type.setEnclosingScope(typeEnclosingScope); + type.getMCQualifiedName().setEnclosingScope(nameEnclosingScope); + return type; + } + + /** + * Returns a {@link ASTMCBasicGenericType} whose format is {@code name.parts}. + * All newly created AST objects are enclosed by {@code enclScope}. + */ + protected static ASTMCBasicGenericType createGenericType(@Nonnull List nameParts, + @Nonnull IComponentSymbolsWithMCBasicTypesTestScope enclScope, + @Nonnull ASTMCType... typeArgs) { + Preconditions.checkNotNull(nameParts); + Preconditions.checkNotNull(enclScope); + Preconditions.checkNotNull(typeArgs); + Preconditions.checkArgument(Arrays.stream(typeArgs).allMatch(Objects::nonNull)); + + ASTMCBasicGenericTypeBuilder builder = ComponentSymbolsWithMCBasicTypesTestMill.mCBasicGenericTypeBuilder() + .setNamesList(nameParts); + + for (ASTMCType typeArg : typeArgs) { + if (typeArg instanceof ASTMCPrimitiveType) { + ASTMCPrimitiveType asPrimitiveType = (ASTMCPrimitiveType) typeArg; + ASTMCPrimitiveTypeArgument asArg = ComponentSymbolsWithMCBasicTypesTestMill.mCPrimitiveTypeArgumentBuilder() + .setMCPrimitiveType(asPrimitiveType).build(); + asArg.setEnclosingScope(enclScope); + builder.addMCTypeArgument(asArg); + + } else if (typeArg instanceof ASTMCQualifiedType) { + ASTMCQualifiedType asQualType = (ASTMCQualifiedType) typeArg; + ASTMCBasicTypeArgument asArg = ComponentSymbolsWithMCBasicTypesTestMill.mCBasicTypeArgumentBuilder().setMCQualifiedType(asQualType).build(); + asArg.setEnclosingScope(enclScope); + builder.addMCTypeArgument(asArg); + + } else { + ASTMCCustomTypeArgument asArg = ComponentSymbolsWithMCBasicTypesTestMill.mCCustomTypeArgumentBuilder().setMCType(typeArg).build(); + asArg.setEnclosingScope(enclScope); + builder.addMCTypeArgument(asArg); + } + } + + ASTMCBasicGenericType type = builder.build(); + type.setEnclosingScope(enclScope); + return type; + } +} diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCArrayTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCArrayTypesTest.java index 2ddd9ffa24..50509956e9 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCArrayTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCArrayTypesTest.java @@ -16,13 +16,12 @@ import de.monticore.types.mcbasictypes._ast.ASTMCVoidType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SynthesizeSymTypeFromMCArrayTypesTest { @@ -77,7 +76,7 @@ public void symTypeFromAST_Test1() throws IOException { String s = "double"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -85,7 +84,7 @@ public void symTypeFromAST_Test2() throws IOException { String s = "int"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -93,7 +92,7 @@ public void symTypeFromAST_Test3() throws IOException { String s = "A"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -101,7 +100,7 @@ public void symTypeFromAST_Test4() throws IOException { String s = "Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -109,27 +108,27 @@ public void symTypeFromAST_Test5() throws IOException { String s = "de.x.Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test public void symTypeFromAST_VoidTest() throws IOException { ASTMCVoidType v = MCBasicTypesMill.mCVoidTypeBuilder().build(); - Assertions.assertEquals("void", tc.symTypeFromAST(v).printFullName()); + assertEquals("void", tc.symTypeFromAST(v).printFullName()); } @Test public void symTypeFromAST_ReturnTest() throws IOException { ASTMCVoidType v = MCBasicTypesMill.mCVoidTypeBuilder().build(); ASTMCReturnType r = MCBasicTypesMill.mCReturnTypeBuilder().setMCVoidType(v).build(); - Assertions.assertEquals("void", tc.symTypeFromAST(r).printFullName()); + assertEquals("void", tc.symTypeFromAST(r).printFullName()); } @Test public void symTypeFromAST_ReturnTest2() throws IOException { // im Prinzip dassselbe via Parser: ASTMCReturnType r = parser.parse_StringMCReturnType("void").get(); - Assertions.assertEquals("void", tc.symTypeFromAST(r).printFullName()); + assertEquals("void", tc.symTypeFromAST(r).printFullName()); } @Test @@ -138,7 +137,7 @@ public void symTypeFromAST_ReturnTest3() throws IOException { String s = "Person"; ASTMCReturnType r = parser.parse_StringMCReturnType(s).get(); r.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(r).printFullName()); + assertEquals(s, tc.symTypeFromAST(r).printFullName()); } @Test @@ -146,7 +145,7 @@ public void symTypeFrom_AST_ArrayTest() throws IOException { ASTMCType prim = parser.parse_StringMCType("int").get(); ASTMCArrayType asttype = MCArrayTypesMill.mCArrayTypeBuilder().setMCType(prim).addDimT("[]").addDimT("[]").build(); asttype.accept(traverser); - Assertions.assertEquals("int[][]", tc.symTypeFromAST(asttype).printFullName()); + assertEquals("int[][]", tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -154,7 +153,7 @@ public void symTypeFrom_AST_ArrayTest2() throws IOException { ASTMCType person = parser.parse_StringMCType("Person").get(); ASTMCArrayType asttype = MCArrayTypesMill.mCArrayTypeBuilder().setMCType(person).addDimT("[]").build(); asttype.accept(traverser); - Assertions.assertEquals("Person[]", tc.symTypeFromAST(asttype).printFullName()); + assertEquals("Person[]", tc.symTypeFromAST(asttype).printFullName()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCBasicTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCBasicTypesTest.java index 8affc8e600..e5c73244d4 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCBasicTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCBasicTypesTest.java @@ -12,13 +12,12 @@ import de.monticore.types.mcbasictypes.MCBasicTypesMill; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SynthesizeSymTypeFromMCBasicTypesTest { @@ -71,7 +70,7 @@ public void symTypeFromAST_Test1() throws IOException { String s = "double"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -79,7 +78,7 @@ public void symTypeFromAST_Test2() throws IOException { String s = "int"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -87,7 +86,7 @@ public void symTypeFromAST_Test3() throws IOException { String s = "A"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -95,7 +94,7 @@ public void symTypeFromAST_Test4() throws IOException { String s = "Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -103,27 +102,27 @@ public void symTypeFromAST_Test5() throws IOException { String s = "de.x.Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test public void symTypeFromAST_VoidTest() throws IOException { ASTMCVoidType v = MCBasicTypesMill.mCVoidTypeBuilder().build(); - Assertions.assertEquals("void", tc.symTypeFromAST(v).printFullName()); + assertEquals("void", tc.symTypeFromAST(v).printFullName()); } @Test public void symTypeFromAST_ReturnTest() throws IOException { ASTMCVoidType v = MCBasicTypesMill.mCVoidTypeBuilder().build(); ASTMCReturnType r = MCBasicTypesMill.mCReturnTypeBuilder().setMCVoidType(v).build(); - Assertions.assertEquals("void", tc.symTypeFromAST(r).printFullName()); + assertEquals("void", tc.symTypeFromAST(r).printFullName()); } @Test public void symTypeFromAST_ReturnTest2() throws IOException { // im Prinzip dassselbe via Parser: ASTMCReturnType r = parser.parse_StringMCReturnType("void").get(); - Assertions.assertEquals("void", tc.symTypeFromAST(r).printFullName()); + assertEquals("void", tc.symTypeFromAST(r).printFullName()); } @Test @@ -132,7 +131,7 @@ public void symTypeFromAST_ReturnTest3() throws IOException { String s = "Person"; ASTMCReturnType r = parser.parse_StringMCReturnType(s).get(); r.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(r).printFullName()); + assertEquals(s, tc.symTypeFromAST(r).printFullName()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCCollectionTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCCollectionTypesTest.java index dc5b9c7d2d..d1fa7c4073 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCCollectionTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCCollectionTypesTest.java @@ -19,7 +19,6 @@ import de.monticore.types.mccollectiontypes._ast.ASTMCListType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,6 +28,8 @@ import java.util.List; import java.util.stream.Collectors; +import static org.junit.jupiter.api.Assertions.*; + public class SynthesizeSymTypeFromMCCollectionTypesTest { /** @@ -101,7 +102,7 @@ public void symTypeFromAST_Test1() throws IOException { String s = "double"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -109,7 +110,7 @@ public void symTypeFromAST_Test4() throws IOException { String s = "Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -117,7 +118,7 @@ public void symTypeFromAST_Test5() throws IOException { String s = "de.x.Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -125,7 +126,7 @@ public void symTypeFromAST_ReturnTest() throws IOException { ASTMCVoidType v = MCBasicTypesMill.mCVoidTypeBuilder().build(); ASTMCReturnType r = MCBasicTypesMill.mCReturnTypeBuilder() .setMCVoidType(v).build(); - Assertions.assertEquals("void", tc.symTypeFromAST(r).printFullName()); + assertEquals("void", tc.symTypeFromAST(r).printFullName()); } @Test @@ -134,7 +135,7 @@ public void symTypeFromAST_ReturnTest3() throws IOException { String s = "Person"; ASTMCReturnType r = parser.parse_StringMCReturnType(s).get(); r.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(r).printFullName()); + assertEquals(s, tc.symTypeFromAST(r).printFullName()); } // new forms of Types coming from MCCollectionType @@ -150,12 +151,12 @@ public void symTypeFromAST_TestListQual() throws IOException { SymTypeExpression result = tc.symTypeFromAST(asttype); // Then - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof OOTypeSymbolSurrogate); } @@ -170,12 +171,12 @@ public void symTypeFromAST_TestListQual2() throws IOException { SymTypeExpression result = tc.symTypeFromAST(asttype); // Then - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof OOTypeSymbolSurrogate); } @Test @@ -189,14 +190,14 @@ public void symTypeFromAST_TestListQual3() throws IOException { SymTypeExpression result = tc.symTypeFromAST(asttype); // Then - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(1).getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(1).getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(1).getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(1).getTypeInfo() instanceof OOTypeSymbolSurrogate); } @Test @@ -210,12 +211,12 @@ public void symTypeFromAST_TestListQual4() throws IOException { SymTypeExpression result = tc.symTypeFromAST(asttype); // Then - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof OOTypeSymbolSurrogate); } @Test @@ -229,12 +230,12 @@ public void symTypeFromAST_TestListQual5() throws IOException { SymTypeExpression result = tc.symTypeFromAST(asttype); // Then - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0).getTypeInfo() instanceof OOTypeSymbolSurrogate); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCFullGenericTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCFullGenericTypesTest.java index ebfcf8aac4..178ecde25b 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCFullGenericTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCFullGenericTypesTest.java @@ -18,13 +18,12 @@ import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SynthesizeSymTypeFromMCFullGenericTypesTest { @@ -108,7 +107,7 @@ public void symTypeFromAST_Test1() throws IOException { parser = new CombineExpressionsWithLiteralsParser(); ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -116,7 +115,7 @@ public void symTypeFromAST_Test4() throws IOException { String s = "Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -124,7 +123,7 @@ public void symTypeFromAST_Test5() throws IOException { String s = "de.x.Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -132,7 +131,7 @@ public void symTypeFromAST_ReturnTest() throws IOException { ASTMCVoidType v = MCBasicTypesMill.mCVoidTypeBuilder().build(); ASTMCReturnType r = MCBasicTypesMill.mCReturnTypeBuilder() .setMCVoidType(v).build(); - Assertions.assertEquals("void", tc.symTypeFromAST(r).printFullName()); + assertEquals("void", tc.symTypeFromAST(r).printFullName()); } @Test @@ -141,7 +140,7 @@ public void symTypeFromAST_ReturnTest3() throws IOException { String s = "Person"; ASTMCReturnType r = parser.parse_StringMCReturnType(s).get(); r.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(r).printFullName()); + assertEquals(s, tc.symTypeFromAST(r).printFullName()); } // reuse some of the tests from MCCollectionType @@ -151,7 +150,7 @@ public void symTypeFromAST_TestListQual() throws IOException { String s = "List"; ASTMCListType asttype = parser.parse_StringMCListType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -159,7 +158,7 @@ public void symTypeFromAST_TestListQual2() throws IOException { String s = "Set"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -167,7 +166,7 @@ public void symTypeFromAST_TestListQual3() throws IOException { String s = "Map"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -175,7 +174,7 @@ public void symTypeFromAST_TestListQual4() throws IOException { String s = "Set"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } //new tests coming from MCSimpleGenericTypes @@ -185,7 +184,7 @@ public void symTypeFromAST_TestGeneric() throws IOException { String s = "Iterator"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -193,7 +192,7 @@ public void symTypeFromAST_TestGeneric2() throws IOException { String s = "java.util.Iterator"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -201,7 +200,7 @@ public void symTypeFromAST_TestGeneric3() throws IOException { String s = "Collection"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -209,7 +208,7 @@ public void symTypeFromAST_TestGeneric4() throws IOException { String s = "java.util.Iterator"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -217,7 +216,7 @@ public void symTypeFromAST_TestGeneric5() throws IOException { String s = "java.util.Iterator"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -225,7 +224,7 @@ public void symTypeFromAST_TestGeneric6() throws IOException { String s = "java.util.Iterator>>"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -233,7 +232,7 @@ public void symTypeFromAST_TestGeneric7() throws IOException { String s = "java.util.Iterator>>"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -241,7 +240,7 @@ public void symTypeFromAST_TestGeneric8() throws IOException { String s = "List"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCSimpleGenericTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCSimpleGenericTypesTest.java index a7191d43cc..33474f059a 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCSimpleGenericTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCSimpleGenericTypesTest.java @@ -16,13 +16,12 @@ import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SynthesizeSymTypeFromMCSimpleGenericTypesTest { @@ -102,7 +101,7 @@ public void symTypeFromAST_Test1() throws IOException { parser = new CombineExpressionsWithLiteralsParser(); ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -110,7 +109,7 @@ public void symTypeFromAST_Test4() throws IOException { String s = "Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -118,7 +117,7 @@ public void symTypeFromAST_Test5() throws IOException { String s = "de.x.Person"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -126,7 +125,7 @@ public void symTypeFromAST_ReturnTest() throws IOException { ASTMCVoidType v = MCBasicTypesMill.mCVoidTypeBuilder().build(); ASTMCReturnType r = MCBasicTypesMill.mCReturnTypeBuilder() .setMCVoidType(v).build(); - Assertions.assertEquals("void", tc.symTypeFromAST(r).printFullName()); + assertEquals("void", tc.symTypeFromAST(r).printFullName()); } @Test @@ -135,7 +134,7 @@ public void symTypeFromAST_ReturnTest3() throws IOException { String s = "Person"; ASTMCReturnType r = parser.parse_StringMCReturnType(s).get(); r.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(r).printFullName()); + assertEquals(s, tc.symTypeFromAST(r).printFullName()); } // reuse some of the tests from MCCollectionType @@ -145,7 +144,7 @@ public void symTypeFromAST_TestListQual() throws IOException { String s = "List"; ASTMCListType asttype = parser.parse_StringMCListType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -153,7 +152,7 @@ public void symTypeFromAST_TestListQual2() throws IOException { String s = "Set"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -161,7 +160,7 @@ public void symTypeFromAST_TestListQual3() throws IOException { String s = "Map"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -169,7 +168,7 @@ public void symTypeFromAST_TestListQual4() throws IOException { String s = "Set"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } //new tests coming from MCSimpleGenericTypes @@ -179,7 +178,7 @@ public void symTypeFromAST_TestGeneric() throws IOException { String s = "Iterator"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -187,7 +186,7 @@ public void symTypeFromAST_TestGeneric2() throws IOException { String s = "java.util.Iterator"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -195,7 +194,7 @@ public void symTypeFromAST_TestGeneric3() throws IOException { String s = "Collection"; ASTMCType asttype = parser.parse_StringMCType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -203,7 +202,7 @@ public void symTypeFromAST_TestGeneric4() throws IOException { String s = "java.util.Iterator"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -211,7 +210,7 @@ public void symTypeFromAST_TestGeneric5() throws IOException { String s = "java.util.Iterator"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -219,7 +218,7 @@ public void symTypeFromAST_TestGeneric6() throws IOException { String s = "java.util.Iterator>>"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } @Test @@ -227,7 +226,7 @@ public void symTypeFromAST_TestGeneric7() throws IOException { String s = "java.util.Iterator>>"; ASTMCBasicGenericType asttype = parser.parse_StringMCBasicGenericType(s).get(); asttype.accept(traverser); - Assertions.assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); + assertEquals(s, tc.symTypeFromAST(asttype).printFullName()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCcFunctionTypesTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCcFunctionTypesTest.java index 5ce5f56fa3..371c5160e1 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCcFunctionTypesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/SynthesizeSymTypeFromMCcFunctionTypesTest.java @@ -9,7 +9,6 @@ import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,10 +16,7 @@ import java.util.Optional; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class SynthesizeSymTypeFromMCcFunctionTypesTest { @@ -74,11 +70,11 @@ public void symTypeFromAST_TestHigherOrderEllipticFunction() throws IOException protected ASTMCFunctionType parse(String mcTypeStr) throws IOException { MCFunctionTypesTestParser parser = new MCFunctionTypesTestParser(); Optional typeOpt = parser.parse_StringMCFunctionType(mcTypeStr); - Assertions.assertNotNull(typeOpt); - Assertions.assertTrue(typeOpt.isPresent(), Log.getFindings().stream() + assertNotNull(typeOpt); + assertTrue(typeOpt.isPresent(), Log.getFindings().stream() .map(Finding::toString) .collect(Collectors.joining("\n"))); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); return typeOpt.get(); } @@ -94,19 +90,19 @@ protected SymTypeOfFunction synthesizeType(ASTMCFunctionType mcType) { mcType.accept(traverser); SymTypeExpression symType = tc.symTypeFromAST(mcType); - Assertions.assertTrue(symType.isFunctionType()); + assertTrue(symType.isFunctionType()); SymTypeOfFunction funcType = (SymTypeOfFunction) symType; - Assertions.assertNotNull(funcType.getTypeInfo()); - Assertions.assertEquals(SymTypeOfFunction.TYPESYMBOL_NAME, funcType.getTypeInfo().getName()); - Assertions.assertNotNull(funcType.getType()); - Assertions.assertFalse(funcType.getType().isObscureType()); - Assertions.assertNotNull(funcType.getArgumentTypeList()); + assertNotNull(funcType.getTypeInfo()); + assertEquals(SymTypeOfFunction.TYPESYMBOL_NAME, funcType.getTypeInfo().getName()); + assertNotNull(funcType.getType()); + assertFalse(funcType.getType().isObscureType()); + assertNotNull(funcType.getArgumentTypeList()); for (SymTypeExpression argType : funcType.getArgumentTypeList()) { - Assertions.assertNotNull(argType); - Assertions.assertFalse(argType.isObscureType()); + assertNotNull(argType); + assertFalse(argType.isObscureType()); } - Assertions.assertTrue(mcType.getDefiningSymbol().isPresent()); - Assertions.assertEquals(SymTypeOfFunction.TYPESYMBOL_NAME, mcType.getDefiningSymbol().get().getName()); + assertTrue(mcType.getDefiningSymbol().isPresent()); + assertEquals(SymTypeOfFunction.TYPESYMBOL_NAME, mcType.getDefiningSymbol().get().getName()); return funcType; } @@ -120,7 +116,7 @@ protected void testSynthesizePrintCompare(String mcTypeStr, String expected) throws IOException { ASTMCFunctionType mcType = parse(mcTypeStr); SymTypeOfFunction symType = synthesizeType(mcType); - Assertions.assertEquals(expected, symType.printFullName()); + assertEquals(expected, symType.printFullName()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/TypeCalculatorTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/TypeCalculatorTest.java index c821eff316..a4ff0d1676 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/TypeCalculatorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/TypeCalculatorTest.java @@ -14,7 +14,6 @@ import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,8 +25,8 @@ import static de.monticore.types.check.DefsTypeBasic.*; import static de.monticore.types.check.SymTypeExpressionFactory.createPrimitive; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test Class for {@link TypeCalculator} @@ -70,11 +69,11 @@ public void init() { OOTypeSymbol s = new OOTypeSymbol("Student"); s.setEnclosingScope(scope); add2scope(scope,s); - s.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObject("Person", scope))); + s.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person", scope))); OOTypeSymbol f = new OOTypeSymbol("FirstSemesterStudent"); f.setEnclosingScope(scope); add2scope(scope,f); - f.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObject("Student", scope))); + f.setSuperTypesList(Lists.newArrayList(SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student", scope))); add2scope(scope, field("foo", _intSymType)); add2scope(scope, field("bar2", _booleanSymType)); add2scope(scope, field("vardouble", _doubleSymType)); @@ -82,12 +81,12 @@ public void init() { add2scope(scope, field("varfloat", _floatSymType)); add2scope(scope, field("varlong", _longSymType)); add2scope(scope, field("varint", _intSymType)); - add2scope(scope, field("varString", SymTypeExpressionFactory.createTypeObject("String", scope))); - add2scope(scope, field("person1", SymTypeExpressionFactory.createTypeObject("Person", scope))); - add2scope(scope, field("person2", SymTypeExpressionFactory.createTypeObject("Person", scope))); - add2scope(scope, field("student1", SymTypeExpressionFactory.createTypeObject("Student", scope))); - add2scope(scope, field("student2", SymTypeExpressionFactory.createTypeObject("Student", scope))); - add2scope(scope, field("firstsemester", SymTypeExpressionFactory.createTypeObject("FirstSemesterStudent", scope))); + add2scope(scope, field("varString", SymTypeExpressionFactory.createTypeObjectViaSurrogate("String", scope))); + add2scope(scope, field("person1", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person", scope))); + add2scope(scope, field("person2", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Person", scope))); + add2scope(scope, field("student1", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student", scope))); + add2scope(scope, field("student2", SymTypeExpressionFactory.createTypeObjectViaSurrogate("Student", scope))); + add2scope(scope, field("firstsemester", SymTypeExpressionFactory.createTypeObjectViaSurrogate("FirstSemesterStudent", scope))); flatExpressionScopeSetter = new FlatExpressionScopeSetter(scope); LogStub.init(); } @@ -111,16 +110,16 @@ public void testIsOfTypeForAssign() throws IOException { ASTExpression char1 = p.parse_StringExpression("\'a\'").get(); char1.accept(traverser); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(bool1), bool2)); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(double1), int1)); - Assertions.assertFalse(tc.isOfTypeForAssign(tc.typeOf(bool1), int1)); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(float1), int1)); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(long1), int1)); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(char1), char1)); - Assertions.assertFalse(tc.isOfTypeForAssign(tc.typeOf(char1), int1)); - Assertions.assertFalse(tc.isOfTypeForAssign(tc.typeOf(double1), bool1)); - Assertions.assertFalse(tc.isOfTypeForAssign(tc.typeOf(long1), float1)); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(float1), int1)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(bool1), bool2)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(double1), int1)); + assertFalse(tc.isOfTypeForAssign(tc.typeOf(bool1), int1)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(float1), int1)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(long1), int1)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(char1), char1)); + assertFalse(tc.isOfTypeForAssign(tc.typeOf(char1), int1)); + assertFalse(tc.isOfTypeForAssign(tc.typeOf(double1), bool1)); + assertFalse(tc.isOfTypeForAssign(tc.typeOf(long1), float1)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(float1), int1)); //non-primitives ASTExpression pers = p.parse_StringExpression("Person").get(); @@ -130,15 +129,15 @@ public void testIsOfTypeForAssign() throws IOException { ASTExpression fstud = p.parse_StringExpression("FirstSemesterStudent").get(); fstud.accept(traverser); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(pers), stud)); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(pers), fstud)); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(stud), fstud)); - Assertions.assertFalse(tc.isOfTypeForAssign(tc.typeOf(stud), pers)); - Assertions.assertFalse(tc.isOfTypeForAssign(tc.typeOf(fstud), pers)); - Assertions.assertFalse(tc.isOfTypeForAssign(tc.typeOf(fstud), stud)); - Assertions.assertTrue(tc.isOfTypeForAssign(tc.typeOf(pers), pers)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(pers), stud)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(pers), fstud)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(stud), fstud)); + assertFalse(tc.isOfTypeForAssign(tc.typeOf(stud), pers)); + assertFalse(tc.isOfTypeForAssign(tc.typeOf(fstud), pers)); + assertFalse(tc.isOfTypeForAssign(tc.typeOf(fstud), stud)); + assertTrue(tc.isOfTypeForAssign(tc.typeOf(pers), pers)); - Assertions.assertFalse(tc.isOfTypeForAssign(tc.typeOf(int1), pers)); + assertFalse(tc.isOfTypeForAssign(tc.typeOf(int1), pers)); } @Test @@ -161,16 +160,16 @@ public void testIsSubtype() throws IOException { char1.accept(traverser); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(bool1), tc.typeOf(bool2))); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(double1))); - Assertions.assertFalse(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(bool1))); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(float1))); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(long1))); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(char1), tc.typeOf(char1))); - Assertions.assertFalse(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(char1))); - Assertions.assertFalse(tc.isSubtypeOf(tc.typeOf(bool1), tc.typeOf(double1))); - Assertions.assertFalse(tc.isSubtypeOf(tc.typeOf(float1), tc.typeOf(long1))); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(float1))); + assertTrue(tc.isSubtypeOf(tc.typeOf(bool1), tc.typeOf(bool2))); + assertTrue(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(double1))); + assertFalse(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(bool1))); + assertTrue(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(float1))); + assertTrue(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(long1))); + assertTrue(tc.isSubtypeOf(tc.typeOf(char1), tc.typeOf(char1))); + assertFalse(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(char1))); + assertFalse(tc.isSubtypeOf(tc.typeOf(bool1), tc.typeOf(double1))); + assertFalse(tc.isSubtypeOf(tc.typeOf(float1), tc.typeOf(long1))); + assertTrue(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(float1))); //non-primitives ASTExpression pers = p.parse_StringExpression("Person").get(); @@ -180,15 +179,15 @@ public void testIsSubtype() throws IOException { ASTExpression fstud = p.parse_StringExpression("FirstSemesterStudent").get(); fstud.accept(traverser); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(stud), tc.typeOf(pers))); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(fstud), tc.typeOf(pers))); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(fstud), tc.typeOf(stud))); - Assertions.assertFalse(tc.isSubtypeOf(tc.typeOf(pers), tc.typeOf(stud))); - Assertions.assertFalse(tc.isSubtypeOf(tc.typeOf(pers), tc.typeOf(fstud))); - Assertions.assertFalse(tc.isSubtypeOf(tc.typeOf(stud), tc.typeOf(fstud))); - Assertions.assertTrue(tc.isSubtypeOf(tc.typeOf(pers), tc.typeOf(pers))); + assertTrue(tc.isSubtypeOf(tc.typeOf(stud), tc.typeOf(pers))); + assertTrue(tc.isSubtypeOf(tc.typeOf(fstud), tc.typeOf(pers))); + assertTrue(tc.isSubtypeOf(tc.typeOf(fstud), tc.typeOf(stud))); + assertFalse(tc.isSubtypeOf(tc.typeOf(pers), tc.typeOf(stud))); + assertFalse(tc.isSubtypeOf(tc.typeOf(pers), tc.typeOf(fstud))); + assertFalse(tc.isSubtypeOf(tc.typeOf(stud), tc.typeOf(fstud))); + assertTrue(tc.isSubtypeOf(tc.typeOf(pers), tc.typeOf(pers))); - Assertions.assertFalse(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(pers))); + assertFalse(tc.isSubtypeOf(tc.typeOf(int1), tc.typeOf(pers))); } @Test @@ -202,33 +201,33 @@ public void testCompatibilityForPrimitives() { SymTypeExpression floatT = createPrimitive(BasicSymbolsMill.FLOAT); SymTypeExpression doubleT = createPrimitive(BasicSymbolsMill.DOUBLE); - Assertions.assertTrue(tc.compatible(booleanT, booleanT)); - Assertions.assertTrue(tc.compatible(byteT, byteT)); - Assertions.assertTrue(tc.compatible(shortT, byteT)); - Assertions.assertTrue(tc.compatible(shortT, shortT)); - Assertions.assertTrue(tc.compatible(charT, charT)); - Assertions.assertTrue(tc.compatible(intT, byteT)); - Assertions.assertTrue(tc.compatible(intT, shortT)); - Assertions.assertTrue(tc.compatible(intT, charT)); - Assertions.assertTrue(tc.compatible(intT, intT)); - Assertions.assertTrue(tc.compatible(longT, byteT)); - Assertions.assertTrue(tc.compatible(longT, shortT)); - Assertions.assertTrue(tc.compatible(longT, charT)); - Assertions.assertTrue(tc.compatible(longT, intT)); - Assertions.assertTrue(tc.compatible(longT, longT)); - Assertions.assertTrue(tc.compatible(floatT, byteT)); - Assertions.assertTrue(tc.compatible(floatT, shortT)); - Assertions.assertTrue(tc.compatible(floatT, charT)); - Assertions.assertTrue(tc.compatible(floatT, intT)); - Assertions.assertTrue(tc.compatible(floatT, longT)); - Assertions.assertTrue(tc.compatible(floatT, floatT)); - Assertions.assertTrue(tc.compatible(doubleT, byteT)); - Assertions.assertTrue(tc.compatible(doubleT, shortT)); - Assertions.assertTrue(tc.compatible(doubleT, charT)); - Assertions.assertTrue(tc.compatible(doubleT, intT)); - Assertions.assertTrue(tc.compatible(doubleT, longT)); - Assertions.assertTrue(tc.compatible(doubleT, floatT)); - Assertions.assertTrue(tc.compatible(doubleT, doubleT)); + assertTrue(tc.compatible(booleanT, booleanT)); + assertTrue(tc.compatible(byteT, byteT)); + assertTrue(tc.compatible(shortT, byteT)); + assertTrue(tc.compatible(shortT, shortT)); + assertTrue(tc.compatible(charT, charT)); + assertTrue(tc.compatible(intT, byteT)); + assertTrue(tc.compatible(intT, shortT)); + assertTrue(tc.compatible(intT, charT)); + assertTrue(tc.compatible(intT, intT)); + assertTrue(tc.compatible(longT, byteT)); + assertTrue(tc.compatible(longT, shortT)); + assertTrue(tc.compatible(longT, charT)); + assertTrue(tc.compatible(longT, intT)); + assertTrue(tc.compatible(longT, longT)); + assertTrue(tc.compatible(floatT, byteT)); + assertTrue(tc.compatible(floatT, shortT)); + assertTrue(tc.compatible(floatT, charT)); + assertTrue(tc.compatible(floatT, intT)); + assertTrue(tc.compatible(floatT, longT)); + assertTrue(tc.compatible(floatT, floatT)); + assertTrue(tc.compatible(doubleT, byteT)); + assertTrue(tc.compatible(doubleT, shortT)); + assertTrue(tc.compatible(doubleT, charT)); + assertTrue(tc.compatible(doubleT, intT)); + assertTrue(tc.compatible(doubleT, longT)); + assertTrue(tc.compatible(doubleT, floatT)); + assertTrue(tc.compatible(doubleT, doubleT)); } @Test @@ -242,43 +241,43 @@ public void testIncompatibilityForPrimitives() { SymTypeExpression floatT = createPrimitive(BasicSymbolsMill.FLOAT); SymTypeExpression doubleT = createPrimitive(BasicSymbolsMill.DOUBLE); - Assertions.assertFalse(tc.compatible(booleanT, byteT)); - Assertions.assertFalse(tc.compatible(booleanT, shortT)); - Assertions.assertFalse(tc.compatible(booleanT, charT)); - Assertions.assertFalse(tc.compatible(booleanT, intT)); - Assertions.assertFalse(tc.compatible(booleanT, longT)); - Assertions.assertFalse(tc.compatible(booleanT, floatT)); - Assertions.assertFalse(tc.compatible(booleanT, doubleT)); - Assertions.assertFalse(tc.compatible(byteT, booleanT)); - Assertions.assertFalse(tc.compatible(byteT, shortT)); - Assertions.assertFalse(tc.compatible(byteT, charT)); - Assertions.assertFalse(tc.compatible(byteT, intT)); - Assertions.assertFalse(tc.compatible(byteT, longT)); - Assertions.assertFalse(tc.compatible(byteT, floatT)); - Assertions.assertFalse(tc.compatible(byteT, doubleT)); - Assertions.assertFalse(tc.compatible(shortT, booleanT)); - Assertions.assertFalse(tc.compatible(shortT, charT)); - Assertions.assertFalse(tc.compatible(shortT, intT)); - Assertions.assertFalse(tc.compatible(shortT, longT)); - Assertions.assertFalse(tc.compatible(shortT, floatT)); - Assertions.assertFalse(tc.compatible(shortT, doubleT)); - Assertions.assertFalse(tc.compatible(charT, booleanT)); - Assertions.assertFalse(tc.compatible(charT, byteT)); - Assertions.assertFalse(tc.compatible(charT, shortT)); - Assertions.assertFalse(tc.compatible(charT, intT)); - Assertions.assertFalse(tc.compatible(charT, longT)); - Assertions.assertFalse(tc.compatible(charT, floatT)); - Assertions.assertFalse(tc.compatible(charT, doubleT)); - Assertions.assertFalse(tc.compatible(intT, booleanT)); - Assertions.assertFalse(tc.compatible(intT, longT)); - Assertions.assertFalse(tc.compatible(intT, floatT)); - Assertions.assertFalse(tc.compatible(intT, doubleT)); - Assertions.assertFalse(tc.compatible(longT, booleanT)); - Assertions.assertFalse(tc.compatible(longT, floatT)); - Assertions.assertFalse(tc.compatible(longT, doubleT)); - Assertions.assertFalse(tc.compatible(floatT, booleanT)); - Assertions.assertFalse(tc.compatible(floatT, doubleT)); - Assertions.assertFalse(tc.compatible(doubleT, booleanT)); + assertFalse(tc.compatible(booleanT, byteT)); + assertFalse(tc.compatible(booleanT, shortT)); + assertFalse(tc.compatible(booleanT, charT)); + assertFalse(tc.compatible(booleanT, intT)); + assertFalse(tc.compatible(booleanT, longT)); + assertFalse(tc.compatible(booleanT, floatT)); + assertFalse(tc.compatible(booleanT, doubleT)); + assertFalse(tc.compatible(byteT, booleanT)); + assertFalse(tc.compatible(byteT, shortT)); + assertFalse(tc.compatible(byteT, charT)); + assertFalse(tc.compatible(byteT, intT)); + assertFalse(tc.compatible(byteT, longT)); + assertFalse(tc.compatible(byteT, floatT)); + assertFalse(tc.compatible(byteT, doubleT)); + assertFalse(tc.compatible(shortT, booleanT)); + assertFalse(tc.compatible(shortT, charT)); + assertFalse(tc.compatible(shortT, intT)); + assertFalse(tc.compatible(shortT, longT)); + assertFalse(tc.compatible(shortT, floatT)); + assertFalse(tc.compatible(shortT, doubleT)); + assertFalse(tc.compatible(charT, booleanT)); + assertFalse(tc.compatible(charT, byteT)); + assertFalse(tc.compatible(charT, shortT)); + assertFalse(tc.compatible(charT, intT)); + assertFalse(tc.compatible(charT, longT)); + assertFalse(tc.compatible(charT, floatT)); + assertFalse(tc.compatible(charT, doubleT)); + assertFalse(tc.compatible(intT, booleanT)); + assertFalse(tc.compatible(intT, longT)); + assertFalse(tc.compatible(intT, floatT)); + assertFalse(tc.compatible(intT, doubleT)); + assertFalse(tc.compatible(longT, booleanT)); + assertFalse(tc.compatible(longT, floatT)); + assertFalse(tc.compatible(longT, doubleT)); + assertFalse(tc.compatible(floatT, booleanT)); + assertFalse(tc.compatible(floatT, doubleT)); + assertFalse(tc.compatible(doubleT, booleanT)); } @Test @@ -308,9 +307,9 @@ public void testCompatibilityForGenerics() { SymTypeExpression linkedlistOfPersonExpr = SymTypeExpressionFactory.createGenerics(linkedListSym, personExpr); // When & Then - Assertions.assertTrue(tc.compatible(listOfPersonExpr, listOfPersonExpr)); - Assertions.assertTrue(tc.compatible(listOfPersonExpr, personListExpr)); - Assertions.assertTrue(tc.compatible(listOfPersonExpr, linkedlistOfPersonExpr)); + assertTrue(tc.compatible(listOfPersonExpr, listOfPersonExpr)); + assertTrue(tc.compatible(listOfPersonExpr, personListExpr)); + assertTrue(tc.compatible(listOfPersonExpr, linkedlistOfPersonExpr)); } @Test @@ -333,13 +332,13 @@ public void testIncompatibilityForGenerics() { SymTypeExpression personListExpr = SymTypeExpressionFactory.createTypeObject(personListSym); // When & Then - Assertions.assertFalse(tc.compatible(listOfIntExpr, _intSymType)); - Assertions.assertFalse(tc.compatible(listOfIntExpr, listOfBoolExpr)); - Assertions.assertFalse(tc.compatible(listOfBoolExpr, listOfIntExpr)); - Assertions.assertFalse(tc.compatible(listOfBoolExpr, listOfPersonExpr)); - Assertions.assertFalse(tc.compatible(listOfPersonExpr, listOfBoolExpr)); - Assertions.assertFalse(tc.compatible(listOfBoolExpr, personListExpr)); - Assertions.assertFalse(tc.compatible(personListExpr, listOfBoolExpr)); + assertFalse(tc.compatible(listOfIntExpr, _intSymType)); + assertFalse(tc.compatible(listOfIntExpr, listOfBoolExpr)); + assertFalse(tc.compatible(listOfBoolExpr, listOfIntExpr)); + assertFalse(tc.compatible(listOfBoolExpr, listOfPersonExpr)); + assertFalse(tc.compatible(listOfPersonExpr, listOfBoolExpr)); + assertFalse(tc.compatible(listOfBoolExpr, personListExpr)); + assertFalse(tc.compatible(personListExpr, listOfBoolExpr)); } public CombineExpressionsWithLiteralsTraverser getTraverser(FlatExpressionScopeSetter flatExpressionScopeSetter){ diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/helpers/DefiningSymbolSetter4CommonExpressionsTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/helpers/DefiningSymbolSetter4CommonExpressionsTest.java index 7f43ee8abf..0f88eb5b95 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/helpers/DefiningSymbolSetter4CommonExpressionsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/helpers/DefiningSymbolSetter4CommonExpressionsTest.java @@ -9,10 +9,11 @@ import de.monticore.symboltable.ISymbol; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + public class DefiningSymbolSetter4CommonExpressionsTest { @BeforeEach @@ -42,8 +43,8 @@ public void setDefiningSymbolForNameExprTest() { definingSymbolSetter.setDefiningSymbol((ASTExpression) expr, symbol); // Then - Assertions.assertTrue(expr.getDefiningSymbol().isPresent()); - Assertions.assertSame(symbol, expr.getDefiningSymbol().get()); + assertTrue(expr.getDefiningSymbol().isPresent()); + assertSame(symbol, expr.getDefiningSymbol().get()); } @@ -71,10 +72,10 @@ public void setDefiningSymbolForFieldAccessExprTest() { definingSymbolSetter.setDefiningSymbol((ASTExpression) fieldAccessExpr, symbol); // Then - Assertions.assertTrue(fieldAccessExpr.getDefiningSymbol().isPresent()); - Assertions.assertSame(symbol, fieldAccessExpr.getDefiningSymbol().get()); + assertTrue(fieldAccessExpr.getDefiningSymbol().isPresent()); + assertSame(symbol, fieldAccessExpr.getDefiningSymbol().get()); - Assertions.assertFalse(qualExpr.getDefiningSymbol().isPresent()); + assertFalse(qualExpr.getDefiningSymbol().isPresent()); } @Test @@ -99,10 +100,10 @@ public void setDefiningSymbolForCallExprTest() { definingSymbolSetter.setDefiningSymbol((ASTExpression) callExpr, symbol); // Then - Assertions.assertTrue(callExpr.getDefiningSymbol().isPresent()); - Assertions.assertSame(symbol, callExpr.getDefiningSymbol().get()); + assertTrue(callExpr.getDefiningSymbol().isPresent()); + assertSame(symbol, callExpr.getDefiningSymbol().get()); - Assertions.assertFalse(methodNameExpr.getDefiningSymbol().isPresent()); + assertFalse(methodNameExpr.getDefiningSymbol().isPresent()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/helpers/SubExprNameExtractionResultTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/helpers/SubExprNameExtractionResultTest.java index dc47ae4c05..e766604b36 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/helpers/SubExprNameExtractionResultTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/helpers/SubExprNameExtractionResultTest.java @@ -5,7 +5,6 @@ import de.monticore.expressions.testcommonexpressions.TestCommonExpressionsMill; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,6 +12,8 @@ import java.util.List; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class SubExprNameExtractionResultTest { @BeforeEach @@ -41,8 +42,8 @@ public void resetCreatesNewList() { // Then List subExprListAfter = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(1, subExprListAfter.size()); - Assertions.assertNotEquals(subExprListBefore, subExprListAfter); + assertEquals(1, subExprListAfter.size()); + assertNotEquals(subExprListBefore, subExprListAfter); } @Test @@ -58,10 +59,10 @@ public void testSetSubExpressions() { // Then List returnedSubExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(1, returnedSubExprList.size()); - Assertions.assertEquals(nameToInsert, returnedSubExprList.get(0).getExpression()); - Assertions.assertEquals("a", returnedSubExprList.get(0).getName().orElse("no name inserted")); - Assertions.assertEquals(subExprList, returnedSubExprList); + assertEquals(1, returnedSubExprList.size()); + assertEquals(nameToInsert, returnedSubExprList.get(0).getExpression()); + assertEquals("a", returnedSubExprList.get(0).getName().orElse("no name inserted")); + assertEquals(subExprList, returnedSubExprList); } @Test @@ -75,9 +76,9 @@ public void maybeAppendInvalidSubExprToEmptyList() { // Then List subExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(1, subExprList.size()); - Assertions.assertEquals(expr, subExprList.get(0).getExpression()); - Assertions.assertFalse(subExprList.get(0).getName().isPresent()); + assertEquals(1, subExprList.size()); + assertEquals(expr, subExprList.get(0).getExpression()); + assertFalse(subExprList.get(0).getName().isPresent()); } @Test @@ -92,13 +93,13 @@ public void maybeAppendInvalidSubExprToFilledListContainingDifferentValidNameExp // Then List subExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(2, subExprList.size()); + assertEquals(2, subExprList.size()); - Assertions.assertEquals(newExpr, subExprList.get(0).getExpression()); - Assertions.assertFalse(subExprList.get(0).getName().isPresent()); + assertEquals(newExpr, subExprList.get(0).getExpression()); + assertFalse(subExprList.get(0).getName().isPresent()); - Assertions.assertEquals(oldExpr, subExprList.get(1).getExpression()); - Assertions.assertEquals("a", subExprList.get(1).getName().orElse("no name inserted")); + assertEquals(oldExpr, subExprList.get(1).getExpression()); + assertEquals("a", subExprList.get(1).getName().orElse("no name inserted")); } @Test @@ -113,13 +114,13 @@ public void maybeAppendInvalidSubExprToFilledListContainingDifferentInvalidNameE // Then List subExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(2, subExprList.size()); + assertEquals(2, subExprList.size()); - Assertions.assertEquals(newExpr, subExprList.get(0).getExpression()); - Assertions.assertFalse(subExprList.get(0).getName().isPresent()); + assertEquals(newExpr, subExprList.get(0).getExpression()); + assertFalse(subExprList.get(0).getName().isPresent()); - Assertions.assertEquals(oldExpr, subExprList.get(1).getExpression()); - Assertions.assertFalse(subExprList.get(1).getName().isPresent()); + assertEquals(oldExpr, subExprList.get(1).getExpression()); + assertFalse(subExprList.get(1).getName().isPresent()); } @Test @@ -134,9 +135,9 @@ public void maybeAppendInvalidSubExprDoesNotOverwriteSameExpression() { // Then List subExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(1, subExprList.size()); - Assertions.assertEquals(expr, subExprList.get(0).getExpression()); - Assertions.assertEquals("a", subExprList.get(0).getName().orElse("no name inserted")); + assertEquals(1, subExprList.size()); + assertEquals(expr, subExprList.get(0).getExpression()); + assertEquals("a", subExprList.get(0).getName().orElse("no name inserted")); } @Test @@ -150,9 +151,9 @@ public void putNameAtStartOfEmptyList() { // Then List subExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(1, subExprList.size()); - Assertions.assertEquals(expr, subExprList.get(0).getExpression()); - Assertions.assertEquals("a", subExprList.get(0).getName().orElse("no name inserted")); + assertEquals(1, subExprList.size()); + assertEquals(expr, subExprList.get(0).getExpression()); + assertEquals("a", subExprList.get(0).getName().orElse("no name inserted")); } @Test @@ -169,13 +170,13 @@ public void putNameAtStartOfFilledListContainingDifferentValidExpressions() { // Then List subExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(2, subExprList.size()); + assertEquals(2, subExprList.size()); - Assertions.assertEquals(newExpr, subExprList.get(0).getExpression()); - Assertions.assertEquals("b", subExprList.get(0).getName().orElse("no name inserted")); + assertEquals(newExpr, subExprList.get(0).getExpression()); + assertEquals("b", subExprList.get(0).getName().orElse("no name inserted")); - Assertions.assertEquals(oldExpr, subExprList.get(1).getExpression()); - Assertions.assertEquals("a", subExprList.get(1).getName().orElse("no name inserted")); + assertEquals(oldExpr, subExprList.get(1).getExpression()); + assertEquals("a", subExprList.get(1).getName().orElse("no name inserted")); } @Test @@ -192,13 +193,13 @@ public void putNameAtStartOverwritesSameExpressionThatHasNoNameYet() { // Then List subExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(2, subExprList.size()); + assertEquals(2, subExprList.size()); - Assertions.assertEquals(expr, subExprList.get(0).getExpression()); - Assertions.assertEquals("b", subExprList.get(0).getName().orElse("no name inserted")); + assertEquals(expr, subExprList.get(0).getExpression()); + assertEquals("b", subExprList.get(0).getName().orElse("no name inserted")); - Assertions.assertEquals(dummyExprNotToAlter, subExprList.get(1).getExpression()); - Assertions.assertFalse(subExprList.get(1).getName().isPresent()); + assertEquals(dummyExprNotToAlter, subExprList.get(1).getExpression()); + assertFalse(subExprList.get(1).getName().isPresent()); } @Test @@ -215,13 +216,13 @@ public void putNameAtStartOverwritesSameExpressionThatAlreadyHasAName() { // Then List subExprList = extractionResult.getNamePartsRaw(); - Assertions.assertEquals(2, subExprList.size()); + assertEquals(2, subExprList.size()); - Assertions.assertEquals(expr, subExprList.get(0).getExpression()); - Assertions.assertEquals("b", subExprList.get(0).getName().orElse("no name inserted")); + assertEquals(expr, subExprList.get(0).getExpression()); + assertEquals("b", subExprList.get(0).getName().orElse("no name inserted")); - Assertions.assertEquals(dummyExprNotToAlter, subExprList.get(1).getExpression()); - Assertions.assertFalse(subExprList.get(1).getName().isPresent()); + assertEquals(dummyExprNotToAlter, subExprList.get(1).getExpression()); + assertFalse(subExprList.get(1).getName().isPresent()); } @Test @@ -233,7 +234,7 @@ public void getNamePartsIfValidOnEmptyNameList() { Optional> subExprList = extractionResult.getNamePartsIfValid(); // Then - Assertions.assertFalse(subExprList.isPresent()); + assertFalse(subExprList.isPresent()); } @Test @@ -253,7 +254,7 @@ public void getNamePartsIfValidOnFilledInvalidNameList() { Optional> subExprList = extractionResult.getNamePartsIfValid(); // Then - Assertions.assertFalse(subExprList.isPresent()); + assertFalse(subExprList.isPresent()); } @Test @@ -271,14 +272,14 @@ public void getNamePartsIfValidOnValidNameList() { Optional> subExprList = extractionResult.getNamePartsIfValid(); // Then - Assertions.assertTrue(subExprList.isPresent()); - Assertions.assertEquals(2, subExprList.get().size()); + assertTrue(subExprList.isPresent()); + assertEquals(2, subExprList.get().size()); - Assertions.assertEquals(bExpr, subExprList.get().get(0).getExpression()); - Assertions.assertEquals("b", subExprList.get().get(0).getName()); + assertEquals(bExpr, subExprList.get().get(0).getExpression()); + assertEquals("b", subExprList.get().get(0).getName()); - Assertions.assertEquals(aExpr, subExprList.get().get(1).getExpression()); - Assertions.assertEquals("a", subExprList.get().get(1).getName()); + assertEquals(aExpr, subExprList.get().get(1).getExpression()); + assertEquals("a", subExprList.get().get(1).getName()); } @Test @@ -290,7 +291,7 @@ public void getNamePartsRawOnEmptyList() { List subExprList = extractionResult.getNamePartsRaw(); // Then - Assertions.assertTrue(subExprList.isEmpty()); + assertTrue(subExprList.isEmpty()); } @Test @@ -309,15 +310,15 @@ public void getNamePartsRawOnFilledList() { List subExprList = extractionResult.getNamePartsRaw(); // Then - Assertions.assertEquals(3, subExprList.size()); + assertEquals(3, subExprList.size()); - Assertions.assertEquals(cExpr, subExprList.get(0).getExpression()); - Assertions.assertEquals(bExpr, subExprList.get(1).getExpression()); - Assertions.assertEquals(aExpr, subExprList.get(2).getExpression()); + assertEquals(cExpr, subExprList.get(0).getExpression()); + assertEquals(bExpr, subExprList.get(1).getExpression()); + assertEquals(aExpr, subExprList.get(2).getExpression()); - Assertions.assertEquals("c", subExprList.get(0).getName().orElse("no name was inserted")); - Assertions.assertFalse(subExprList.get(1).getName().isPresent()); - Assertions.assertEquals("a", subExprList.get(2).getName().orElse("no name was inserted")); + assertEquals("c", subExprList.get(0).getName().orElse("no name was inserted")); + assertFalse(subExprList.get(1).getName().isPresent()); + assertEquals("a", subExprList.get(2).getName().orElse("no name was inserted")); } @Test @@ -329,7 +330,7 @@ public void getLastNameOnEmptyList() { Optional lastName = extractionResult.getLastName(); // Then - Assertions.assertFalse(lastName.isPresent()); + assertFalse(lastName.isPresent()); } @Test @@ -346,7 +347,7 @@ public void getLastNameOnAbsentName() { Optional lastName = extractionResult.getLastName(); // Then - Assertions.assertFalse(lastName.isPresent()); + assertFalse(lastName.isPresent()); } @Test @@ -363,8 +364,8 @@ public void getLastNameOnValidLastName() { Optional lastName = extractionResult.getLastName(); // Then - Assertions.assertTrue(lastName.isPresent()); - Assertions.assertEquals("a", lastName.get()); + assertTrue(lastName.isPresent()); + assertEquals("a", lastName.get()); } @Test @@ -376,7 +377,7 @@ public void resultIsValidNameOnEmptyNameList() { boolean resultIsValidName = extractionResult.resultIsValidName(); // Then - Assertions.assertFalse(resultIsValidName); + assertFalse(resultIsValidName); } @Test @@ -395,7 +396,7 @@ public void resultIsValidNameOnInvalidNameList() { boolean resultIsValidName = extractionResult.resultIsValidName(); // Then - Assertions.assertFalse(resultIsValidName); + assertFalse(resultIsValidName); } @Test @@ -413,7 +414,7 @@ public void resultIsValidOnValidNameList() { boolean resultIsValidName = extractionResult.resultIsValidName(); // Then - Assertions.assertTrue(resultIsValidName); + assertTrue(resultIsValidName); } @Test @@ -437,14 +438,14 @@ public void testCopy() { // Then List originalExpressions = originalResult.getNamePartsRaw(); List copiedSubExpressions = copiedResult.getNamePartsRaw(); - Assertions.assertNotEquals(originalExpressions, copiedSubExpressions); + assertNotEquals(originalExpressions, copiedSubExpressions); - Assertions.assertEquals(3, copiedSubExpressions.size()); - Assertions.assertEquals(cExpr, copiedSubExpressions.get(0).getExpression()); - Assertions.assertEquals(bExpr, copiedSubExpressions.get(1).getExpression()); - Assertions.assertEquals(aExpr, copiedSubExpressions.get(2).getExpression()); + assertEquals(3, copiedSubExpressions.size()); + assertEquals(cExpr, copiedSubExpressions.get(0).getExpression()); + assertEquals(bExpr, copiedSubExpressions.get(1).getExpression()); + assertEquals(aExpr, copiedSubExpressions.get(2).getExpression()); - Assertions.assertEquals(1, originalExpressions.size()); - Assertions.assertEquals(dExpr, originalExpressions.get(0).getExpression()); + assertEquals(1, originalExpressions.size()); + assertEquals(dExpr, originalExpressions.get(0).getExpression()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/check/helpers/SubExprNameExtractor4CommonExpressionsTest.java b/monticore-grammar/src/test/java/de/monticore/types/check/helpers/SubExprNameExtractor4CommonExpressionsTest.java index 08f3660493..c53cacb52a 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/check/helpers/SubExprNameExtractor4CommonExpressionsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/check/helpers/SubExprNameExtractor4CommonExpressionsTest.java @@ -8,13 +8,14 @@ import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + public class SubExprNameExtractor4CommonExpressionsTest { private CombineExpressionsWithLiteralsParser parser = new CombineExpressionsWithLiteralsParser(); @@ -41,12 +42,12 @@ public void nameTest() throws IOException { SubExprNameExtractionResult result = nameCalculator.calculateNameParts(methodNameExpr); // Then - Assertions.assertTrue(result.resultIsValidName()); - Assertions.assertEquals(1, result.getNamePartsRaw().size()); - Assertions.assertEquals("test", result.getLastName().get()); - Assertions.assertEquals(methodNameExpr, result.getNamePartsIfValid().get().get(0).getExpression()); + assertTrue(result.resultIsValidName()); + assertEquals(1, result.getNamePartsRaw().size()); + assertEquals("test", result.getLastName().get()); + assertEquals(methodNameExpr, result.getNamePartsIfValid().get().get(0).getExpression()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } /** @@ -63,15 +64,15 @@ public void fieldAccessTest() throws IOException { SubExprNameExtractionResult result = nameCalculator.calculateNameParts(methodNameExpr); // Then - Assertions.assertTrue(result.resultIsValidName()); + assertTrue(result.resultIsValidName()); List nameParts = result.getNamePartsIfValid().get(); - Assertions.assertEquals(3, result.getNamePartsRaw().size()); - Assertions.assertEquals("test", result.getLastName().get()); - Assertions.assertEquals(methodNameExpr, nameParts.get(nameParts.size() - 1).getExpression()); - Assertions.assertEquals(((ASTFieldAccessExpression) methodNameExpr).getExpression(), nameParts.get(nameParts.size() - 2).getExpression()); + assertEquals(3, result.getNamePartsRaw().size()); + assertEquals("test", result.getLastName().get()); + assertEquals(methodNameExpr, nameParts.get(nameParts.size() - 1).getExpression()); + assertEquals(((ASTFieldAccessExpression) methodNameExpr).getExpression(), nameParts.get(nameParts.size() - 2).getExpression()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -85,17 +86,17 @@ public void methodChainTest() throws IOException { SubExprNameExtractionResult result = nameCalculator.calculateNameParts(methodNameExpr); // Then - Assertions.assertFalse(result.resultIsValidName()); - Assertions.assertTrue(result.getLastName().isPresent()); + assertFalse(result.resultIsValidName()); + assertTrue(result.getLastName().isPresent()); List subExprs = result.getNamePartsRaw(); - Assertions.assertEquals(3, result.getNamePartsRaw().size()); // tezt NameExpr, tezt() CallExpr, tezt().test fAccExpr - Assertions.assertEquals("test", result.getLastName().get()); - Assertions.assertEquals(methodNameExpr, subExprs.get(subExprs.size() - 1).getExpression()); - Assertions.assertEquals(((ASTFieldAccessExpression) methodNameExpr).getExpression(), subExprs.get(subExprs.size() - 2).getExpression()); + assertEquals(3, result.getNamePartsRaw().size()); // tezt NameExpr, tezt() CallExpr, tezt().test fAccExpr + assertEquals("test", result.getLastName().get()); + assertEquals(methodNameExpr, subExprs.get(subExprs.size() - 1).getExpression()); + assertEquals(((ASTFieldAccessExpression) methodNameExpr).getExpression(), subExprs.get(subExprs.size() - 2).getExpression()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/helper/MCArrayTypesNodeIdentHelperTest.java b/monticore-grammar/src/test/java/de/monticore/types/helper/MCArrayTypesNodeIdentHelperTest.java index 5659e6e865..664a8b2365 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/helper/MCArrayTypesNodeIdentHelperTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/helper/MCArrayTypesNodeIdentHelperTest.java @@ -9,15 +9,13 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MCArrayTypesNodeIdentHelperTest { @@ -36,12 +34,12 @@ public void testGetIdent() throws IOException { Optional astmcArrayType = p.parse_StringMCType("A[]"); - Assertions.assertTrue(astmcArrayType.isPresent()); - Assertions.assertTrue(astmcArrayType.get() instanceof ASTMCArrayType); + assertTrue(astmcArrayType.isPresent()); + assertInstanceOf(ASTMCArrayType.class, astmcArrayType.get()); - Assertions.assertEquals("@A!MCArrayType", identHelper.getIdent((ASTMCArrayType)astmcArrayType.get())); + assertEquals("@A!MCArrayType", identHelper.getIdent((ASTMCArrayType)astmcArrayType.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/helper/MCBasicTypesHelperTest.java b/monticore-grammar/src/test/java/de/monticore/types/helper/MCBasicTypesHelperTest.java index cc1bcb1c99..bcbb84c177 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/helper/MCBasicTypesHelperTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/helper/MCBasicTypesHelperTest.java @@ -6,12 +6,11 @@ import de.monticore.types.mcbasictypes._ast.ASTConstantsMCBasicTypes; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCBasicTypesHelperTest { @@ -25,17 +24,17 @@ public void init() { @Test public void testGetPrimitive(){ - Assertions.assertEquals(ASTConstantsMCBasicTypes.BOOLEAN, MCBasicTypesHelper.primitiveName2Const("boolean")); - Assertions.assertEquals(-1, MCBasicTypesHelper.primitiveName2Const(null)); - Assertions.assertEquals(-1, MCBasicTypesHelper.primitiveName2Const("")); - Assertions.assertEquals(ASTConstantsMCBasicTypes.BYTE, MCBasicTypesHelper.primitiveName2Const("byte")); - Assertions.assertEquals(ASTConstantsMCBasicTypes.CHAR, MCBasicTypesHelper.primitiveName2Const("char")); - Assertions.assertEquals(ASTConstantsMCBasicTypes.DOUBLE, MCBasicTypesHelper.primitiveName2Const("double")); - Assertions.assertEquals(ASTConstantsMCBasicTypes.FLOAT, MCBasicTypesHelper.primitiveName2Const("float")); - Assertions.assertEquals(ASTConstantsMCBasicTypes.INT, MCBasicTypesHelper.primitiveName2Const("int")); - Assertions.assertEquals(ASTConstantsMCBasicTypes.LONG, MCBasicTypesHelper.primitiveName2Const("long")); - Assertions.assertEquals(ASTConstantsMCBasicTypes.SHORT, MCBasicTypesHelper.primitiveName2Const("short")); + assertEquals(ASTConstantsMCBasicTypes.BOOLEAN, MCBasicTypesHelper.primitiveName2Const("boolean")); + assertEquals(-1, MCBasicTypesHelper.primitiveName2Const(null)); + assertEquals(-1, MCBasicTypesHelper.primitiveName2Const("")); + assertEquals(ASTConstantsMCBasicTypes.BYTE, MCBasicTypesHelper.primitiveName2Const("byte")); + assertEquals(ASTConstantsMCBasicTypes.CHAR, MCBasicTypesHelper.primitiveName2Const("char")); + assertEquals(ASTConstantsMCBasicTypes.DOUBLE, MCBasicTypesHelper.primitiveName2Const("double")); + assertEquals(ASTConstantsMCBasicTypes.FLOAT, MCBasicTypesHelper.primitiveName2Const("float")); + assertEquals(ASTConstantsMCBasicTypes.INT, MCBasicTypesHelper.primitiveName2Const("int")); + assertEquals(ASTConstantsMCBasicTypes.LONG, MCBasicTypesHelper.primitiveName2Const("long")); + assertEquals(ASTConstantsMCBasicTypes.SHORT, MCBasicTypesHelper.primitiveName2Const("short")); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/helper/MCBasicTypesNodeIdentHelperTest.java b/monticore-grammar/src/test/java/de/monticore/types/helper/MCBasicTypesNodeIdentHelperTest.java index bd2ab6e86b..d7a04f9700 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/helper/MCBasicTypesNodeIdentHelperTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/helper/MCBasicTypesNodeIdentHelperTest.java @@ -7,13 +7,14 @@ import de.monticore.types.mcbasictypestest._parser.MCBasicTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCBasicTypesNodeIdentHelperTest { @BeforeEach @@ -34,23 +35,23 @@ public void testGetIdent() throws IOException { Optional astmcReturnType = parser.parse_StringMCReturnType("float"); Optional astmcReturnTypeVoid = parser.parse_StringMCReturnType("void"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astmcQualifiedName.isPresent()); - Assertions.assertTrue(astmcPrimitiveType.isPresent()); - Assertions.assertTrue(astmcQualifiedType.isPresent()); - Assertions.assertTrue(astmcVoidType.isPresent()); - Assertions.assertTrue(astmcReturnType.isPresent()); - Assertions.assertTrue(astmcReturnTypeVoid.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astmcQualifiedName.isPresent()); + assertTrue(astmcPrimitiveType.isPresent()); + assertTrue(astmcQualifiedType.isPresent()); + assertTrue(astmcVoidType.isPresent()); + assertTrue(astmcReturnType.isPresent()); + assertTrue(astmcReturnTypeVoid.isPresent()); MCBasicTypesNodeIdentHelper helper = new MCBasicTypesNodeIdentHelper(); - Assertions.assertEquals("@java.util.List!MCQualifiedName", helper.getIdent(astmcQualifiedName.get())); - Assertions.assertEquals("@int!MCPrimitiveType", helper.getIdent(astmcPrimitiveType.get())); - Assertions.assertEquals("@java.util.Set!MCQualifiedType", helper.getIdent(astmcQualifiedType.get())); - Assertions.assertEquals("@void!MCVoidType", helper.getIdent(astmcVoidType.get())); - Assertions.assertEquals("@float!MCPrimitiveType", helper.getIdent(astmcReturnType.get())); - Assertions.assertEquals("@void!MCVoidType", helper.getIdent(astmcReturnTypeVoid.get())); + assertEquals("@java.util.List!MCQualifiedName", helper.getIdent(astmcQualifiedName.get())); + assertEquals("@int!MCPrimitiveType", helper.getIdent(astmcPrimitiveType.get())); + assertEquals("@java.util.Set!MCQualifiedType", helper.getIdent(astmcQualifiedType.get())); + assertEquals("@void!MCVoidType", helper.getIdent(astmcVoidType.get())); + assertEquals("@float!MCPrimitiveType", helper.getIdent(astmcReturnType.get())); + assertEquals("@void!MCVoidType", helper.getIdent(astmcReturnTypeVoid.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/helper/MCCollectionTypesNodeIdentHelperTest.java b/monticore-grammar/src/test/java/de/monticore/types/helper/MCCollectionTypesNodeIdentHelperTest.java index 78cf135a34..a9ae603a6c 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/helper/MCCollectionTypesNodeIdentHelperTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/helper/MCCollectionTypesNodeIdentHelperTest.java @@ -9,13 +9,14 @@ import de.monticore.types.mccollectiontypestest._parser.MCCollectionTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCCollectionTypesNodeIdentHelperTest { @BeforeEach @@ -36,20 +37,20 @@ public void testGetIdent() throws IOException { Optional astmcBasicTypeArgument = parser.parse_StringMCBasicTypeArgument("a.B.C"); Optional astmcPrimitiveTypeArgument = parser.parse_StringMCPrimitiveTypeArgument("boolean"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astmcGenericType.isPresent()); - Assertions.assertTrue(astmcGenericType1.isPresent()); - Assertions.assertTrue(astmcGenericType2.isPresent()); - Assertions.assertTrue(astmcGenericType3.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astmcGenericType.isPresent()); + assertTrue(astmcGenericType1.isPresent()); + assertTrue(astmcGenericType2.isPresent()); + assertTrue(astmcGenericType3.isPresent()); MCCollectionTypesNodeIdentHelper helper = new MCCollectionTypesNodeIdentHelper(); - Assertions.assertEquals("@Map!MCMapType", helper.getIdent(astmcGenericType.get())); - Assertions.assertEquals("@List!MCListType", helper.getIdent(astmcGenericType1.get())); - Assertions.assertEquals("@Set!MCSetType", helper.getIdent(astmcGenericType2.get())); - Assertions.assertEquals("@Optional!MCOptionalType", helper.getIdent(astmcGenericType3.get())); - Assertions.assertEquals("@a.B.C!MCBasicTypeArgument", helper.getIdent(astmcBasicTypeArgument.get())); - Assertions.assertEquals("@boolean!MCPrimitiveTypeArgument", helper.getIdent(astmcPrimitiveTypeArgument.get())); + assertEquals("@Map!MCMapType", helper.getIdent(astmcGenericType.get())); + assertEquals("@List!MCListType", helper.getIdent(astmcGenericType1.get())); + assertEquals("@Set!MCSetType", helper.getIdent(astmcGenericType2.get())); + assertEquals("@Optional!MCOptionalType", helper.getIdent(astmcGenericType3.get())); + assertEquals("@a.B.C!MCBasicTypeArgument", helper.getIdent(astmcBasicTypeArgument.get())); + assertEquals("@boolean!MCPrimitiveTypeArgument", helper.getIdent(astmcPrimitiveTypeArgument.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/helper/MCFullGenericTypesNodeIdentHelperTest.java b/monticore-grammar/src/test/java/de/monticore/types/helper/MCFullGenericTypesNodeIdentHelperTest.java index e27d3187bb..4992f73435 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/helper/MCFullGenericTypesNodeIdentHelperTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/helper/MCFullGenericTypesNodeIdentHelperTest.java @@ -8,15 +8,14 @@ import de.monticore.types.mcfullgenerictypestest._parser.MCFullGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCFullGenericTypesNodeIdentHelperTest { @@ -34,11 +33,11 @@ public void testGetIdent() throws IOException { MCFullGenericTypesNodeIdentHelper identHelper = new MCFullGenericTypesNodeIdentHelper(); Optional astmcMultipleGenericType = p.parse_StringMCMultipleGenericType("a.b.D.d.E"); - Assertions.assertTrue(astmcMultipleGenericType.isPresent()); + assertTrue(astmcMultipleGenericType.isPresent()); - Assertions.assertEquals("@a.b.D.d.E!MCMultipleGenericType", identHelper.getIdent(astmcMultipleGenericType.get())); + assertEquals("@a.b.D.d.E!MCMultipleGenericType", identHelper.getIdent(astmcMultipleGenericType.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/helper/MCSimpleGenericTypesNodeIdentHelperTest.java b/monticore-grammar/src/test/java/de/monticore/types/helper/MCSimpleGenericTypesNodeIdentHelperTest.java index 9cec87751a..bf486d6cdb 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/helper/MCSimpleGenericTypesNodeIdentHelperTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/helper/MCSimpleGenericTypesNodeIdentHelperTest.java @@ -7,14 +7,13 @@ import de.monticore.types.mcsimplegenerictypestest._parser.MCSimpleGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; public class MCSimpleGenericTypesNodeIdentHelperTest { @@ -35,19 +34,19 @@ public void testGetIdent() throws IOException { Optional astmcType3 = parser.parse_StringMCBasicGenericType("java.util.Optional"); Optional astmcType4 = parser.parse_StringMCBasicGenericType("a.b.c.D"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astmcType.isPresent()); - Assertions.assertTrue(astmcType1.isPresent()); - Assertions.assertTrue(astmcType2.isPresent()); - Assertions.assertTrue(astmcType3.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astmcType.isPresent()); + assertTrue(astmcType1.isPresent()); + assertTrue(astmcType2.isPresent()); + assertTrue(astmcType3.isPresent()); MCSimpleGenericTypesNodeIdentHelper helper = new MCSimpleGenericTypesNodeIdentHelper(); - Assertions.assertEquals("@List!MCBasicGenericType", helper.getIdent(astmcType.get())); - Assertions.assertEquals("@java.util.List!MCBasicGenericType", helper.getIdent(astmcType1.get())); - Assertions.assertEquals("@Optional!MCBasicGenericType", helper.getIdent(astmcType2.get())); - Assertions.assertEquals("@java.util.Optional!MCBasicGenericType", helper.getIdent(astmcType3.get())); - Assertions.assertEquals("@a.b.c.D!MCBasicGenericType", helper.getIdent(astmcType4.get())); + assertEquals("@List!MCBasicGenericType", helper.getIdent(astmcType.get())); + assertEquals("@java.util.List!MCBasicGenericType", helper.getIdent(astmcType1.get())); + assertEquals("@Optional!MCBasicGenericType", helper.getIdent(astmcType2.get())); + assertEquals("@java.util.Optional!MCBasicGenericType", helper.getIdent(astmcType3.get())); + assertEquals("@a.b.c.D!MCBasicGenericType", helper.getIdent(astmcType4.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/helper/MCType2SymTypeExpressionTest.java b/monticore-grammar/src/test/java/de/monticore/types/helper/MCType2SymTypeExpressionTest.java index 10b3f39ba6..11ee8c73dd 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/helper/MCType2SymTypeExpressionTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/helper/MCType2SymTypeExpressionTest.java @@ -18,7 +18,6 @@ import de.monticore.types.mcsimplegenerictypes._ast.ASTMCBasicGenericType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,8 +26,7 @@ import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MCType2SymTypeExpressionTest { @@ -113,81 +111,81 @@ private SymTypeExpression mcType2TypeExpression(ASTMCQualifiedName qName){ @Test public void testBasicGeneric() throws IOException { Optional type = new MCFullGenericTypesTestParser().parse_StringMCBasicGenericType("de.util.Pair"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression listSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(listSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("de.util.Pair", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, listSymTypeExpression); + assertEquals("de.util.Pair", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression keyTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(keyTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.PairA", keyTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, keyTypeArgument); + assertEquals("de.mc.PairA", keyTypeArgument.printFullName()); SymTypeExpression valueTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(1); - Assertions.assertTrue(valueTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.PairB", valueTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, valueTypeArgument); + assertEquals("de.mc.PairB", valueTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testBasicGenericRekursiv() throws IOException { Optional type = new MCFullGenericTypesTestParser().parse_StringMCBasicGenericType("de.util.Pair>"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression listSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(listSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("de.util.Pair", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, listSymTypeExpression); + assertEquals("de.util.Pair", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression keyTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(keyTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.PairA", keyTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, keyTypeArgument); + assertEquals("de.mc.PairA", keyTypeArgument.printFullName()); SymTypeExpression valueTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(1); - Assertions.assertTrue(valueTypeArgument instanceof SymTypeOfGenerics); - Assertions.assertEquals("de.util.Pair2", ((SymTypeOfGenerics) valueTypeArgument).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, valueTypeArgument); + assertEquals("de.util.Pair2", ((SymTypeOfGenerics) valueTypeArgument).getTypeConstructorFullName()); SymTypeOfGenerics valueTypeArg = (SymTypeOfGenerics) valueTypeArgument; SymTypeExpression argument1 = valueTypeArg.getArgumentList().get(0); - Assertions.assertEquals("de.mc.PairB", argument1.printFullName()); + assertEquals("de.mc.PairB", argument1.printFullName()); SymTypeExpression argument2 = valueTypeArg.getArgumentList().get(1); - Assertions.assertEquals("de.mc.PairC", argument2.printFullName()); + assertEquals("de.mc.PairC", argument2.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMap() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCMapType("Map"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression listSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(listSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("Map", listSymTypeExpression.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, listSymTypeExpression); + assertEquals("Map", listSymTypeExpression.printFullName()); SymTypeExpression keyTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(keyTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.PersonKey", keyTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, keyTypeArgument); + assertEquals("de.mc.PersonKey", keyTypeArgument.printFullName()); SymTypeExpression valueTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(1); - Assertions.assertTrue(valueTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.PersonValue", valueTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, valueTypeArgument); + assertEquals("de.mc.PersonValue", valueTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMapUnqualified() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCMapType("Map"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression listSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(listSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("Map", listSymTypeExpression.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, listSymTypeExpression); + assertEquals("Map", listSymTypeExpression.printFullName()); SymTypeExpression keyTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(keyTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("PersonKey", keyTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, keyTypeArgument); + assertEquals("PersonKey", keyTypeArgument.printFullName()); SymTypeExpression valueTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(1); - Assertions.assertTrue(valueTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("PersonValue", valueTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, valueTypeArgument); + assertEquals("PersonValue", valueTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -195,156 +193,156 @@ public void testMapPrimitives() throws IOException { for (String primitiveKey : primitiveTypes) { for (String primitiveValue : primitiveTypes) { Optional type = new MCCollectionTypesTestParser().parse_StringMCMapType("Map<" + primitiveKey + "," + primitiveValue + ">"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression listSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(listSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals(("Map<" + primitiveKey + "," + primitiveValue + ">"), listSymTypeExpression.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, listSymTypeExpression); + assertEquals(("Map<" + primitiveKey + "," + primitiveValue + ">"), listSymTypeExpression.printFullName()); SymTypeExpression keyTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(keyTypeArgument instanceof SymTypePrimitive); - Assertions.assertEquals(primitiveKey, keyTypeArgument.printFullName()); + assertInstanceOf(SymTypePrimitive.class, keyTypeArgument); + assertEquals(primitiveKey, keyTypeArgument.printFullName()); SymTypeExpression valueTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(1); - Assertions.assertTrue(valueTypeArgument instanceof SymTypePrimitive); - Assertions.assertEquals(primitiveValue, valueTypeArgument.printFullName()); + assertInstanceOf(SymTypePrimitive.class, valueTypeArgument); + assertEquals(primitiveValue, valueTypeArgument.printFullName()); } } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testOptional() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCOptionalType("Optional"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression optSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(optSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("Optional", ((SymTypeOfGenerics) optSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, optSymTypeExpression); + assertEquals("Optional", ((SymTypeOfGenerics) optSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) optSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.Person", listTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, listTypeArgument); + assertEquals("de.mc.Person", listTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testOptionalUnqualified() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCOptionalType("Optional"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression optSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(optSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("Optional", ((SymTypeOfGenerics) optSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, optSymTypeExpression); + assertEquals("Optional", ((SymTypeOfGenerics) optSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) optSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("Person", listTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, listTypeArgument); + assertEquals("Person", listTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testOptionalPrimitive() throws IOException { for (String primitive : primitiveTypes) { Optional type = new MCCollectionTypesTestParser().parse_StringMCOptionalType("Optional<" + primitive + ">"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression optSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(optSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("Optional", ((SymTypeOfGenerics) optSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, optSymTypeExpression); + assertEquals("Optional", ((SymTypeOfGenerics) optSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) optSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypePrimitive); - Assertions.assertEquals(primitive, listTypeArgument.printFullName()); + assertInstanceOf(SymTypePrimitive.class, listTypeArgument); + assertEquals(primitive, listTypeArgument.printFullName()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSet() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCSetType("Set"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression setSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(setSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("Set", ((SymTypeOfGenerics) setSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, setSymTypeExpression); + assertEquals("Set", ((SymTypeOfGenerics) setSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) setSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.Person", listTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, listTypeArgument); + assertEquals("de.mc.Person", listTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSetUnqualified() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCSetType("Set"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression setSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(setSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("Set", ((SymTypeOfGenerics) setSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, setSymTypeExpression); + assertEquals("Set", ((SymTypeOfGenerics) setSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) setSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("Person", listTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, listTypeArgument); + assertEquals("Person", listTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testSetPrimitives() throws IOException { for (String primitive : primitiveTypes) { Optional type = new MCCollectionTypesTestParser().parse_StringMCSetType("Set<" + primitive + ">"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression setSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(setSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("Set", ((SymTypeOfGenerics) setSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, setSymTypeExpression); + assertEquals("Set", ((SymTypeOfGenerics) setSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) setSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypePrimitive); - Assertions.assertEquals(primitive, listTypeArgument.printFullName()); + assertInstanceOf(SymTypePrimitive.class, listTypeArgument); + assertEquals(primitive, listTypeArgument.printFullName()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testList() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCListType("List"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression listSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(listSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("List", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, listSymTypeExpression); + assertEquals("List", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.Person", listTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, listTypeArgument); + assertEquals("de.mc.Person", listTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testListUnqualified() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCListType("List"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression listSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(listSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("List", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, listSymTypeExpression); + assertEquals("List", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypeOfObject); - Assertions.assertEquals("Person", listTypeArgument.printFullName()); + assertInstanceOf(SymTypeOfObject.class, listTypeArgument); + assertEquals("Person", listTypeArgument.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testListPrimitive() throws IOException { for (String primitive : primitiveTypes) { Optional type = new MCCollectionTypesTestParser().parse_StringMCListType("List<" + primitive + ">"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); SymTypeExpression listSymTypeExpression = mcType2TypeExpression(type.get()); - Assertions.assertTrue(listSymTypeExpression instanceof SymTypeOfGenerics); - Assertions.assertEquals("List", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); + assertInstanceOf(SymTypeOfGenerics.class, listSymTypeExpression); + assertEquals("List", ((SymTypeOfGenerics) listSymTypeExpression).getTypeConstructorFullName()); SymTypeExpression listTypeArgument = ((SymTypeOfGenerics) listSymTypeExpression).getArgumentList().get(0); - Assertions.assertTrue(listTypeArgument instanceof SymTypePrimitive); - Assertions.assertEquals(primitive, listTypeArgument.printFullName()); + assertInstanceOf(SymTypePrimitive.class, listTypeArgument); + assertEquals(primitive, listTypeArgument.printFullName()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -352,75 +350,75 @@ public void testListPrimitive() throws IOException { public void testPrimitives() throws IOException { for (String primitive : primitiveTypes) { Optional type = new MCCollectionTypesTestParser().parse_StringMCPrimitiveType(primitive); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); ASTMCPrimitiveType booleanType = type.get(); SymTypeExpression symTypeExpression = mcType2TypeExpression(booleanType); - Assertions.assertTrue(symTypeExpression instanceof SymTypePrimitive); - Assertions.assertEquals(primitive, symTypeExpression.printFullName()); + assertInstanceOf(SymTypePrimitive.class, symTypeExpression); + assertEquals(primitive, symTypeExpression.printFullName()); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testVoid() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCVoidType("void"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); ASTMCVoidType booleanType = type.get(); SymTypeExpression symTypeExpression = mcType2TypeExpression(booleanType); - Assertions.assertTrue(symTypeExpression instanceof SymTypeVoid); - Assertions.assertEquals("void", symTypeExpression.printFullName()); + assertInstanceOf(SymTypeVoid.class, symTypeExpression); + assertEquals("void", symTypeExpression.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testQualifiedType() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCQualifiedType("de.mc.Person"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); ASTMCQualifiedType qualifiedType = type.get(); SymTypeExpression symTypeExpression = mcType2TypeExpression(qualifiedType); - Assertions.assertTrue(symTypeExpression instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.Person", symTypeExpression.printFullName()); + assertInstanceOf(SymTypeOfObject.class, symTypeExpression); + assertEquals("de.mc.Person", symTypeExpression.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testQualifiedTypeUnqualified() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCQualifiedType("Person"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); ASTMCQualifiedType qualifiedType = type.get(); SymTypeExpression symTypeExpression = mcType2TypeExpression(qualifiedType); - Assertions.assertTrue(symTypeExpression instanceof SymTypeOfObject); - Assertions.assertEquals("Person", symTypeExpression.printFullName()); + assertInstanceOf(SymTypeOfObject.class, symTypeExpression); + assertEquals("Person", symTypeExpression.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testQualifiedName() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCQualifiedName("de.mc.Person"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); ASTMCQualifiedName qualifiedName = type.get(); SymTypeExpression symTypeExpression = mcType2TypeExpression(qualifiedName); - Assertions.assertTrue(symTypeExpression instanceof SymTypeOfObject); - Assertions.assertEquals("de.mc.Person", symTypeExpression.printFullName()); + assertInstanceOf(SymTypeOfObject.class, symTypeExpression); + assertEquals("de.mc.Person", symTypeExpression.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testQualifiedNameUnqualified() throws IOException { Optional type = new MCCollectionTypesTestParser().parse_StringMCQualifiedName("Person"); - Assertions.assertTrue(type.isPresent()); + assertTrue(type.isPresent()); ASTMCQualifiedName qualifiedName = type.get(); SymTypeExpression symTypeExpression = mcType2TypeExpression(qualifiedName); - Assertions.assertTrue(symTypeExpression instanceof SymTypeOfObject); - Assertions.assertEquals("Person", symTypeExpression.printFullName()); + assertInstanceOf(SymTypeOfObject.class, symTypeExpression); + assertEquals("Person", symTypeExpression.printFullName()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/mcbasictypes/cocos/QualifiedTypeHasNoTypeParametersTest.java b/monticore-grammar/src/test/java/de/monticore/types/mcbasictypes/cocos/QualifiedTypeHasNoTypeParametersTest.java index 095ee50a49..31e016dcb3 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/mcbasictypes/cocos/QualifiedTypeHasNoTypeParametersTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/mcbasictypes/cocos/QualifiedTypeHasNoTypeParametersTest.java @@ -1,5 +1,6 @@ package de.monticore.types.mcbasictypes.cocos; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mcbasictypes._cocos.MCBasicTypesCoCoChecker; import de.monticore.types.mcbasictypestest.MCBasicTypesTestMill; @@ -7,7 +8,6 @@ import de.monticore.types.mcbasictypeswithbasicsymbolstest.MCBasicTypesWithBasicSymbolsTestMill; import de.monticore.types.mcbasictypeswithbasicsymbolstest._symboltable.IMCBasicTypesWithBasicSymbolsTestArtifactScope; import de.monticore.types.mcbasictypeswithbasicsymbolstest.types3.MCBasicTypesWithBasicSymbolsTestTypeCheck3; -import de.monticore.types3.util.DefsTypesForTests; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; import org.junit.jupiter.api.BeforeEach; diff --git a/monticore-grammar/src/test/java/de/monticore/types/mccollectiontypes/types3/util/MCCollectionSymTypeFactoryTest.java b/monticore-grammar/src/test/java/de/monticore/types/mccollectiontypes/types3/util/MCCollectionSymTypeFactoryTest.java index eb6799a07c..fa8104c0bc 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/mccollectiontypes/types3/util/MCCollectionSymTypeFactoryTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/mccollectiontypes/types3/util/MCCollectionSymTypeFactoryTest.java @@ -1,13 +1,12 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types.mccollectiontypes.types3.util; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; import de.monticore.types.check.SymTypeOfGenerics; import de.monticore.types.mccollectiontypes.types3.MCCollectionSymTypeRelations; -import de.monticore.types3.AbstractTypeTest; -import de.monticore.types3.util.DefsTypesForTests; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,8 +20,9 @@ import static de.monticore.types3.util.DefsTypesForTests._unboxedMapSymType; import static de.monticore.types3.util.DefsTypesForTests._unboxedOptionalSymType; import static de.monticore.types3.util.DefsTypesForTests._unboxedSetSymType; +import static org.junit.jupiter.api.Assertions.*; -public class MCCollectionSymTypeFactoryTest extends AbstractTypeTest { +public class MCCollectionSymTypeFactoryTest extends AbstractMCTest { @BeforeEach public void setup() { @@ -38,22 +38,22 @@ public void createsList() { IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); SymTypeOfGenerics intList = MCCollectionSymTypeFactory.createList(_intSymType); - Assertions.assertTrue(intList.hasTypeInfo()); - Assertions.assertSame(_unboxedListSymType.getTypeInfo(), intList.getTypeInfo()); - Assertions.assertEquals("List", intList.getTypeConstructorFullName()); - Assertions.assertEquals(1, intList.sizeArguments()); - Assertions.assertTrue(_intSymType.deepEquals(intList.getArgument(0))); - Assertions.assertTrue(MCCollectionSymTypeRelations.isList(intList)); + assertTrue(intList.hasTypeInfo()); + assertSame(_unboxedListSymType.getTypeInfo(), intList.getTypeInfo()); + assertEquals("List", intList.getTypeConstructorFullName()); + assertEquals(1, intList.sizeArguments()); + assertTrue(_intSymType.deepEquals(intList.getArgument(0))); + assertTrue(MCCollectionSymTypeRelations.isList(intList)); // again, but with the unboxed "List" not being available gs.remove(gs.resolveType("List").get()); intList = MCCollectionSymTypeFactory.createList(_intSymType); - Assertions.assertTrue(intList.hasTypeInfo()); - Assertions.assertSame(_boxedListSymType.getTypeInfo(), intList.getTypeInfo()); - Assertions.assertEquals("java.util.List", intList.getTypeConstructorFullName()); - Assertions.assertEquals(1, intList.sizeArguments()); - Assertions.assertTrue(_intSymType.deepEquals(intList.getArgument(0))); - Assertions.assertTrue(MCCollectionSymTypeRelations.isList(intList)); + assertTrue(intList.hasTypeInfo()); + assertSame(_boxedListSymType.getTypeInfo(), intList.getTypeInfo()); + assertEquals("java.util.List", intList.getTypeConstructorFullName()); + assertEquals(1, intList.sizeArguments()); + assertTrue(_intSymType.deepEquals(intList.getArgument(0))); + assertTrue(MCCollectionSymTypeRelations.isList(intList)); } @Test @@ -61,22 +61,22 @@ public void createsSet() { IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); SymTypeOfGenerics intSet = MCCollectionSymTypeFactory.createSet(_intSymType); - Assertions.assertTrue(intSet.hasTypeInfo()); - Assertions.assertSame(_unboxedSetSymType.getTypeInfo(), intSet.getTypeInfo()); - Assertions.assertEquals("Set", intSet.getTypeConstructorFullName()); - Assertions.assertEquals(1, intSet.sizeArguments()); - Assertions.assertTrue(_intSymType.deepEquals(intSet.getArgument(0))); - Assertions.assertTrue(MCCollectionSymTypeRelations.isSet(intSet)); + assertTrue(intSet.hasTypeInfo()); + assertSame(_unboxedSetSymType.getTypeInfo(), intSet.getTypeInfo()); + assertEquals("Set", intSet.getTypeConstructorFullName()); + assertEquals(1, intSet.sizeArguments()); + assertTrue(_intSymType.deepEquals(intSet.getArgument(0))); + assertTrue(MCCollectionSymTypeRelations.isSet(intSet)); // again, but with the unboxed "Set" not being available gs.remove(gs.resolveType("Set").get()); intSet = MCCollectionSymTypeFactory.createSet(_intSymType); - Assertions.assertTrue(intSet.hasTypeInfo()); - Assertions.assertSame(_boxedSetSymType.getTypeInfo(), intSet.getTypeInfo()); - Assertions.assertEquals("java.util.Set", intSet.getTypeConstructorFullName()); - Assertions.assertEquals(1, intSet.sizeArguments()); - Assertions.assertTrue(_intSymType.deepEquals(intSet.getArgument(0))); - Assertions.assertTrue(MCCollectionSymTypeRelations.isSet(intSet)); + assertTrue(intSet.hasTypeInfo()); + assertSame(_boxedSetSymType.getTypeInfo(), intSet.getTypeInfo()); + assertEquals("java.util.Set", intSet.getTypeConstructorFullName()); + assertEquals(1, intSet.sizeArguments()); + assertTrue(_intSymType.deepEquals(intSet.getArgument(0))); + assertTrue(MCCollectionSymTypeRelations.isSet(intSet)); } @Test @@ -84,22 +84,22 @@ public void createsOptional() { IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); SymTypeOfGenerics intOptional = MCCollectionSymTypeFactory.createOptional(_intSymType); - Assertions.assertTrue(intOptional.hasTypeInfo()); - Assertions.assertSame(_unboxedOptionalSymType.getTypeInfo(), intOptional.getTypeInfo()); - Assertions.assertEquals("Optional", intOptional.getTypeConstructorFullName()); - Assertions.assertEquals(1, intOptional.sizeArguments()); - Assertions.assertTrue(_intSymType.deepEquals(intOptional.getArgument(0))); - Assertions.assertTrue(MCCollectionSymTypeRelations.isOptional(intOptional)); + assertTrue(intOptional.hasTypeInfo()); + assertSame(_unboxedOptionalSymType.getTypeInfo(), intOptional.getTypeInfo()); + assertEquals("Optional", intOptional.getTypeConstructorFullName()); + assertEquals(1, intOptional.sizeArguments()); + assertTrue(_intSymType.deepEquals(intOptional.getArgument(0))); + assertTrue(MCCollectionSymTypeRelations.isOptional(intOptional)); // again, but with the unboxed "Optional" not being available gs.remove(gs.resolveType("Optional").get()); intOptional = MCCollectionSymTypeFactory.createOptional(_intSymType); - Assertions.assertTrue(intOptional.hasTypeInfo()); - Assertions.assertSame(_boxedOptionalSymType.getTypeInfo(), intOptional.getTypeInfo()); - Assertions.assertEquals("java.util.Optional", intOptional.getTypeConstructorFullName()); - Assertions.assertEquals(1, intOptional.sizeArguments()); - Assertions.assertTrue(_intSymType.deepEquals(intOptional.getArgument(0))); - Assertions.assertTrue(MCCollectionSymTypeRelations.isOptional(intOptional)); + assertTrue(intOptional.hasTypeInfo()); + assertSame(_boxedOptionalSymType.getTypeInfo(), intOptional.getTypeInfo()); + assertEquals("java.util.Optional", intOptional.getTypeConstructorFullName()); + assertEquals(1, intOptional.sizeArguments()); + assertTrue(_intSymType.deepEquals(intOptional.getArgument(0))); + assertTrue(MCCollectionSymTypeRelations.isOptional(intOptional)); } @Test @@ -108,24 +108,24 @@ public void createsMap() { SymTypeOfGenerics intMap = MCCollectionSymTypeFactory.createMap(_intSymType, _floatSymType); - Assertions.assertTrue(intMap.hasTypeInfo()); - Assertions.assertSame(_unboxedMapSymType.getTypeInfo(), intMap.getTypeInfo()); - Assertions.assertEquals("Map", intMap.getTypeConstructorFullName()); - Assertions.assertEquals(2, intMap.sizeArguments()); - Assertions.assertTrue(_intSymType.deepEquals(intMap.getArgument(0))); - Assertions.assertTrue(_floatSymType.deepEquals(intMap.getArgument(1))); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMap(intMap)); + assertTrue(intMap.hasTypeInfo()); + assertSame(_unboxedMapSymType.getTypeInfo(), intMap.getTypeInfo()); + assertEquals("Map", intMap.getTypeConstructorFullName()); + assertEquals(2, intMap.sizeArguments()); + assertTrue(_intSymType.deepEquals(intMap.getArgument(0))); + assertTrue(_floatSymType.deepEquals(intMap.getArgument(1))); + assertTrue(MCCollectionSymTypeRelations.isMap(intMap)); // again, but with the unboxed "Map" not being available gs.remove(gs.resolveType("Map").get()); intMap = MCCollectionSymTypeFactory.createMap(_intSymType, _floatSymType); - Assertions.assertTrue(intMap.hasTypeInfo()); - Assertions.assertSame(_boxedMapSymType.getTypeInfo(), intMap.getTypeInfo()); - Assertions.assertEquals("java.util.Map", intMap.getTypeConstructorFullName()); - Assertions.assertEquals(2, intMap.sizeArguments()); - Assertions.assertTrue(_intSymType.deepEquals(intMap.getArgument(0))); - Assertions.assertTrue(_floatSymType.deepEquals(intMap.getArgument(1))); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMap(intMap)); + assertTrue(intMap.hasTypeInfo()); + assertSame(_boxedMapSymType.getTypeInfo(), intMap.getTypeInfo()); + assertEquals("java.util.Map", intMap.getTypeConstructorFullName()); + assertEquals(2, intMap.sizeArguments()); + assertTrue(_intSymType.deepEquals(intMap.getArgument(0))); + assertTrue(_floatSymType.deepEquals(intMap.getArgument(1))); + assertTrue(MCCollectionSymTypeRelations.isMap(intMap)); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/mccollectiontypes/types3/util/MCCollectionTypeRelationsTest.java b/monticore-grammar/src/test/java/de/monticore/types/mccollectiontypes/types3/util/MCCollectionTypeRelationsTest.java index a93c7e11c3..7bb3301143 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/mccollectiontypes/types3/util/MCCollectionTypeRelationsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/mccollectiontypes/types3/util/MCCollectionTypeRelationsTest.java @@ -1,18 +1,18 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types.mccollectiontypes.types3.util; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.mccollectiontypes.types3.MCCollectionSymTypeRelations; -import de.monticore.types3.AbstractTypeTest; -import de.monticore.types3.util.DefsTypesForTests; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; +import static de.monticore.runtime.junit.MCAssertions.assertHasFindingStartingWith; import static de.monticore.types3.util.DefsTypesForTests._boxedListSymType; import static de.monticore.types3.util.DefsTypesForTests._boxedMapSymType; import static de.monticore.types3.util.DefsTypesForTests._boxedOptionalSymType; @@ -24,11 +24,9 @@ import static de.monticore.types3.util.DefsTypesForTests._unboxedOptionalSymType; import static de.monticore.types3.util.DefsTypesForTests._unboxedSetSymType; import static de.monticore.types3.util.DefsTypesForTests._unboxedString; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; -public class MCCollectionTypeRelationsTest extends AbstractTypeTest { +public class MCCollectionTypeRelationsTest extends AbstractMCTest { @BeforeEach public void init() { @@ -38,156 +36,174 @@ public void init() { @Test public void recognizeUnboxedCollectionTypes() { - Assertions.assertTrue(MCCollectionSymTypeRelations.isMCCollection(_unboxedListSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMCCollection(_unboxedSetSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMCCollection(_unboxedOptionalSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMCCollection(_unboxedMapSymType)); + assertTrue(MCCollectionSymTypeRelations.isMCCollection(_unboxedListSymType)); + assertTrue(MCCollectionSymTypeRelations.isMCCollection(_unboxedSetSymType)); + assertTrue(MCCollectionSymTypeRelations.isMCCollection(_unboxedOptionalSymType)); + assertTrue(MCCollectionSymTypeRelations.isMCCollection(_unboxedMapSymType)); } @Test public void recognizeBoxedCollectionTypes() { - Assertions.assertTrue(MCCollectionSymTypeRelations.isMCCollection(_boxedListSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMCCollection(_boxedSetSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMCCollection(_boxedOptionalSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMCCollection(_boxedMapSymType)); + assertTrue(MCCollectionSymTypeRelations.isMCCollection(_boxedListSymType)); + assertTrue(MCCollectionSymTypeRelations.isMCCollection(_boxedSetSymType)); + assertTrue(MCCollectionSymTypeRelations.isMCCollection(_boxedOptionalSymType)); + assertTrue(MCCollectionSymTypeRelations.isMCCollection(_boxedMapSymType)); } @Test public void recognizeNonCollectionTypes() { - Assertions.assertFalse(MCCollectionSymTypeRelations.isMCCollection(_intSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMCCollection(_personSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMCCollection(_unboxedString)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMCCollection(SymTypeExpressionFactory.createGenerics( + assertFalse(MCCollectionSymTypeRelations.isMCCollection(_intSymType)); + assertFalse(MCCollectionSymTypeRelations.isMCCollection(_personSymType)); + assertFalse(MCCollectionSymTypeRelations.isMCCollection(_unboxedString)); + assertFalse(MCCollectionSymTypeRelations.isMCCollection(SymTypeExpressionFactory.createGenerics( "noList", BasicSymbolsMill.scope(), _intSymType ))); } @Test public void recognizeLists() { - Assertions.assertTrue(MCCollectionSymTypeRelations.isList(_unboxedListSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isList(_boxedListSymType)); + assertTrue(MCCollectionSymTypeRelations.isList(_unboxedListSymType)); + assertTrue(MCCollectionSymTypeRelations.isList(_boxedListSymType)); } @Test public void recognizeNonLists() { - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_unboxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_unboxedSetSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_unboxedOptionalSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_boxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_boxedSetSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_boxedOptionalSymType)); + assertFalse(MCCollectionSymTypeRelations.isList(_unboxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isList(_unboxedSetSymType)); + assertFalse(MCCollectionSymTypeRelations.isList(_unboxedOptionalSymType)); + assertFalse(MCCollectionSymTypeRelations.isList(_boxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isList(_boxedSetSymType)); + assertFalse(MCCollectionSymTypeRelations.isList(_boxedOptionalSymType)); // incorrect number of arguments _unboxedListSymType.setArgumentList(Collections.emptyList()); _boxedListSymType.setArgumentList(Collections.emptyList()); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_unboxedListSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_boxedListSymType)); + assertFalse(MCCollectionSymTypeRelations.isList(_unboxedListSymType)); + assertHasFindingStartingWith("0xFD1C4"); + assertFalse(MCCollectionSymTypeRelations.isList(_boxedListSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedListSymType.setArgumentList(List.of(_intSymType, _intSymType)); _boxedListSymType.setArgumentList(List.of(_intSymType, _intSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_unboxedListSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isList(_boxedListSymType)); + assertFalse(MCCollectionSymTypeRelations.isList(_unboxedListSymType)); + assertHasFindingStartingWith("0xFD1C4"); + assertFalse(MCCollectionSymTypeRelations.isList(_boxedListSymType)); + assertHasFindingStartingWith("0xFD1C4"); } @Test public void recognizeSets() { - Assertions.assertTrue(MCCollectionSymTypeRelations.isSet(_unboxedSetSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isSet(_boxedSetSymType)); + assertTrue(MCCollectionSymTypeRelations.isSet(_unboxedSetSymType)); + assertTrue(MCCollectionSymTypeRelations.isSet(_boxedSetSymType)); } @Test public void recognizeNonSets() { - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedListSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedOptionalSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_boxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_boxedListSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_boxedOptionalSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedListSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedOptionalSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_boxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_boxedListSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_boxedOptionalSymType)); // incorrect number of arguments _unboxedSetSymType.setArgumentList(Collections.emptyList()); + assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedSetSymType)); + assertHasFindingStartingWith("0xFD1C4"); _boxedSetSymType.setArgumentList(Collections.emptyList()); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedSetSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_boxedSetSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_boxedSetSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedSetSymType.setArgumentList(List.of(_intSymType, _intSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedSetSymType)); + assertHasFindingStartingWith("0xFD1C4"); _boxedSetSymType.setArgumentList(List.of(_intSymType, _intSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedSetSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isSet(_boxedSetSymType)); + assertFalse(MCCollectionSymTypeRelations.isSet(_boxedSetSymType)); + assertHasFindingStartingWith("0xFD1C4"); } @Test public void recognizeOptionals() { - Assertions.assertTrue(MCCollectionSymTypeRelations.isOptional(_unboxedOptionalSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isOptional(_boxedOptionalSymType)); + assertTrue(MCCollectionSymTypeRelations.isOptional(_unboxedOptionalSymType)); + assertTrue(MCCollectionSymTypeRelations.isOptional(_boxedOptionalSymType)); } @Test public void recognizeNonOptionals() { - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedListSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedSetSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedListSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedSetSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedListSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedSetSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedListSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedSetSymType)); // incorrect number of arguments _unboxedOptionalSymType.setArgumentList(Collections.emptyList()); + assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedOptionalSymType)); + assertHasFindingStartingWith("0xFD1C4"); _boxedOptionalSymType.setArgumentList(Collections.emptyList()); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedOptionalSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedOptionalSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedOptionalSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedOptionalSymType.setArgumentList(List.of(_intSymType, _intSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedOptionalSymType)); + assertHasFindingStartingWith("0xFD1C4"); _boxedOptionalSymType.setArgumentList(List.of(_intSymType, _intSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedOptionalSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedOptionalSymType)); + assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedOptionalSymType)); + assertHasFindingStartingWith("0xFD1C4"); } @Test public void recognizeMaps() { - Assertions.assertTrue(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); - Assertions.assertTrue(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertTrue(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); + assertTrue(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); } @Test public void recognizeNonMaps() { - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedListSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedSetSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedOptionalSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_boxedListSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_boxedSetSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_boxedOptionalSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedListSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedSetSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedOptionalSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_boxedListSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_boxedSetSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_boxedOptionalSymType)); // incorrect number of arguments _unboxedMapSymType.setArgumentList(Collections.emptyList()); + assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); _boxedMapSymType.setArgumentList(Collections.emptyList()); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedMapSymType.setArgumentList(List.of(_intSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); _boxedMapSymType.setArgumentList(List.of(_intSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedMapSymType.setArgumentList( List.of(_intSymType, _intSymType, _intSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); _boxedMapSymType.setArgumentList( List.of(_intSymType, _intSymType, _intSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); - Assertions.assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); } @Test public void getCollectionElementTypeTest() { - Assertions.assertSame(_unboxedListSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_unboxedListSymType)); - Assertions.assertSame(_unboxedSetSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_unboxedSetSymType)); - Assertions.assertSame(_unboxedOptionalSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_unboxedOptionalSymType)); - Assertions.assertSame(_unboxedMapSymType.getArgument(1), MCCollectionSymTypeRelations.getCollectionElementType(_unboxedMapSymType)); - Assertions.assertSame(_boxedListSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_boxedListSymType)); - Assertions.assertSame(_boxedSetSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_boxedSetSymType)); - Assertions.assertSame(_boxedOptionalSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_boxedOptionalSymType)); - Assertions.assertSame(_boxedMapSymType.getArgument(1), MCCollectionSymTypeRelations.getCollectionElementType(_boxedMapSymType)); + assertSame(_unboxedListSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_unboxedListSymType)); + assertSame(_unboxedSetSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_unboxedSetSymType)); + assertSame(_unboxedOptionalSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_unboxedOptionalSymType)); + assertSame(_unboxedMapSymType.getArgument(1), MCCollectionSymTypeRelations.getCollectionElementType(_unboxedMapSymType)); + assertSame(_boxedListSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_boxedListSymType)); + assertSame(_boxedSetSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_boxedSetSymType)); + assertSame(_boxedOptionalSymType.getArgument(0), MCCollectionSymTypeRelations.getCollectionElementType(_boxedOptionalSymType)); + assertSame(_boxedMapSymType.getArgument(1), MCCollectionSymTypeRelations.getCollectionElementType(_boxedMapSymType)); } @Test public void getMapKeyTest() { - Assertions.assertSame(_unboxedMapSymType.getArgument(0), MCCollectionSymTypeRelations.getMapKeyType(_unboxedMapSymType)); - Assertions.assertSame(_boxedMapSymType.getArgument(0), MCCollectionSymTypeRelations.getMapKeyType(_boxedMapSymType)); + assertSame(_unboxedMapSymType.getArgument(0), MCCollectionSymTypeRelations.getMapKeyType(_unboxedMapSymType)); + assertSame(_boxedMapSymType.getArgument(0), MCCollectionSymTypeRelations.getMapKeyType(_boxedMapSymType)); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCArrayTypesPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCArrayTypesPrettyPrinterTest.java index fd71403029..ef84d17ecd 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCArrayTypesPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCArrayTypesPrettyPrinterTest.java @@ -9,15 +9,13 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MCArrayTypesPrettyPrinterTest { @@ -34,17 +32,17 @@ public void testMCArrayType() throws IOException { //have to use ASTMCType because of left recursion in ASTMCArrayType there is no parse Method MCArrayTypesTestParser parser = new MCArrayTypesTestParser(); Optional ast = parser.parse_StringMCType("String[][]"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.get() instanceof ASTMCArrayType); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); + assertInstanceOf(ASTMCArrayType.class, ast.get()); ASTMCArrayType type = (ASTMCArrayType) ast.get(); MCArrayTypesFullPrettyPrinter printer = new MCArrayTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(type); ast = parser.parse_StringMCType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(type.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(type.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCBasicTypesPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCBasicTypesPrettyPrinterTest.java index 242d349925..f2fbea5613 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCBasicTypesPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCBasicTypesPrettyPrinterTest.java @@ -8,13 +8,14 @@ import de.monticore.types.mcbasictypestest._parser.MCBasicTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCBasicTypesPrettyPrinterTest { @BeforeEach @@ -31,136 +32,136 @@ public void init() { public void testMCQualifiedName() throws IOException { MCBasicTypesTestParser parser = new MCBasicTypesTestParser(); Optional ast = parser.parse_StringMCQualifiedName("Name1.Name2.Name3"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCQualifiedName qualifiedName = ast.get(); MCBasicTypesFullPrettyPrinter printer = new MCBasicTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCQualifiedName(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(qualifiedName.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(qualifiedName.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMcImportStatement() throws IOException { MCBasicTypesTestParser parser = new MCBasicTypesTestParser(); Optional ast = parser.parse_StringMCImportStatement("import de.monticore.types.*;"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCImportStatement importStatement = ast.get(); MCBasicTypesFullPrettyPrinter printer = new MCBasicTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCImportStatement(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(importStatement.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(importStatement.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMcPrimitiveType() throws IOException { MCBasicTypesTestParser parser = new MCBasicTypesTestParser(); Optional ast = parser.parse_StringMCPrimitiveType("long"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCPrimitiveType primitiveType = ast.get(); MCBasicTypesFullPrettyPrinter printer = new MCBasicTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCPrimitiveType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(primitiveType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(primitiveType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCVoidType() throws IOException { MCBasicTypesTestParser parser = new MCBasicTypesTestParser(); Optional ast = parser.parse_StringMCVoidType("void"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCVoidType voidType = ast.get(); MCBasicTypesFullPrettyPrinter printer = new MCBasicTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCVoidType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(voidType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(voidType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCReturnTypeVoid() throws IOException { MCBasicTypesTestParser parser = new MCBasicTypesTestParser(); Optional ast = parser.parse_StringMCReturnType("void"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCReturnType voidType = ast.get(); MCBasicTypesFullPrettyPrinter printer = new MCBasicTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCReturnType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(voidType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(voidType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCReturnType() throws IOException { MCBasicTypesTestParser parser = new MCBasicTypesTestParser(); Optional ast = parser.parse_StringMCReturnType("boolean"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCReturnType voidType = ast.get(); MCBasicTypesFullPrettyPrinter printer = new MCBasicTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCReturnType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(voidType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(voidType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCQualifiedType() throws IOException { MCBasicTypesTestParser parser = new MCBasicTypesTestParser(); Optional ast = parser.parse_StringMCQualifiedType("a.b.c.d"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCQualifiedType qualifiedReferenceType = ast.get(); MCBasicTypesFullPrettyPrinter printer = new MCBasicTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCQualifiedType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(qualifiedReferenceType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(qualifiedReferenceType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCPackageDeclaration() throws IOException { MCBasicTypesTestParser parser = MCBasicTypesTestMill.parser(); Optional ast = parser.parse_StringMCPackageDeclaration("package a.b.c.d;"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCPackageDeclaration packageDeclaration = ast.get(); MCBasicTypesFullPrettyPrinter printer = new MCBasicTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCPackageDeclaration(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(packageDeclaration.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(packageDeclaration.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -177,15 +178,15 @@ public void primitivesTest(){ // .parseType(primitive); Optional type = mcBasicTypesParser.parse_StringMCPrimitiveType(primitive); - Assertions.assertTrue(type.isPresent()); - Assertions.assertEquals(primitive, prettyprinter.prettyprint(type.get())); - Assertions.assertTrue(type.get() instanceof ASTMCPrimitiveType); + assertTrue(type.isPresent()); + assertEquals(primitive, prettyprinter.prettyprint(type.get())); + assertInstanceOf(ASTMCPrimitiveType.class, type.get()); } } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -195,13 +196,13 @@ public void simpleReferenceTest(){ try{ MCBasicTypesTestParser mcBasicTypesParser= new MCBasicTypesTestParser(); Optional type = mcBasicTypesParser.parse_StringMCQualifiedType(simpleReference); - Assertions.assertTrue(type.isPresent()); - Assertions.assertEquals(simpleReference, prettyprinter.prettyprint(type.get())); - Assertions.assertTrue(type.get() instanceof ASTMCQualifiedType); + assertTrue(type.isPresent()); + assertEquals(simpleReference, prettyprinter.prettyprint(type.get())); + assertInstanceOf(ASTMCQualifiedType.class, type.get()); }catch(IOException e){ e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCCollectionTypesPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCCollectionTypesPrettyPrinterTest.java index 98fb1dad5f..dcad861169 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCCollectionTypesPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCCollectionTypesPrettyPrinterTest.java @@ -8,15 +8,14 @@ import de.monticore.types.mccollectiontypes._prettyprint.MCCollectionTypesFullPrettyPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCCollectionTypesPrettyPrinterTest { @@ -31,101 +30,101 @@ public void init() { public void testMCPrimitiveTypeArgument() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional ast = parser.parse_StringMCPrimitiveTypeArgument("boolean"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCPrimitiveTypeArgument typeArgument = ast.get(); MCCollectionTypesFullPrettyPrinter printer = new MCCollectionTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCPrimitiveTypeArgument(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(typeArgument.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(typeArgument.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCBasicTypeArgument() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional ast = parser.parse_StringMCBasicTypeArgument("a.b.c.d"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCBasicTypeArgument typeArgument = ast.get(); MCCollectionTypesFullPrettyPrinter printer = new MCCollectionTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCBasicTypeArgument(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(typeArgument.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(typeArgument.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCListType() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional ast = parser.parse_StringMCListType("List"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCListType listType = ast.get(); MCCollectionTypesFullPrettyPrinter printer = new MCCollectionTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCListType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(listType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(listType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCOptionalType() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional ast = parser.parse_StringMCOptionalType("Optional"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCOptionalType optionalType = ast.get(); MCCollectionTypesFullPrettyPrinter printer = new MCCollectionTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCOptionalType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(optionalType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(optionalType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCMapType() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional ast = parser.parse_StringMCMapType("Map"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCMapType mapType = ast.get(); MCCollectionTypesFullPrettyPrinter printer = new MCCollectionTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCMapType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(mapType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(mapType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCSetType() throws IOException { MCCollectionTypesTestParser parser = new MCCollectionTypesTestParser(); Optional ast = parser.parse_StringMCSetType("Set"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCSetType setType = ast.get(); MCCollectionTypesFullPrettyPrinter printer = new MCCollectionTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCSetType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(setType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(setType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCFullGenericTypesPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCFullGenericTypesPrettyPrinterTest.java index 2972f97f05..72a17975f8 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCFullGenericTypesPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCFullGenericTypesPrettyPrinterTest.java @@ -9,15 +9,14 @@ import de.monticore.types.mcfullgenerictypes._prettyprint.MCFullGenericTypesFullPrettyPrinter; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MCFullGenericTypesPrettyPrinterTest { @@ -33,51 +32,51 @@ public void init() { public void testMCWildcardTypeArgumentExtends() throws IOException { MCFullGenericTypesTestParser parser = new MCFullGenericTypesTestParser(); Optional ast = parser.parse_StringMCWildcardTypeArgument("? extends java.util.List"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCWildcardTypeArgument wildcardType = ast.get(); MCFullGenericTypesFullPrettyPrinter printer = new MCFullGenericTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCWildcardTypeArgument(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(wildcardType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(wildcardType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCWildcardTypeArgumentSuper() throws IOException { MCFullGenericTypesTestParser parser = new MCFullGenericTypesTestParser(); Optional ast = parser.parse_StringMCWildcardTypeArgument("? super de.monticore.ASTNode"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCWildcardTypeArgument wildcardType = ast.get(); MCFullGenericTypesFullPrettyPrinter printer = new MCFullGenericTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCWildcardTypeArgument(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(wildcardType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(wildcardType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCMultipleGenericType() throws IOException { MCFullGenericTypesTestParser parser = new MCFullGenericTypesTestParser(); Optional ast = parser.parse_StringMCMultipleGenericType("java.util.List.some.util.Set.Opt>"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCMultipleGenericType complexReferenceType = ast.get(); MCFullGenericTypesFullPrettyPrinter printer = new MCFullGenericTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCMultipleGenericType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(complexReferenceType.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(complexReferenceType.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCFunctionTypesPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCFunctionTypesPrettyPrinterTest.java index 09114b7834..1174886fc0 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCFunctionTypesPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCFunctionTypesPrettyPrinterTest.java @@ -8,16 +8,13 @@ import de.monticore.types.mcfunctiontypestest._parser.MCFunctionTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MCFunctionTypesPrettyPrinterTest { @@ -67,9 +64,9 @@ public void testHigherOrderFunction2() throws IOException { protected ASTMCFunctionType parse(String mcTypeStr) throws IOException { MCFunctionTypesTestParser parser = new MCFunctionTypesTestParser(); Optional typeOpt = parser.parse_StringMCFunctionType(mcTypeStr); - Assertions.assertNotNull(typeOpt); - Assertions.assertTrue(typeOpt.isPresent()); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertNotNull(typeOpt); + assertTrue(typeOpt.isPresent()); + assertEquals(0, Log.getFindingsCount()); return typeOpt.get(); } @@ -77,7 +74,7 @@ protected String print(ASTMCFunctionType type) { MCFunctionTypesFullPrettyPrinter printer = new MCFunctionTypesFullPrettyPrinter( new IndentPrinter()); String typeStr = printer.prettyprint(type); - Assertions.assertEquals(0, Log.getFindingsCount()); + assertEquals(0, Log.getFindingsCount()); return typeStr; } @@ -85,8 +82,8 @@ protected void testPrintParseCompare(String typeStr) throws IOException { ASTMCFunctionType type = parse(typeStr); String printed = print(type); ASTMCFunctionType typeOfPrinted = parse(printed); - Assertions.assertTrue(typeOfPrinted.deepEquals(type)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(typeOfPrinted.deepEquals(type)); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCSimpleGenericTypesPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCSimpleGenericTypesPrettyPrinterTest.java index c1a847213d..e5a16410e4 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCSimpleGenericTypesPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/MCSimpleGenericTypesPrettyPrinterTest.java @@ -9,13 +9,14 @@ import de.monticore.types.mcsimplegenerictypestest._parser.MCSimpleGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class MCSimpleGenericTypesPrettyPrinterTest { @BeforeEach @@ -32,51 +33,51 @@ public void init() { public void testMCBasicTypeArgument() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional ast = parser.parse_StringMCBasicGenericType("java.util.List>>"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCBasicGenericType typeArgument = ast.get(); MCSimpleGenericTypesFullPrettyPrinter printer = new MCSimpleGenericTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCBasicGenericType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(typeArgument.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(typeArgument.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCBasicTypeArgument2() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional ast = parser.parse_StringMCBasicGenericType("some.randomObject>>>>"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCBasicGenericType typeArgument = ast.get(); MCSimpleGenericTypesFullPrettyPrinter printer = new MCSimpleGenericTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCBasicGenericType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(typeArgument.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(typeArgument.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test public void testMCCustomTypeArgument() throws IOException { MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional ast = parser.parse_StringMCCustomTypeArgument("some.randomObject>>>>"); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); ASTMCCustomTypeArgument typeArgument = ast.get(); MCSimpleGenericTypesFullPrettyPrinter printer = new MCSimpleGenericTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); ast = parser.parse_StringMCCustomTypeArgument(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(typeArgument.deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(typeArgument.deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -84,20 +85,20 @@ public void testMultipleMCCustomTypeArgument() throws IOException { String type = "java.util.List,List>"; MCSimpleGenericTypesTestParser parser = new MCSimpleGenericTypesTestParser(); Optional ast = parser.parse_StringMCBasicGenericType(type); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertFalse(parser.hasErrors()); Optional astBefore = ast; MCSimpleGenericTypesFullPrettyPrinter printer = new MCSimpleGenericTypesFullPrettyPrinter(new IndentPrinter()); String output = printer.prettyprint(ast.get()); - Assertions.assertEquals(type, output); + assertEquals(type, output); ast = parser.parse_StringMCBasicGenericType(output); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(ast.isPresent()); - Assertions.assertTrue(astBefore.get().deepEquals(ast.get())); + assertFalse(parser.hasErrors()); + assertTrue(ast.isPresent()); + assertTrue(astBefore.get().deepEquals(ast.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/PrintTypeAstExtensionTests.java b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/PrintTypeAstExtensionTests.java index e228b7316e..5e51d2ffec 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/PrintTypeAstExtensionTests.java +++ b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/PrintTypeAstExtensionTests.java @@ -11,15 +11,14 @@ import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class PrintTypeAstExtensionTests { @@ -46,7 +45,7 @@ public void printTypeMethodPrimitiveBooleanTest() { System.out.println(f.getMsg()); } - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { @@ -54,7 +53,7 @@ public void printTypeMethodPrimitiveBooleanTest() { } } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -64,12 +63,12 @@ public void printTypeMethodObjectTypeTest() { String simpleReference = "de.monticore.types.prettyprint"; try { Optional type = mcBasicTypesParser.parse_StringMCObjectType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -78,12 +77,12 @@ public void printTypeMethodQualifiedTypeTest() { String simpleReference = "de.monticore.types.prettyprint"; try { Optional type = mcBasicTypesParser.parse_StringMCQualifiedType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -93,12 +92,12 @@ public void printTypeMethodReturnTypeTest() { String simpleReference = "de.monticore.types.Prettyprint"; try { Optional type = mcBasicTypesParser.parse_StringMCReturnType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -107,12 +106,12 @@ public void printTypeMethodReturnTypeVoidTest() { String simpleReference = "void"; try { Optional type = mcBasicTypesParser.parse_StringMCReturnType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -121,14 +120,14 @@ public void printTypeMethodTullGenericTypeTest() { String simpleReference = "de.monticore.types.prettyprint"; try { Optional type = parser.parse_StringMCType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -138,14 +137,14 @@ public void printTypeMethodTullGenericType2Test() { String simpleReference = "de.monticore.types.prettyprint"; try { Optional type = parser.parse_StringMCType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -155,7 +154,7 @@ public void printTypeMethodTSimpleGenericsArrayTest() { for(String simpleReference:types) { try { Optional type = parser.parse_StringMCType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { @@ -163,7 +162,7 @@ public void printTypeMethodTSimpleGenericsArrayTest() { } } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -176,7 +175,7 @@ public void printTypeMethodCollectionTypesTest() { for(String simpleReference:collectionTypes) { try { Optional type = parser.parse_StringMCType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { @@ -184,7 +183,7 @@ public void printTypeMethodCollectionTypesTest() { } } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -194,14 +193,14 @@ public void printTypeMethodTullGenericTypeWildcardExtendsTest() { String simpleReference = "de.monticore.types.prettyprint"; try { Optional type = parser.parse_StringMCType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -216,14 +215,14 @@ public void printTypeMethodTullGenericTypeExtendsTest() { System.out.println(f.getMsg()); } - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @@ -234,14 +233,14 @@ public void printTypeMethodTullGenericTypeWildcardSuperTest() { try { Optional type = parser.parse_StringMCType(simpleReference); - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -255,14 +254,14 @@ public void printTypeMethodImportStatementTest() { System.out.println(f.getMsg()); } - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @Test @@ -276,14 +275,14 @@ public void printTypeMethodStarImportStatementTest() { System.out.println(f.getMsg()); } - Assertions.assertEquals(simpleReference.trim(), type.get().printType().trim()); + assertEquals(simpleReference.trim(), type.get().printType().trim()); } catch (IOException e) { e.printStackTrace(); } - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/TypeParametersPrettyPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/TypeParametersPrettyPrinterTest.java index d07d874a87..e9ae27bd1b 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/prettyprint/TypeParametersPrettyPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/prettyprint/TypeParametersPrettyPrinterTest.java @@ -1,21 +1,20 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types.prettyprint; -import de.monticore.antlr4.MCConcreteParser; import de.monticore.ast.ASTNode; +import de.monticore.runtime.junit.AbstractMCTest; import de.monticore.types.typeparameterstest.TypeParametersTestMill; import de.monticore.types.typeparameterstest._parser.TypeParametersTestParser; -import de.monticore.types3.AbstractTypeTest; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; import java.util.Optional; -import java.util.function.Function; -public class TypeParametersPrettyPrinterTest extends AbstractTypeTest { +import static de.monticore.runtime.junit.PrettyPrinterTester.testPrettyPrinter; + +public class TypeParametersPrettyPrinterTest extends AbstractMCTest { @BeforeEach public void init() { @@ -57,28 +56,6 @@ public void testTypeParameter(String model) throws IOException { ); } - // this function could be used for all pretty printer tests if required, - // however, the parameters are not great. - protected void testPrettyPrinter( - String model, - MCConcreteParser parser, - ParseFunction parseFunc, - Function prettyPrintFunc - ) throws IOException { - Optional astOpt = parseFunc.apply(model); - assertNoFindings(); - Assertions.assertTrue(astOpt.isPresent()); - Assertions.assertFalse(parser.hasErrors()); - N ast = astOpt.get(); - String output = prettyPrintFunc.apply(ast); - assertNoFindings(); - astOpt = parseFunc.apply(output); - assertNoFindings(); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astOpt.isPresent()); - Assertions.assertTrue(ast.deepEquals(astOpt.get())); - } - @FunctionalInterface protected interface ParseFunction { Optional apply(String t) throws IOException; diff --git a/monticore-grammar/src/test/java/de/monticore/types/printer/BasicTypesPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/printer/BasicTypesPrinterTest.java index 20084a2265..7e24773833 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/printer/BasicTypesPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/printer/BasicTypesPrinterTest.java @@ -7,13 +7,14 @@ import de.monticore.types.mcbasictypestest._parser.MCBasicTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class BasicTypesPrinterTest { @BeforeEach @@ -35,21 +36,21 @@ public void testPrintType() throws IOException{ Optional astmcPrimitiveType = parser.parse_StringMCPrimitiveType("int"); Optional astmcQualifiedType = parser.parse_StringMCQualifiedType("java.util.List"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astmcImportStatement.isPresent()); - Assertions.assertTrue(astmcImportStatement.isPresent()); - Assertions.assertTrue(astmcImportStatement1.isPresent()); - Assertions.assertTrue(astmcQualifiedName.isPresent()); - Assertions.assertTrue(astmcReturnType.isPresent()); - Assertions.assertTrue(astmcVoidType.isPresent()); - Assertions.assertTrue(astmcPrimitiveType.isPresent()); - Assertions.assertTrue(astmcQualifiedType.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astmcImportStatement.isPresent()); + assertTrue(astmcImportStatement.isPresent()); + assertTrue(astmcImportStatement1.isPresent()); + assertTrue(astmcQualifiedName.isPresent()); + assertTrue(astmcReturnType.isPresent()); + assertTrue(astmcVoidType.isPresent()); + assertTrue(astmcPrimitiveType.isPresent()); + assertTrue(astmcQualifiedType.isPresent()); - Assertions.assertEquals("String", MCBasicTypesMill.prettyPrint(astmcReturnType.get(), true)); - Assertions.assertEquals("void", MCBasicTypesMill.prettyPrint(astmcVoidType.get(), true)); - Assertions.assertEquals("int", MCBasicTypesMill.prettyPrint(astmcPrimitiveType.get(), true)); - Assertions.assertEquals("java.util.List", MCBasicTypesMill.prettyPrint(astmcQualifiedType.get(), true)); + assertEquals("String", MCBasicTypesMill.prettyPrint(astmcReturnType.get(), true)); + assertEquals("void", MCBasicTypesMill.prettyPrint(astmcVoidType.get(), true)); + assertEquals("int", MCBasicTypesMill.prettyPrint(astmcPrimitiveType.get(), true)); + assertEquals("java.util.List", MCBasicTypesMill.prettyPrint(astmcQualifiedType.get(), true)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/printer/CollectionTypesPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/printer/CollectionTypesPrinterTest.java index 0cfe3b5885..316a0f117d 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/printer/CollectionTypesPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/printer/CollectionTypesPrinterTest.java @@ -7,13 +7,14 @@ import de.monticore.types.mccollectiontypestest._parser.MCCollectionTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class CollectionTypesPrinterTest { @BeforeEach @@ -34,21 +35,21 @@ public void testPrintType() throws IOException { Optional astmcOptionalType = parser.parse_StringMCOptionalType("Optional"); Optional astmcMapType = parser.parse_StringMCMapType("Map"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astmcBasicTypeArgument.isPresent()); - Assertions.assertTrue(astmcPrimitiveTypeArgument.isPresent()); - Assertions.assertTrue(astmcListType.isPresent()); - Assertions.assertTrue(astmcSetType.isPresent()); - Assertions.assertTrue(astmcOptionalType.isPresent()); - Assertions.assertTrue(astmcMapType.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astmcBasicTypeArgument.isPresent()); + assertTrue(astmcPrimitiveTypeArgument.isPresent()); + assertTrue(astmcListType.isPresent()); + assertTrue(astmcSetType.isPresent()); + assertTrue(astmcOptionalType.isPresent()); + assertTrue(astmcMapType.isPresent()); - Assertions.assertEquals("java.util.List", MCCollectionTypesMill.prettyPrint(astmcBasicTypeArgument.get(), true)); - Assertions.assertEquals("int", MCCollectionTypesMill.prettyPrint(astmcPrimitiveTypeArgument.get(), true)); - Assertions.assertEquals("List", MCCollectionTypesMill.prettyPrint(astmcListType.get(), true)); - Assertions.assertEquals("Set", MCCollectionTypesMill.prettyPrint(astmcSetType.get(), true)); - Assertions.assertEquals("Optional", MCCollectionTypesMill.prettyPrint(astmcOptionalType.get(), true)); - Assertions.assertEquals("Map", MCCollectionTypesMill.prettyPrint(astmcMapType.get(), true)); + assertEquals("java.util.List", MCCollectionTypesMill.prettyPrint(astmcBasicTypeArgument.get(), true)); + assertEquals("int", MCCollectionTypesMill.prettyPrint(astmcPrimitiveTypeArgument.get(), true)); + assertEquals("List", MCCollectionTypesMill.prettyPrint(astmcListType.get(), true)); + assertEquals("Set", MCCollectionTypesMill.prettyPrint(astmcSetType.get(), true)); + assertEquals("Optional", MCCollectionTypesMill.prettyPrint(astmcOptionalType.get(), true)); + assertEquals("Map", MCCollectionTypesMill.prettyPrint(astmcMapType.get(), true)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/printer/FullGenericTypesPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/printer/FullGenericTypesPrinterTest.java index c428492ab1..5c476874fa 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/printer/FullGenericTypesPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/printer/FullGenericTypesPrinterTest.java @@ -8,13 +8,14 @@ import de.monticore.types.mcfullgenerictypestest._parser.MCFullGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class FullGenericTypesPrinterTest { @BeforeEach @@ -35,21 +36,21 @@ public void testPrintType() throws IOException { // Optional astmcTypeVariableDeclaration = parser.parse_StringMCTypeVariableDeclaration("a extends b&c&d"); // Optional astmcTypeParameters = parser.parse_StringMCTypeParameters(""); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astmcWildcardTypeArgument.isPresent()); - Assertions.assertTrue(astmcWildcardTypeArgument1.isPresent()); - Assertions.assertTrue(astmcWildcardTypeArgument2.isPresent()); - Assertions.assertTrue(astmcMultipleGenericType.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astmcWildcardTypeArgument.isPresent()); + assertTrue(astmcWildcardTypeArgument1.isPresent()); + assertTrue(astmcWildcardTypeArgument2.isPresent()); + assertTrue(astmcMultipleGenericType.isPresent()); // assertTrue(astmcTypeVariableDeclaration.isPresent()); // assertTrue(astmcTypeParameters.isPresent()); - Assertions.assertEquals("?", MCFullGenericTypesMill.prettyPrint(astmcWildcardTypeArgument.get(), true)); - Assertions.assertEquals("? extends List", MCFullGenericTypesMill.prettyPrint(astmcWildcardTypeArgument1.get(), true)); - Assertions.assertEquals("? super Stream", MCFullGenericTypesMill.prettyPrint(astmcWildcardTypeArgument2.get(), true)); - Assertions.assertEquals("java.util.List>.c.d", MCFullGenericTypesMill.prettyPrint(astmcMultipleGenericType.get(), true)); + assertEquals("?", MCFullGenericTypesMill.prettyPrint(astmcWildcardTypeArgument.get(), true)); + assertEquals("? extends List", MCFullGenericTypesMill.prettyPrint(astmcWildcardTypeArgument1.get(), true)); + assertEquals("? super Stream", MCFullGenericTypesMill.prettyPrint(astmcWildcardTypeArgument2.get(), true)); + assertEquals("java.util.List>.c.d", MCFullGenericTypesMill.prettyPrint(astmcMultipleGenericType.get(), true)); // assertEquals("", FullGenericTypesPrinter.printType(astmcTypeParameters.get())); // assertEquals("a extends b &c &d", FullGenericTypesPrinter.printType(astmcTypeVariableDeclaration.get())); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/printer/SimpleGenericTypesPrinterTest.java b/monticore-grammar/src/test/java/de/monticore/types/printer/SimpleGenericTypesPrinterTest.java index 71a219481a..5c34f9c854 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/printer/SimpleGenericTypesPrinterTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/printer/SimpleGenericTypesPrinterTest.java @@ -8,13 +8,14 @@ import de.monticore.types.mcsimplegenerictypestest._parser.MCSimpleGenericTypesTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class SimpleGenericTypesPrinterTest { @BeforeEach @@ -31,13 +32,13 @@ public void testPrintType() throws IOException { Optional astmcCustomTypeArgument = parser.parse_StringMCCustomTypeArgument("List"); Optional astmcBasicGenericType = parser.parse_StringMCBasicGenericType("java.util.List>"); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astmcBasicGenericType.isPresent()); - Assertions.assertTrue(astmcCustomTypeArgument.isPresent()); + assertFalse(parser.hasErrors()); + assertTrue(astmcBasicGenericType.isPresent()); + assertTrue(astmcCustomTypeArgument.isPresent()); - Assertions.assertEquals("List", MCSimpleGenericTypesMill.prettyPrint(astmcCustomTypeArgument.get(), false)); - Assertions.assertEquals("java.util.List>", MCSimpleGenericTypesMill.prettyPrint(astmcBasicGenericType.get(), false)); + assertEquals("List", MCSimpleGenericTypesMill.prettyPrint(astmcCustomTypeArgument.get(), false)); + assertEquals("java.util.List>", MCSimpleGenericTypesMill.prettyPrint(astmcBasicGenericType.get(), false)); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types/typeparameters/cocos/TypeParametersHaveUniqueNamesTest.java b/monticore-grammar/src/test/java/de/monticore/types/typeparameters/cocos/TypeParametersHaveUniqueNamesTest.java index f3b2e77d7c..cd124c093a 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/typeparameters/cocos/TypeParametersHaveUniqueNamesTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/typeparameters/cocos/TypeParametersHaveUniqueNamesTest.java @@ -7,7 +7,6 @@ import de.monticore.types.typeparameterstest._parser.TypeParametersTestParser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -15,6 +14,8 @@ import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class TypeParametersHaveUniqueNamesTest { TypeParametersTestCoCoChecker checker; @@ -39,7 +40,7 @@ public void init() { public void testValid(String model) throws IOException { ASTTypeParameters params = parseAndCreateSymTab(model); checker.checkAll(params); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @ParameterizedTest @@ -51,8 +52,8 @@ public void testValid(String model) throws IOException { public void testInvalid(String model) throws IOException { ASTTypeParameters params = parseAndCreateSymTab(model); checker.checkAll(params); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertEquals( + assertFalse(Log.getFindings().isEmpty()); + assertEquals( "0xFDC14", Log.getFindings().get(0).getMsg().substring(0, 7) ); @@ -63,9 +64,9 @@ protected ASTTypeParameters parseAndCreateSymTab(String model) TypeParametersTestParser parser = TypeParametersTestMill.parser(); Optional astOpt = parser.parse_StringTypeParameters(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astOpt.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(parser.hasErrors()); + assertTrue(astOpt.isPresent()); + assertTrue(Log.getFindings().isEmpty()); TypeParametersMill.scopesGenitorDelegator().createFromAST(astOpt.get()); return astOpt.get(); } diff --git a/monticore-grammar/src/test/java/de/monticore/types/typeparameters/cocos/TypeParametersNoCyclicInheritanceTest.java b/monticore-grammar/src/test/java/de/monticore/types/typeparameters/cocos/TypeParametersNoCyclicInheritanceTest.java index 4209473039..566a6a1899 100644 --- a/monticore-grammar/src/test/java/de/monticore/types/typeparameters/cocos/TypeParametersNoCyclicInheritanceTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types/typeparameters/cocos/TypeParametersNoCyclicInheritanceTest.java @@ -16,7 +16,6 @@ import de.monticore.visitor.ITraverser; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -24,6 +23,8 @@ import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; + public class TypeParametersNoCyclicInheritanceTest { TypeParametersTestCoCoChecker checker; @@ -47,7 +48,7 @@ public void init() { public void testValid(String model) throws IOException { ASTTypeParameters params = parseAndCreateSymTab(model); checker.checkAll(params); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertTrue(Log.getFindings().isEmpty()); } @ParameterizedTest @@ -58,8 +59,8 @@ public void testValid(String model) throws IOException { public void testInvalid(String model) throws IOException { ASTTypeParameters params = parseAndCreateSymTab(model); checker.checkAll(params); - Assertions.assertFalse(Log.getFindings().isEmpty()); - Assertions.assertEquals( + assertFalse(Log.getFindings().isEmpty()); + assertEquals( "0xFDC12", Log.getFindings().get(0).getMsg().substring(0, 7) ); @@ -70,20 +71,20 @@ protected ASTTypeParameters parseAndCreateSymTab(String model) TypeParametersTestParser parser = TypeParametersTestMill.parser(); Optional astOpt = parser.parse_StringTypeParameters(model); - Assertions.assertFalse(parser.hasErrors()); - Assertions.assertTrue(astOpt.isPresent()); - Assertions.assertTrue(Log.getFindings().isEmpty()); + assertFalse(parser.hasErrors()); + assertTrue(astOpt.isPresent()); + assertTrue(Log.getFindings().isEmpty()); ITypeParametersArtifactScope artifactScope = TypeParametersMill .scopesGenitorDelegator().createFromAST(astOpt.get()); artifactScope.setName("aName"); TypeParametersTestTraverser stCompleter = TypeParametersTestMill.traverser(); - ITypeCalculator tc = getTypeCalculator(); - stCompleter.add4TypeParameters(new TypeParametersSTCompleteTypes(tc)); + stCompleter.add4TypeParameters(new TypeParametersSTCompleteTypes()); astOpt.get().accept(stCompleter); return astOpt.get(); } + @Deprecated protected ITypeCalculator getTypeCalculator() { Type4Ast type4Ast = new Type4Ast(); InferenceContext4Ast infCtx4Ast = new InferenceContext4Ast(); diff --git a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java index 4ae94c38f7..a8c3fbf147 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeTest.java @@ -1,15 +1,20 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3; +import de.monticore.runtime.junit.MCAssertions; import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; import de.se_rwth.commons.logging.LogStub; -import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; - import java.util.stream.Collectors; -public class AbstractTypeTest { +/** + * @deprecated use {@link de.monticore.runtime.junit.AbstractMCTest} directly. + * This class contains duplicate code from the AbstractMCTest, etc. to avoid breaking changes + */ +@Deprecated(forRemoval = true) +public class AbstractTypeTest { @BeforeEach public void initLog() { @@ -32,4 +37,37 @@ protected static String getAllFindingsAsString() { ; } + protected static void assertNoFindings() { + MCAssertions.assertNoFindings(); + } + + @BeforeEach + public void initAbstract() { + defaultInitAbstract(); + } + + static void defaultInitAbstract() { + Log.clearFindings(); // clear previous findings + LogStub.init(); // replace log by a sideeffect free variant + Log.enableFailQuick(false); // do not fail quick/exit on the first error + } + + @AfterEach + public void checkLogAfterTest() { + defaultCheckLogAfterTest(); + } + + static void defaultCheckLogAfterTest() { + try { + // Ensure, no Findings are present + // the various Finding-methods of MCAssertions check for & remove + // expected findings + MCAssertions.assertNoFindings( + "After the test has run, findings were present." + ); + } finally { + Log.clearFindings(); + } + } + } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java index 0abad140b0..b1ba336eb7 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/AbstractTypeVisitorTest.java @@ -11,16 +11,14 @@ import de.monticore.expressions.lambdaexpressions._symboltable.LambdaExpressionsSTCompleteTypes2; import de.monticore.ocl.oclexpressions.symboltable.OCLExpressionsSymbolTableCompleter; import de.monticore.ocl.setexpressions.symboltable.SetExpressionsSymbolTableCompleter; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.runtime.junit.MCAssertions; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; -import de.monticore.types.check.IDerive; -import de.monticore.types.check.ISynthesize; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types.check.types3wrapper.TypeCheck3AsIDerive; -import de.monticore.types.check.types3wrapper.TypeCheck3AsISynthesize; import de.monticore.types.mcbasictypes.MCBasicTypesMill; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; @@ -33,7 +31,6 @@ import de.monticore.visitor.ITraverser; import de.se_rwth.commons.logging.Finding; import de.se_rwth.commons.logging.Log; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import java.io.IOException; @@ -41,6 +38,7 @@ import java.util.Optional; import java.util.stream.Collectors; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests._booleanSymType; import static de.monticore.types3.util.DefsTypesForTests._boxedListSymType; import static de.monticore.types3.util.DefsTypesForTests._csStudentSymType; @@ -53,15 +51,14 @@ import static de.monticore.types3.util.DefsTypesForTests.inScope; import static de.monticore.types3.util.DefsTypesForTests.typeVariable; import static de.monticore.types3.util.DefsTypesForTests.variable; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * used to provide facilities to test type derivers. * main extensions point are the methods * setup, setupValues, parseString*, generateScopes, calculateTypes */ -public class AbstractTypeVisitorTest extends AbstractTypeTest { +public class AbstractTypeVisitorTest extends AbstractMCTest { // Parser, etc. used for convenience: // (may be any other Parser that understands CommonExpressions) @@ -117,24 +114,15 @@ protected void setupSymbolTableCompleter( ITraverser typeMapTraverser, Type4Ast type4Ast) { CombineExpressionsWithLiteralsTraverser combinedScopesCompleter = CombineExpressionsWithLiteralsMill.traverser(); - IDerive deriver = new TypeCheck3AsIDerive(); - ISynthesize synthesizer = new TypeCheck3AsISynthesize(); combinedScopesCompleter.add4LambdaExpressions( - new LambdaExpressionsSTCompleteTypes2( - typeMapTraverser, - getType4Ast() - ) + new LambdaExpressionsSTCompleteTypes2() ); OCLExpressionsSymbolTableCompleter oclExprCompleter = new OCLExpressionsSymbolTableCompleter(); - oclExprCompleter.setDeriver(deriver); - oclExprCompleter.setSynthesizer(synthesizer); combinedScopesCompleter.add4OCLExpressions(oclExprCompleter); combinedScopesCompleter.setOCLExpressionsHandler(oclExprCompleter); SetExpressionsSymbolTableCompleter setExprCompleter = new SetExpressionsSymbolTableCompleter(); - setExprCompleter.setDeriver(deriver); - setExprCompleter.setSynthesizer(synthesizer); combinedScopesCompleter.add4SetExpressions(setExprCompleter); combinedScopesCompleter.setSetExpressionsHandler(setExprCompleter); symbolTableCompleter = combinedScopesCompleter; @@ -183,15 +171,23 @@ protected void setupValues() { } // Parse a String expression of the according language - protected Optional parseStringExpr(String exprStr) - throws IOException { - return parser.parse_StringExpression(exprStr); + protected Optional parseStringExpr(String exprStr) { + try { + return parser.parse_StringExpression(exprStr); + } + catch (IOException e) { + return fail(e); + } } // Parse a String type identifier of the according language - protected Optional parseStringMCType(String mcTypeStr) - throws IOException { - return parser.parse_StringMCType(mcTypeStr); + protected Optional parseStringMCType(String mcTypeStr) { + try { + return parser.parse_StringMCType(mcTypeStr); + } + catch (IOException e) { + return fail(e); + } } protected void generateScopes(ASTExpression expr) { @@ -250,15 +246,17 @@ protected void generateScopes(ASTMCType mcType) { rootScope.setName("fooRoot"); } - protected ASTExpression parseExpr(String exprStr) throws IOException { + protected ASTExpression parseExpr(String exprStr) { Optional astExpression = parseStringExpr(exprStr); - Assertions.assertTrue(astExpression.isPresent(), getAllFindingsAsString()); + assertNoFindings(); + assertTrue(astExpression.isPresent()); return astExpression.get(); } - protected ASTMCType parseMCType(String typeStr) throws IOException { + protected ASTMCType parseMCType(String typeStr) { Optional mcType = parseStringMCType(typeStr); - Assertions.assertTrue(mcType.isPresent(), getAllFindingsAsString()); + assertNoFindings(); + assertTrue(mcType.isPresent()); return mcType.get(); } @@ -266,18 +264,17 @@ protected void checkExpr( String exprStr, String targetTypeStr, String expectedType - ) throws IOException { + ) { checkExpr(exprStr, targetTypeStr, expectedType, true); } - protected void checkExpr(String exprStr, String expectedType) - throws IOException { + protected void checkExpr(String exprStr, String expectedType) { checkExpr(exprStr, expectedType, true); } protected void checkExpr( String exprStr, String expectedType, boolean allowNormalization - ) throws IOException { + ) { checkExpr(exprStr, "", expectedType, allowNormalization); } @@ -287,34 +284,19 @@ protected void checkExpr( String targetTypeStr, String expectedType, boolean allowNormalization - ) throws IOException { - ASTExpression astExpr = parseExpr(exprStr); - // target type - Optional targetTypeOpt = getTargetType(targetTypeStr); - // calculate expression - generateScopes(astExpr); - assertNoFindings(); - SymTypeExpression type; - if (targetTypeOpt.isPresent()) { - type = TypeCheck3.typeOf(astExpr, targetTypeOpt.get()); - } - else { - type = TypeCheck3.typeOf(astExpr); - } - assertNoFindings(); - assertFalse(type.isObscureType(), "No type calculated for expression " + exprStr); + ) { + SymTypeExpression type = getTypeOfExpr(exprStr, targetTypeStr); // usually, type normalization is expected and (basically) always allowed // for specific tests, however, it may be required to disable this SymTypeExpression typeNormalized = SymTypeRelations.normalize(type); boolean equalsNormalized = expectedType.equals(typeNormalized.printFullName()); if (!allowNormalization || !equalsNormalized) { - Assertions.assertEquals(expectedType, type.printFullName(), "Wrong type for expression " + exprStr); + assertEquals(expectedType, type.printFullName(), "Wrong type for expression " + exprStr); } } - protected void checkType(String typeStr, String expectedType) - throws IOException { + protected void checkType(String typeStr, String expectedType) { ASTMCType astType = parseMCType(typeStr); checkType(astType, expectedType); } @@ -323,7 +305,7 @@ protected void checkType(ASTMCType astType, String expectedType) { generateScopes(astType); SymTypeExpression type = TypeCheck3.symTypeFromAST(astType); assertNoFindings(); - Assertions.assertEquals(expectedType, type.printFullName(), + assertEquals(expectedType, type.printFullName(), "Wrong type for type identifier " + MCBasicTypesMill.prettyPrint(astType, false) ); @@ -332,12 +314,11 @@ protected void checkType(ASTMCType astType, String expectedType) { /** * roundtrip test: parse, calculate type, print, compare */ - protected void checkTypeRoundTrip(String typeStr) throws IOException { + protected void checkTypeRoundTrip(String typeStr) { checkType(typeStr, typeStr); } - protected void checkErrorExpr(String exprStr, String expectedError) - throws IOException { + protected void checkErrorExpr(String exprStr, String expectedError) { checkErrorExpr(exprStr, "", expectedError); } @@ -345,7 +326,7 @@ protected void checkErrorExpr( String exprStr, String targetTypeStr, String expectedError - ) throws IOException { + ) { ASTExpression astExpr = parseExpr(exprStr); // add target type Optional targetTypeOpt = getTargetType(targetTypeStr); @@ -363,13 +344,12 @@ protected void checkErrorExpr( "\" but got " + type.printFullName()); // check that the typecheck did something; // if not correctly configured, this will not hold true - Assertions.assertTrue(getType4Ast().hasPartialTypeOfExpression(astExpr)); + assertTrue(getType4Ast().hasPartialTypeOfExpression(astExpr)); assertHasErrorCode(expectedError); Log.getFindings().clear(); } - protected void checkErrorMCType(String typeStr, String expectedError) - throws IOException { + protected void checkErrorMCType(String typeStr, String expectedError) { ASTMCType astType = parseMCType(typeStr); generateScopes(astType); assertNoFindings(); @@ -379,17 +359,50 @@ protected void checkErrorMCType(String typeStr, String expectedError) + "\" but got " + type.printFullName()); // check that the typecheck did something; // if not correctly configured, this will not hold true - Assertions.assertTrue(getType4Ast().hasPartialTypeOfTypeIdentifier(astType)); + assertTrue(getType4Ast().hasPartialTypeOfTypeIdentifier(astType)); assertHasErrorCode(expectedError); } // Helper + protected SymTypeExpression getTypeOfExpr(String exprStr, String targetTypeStr) { + ASTExpression astExpr = parseExpr(exprStr); + // target type + Optional targetTypeOpt = getTargetType(targetTypeStr); + // calculate expression + generateScopes(astExpr); + assertNoFindings(); + SymTypeExpression type; + if (targetTypeOpt.isPresent()) { + type = TypeCheck3.typeOf(astExpr, targetTypeOpt.get()); + } + else { + type = TypeCheck3.typeOf(astExpr); + } + assertNoFindings(); + assertFalse(type.isObscureType(), "No type calculated for expression " + exprStr); + return type; + } + + protected SymTypeExpression getTypeOfExpr(String exprStr) { + return getTypeOfExpr(exprStr, ""); + } + + protected SymTypeExpression getTypeOfMCType(String typeStr) { + ASTMCType astTargetType = parseMCType(typeStr); + generateScopes(astTargetType); + SymTypeExpression type = TypeCheck3.symTypeFromAST(astTargetType); + assertNoFindings(); + assertFalse(type.isObscureType(), + "No type calculated for MCType " + typeStr + ); + return type; + } + /** * @param targetTypeStr is allowed to be empty */ - protected Optional getTargetType(String targetTypeStr) - throws IOException { + protected Optional getTargetType(String targetTypeStr) { if (!targetTypeStr.isEmpty()) { ASTMCType astTargetType = parseMCType(targetTypeStr); generateScopes(astTargetType); @@ -433,14 +446,12 @@ protected boolean hasErrorCode(String code) { return getAllErrorCodes().stream().anyMatch(code::equals); } + /** + * @deprecated use MCAssertions directly instead + */ + @Deprecated protected void assertHasErrorCode(String code) { - Assertions.assertTrue(hasErrorCode(code), "Error \"" + code + "\" expected, " - + "but instead the errors are:" - + System.lineSeparator() - + Log.getFindings().stream() - .map(Finding::buildMsg) - .collect(Collectors.joining(System.lineSeparator())) - + System.lineSeparator()); + MCAssertions.assertHasFindingStartingWith(code); } protected Type4Ast getType4Ast() { diff --git a/monticore-grammar/src/test/java/de/monticore/types3/CallGenericFunctionsTest.java b/monticore-grammar/src/test/java/de/monticore/types3/CallGenericFunctionsTest.java index e54358160a..9c8c93653c 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/CallGenericFunctionsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/CallGenericFunctionsTest.java @@ -17,12 +17,7 @@ import java.util.List; import java.util.stream.Stream; -import static de.monticore.types.check.SymTypeExpressionFactory.createFunction; -import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; -import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; -import static de.monticore.types.check.SymTypeExpressionFactory.createTypeVariable; -import static de.monticore.types.check.SymTypeExpressionFactory.createWildcard; -import static de.monticore.types.mccollectiontypes.types3.util.MCCollectionSymTypeFactory.createList; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests._IntegerSymType; import static de.monticore.types3.util.DefsTypesForTests._carSymType; import static de.monticore.types3.util.DefsTypesForTests._floatSymType; @@ -38,6 +33,12 @@ import static de.monticore.types3.util.DefsTypesForTests.variable; import static de.monticore.types3.util.DefsVariablesForTests._carVarSym; import static de.monticore.types3.util.DefsVariablesForTests._personVarSym; +import static de.monticore.types.check.SymTypeExpressionFactory.createFunction; +import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeVariable; +import static de.monticore.types.check.SymTypeExpressionFactory.createWildcard; +import static de.monticore.types.mccollectiontypes.types3.util.MCCollectionSymTypeFactory.createList; import static org.junit.jupiter.params.provider.Arguments.arguments; public class CallGenericFunctionsTest diff --git a/monticore-grammar/src/test/java/de/monticore/types3/CommonExpressionTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/CommonExpressionTypeVisitorTest.java index 2f64c4c0f8..ca6c0d92b8 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/CommonExpressionTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/CommonExpressionTypeVisitorTest.java @@ -27,7 +27,6 @@ import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,6 +34,9 @@ import java.util.Collections; import java.util.List; +import static de.monticore.runtime.junit.MCAssertions.assertHasFindingsStartingWith; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; +import static de.monticore.types3.util.DefsTypesForTests.*; import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; import static de.monticore.types.check.SymTypeExpressionFactory.createIntersection; import static de.monticore.types.check.SymTypeExpressionFactory.createTuple; @@ -42,7 +44,7 @@ import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; import static de.monticore.types.check.SymTypeExpressionFactory.createTypeVariable; import static de.monticore.types.check.SymTypeExpressionFactory.createUnion; -import static de.monticore.types3.util.DefsTypesForTests.*; +import static org.junit.jupiter.api.Assertions.*; public class CommonExpressionTypeVisitorTest extends AbstractTypeVisitorTest { @@ -1164,352 +1166,352 @@ public void deriveFromConditionalExpression() throws IOException { generateScopes(astExpr); assertNoFindings(); SymTypeExpression type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_shortSymType, type)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_byteSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_shortSymType, type)); + assertFalse(SymTypeRelations.isCompatible(_byteSymType, type)); //test with two ints as true and false expression astExpr = parseExpr("3<4?9:10"); generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); // test with boolean and int astExpr = parseExpr("3<4?true:7"); generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, type)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, type)); + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, type)); + assertFalse(SymTypeRelations.isCompatible(_intSymType, type)); //test with float and long astExpr = parseExpr("3>4?4.5f:10L"); generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertFalse(SymTypeRelations.isCompatible(_longSymType, type)); //test without primitive types as true and false expression astExpr = parseExpr("3<9?person1:person2"); generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_personSymType, type)); //test with two objects in a sub-supertype relation astExpr = parseExpr("3<9?student1:person2"); generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, type)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_studentSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_personSymType, type)); + assertFalse(SymTypeRelations.isCompatible(_studentSymType, type)); astExpr = parseExpr("varboolean ? 0 : 1"); // ? applicable to boolean generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varboolean ? varboolean : varboolean"); // ? applicable to boolean, boolean, result is boolean generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_booleanSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_booleanSymType, type)); astExpr = parseExpr("varbyte = varboolean ? varbyte : varbyte"); // ? applicable to byte, byte, result is byte generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_byteSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_byteSymType, type)); astExpr = parseExpr("varshort = varboolean ? varbyte : varshort"); // ? applicable to byte, short, result is short generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_shortSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_shortSymType, type)); astExpr = parseExpr("varshort = varboolean ? varshort : varbyte"); // ? applicable to short, byte, result is short generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_shortSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_shortSymType, type)); astExpr = parseExpr("varshort = varboolean ? varshort : varshort"); // ? applicable to short, short, result is short generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_shortSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_shortSymType, type)); astExpr = parseExpr("varchar = varboolean ? varchar : varchar"); // ? applicable to char, char, result is char generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_charSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_charSymType, type)); astExpr = parseExpr("varint = varboolean ? varchar : varbyte"); // ? applicable to char, byte, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varbyte : varchar"); // ? applicable to byte, char, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varchar : varshort"); // ? applicable to char, short, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varshort : varchar"); // ? applicable to short, char, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varint : varbyte"); // ? applicable to int, byte, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varint : varshort"); // ? applicable to int, short, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varint : varchar"); // ? applicable to int, char, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varbyte : varint"); // ? applicable to byte, int, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varshort : varint"); // ? applicable to short, int, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varchar : varint"); // ? applicable to char, int, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, type)); astExpr = parseExpr("varint = varboolean ? varint : varint"); // ? applicable to int, int, result is int generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varlong : varbyte"); // ? applicable to long, byte, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varlong : varshort"); // ? applicable to long, short, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varlong : varchar"); // ? applicable to long, char, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varlong : varint"); // ? applicable to long, int, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varbyte : varlong"); // ? applicable to byte, long, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varshort : varlong"); // ? applicable to short, long, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varchar : varlong"); // ? applicable to char, long, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varint : varlong"); // ? applicable to int, long, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varlong = varboolean ? varlong : varlong"); // ? applicable to long, long, result is long generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varfloat : varbyte"); // ? applicable to float, byte, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varfloat : varshort"); // ? applicable to float, short, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varfloat : varchar"); // ? applicable to float, char, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varfloat : varint"); // ? applicable to float, int, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varfloat : varlong"); // ? applicable to float, long, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varbyte : varfloat"); // ? applicable to byte, float, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varshort : varfloat"); // ? applicable to short, float, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varchar : varfloat"); // ? applicable to char, float, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varint : varfloat"); // ? applicable to int, float, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varlong : varfloat"); // ? applicable to long, float, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("varfloat = varboolean ? varfloat : varfloat"); // ? applicable to float, float, result is float generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, type)); astExpr = parseExpr("vardouble = varboolean ? vardouble : varbyte"); // ? applicable to double, byte, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? vardouble : varshort"); // ? applicable to double, short, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? vardouble : varchar"); // ? applicable to double, char, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? vardouble : varint"); // ? applicable to double, int, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? vardouble : varlong"); // ? applicable to double, long, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? vardouble : varfloat"); // ? applicable to double, long, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? varbyte : vardouble"); // ? applicable to byte, double, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? varshort : vardouble"); // ? applicable to short, double, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? varchar : vardouble"); // ? applicable to char, double, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? varint : vardouble"); // ? applicable to int, double, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? varlong : vardouble"); // ? applicable to long, double, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? varfloat : vardouble"); // ? applicable to float, double, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); astExpr = parseExpr("vardouble = varboolean ? vardouble : vardouble"); // ? applicable to double, double, result is double generateScopes(astExpr); assertNoFindings(); type = TypeCheck3.typeOf(astExpr); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, type)); } @Test @@ -1622,7 +1624,7 @@ public void init_advanced() { variable("selfVar", createTypeObject(selfReflectiveStudent)) ); inScope(globalScope, variable("selfReflectiveStudent", - createTypeObject("SelfReflectiveStudent", globalScope)) + SymTypeExpressionFactory.createTypeObjectViaSurrogate("SelfReflectiveStudent", globalScope)) ); inScope(artifactScope2, type("AClass")); @@ -1723,6 +1725,11 @@ public void init_advanced() { SymTypeExpressionFactory.createTypeExpression(oneFieldMember)); firstLayer.setIsStatic(true); inScope(deepNesting.getSpannedScope(), firstLayer); + + // specifically not normalized intersection + inScope(globalScope, variable("intersectionNotNormalized", + createIntersection(createTypeObject(testType), createTypeObject(testType)) + )); } @Test @@ -1764,22 +1771,32 @@ public void deriveFromFieldAccessExpressionInnerResults() throws IOException { // calculate all the types TypeCheck3.typeOf(astTestVariable); assertNoFindings(); - Assertions.assertTrue(getType4Ast().hasTypeOfExpression(astTestVariable)); - Assertions.assertFalse(getType4Ast().hasTypeOfTypeIdentifierForName(astTestVariable)); - Assertions.assertEquals("short", getType4Ast().getTypeOfExpression(astTestVariable).printFullName()); - Assertions.assertFalse(getType4Ast().hasTypeOfExpression(astTestInnerType)); - Assertions.assertTrue(getType4Ast().hasTypeOfTypeIdentifierForName(astTestInnerType)); - Assertions.assertEquals("types3.types2.Test.TestInnerType", getType4Ast().getPartialTypeOfTypeIdForName(astTestInnerType).printFullName()); - Assertions.assertFalse(getType4Ast().hasTypeOfExpression(astTest)); - Assertions.assertTrue(getType4Ast().hasTypeOfTypeIdentifierForName(astTest)); - Assertions.assertEquals("types3.types2.Test", getType4Ast().getPartialTypeOfTypeIdForName(astTest).printFullName()); - Assertions.assertFalse(getType4Ast().hasTypeOfExpression(astTypes2)); - Assertions.assertFalse(getType4Ast().hasTypeOfTypeIdentifierForName(astTypes2)); - Assertions.assertFalse(getType4Ast().hasTypeOfExpression(astTypes3)); - Assertions.assertFalse(getType4Ast().hasTypeOfTypeIdentifierForName(astTypes3)); + assertTrue(getType4Ast().hasTypeOfExpression(astTestVariable)); + assertFalse(getType4Ast().hasTypeOfTypeIdentifierForName(astTestVariable)); + assertEquals("short", getType4Ast().getTypeOfExpression(astTestVariable).printFullName()); + assertFalse(getType4Ast().hasTypeOfExpression(astTestInnerType)); + assertTrue(getType4Ast().hasTypeOfTypeIdentifierForName(astTestInnerType)); + assertEquals("types3.types2.Test.TestInnerType", getType4Ast().getPartialTypeOfTypeIdForName(astTestInnerType).printFullName()); + assertFalse(getType4Ast().hasTypeOfExpression(astTest)); + assertTrue(getType4Ast().hasTypeOfTypeIdentifierForName(astTest)); + assertEquals("types3.types2.Test", getType4Ast().getPartialTypeOfTypeIdForName(astTest).printFullName()); + assertFalse(getType4Ast().hasTypeOfExpression(astTypes2)); + assertFalse(getType4Ast().hasTypeOfTypeIdentifierForName(astTypes2)); + assertFalse(getType4Ast().hasTypeOfExpression(astTypes3)); + assertFalse(getType4Ast().hasTypeOfTypeIdentifierForName(astTypes3)); assertNoFindings(); } + /** + * tests whether intersection types are properly supported + */ + @Test + public void deriveFromFieldAccessExpressionDoubleIntersection() { + init_advanced(); + + checkExpr("intersectionNotNormalized.variable", "int"); + } + /** * tests whether inner results are all present */ @@ -1997,6 +2014,12 @@ public void deriveFromCallExpressionIntersection() throws IOException { checkExpr("talkingCar.getAge()", "int"); } + @Test + public void deriveFromCallExpressionOverloaded() { + checkExpr("overloadedFunc1(true)", "int"); + checkExpr("overloadedFunc1(42)", "boolean"); + } + @Test public void testInvalidCallExpression() throws IOException { //method isNot() is not in scope -> method cannot be resolved -> method has no return type @@ -2009,7 +2032,7 @@ public void testInvalidCallExpressionWithMissingNameAndNotComposedOfCallback() throws IOException { // Expression (2 + 3)() and all other Expressions in front of brackets are parsable init_advanced(); - checkErrorExpr("(2 + 3)()", "0xFDABC"); + checkErrorExpr("(2 + 3)()", "0xFDAB4"); } @Test @@ -2487,42 +2510,42 @@ public void visit(ASTExpression node) { // todo https://git.rwth-aachen.de/monticore/monticore/-/issues/4362 // = TypeCheck3.typeOf(astexpr); assertNoFindings(); - //Assertions.assertEquals("void", type.printFullName()); + //assertEquals("void", type.printFullName()); astexpr = parseExpr("myName"); generateScopes(astexpr); astexpr.accept(scopeSetter); type = TypeCheck3.typeOf(astexpr); assertNoFindings(); - Assertions.assertEquals("String", type.printFullName()); + assertEquals("String", type.printFullName()); astexpr = parseExpr("next"); generateScopes(astexpr); astexpr.accept(scopeSetter); type = TypeCheck3.typeOf(astexpr); assertNoFindings(); - Assertions.assertEquals("MySubList.V", type.printFullName()); + assertEquals("MySubList.V", type.printFullName()); astexpr = parseExpr("name"); generateScopes(astexpr); astexpr.accept(scopeSetter); type = TypeCheck3.typeOf(astexpr); assertNoFindings(); - Assertions.assertEquals("String", type.printFullName()); + assertEquals("String", type.printFullName()); astexpr = parseExpr("parameter"); generateScopes(astexpr); astexpr.accept(scopeSetter); type = TypeCheck3.typeOf(astexpr); assertNoFindings(); - Assertions.assertEquals("MySubList.V", type.printFullName()); + assertEquals("MySubList.V", type.printFullName()); astexpr = parseExpr("add(parameter)"); generateScopes(astexpr); astexpr.accept(scopeSetter); type = TypeCheck3.typeOf(astexpr); assertNoFindings(); - Assertions.assertEquals("void", type.printFullName()); + assertEquals("void", type.printFullName()); } public void init_static_example() { @@ -2588,7 +2611,9 @@ public void testStaticType() throws IOException { public void testInvalidStaticType() throws IOException { init_static_example(); - checkErrorMCType("A.NotAType", "0xA0324"); + checkErrorMCType("A.NotAType", "0xFDAE3"); + // legacy error code... + assertHasFindingsStartingWith("0xA0324"); } @Test diff --git a/monticore-grammar/src/test/java/de/monticore/types3/CommonLiteralsTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/CommonLiteralsTypeVisitorTest.java index fb39c8c772..f06f2559c2 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/CommonLiteralsTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/CommonLiteralsTypeVisitorTest.java @@ -4,14 +4,16 @@ import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.literals.mccommonliterals.MCCommonLiteralsMill; import de.monticore.literals.mcliteralsbasis._ast.ASTLiteral; -import de.monticore.types.check.SymTypeExpression; import de.monticore.types3.util.DefsTypesForTests; -import org.junit.jupiter.api.Assertions; +import de.monticore.types.check.SymTypeExpression; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class CommonLiteralsTypeVisitorTest extends AbstractTypeVisitorTest { @BeforeEach @@ -138,7 +140,7 @@ public void deriveTFromLiteral1BasicDouble() { protected void check(ASTLiteral lit, String expected) { lit.setEnclosingScope(CombineExpressionsWithLiteralsMill.globalScope()); SymTypeExpression type = TypeCheck3.typeOf(lit); - Assertions.assertEquals(expected, type.printFullName()); + assertEquals(expected, type.printFullName()); assertNoFindings(); } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/JavaClassExpressionsTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/JavaClassExpressionsTypeVisitorTest.java index cc5bbefe25..c64ac03339 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/JavaClassExpressionsTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/JavaClassExpressionsTypeVisitorTest.java @@ -10,6 +10,8 @@ import java.io.IOException; import java.util.stream.Stream; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; + public class JavaClassExpressionsTypeVisitorTest extends AbstractTypeVisitorTest { diff --git a/monticore-grammar/src/test/java/de/monticore/types3/MCArrayTypesTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/MCArrayTypesTypeVisitorTest.java index cef691e8e0..f5798cbf6e 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/MCArrayTypesTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/MCArrayTypesTypeVisitorTest.java @@ -5,6 +5,8 @@ import java.io.IOException; +import static de.monticore.runtime.junit.MCAssertions.assertHasFindingStartingWith; + public class MCArrayTypesTypeVisitorTest extends AbstractTypeVisitorTest { @@ -21,6 +23,8 @@ public void symTypeFromAST_ArrayTest2() throws IOException { @Test public void symTypeFromAST_ArrayTest3() throws IOException { checkErrorMCType("notAType[]", "0xE9CDC"); + // legacy error code + assertHasFindingStartingWith("0xA0324"); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/MCBasicTypesTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/MCBasicTypesTypeVisitorTest.java index 6b8673d381..a06599f583 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/MCBasicTypesTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/MCBasicTypesTypeVisitorTest.java @@ -4,12 +4,15 @@ import de.monticore.types.check.SymTypeExpression; import de.monticore.types.mcbasictypes._ast.ASTMCReturnType; import de.monticore.types.mcbasictypes._ast.ASTMCType; -import org.junit.jupiter.api.Assertions; +import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class MCBasicTypesTypeVisitorTest extends AbstractTypeVisitorTest { @@ -38,10 +41,12 @@ public void symTypeFromAST_VoidTest() throws IOException { Optional typeOpt = parser.parse_StringMCType("void"); if (parser.hasErrors()) { // OK + // to be fixed: currently, Parser error has no error code + Log.clearFindings(); } else { // if it can be parsed, we expect an error - Assertions.assertTrue(typeOpt.isPresent()); + assertTrue(typeOpt.isPresent()); generateScopes(typeOpt.get()); checkType(typeOpt.get(), "void"); } @@ -51,22 +56,20 @@ public void symTypeFromAST_VoidTest() throws IOException { public void symTypeFromAST_ReturnTest() throws IOException { Optional typeOpt = parser.parse_StringMCReturnType("void"); - Assertions.assertTrue(typeOpt.isPresent()); + assertTrue(typeOpt.isPresent()); SymTypeExpression type = TypeCheck3.symTypeFromAST(typeOpt.get()); - Assertions.assertEquals("void", type.printFullName()); - assertNoFindings(); + assertEquals("void", type.printFullName()); } @Test public void symTypeFromAST_ReturnTest2() throws IOException { Optional typeOpt = parser.parse_StringMCReturnType("Person"); - Assertions.assertTrue(typeOpt.isPresent()); - Assertions.assertTrue(typeOpt.get().isPresentMCType()); + assertTrue(typeOpt.isPresent()); + assertTrue(typeOpt.get().isPresentMCType()); generateScopes(typeOpt.get().getMCType()); SymTypeExpression type = TypeCheck3.symTypeFromAST(typeOpt.get()); - Assertions.assertEquals("Person", type.printFullName()); - assertNoFindings(); + assertEquals("Person", type.printFullName()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/MCCollectionTypesTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/MCCollectionTypesTypeVisitorTest.java index dcce461821..b81dc4597e 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/MCCollectionTypesTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/MCCollectionTypesTypeVisitorTest.java @@ -10,14 +10,15 @@ import de.monticore.types.check.SymTypeOfGenerics; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mccollectiontypes._ast.ASTMCListType; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests.inScope; import static de.monticore.types3.util.DefsTypesForTests.type; +import static org.junit.jupiter.api.Assertions.*; public class MCCollectionTypesTypeVisitorTest extends AbstractTypeVisitorTest { @@ -49,13 +50,13 @@ public void symTypeFromAST_TestList1() throws IOException { // Then assertNoFindings(); - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof OOTypeSymbolSurrogate); } @@ -72,13 +73,13 @@ public void symTypeFromAST_TestSet1() throws IOException { // Then assertNoFindings(); - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof OOTypeSymbolSurrogate); } @@ -94,17 +95,17 @@ public void symTypeFromAST_TestMap1() throws IOException { // Then assertNoFindings(); - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(1) + assertFalse(((SymTypeOfGenerics) result).getArgument(1) .getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(1) + assertFalse(((SymTypeOfGenerics) result).getArgument(1) .getTypeInfo() instanceof OOTypeSymbolSurrogate); } @@ -120,13 +121,13 @@ public void symTypeFromAST_TestSet2() throws IOException { // Then assertNoFindings(); - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof OOTypeSymbolSurrogate); } @@ -142,13 +143,13 @@ public void symTypeFromAST_TestOptional1() throws IOException { // Then assertNoFindings(); - Assertions.assertEquals(s, result.printFullName()); - Assertions.assertTrue(result instanceof SymTypeOfGenerics); - Assertions.assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertEquals(s, result.printFullName()); + assertInstanceOf(SymTypeOfGenerics.class, result); + assertFalse(result.getTypeInfo() instanceof TypeSymbolSurrogate); + assertFalse(result.getTypeInfo() instanceof OOTypeSymbolSurrogate); + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof TypeSymbolSurrogate); - Assertions.assertFalse(((SymTypeOfGenerics) result).getArgument(0) + assertFalse(((SymTypeOfGenerics) result).getArgument(0) .getTypeInfo() instanceof OOTypeSymbolSurrogate); } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/MCSimpleGenericTypesTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/MCSimpleGenericTypesTypeVisitorTest.java index 3a9e4dc576..720c3a1429 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/MCSimpleGenericTypesTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/MCSimpleGenericTypesTypeVisitorTest.java @@ -1,10 +1,10 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; -import de.monticore.types3.util.DefsTypesForTests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/monticore-grammar/src/test/java/de/monticore/types3/MapBasedTypeCheck3Test.java b/monticore-grammar/src/test/java/de/monticore/types3/MapBasedTypeCheck3Test.java index 31a2d0ac4c..b3a7fbf063 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/MapBasedTypeCheck3Test.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/MapBasedTypeCheck3Test.java @@ -7,10 +7,11 @@ import java.io.IOException; -import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests._floatSymType; import static de.monticore.types3.util.DefsTypesForTests._intSymType; import static de.monticore.types3.util.DefsTypesForTests._unboxedListSymType; +import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; import static org.junit.jupiter.api.Assertions.assertTrue; public class MapBasedTypeCheck3Test extends AbstractTypeVisitorTest { diff --git a/monticore-grammar/src/test/java/de/monticore/types3/OCLExpressionsTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/OCLExpressionsTypeVisitorTest.java index 7e4c34d304..158afc452e 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/OCLExpressionsTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/OCLExpressionsTypeVisitorTest.java @@ -1,18 +1,19 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3; +import de.monticore.types3.util.DefsVariablesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.mccollectiontypes.types3.MCCollectionSymTypeRelations; -import de.monticore.types3.util.DefsVariablesForTests; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests._intSymType; import static de.monticore.types3.util.DefsTypesForTests.function; import static de.monticore.types3.util.DefsTypesForTests.inScope; diff --git a/monticore-grammar/src/test/java/de/monticore/types3/OptionalOperatorsTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/OptionalOperatorsTypeVisitorTest.java index 71e317ee6b..3522812dcb 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/OptionalOperatorsTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/OptionalOperatorsTypeVisitorTest.java @@ -1,11 +1,11 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3; +import de.monticore.types3.util.DefsVariablesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; import de.monticore.types.mccollectiontypes.types3.MCCollectionSymTypeRelations; import de.monticore.types.mccollectiontypes.types3.util.MCCollectionSymTypeFactory; -import de.monticore.types3.util.DefsVariablesForTests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/monticore-grammar/src/test/java/de/monticore/types3/ResolveTypeIdAsConstructorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/ResolveTypeIdAsConstructorTest.java index 15d1231385..e533337965 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/ResolveTypeIdAsConstructorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/ResolveTypeIdAsConstructorTest.java @@ -9,6 +9,8 @@ import de.monticore.mcbasics._symboltable.IMCBasicsScope; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; +import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.symbols.oosymbols._symboltable.MethodSymbol; import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; import de.monticore.types.check.SymTypeExpression; @@ -16,7 +18,6 @@ import de.monticore.types.check.SymTypeOfFunction; import de.monticore.types.check.SymTypeOfIntersection; import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,18 +25,22 @@ import java.util.Collection; import java.util.stream.Collectors; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests._floatSymType; import static de.monticore.types3.util.DefsTypesForTests._intSymType; import static de.monticore.types3.util.DefsTypesForTests.inScope; import static de.monticore.types3.util.DefsTypesForTests.method; import static de.monticore.types3.util.DefsTypesForTests.oOtype; +import static de.monticore.types3.util.DefsTypesForTests.typeVariable; +import static de.monticore.types3.util.DefsTypesForTests.variable; +import static org.junit.jupiter.api.Assertions.*; /** * tests whether we can resolve correctly constructors * based solely on their Type identifiers, * e.g., Foo(1) -> based on Constructor Foo::Foo(int) - * It mostly tests {@link de.monticore.expressions.expressionsbasis.types3.ExpressionBasisTypeIdAsConstructorTypeVisitor} - * and {@link de.monticore.expressions.commonexpressions.types3.CommonExpressionsTypeIdAsConstructorTypeVisitor} + * It mostly tests {@link de.monticore.expressions.expressionsbasis.types3.ExpressionBasisTypeIdAsConstructorCTTIVisitor} + * and {@link de.monticore.expressions.commonexpressions.types3.CommonExpressionsTypeIdAsConstructorCTTIVisitor} */ public class ResolveTypeIdAsConstructorTest extends AbstractTypeVisitorTest { @@ -44,7 +49,7 @@ public void before() { CombineExpressionsWithLiteralsMill.reset(); CombineExpressionsWithLiteralsMill.init(); // replace the typeMapTraverser with an OO-aware variant - new CombineExpressionsWithLiteralsTypeTraverserFactory() + CombineExpressionsWithLiteralsTypeTraverserFactory .initTypeCheck3ForOOWithConstructors(); } @@ -56,7 +61,7 @@ public void before() { // } // => test to resolve constructor here @Test - public void test1() throws IOException { + public void test1() { IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); OOTypeSymbol oOType = oOtype("t"); @@ -79,30 +84,30 @@ public void test1() throws IOException { // do not find the constructor if we find a function SymTypeExpression type = calculateTypeWithinScope("t", oOType.getSpannedScope()); - Assertions.assertEquals("() -> int", type.printFullName()); - Assertions.assertSame(method, ((SymTypeOfFunction) type).getSymbol()); + assertEquals("() -> int", type.printFullName()); + assertSame(method, ((SymTypeOfFunction) type).getSymbol()); // do not find the constructor if we find a function type = calculateTypeWithinScope("t.t", gs); - Assertions.assertEquals("() -> int", type.printFullName()); - Assertions.assertSame(method, ((SymTypeOfFunction) type).getSymbol()); + assertEquals("() -> int", type.printFullName()); + assertSame(method, ((SymTypeOfFunction) type).getSymbol()); // find the constructor based on the type id type = calculateTypeWithinScope("t", gs); - Assertions.assertTrue(type.isIntersectionType()); + assertTrue(type.isIntersectionType()); Collection functions = ((SymTypeOfIntersection) type).getIntersectedTypeSet(); - Assertions.assertTrue(functions.stream().allMatch(f -> f.isFunctionType())); + assertTrue(functions.stream().allMatch(f -> f.isFunctionType())); Collection constructors = functions.stream() .map(f -> (SymTypeOfFunction) f) .collect(Collectors.toSet()); - Assertions.assertEquals(2, constructors.size()); - Assertions.assertTrue(constructors.stream().anyMatch(c -> c.getSymbol() == constructor)); - Assertions.assertTrue(constructors.stream().anyMatch(c -> c.getSymbol() == constructor2)); - Assertions.assertTrue(constructors.stream() + assertEquals(2, constructors.size()); + assertTrue(constructors.stream().anyMatch(c -> c.getSymbol() == constructor)); + assertTrue(constructors.stream().anyMatch(c -> c.getSymbol() == constructor2)); + assertTrue(constructors.stream() .map(SymTypeOfFunction::printFullName) .anyMatch(p -> p.equals("() -> t"))); - Assertions.assertTrue(constructors.stream() + assertTrue(constructors.stream() .map(SymTypeOfFunction::printFullName) .anyMatch(p -> p.equals("t -> t"))); @@ -120,7 +125,7 @@ public void test1() throws IOException { // } // => test to resolve constructor here @Test - public void test2() throws IOException { + public void test2() { IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); OOTypeSymbol oOType = oOtype("t"); @@ -151,27 +156,57 @@ public void test2() throws IOException { // find the constructor based on the type id SymTypeExpression type = calculateTypeWithinScope("t", gs); - Assertions.assertTrue(type.isFunctionType()); - Assertions.assertSame(constructor, ((SymTypeOfFunction) type).getSymbol()); + assertTrue(type.isFunctionType()); + assertSame(constructor, ((SymTypeOfFunction) type).getSymbol()); // find the constructor of the inner type, // as the constructor of the outer type is filtered out type = calculateTypeWithinScope("t.t", gs); - Assertions.assertTrue(type.isFunctionType()); - Assertions.assertSame(innerConstructor2, ((SymTypeOfFunction) type).getSymbol()); + assertTrue(type.isFunctionType()); + assertSame(innerConstructor2, ((SymTypeOfFunction) type).getSymbol()); // find the constructor of the inner type, // as the constructor of the outer type is filtered out type = calculateTypeWithinScope("t", oOType.getSpannedScope()); - Assertions.assertTrue(type.isFunctionType()); - Assertions.assertSame(innerConstructor2, ((SymTypeOfFunction) type).getSymbol()); + assertTrue(type.isFunctionType()); + assertSame(innerConstructor2, ((SymTypeOfFunction) type).getSymbol()); type = calculateTypeWithinScope("t", innerOOType.getSpannedScope()); - Assertions.assertEquals("(float -> t.t) & (int -> t.t)", type.printFullName()); + assertEquals("(float -> t.t) & (int -> t.t)", type.printFullName()); assertNoFindings(); } + // class t { + // public t() {} + // } + // => test to resolve constructor here using + // t a = t(); + @Test + public void resolveTypeIDAsConstructorCTTI() { + IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); + + TypeVarSymbol typeVar = typeVariable("t"); + + OOTypeSymbol oOType = oOtype("t"); + inScope(oOType.getSpannedScope(), typeVar); + inScope(gs, oOType); + + SymTypeExpression oOTypeSymType = + SymTypeExpressionFactory.createGenericsDeclaredType(oOType); + + MethodSymbol constructor = method("t", oOTypeSymType); + constructor.setIsConstructor(true); + inScope(oOType.getSpannedScope(), constructor); + + // since it is generic, cannot directly check, thus using assignment + VariableSymbol assignee = variable("a", + SymTypeExpressionFactory.createGenerics(oOType, _intSymType) + ); + inScope(gs, assignee); + checkExpr("a = t()", "t"); + } + // Helper /** @@ -181,7 +216,7 @@ public void test2() throws IOException { protected SymTypeExpression calculateTypeWithinScope( String exprStr, IMCBasicsScope scope - ) throws IOException { + ) { ASTExpression expr = parseExpr(exprStr); generateScopes(expr); expr.accept(getExpressionScopeSetter(scope)); diff --git a/monticore-grammar/src/test/java/de/monticore/types3/ResolveWithinOOTypeTest.java b/monticore-grammar/src/test/java/de/monticore/types3/ResolveWithinOOTypeTest.java index 8718cf1600..a75cd9b773 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/ResolveWithinOOTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/ResolveWithinOOTypeTest.java @@ -11,6 +11,9 @@ import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; +import de.monticore.symbols.oosymbols.OOSymbolsMill; +import de.monticore.symbols.oosymbols._symboltable.FieldSymbol; +import de.monticore.symbols.oosymbols._symboltable.IOOSymbolsScope; import de.monticore.symbols.oosymbols._symboltable.MethodSymbol; import de.monticore.symbols.oosymbols._symboltable.MethodSymbolTOP; import de.monticore.symbols.oosymbols._symboltable.OOTypeSymbol; @@ -21,18 +24,22 @@ import de.monticore.types.check.SymTypeOfFunction; import de.monticore.types3.util.CombineExpressionsWithLiteralsTypeTraverserFactory; import de.monticore.types3.util.OOWithinTypeBasicSymbolsResolver; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests._intSymType; +import static de.monticore.types3.util.DefsTypesForTests.field; import static de.monticore.types3.util.DefsTypesForTests.inScope; import static de.monticore.types3.util.DefsTypesForTests.method; import static de.monticore.types3.util.DefsTypesForTests.oOtype; +import static org.junit.jupiter.api.Assertions.*; /** * tests whether we can resolve correctly constructors within a type. @@ -45,7 +52,7 @@ public void before() { CombineExpressionsWithLiteralsMill.reset(); CombineExpressionsWithLiteralsMill.init(); // replace the typeMapTraverser with an OO-aware variant - new CombineExpressionsWithLiteralsTypeTraverserFactory() + CombineExpressionsWithLiteralsTypeTraverserFactory .initTypeCheck3ForOO(); } @@ -78,15 +85,15 @@ public void test1() throws IOException { SymTypeExpression type = calculateTypeWithinScope("t", oOType.getSpannedScope()); - Assertions.assertEquals("() -> int", type.printFullName()); - Assertions.assertSame(method, ((SymTypeOfFunction) type).getSymbol()); + assertEquals("() -> int", type.printFullName()); + assertSame(method, ((SymTypeOfFunction) type).getSymbol()); List constructors = calculateConstructorWithinScope( oOType.getSpannedScope(), "t", BasicAccessModifier.PRIVATE ); - Assertions.assertEquals(2, constructors.size()); - Assertions.assertTrue(constructors.contains(constructor)); - Assertions.assertTrue(constructors.contains(constructor2)); + assertEquals(2, constructors.size()); + assertTrue(constructors.contains(constructor)); + assertTrue(constructors.contains(constructor2)); } // class t { @@ -122,15 +129,92 @@ public void test2() throws IOException { List constructors = calculateConstructorWithinScope( oOType.getSpannedScope(), "t", BasicAccessModifier.PRIVATE ); - Assertions.assertEquals(2, constructors.size()); - Assertions.assertTrue(constructors.contains(constructor)); - Assertions.assertTrue(constructors.contains(constructor2)); + assertEquals(2, constructors.size()); + assertTrue(constructors.contains(constructor)); + assertTrue(constructors.contains(constructor2)); constructors = calculateConstructorWithinScope( oOType.getSpannedScope(), "t", BasicAccessModifier.PUBLIC ); - Assertions.assertEquals(1, constructors.size()); - Assertions.assertTrue(constructors.contains(constructor2)); + assertEquals(1, constructors.size()); + assertTrue(constructors.contains(constructor2)); + } + + // test if we get a list of all resolvable elements + // class s { + // public class v {} + // public s s(); + // public s s; + // } + // class t extends s { + // public class u {} + // public t(); + // public t u(); + // pulbic t u(t t); + // public t v; + // private t w; + // } + @Test + public void resolveAllElementsTest() throws IOException { + IOOSymbolsScope gs = OOSymbolsMill.globalScope(); + + OOTypeSymbol sType = inScope(gs, oOtype("s")); + SymTypeExpression sSymType = + SymTypeExpressionFactory.createTypeObject(sType); + + inScope(sType.getSpannedScope(), oOtype("v")); + inScope(sType.getSpannedScope(), method("s", sSymType)); + inScope(sType.getSpannedScope(), field("s", sSymType)); + + OOTypeSymbol tType = inScope(gs, oOtype("t", List.of(sSymType))); + SymTypeExpression tSymType = + SymTypeExpressionFactory.createTypeObject(tType); + + inScope(tType.getSpannedScope(), oOtype("u")); + MethodSymbol tConstructor = inScope( + tType.getSpannedScope(), + method("t", tSymType) + ); + tConstructor.setIsConstructor(true); + inScope(tType.getSpannedScope(), method("u", tSymType)); + inScope(tType.getSpannedScope(), + method("u", tSymType, List.of(tSymType)) + ); + inScope(tType.getSpannedScope(), field("v", tSymType)); + FieldSymbol wField = inScope( + tType.getSpannedScope(), + field("w", tSymType) + ); + wField.setIsPublic(false); + wField.setIsPrivate(true); + + Map allTypes = + OOWithinTypeBasicSymbolsResolver.getAllTypes( + tSymType, + BasicAccessModifier.PUBLIC, + t -> true + ); + assertEquals(Set.of("v", "u"), allTypes.keySet()); + + Map> allFunctions = + OOWithinTypeBasicSymbolsResolver.getAllFunctions( + tSymType, + BasicAccessModifier.PUBLIC, + f -> true + ); + // may not contain constructor + assertEquals(Set.of("s", "u"), allFunctions.keySet()); + assertEquals(1, allFunctions.get("s").size()); + assertEquals(2, allFunctions.get("u").size()); + + Map allFields = + OOWithinTypeBasicSymbolsResolver.getAllVariables( + tSymType, + BasicAccessModifier.PUBLIC, + v -> true + ); + // may not contain the private w + assertEquals(Set.of("s", "v"), allFields.keySet()); } // Helper @@ -164,11 +248,11 @@ protected List calculateConstructorWithinScope( scope, name, accessModifier, c -> true ); assertNoFindings(); - Assertions.assertTrue(functions.stream().allMatch(f -> f instanceof MethodSymbol)); + assertTrue(functions.stream().allMatch(f -> f instanceof MethodSymbol)); List constructors = functions.stream() .map(f -> (MethodSymbol) f) .collect(Collectors.toList()); - Assertions.assertTrue(constructors.stream().allMatch(MethodSymbolTOP::isIsConstructor)); + assertTrue(constructors.stream().allMatch(MethodSymbolTOP::isIsConstructor)); return constructors; } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/ResolveWithinTypeTest.java b/monticore-grammar/src/test/java/de/monticore/types3/ResolveWithinTypeTest.java index 2d1273c6db..9636af7027 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/ResolveWithinTypeTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/ResolveWithinTypeTest.java @@ -10,6 +10,8 @@ import de.monticore.mcbasics._symboltable.IMCBasicsScope; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; +import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; +import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.symbols.oosymbols._symboltable.FieldSymbol; import de.monticore.symbols.oosymbols._symboltable.MethodSymbol; @@ -21,13 +23,14 @@ import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mcbasictypes._visitor.MCBasicTypesTraverser; import de.monticore.types.mcbasictypes._visitor.MCBasicTypesVisitor2; -import org.junit.jupiter.api.Assertions; +import de.se_rwth.commons.logging.Log; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests._booleanSymType; import static de.monticore.types3.util.DefsTypesForTests.field; import static de.monticore.types3.util.DefsTypesForTests.inScope; @@ -35,6 +38,7 @@ import static de.monticore.types3.util.DefsTypesForTests.oOtype; import static de.monticore.types3.util.DefsTypesForTests.typeVariable; import static de.monticore.types3.util.DefsTypesForTests.variable; +import static org.junit.jupiter.api.Assertions.*; /** * tests whether we can resolve correctly within a type. @@ -74,21 +78,21 @@ public void test1() throws IOException { SymTypeExpression type = calculateTypeWithinScope("t", oOType.getSpannedScope()); - Assertions.assertEquals("(() -> t) & t", type.printFullName()); - Assertions.assertTrue(type.isIntersectionType()); - Assertions.assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() + assertEquals("(() -> t) & t", type.printFullName()); + assertTrue(type.isIntersectionType()); + assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() .stream() .anyMatch(t -> t.hasTypeInfo() && t.getTypeInfo() == oOType)); type = calculateTypeWithinScope("t()", oOType.getSpannedScope()); assertNoFindings(); - Assertions.assertEquals("t", type.printFullName()); - Assertions.assertSame(type.getTypeInfo(), oOType); + assertEquals("t", type.printFullName()); + assertSame(type.getTypeInfo(), oOType); type = calculateTypeWithinScope("t", method.getSpannedScope()); - Assertions.assertEquals("(() -> t) & t", type.printFullName()); - Assertions.assertTrue(type.isIntersectionType()); - Assertions.assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() + assertEquals("(() -> t) & t", type.printFullName()); + assertTrue(type.isIntersectionType()); + assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() .stream() .anyMatch(t -> t.hasTypeInfo() && t.getTypeInfo() == oOType)); } @@ -99,7 +103,8 @@ public void test1() throws IOException { // t t; // => test expression "t" in this method scope // } - // => test expressions "t" and "t()" in this class scope + // => cannot test expressions "t" in this class scope, + // as target type is missing // } @Test public void test2() throws IOException { @@ -107,35 +112,25 @@ public void test2() throws IOException { OOTypeSymbol oOType = oOtype("t"); inScope(gs, oOType); - inScope(oOType.getSpannedScope(), typeVariable("t")); + TypeVarSymbol oOTypeVar = + inScope(oOType.getSpannedScope(), typeVariable("t")); FieldSymbol field = field("t", SymTypeExpressionFactory.createTypeObject(oOType)); inScope(oOType.getSpannedScope(), field); + TypeVarSymbol methodTypeVar = typeVariable("t"); MethodSymbol method = method("t", - SymTypeExpressionFactory.createTypeObject(oOType)); + SymTypeExpressionFactory.createTypeVariable(methodTypeVar)); + inScope(method.getSpannedScope(), methodTypeVar); inScope(oOType.getSpannedScope(), method); - inScope(method.getSpannedScope(), typeVariable("t")); + IBasicSymbolsScope methodScope = inScope(method.getSpannedScope(), BasicSymbolsMill.scope()); VariableSymbol variable = variable("t", - SymTypeExpressionFactory.createTypeObject(oOType)); - inScope(method.getSpannedScope(), variable); - - SymTypeExpression type = - calculateTypeWithinScope("t", oOType.getSpannedScope()); - Assertions.assertEquals("(t -> t) & t", type.printFullName()); - Assertions.assertTrue(type.isIntersectionType()); - Assertions.assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() - .stream() - .anyMatch(t -> t.hasTypeInfo() && t.getTypeInfo() == oOType)); + SymTypeExpressionFactory.createTypeVariable(oOTypeVar)); + inScope(methodScope, variable); - type = calculateTypeWithinScope("t", method.getSpannedScope()); - Assertions.assertEquals("(t -> t) & t", type.printFullName()); - Assertions.assertTrue(type.isIntersectionType()); - Assertions.assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() - .stream() - .anyMatch(t -> t.hasTypeInfo() && t.getTypeInfo() == oOType)); + // cannot resolve t, as no target type exists. } // class s { @@ -143,7 +138,7 @@ public void test2() throws IOException { // t t; // t t() { // t t; - // => test expression "t" in this class scope + // => test expression "t" in this method scope // } // } @Test @@ -152,7 +147,8 @@ public void test3() throws IOException { OOTypeSymbol oOType = oOtype("s"); inScope(gs, oOType); - inScope(oOType.getSpannedScope(), typeVariable("t")); + TypeVarSymbol oOTypeVar = + inScope(oOType.getSpannedScope(), typeVariable("t")); OOTypeSymbol oOType1 = oOtype("t"); inScope(oOType.getSpannedScope(), oOType1); @@ -161,29 +157,19 @@ public void test3() throws IOException { SymTypeExpressionFactory.createTypeObject(oOType1)); inScope(oOType.getSpannedScope(), field); + TypeVarSymbol methodTypeVar = typeVariable("t"); MethodSymbol method = method("t", - SymTypeExpressionFactory.createTypeObject(oOType)); + SymTypeExpressionFactory.createTypeVariable(methodTypeVar) + ); inScope(oOType.getSpannedScope(), method); - inScope(method.getSpannedScope(), typeVariable("t")); + inScope(method.getSpannedScope(), methodTypeVar); + IBasicSymbolsScope methodScope = inScope(method.getSpannedScope(), BasicSymbolsMill.scope()); VariableSymbol variable = variable("t", - SymTypeExpressionFactory.createTypeObject(oOType)); - inScope(method.getSpannedScope(), variable); - - SymTypeExpression type = - calculateTypeWithinScope("t", oOType.getSpannedScope()); - Assertions.assertEquals("(s -> s) & s.t", type.printFullName()); - Assertions.assertTrue(type.isIntersectionType()); - Assertions.assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() - .stream() - .anyMatch(t -> t.hasTypeInfo() && t.getTypeInfo() == oOType1)); + SymTypeExpressionFactory.createTypeVariable(oOTypeVar)); + inScope(methodScope, variable); - type = calculateTypeWithinScope("t", method.getSpannedScope()); - Assertions.assertEquals("(s -> s) & s", type.printFullName()); - Assertions.assertTrue(type.isIntersectionType()); - Assertions.assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() - .stream() - .anyMatch(t -> t.hasTypeInfo() && t.getTypeInfo() == oOType)); + // cannot resolve t in method scope as target type for method is not present } // class s { @@ -214,27 +200,27 @@ public void test4() throws IOException { SymTypeExpression type = calculateTypeWithinScope("t", oOType.getSpannedScope()); - Assertions.assertEquals("(() -> s.t) & s.t", type.printFullName()); - Assertions.assertTrue(type.isIntersectionType()); - Assertions.assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() + assertEquals("(() -> s.t) & s.t", type.printFullName()); + assertTrue(type.isIntersectionType()); + assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() .stream() .anyMatch(t -> t.hasTypeInfo() && t.getTypeInfo() == oOType1)); type = calculateTypeWithinScope("t()", oOType.getSpannedScope()); - Assertions.assertEquals("s.t", type.printFullName()); - Assertions.assertSame(type.getTypeInfo(), oOType1); + assertEquals("s.t", type.printFullName()); + assertSame(type.getTypeInfo(), oOType1); type = calculateTypeWithinScope("t", method.getSpannedScope()); - Assertions.assertEquals("(() -> s.t) & s.t", type.printFullName()); - Assertions.assertTrue(type.isIntersectionType()); - Assertions.assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() + assertEquals("(() -> s.t) & s.t", type.printFullName()); + assertTrue(type.isIntersectionType()); + assertTrue(((SymTypeOfIntersection) type).getIntersectedTypeSet() .stream() .anyMatch(t -> t.hasTypeInfo() && t.getTypeInfo() == oOType1)); } // class t {} // class s extends t { - // t t; + // t t; // => test expression "t" in this class scope // } @Test @@ -251,13 +237,16 @@ public void test5() throws IOException { inScope(gs, oOType1); FieldSymbol field = field("t", - SymTypeExpressionFactory.createTypeObject(oOType)); + SymTypeExpressionFactory.createGenerics(oOType, + SymTypeExpressionFactory.createTypeObject(oOType1) + ) + ); inScope(oOType1.getSpannedScope(), field); SymTypeExpression type = calculateTypeWithinScope("t", oOType1.getSpannedScope()); - Assertions.assertEquals("t", type.printFullName()); - Assertions.assertSame(oOType, type.getTypeInfo()); + assertEquals("t", type.printFullName()); + assertSame(oOType, type.getTypeInfo()); } // class t {} @@ -291,8 +280,8 @@ public void test6() throws IOException { SymTypeExpression type = calculateTypeWithinScope("t", oOType2.getSpannedScope()); - Assertions.assertEquals("t", type.printFullName()); - Assertions.assertSame(type.getTypeInfo(), oOType); + assertEquals("t", type.printFullName()); + assertSame(type.getTypeInfo(), oOType); } // class t { @@ -309,7 +298,10 @@ public void testError1() throws IOException { inScope(oOType1.getSpannedScope(), typeVariable("t")); calculateTypeIDWithinScopeError("t.t", oOType1.getSpannedScope(), "0xFDAE3"); + // ignore legacy error codes explicitly + Log.clearFindings(); calculateTypeIDWithinScopeError("t.t", oOType1.getEnclosingScope(), "0xFDAE3"); + Log.clearFindings(); } // Helper diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SIUnitTypes4MathTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SIUnitTypes4MathTypeVisitorTest.java index e24f72e225..0304dd4f70 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/SIUnitTypes4MathTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/SIUnitTypes4MathTypeVisitorTest.java @@ -3,7 +3,6 @@ import de.monticore.types.check.SymTypeExpression; import de.monticore.types.mcbasictypes._ast.ASTMCType; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -11,9 +10,11 @@ import java.util.Iterator; import java.util.List; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.SIUnitIteratorForTests.get2UnitsGroup; import static de.monticore.types3.util.SIUnitIteratorForTests.getPrefixedUnits; import static de.monticore.types3.util.SIUnitIteratorForTests.getUnits; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SIUnitTypes4MathTypeVisitorTest extends AbstractTypeVisitorTest { @@ -64,7 +65,7 @@ public void synTFromSIUnitTypes4MathAmbiguousUnitsGroups() throws IOException { // But, if the amount decreases, issues have been fixed // and this number can be decreased. // This number should never increase, as it would indicate a new bug. - Assertions.assertEquals(609, ambiguous.size()); + assertEquals(609, ambiguous.size()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SetExpressionsTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SetExpressionsTypeVisitorTest.java index 3f6d7467cc..6bc7f81ae8 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/SetExpressionsTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/SetExpressionsTypeVisitorTest.java @@ -1,12 +1,12 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3; +import de.monticore.types3.util.DefsVariablesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.mccollectiontypes.types3.MCCollectionSymTypeRelations; import de.monticore.types.mccollectiontypes.types3.util.MCCollectionSymTypeFactory; -import de.monticore.types3.util.DefsVariablesForTests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -339,6 +339,8 @@ protected static Stream deriveFromSetEnumeration() { arguments("{\"1\", varPerson}", "Set<(Person | R\"1\")>"), // complex arguments("{{1}}", "Set>") + // too hard to solve due to union + //arguments("{{1}, {1.0}}", "Set | Set>") ); } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SourceSymbolsTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SourceSymbolsTest.java index 5179f8f601..c9be867a99 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/SourceSymbolsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/SourceSymbolsTest.java @@ -11,6 +11,7 @@ import de.monticore.expressions.expressionsbasis._ast.ASTExpression; import de.monticore.expressions.expressionsbasis._ast.ASTNameExpression; import de.monticore.expressions.expressionsbasis._symboltable.IExpressionsBasisScope; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol; import de.monticore.symbols.oosymbols._symboltable.FieldSymbol; @@ -19,7 +20,6 @@ import de.monticore.types.check.FlatExpressionScopeSetter; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types3.util.DefsTypesForTests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -87,8 +87,6 @@ public void testQualifiedField() throws IOException { assertTrue(listOfIntType.getSourceInfo().getSourceSymbol().isPresent()); definingSymbol = listOfIntType.getSourceInfo().getSourceSymbol().get(); assertSame(this.listOfInt, definingSymbol); - - assertNoFindings(); } @Test @@ -114,8 +112,6 @@ public void testQualifiedMethod() throws IOException { assertTrue(listOfIntType.getSourceInfo().getSourceSymbol().isPresent()); definingSymbol = listOfIntType.getSourceInfo().getSourceSymbol().get(); assertEquals(this.listOfInt, definingSymbol); - - assertNoFindings(); } @Test @@ -129,8 +125,6 @@ public void testWithinTypeField() throws IOException { assertTrue(eType.getSourceInfo().getSourceSymbol().isPresent()); ISymbol definingSymbol = eType.getSourceInfo().getSourceSymbol().get(); assertSame(this.e, definingSymbol); - - assertNoFindings(); } @Test @@ -146,8 +140,6 @@ public void testWithinTypeMethod() throws IOException { assertTrue(addType.getSourceInfo().getSourceSymbol().isPresent()); ISymbol definingSymbol = addType.getSourceInfo().getSourceSymbol().get(); assertSame(this.add, definingSymbol); - - assertNoFindings(); } protected CombineExpressionsWithLiteralsTraverser getFlatExpressionScopeSetter(IExpressionsBasisScope scope) { diff --git a/monticore-grammar/src/test/java/de/monticore/types3/StreamExpressionsTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/StreamExpressionsTypeVisitorTest.java index d01da58d45..8f9421103e 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/StreamExpressionsTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/StreamExpressionsTypeVisitorTest.java @@ -1,8 +1,8 @@ /* (c) https://github.com/MontiCore/monticore */ package de.monticore.types3; -import de.monticore.types3.streams.StreamSymTypeRelations; import de.monticore.types3.util.DefsVariablesForTests; +import de.monticore.types3.streams.StreamSymTypeRelations; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeBoxingVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeBoxingVisitorTest.java index 227b40ae6e..37f38bbe02 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeBoxingVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeBoxingVisitorTest.java @@ -3,21 +3,28 @@ import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsGlobalScope; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types3.util.DefsTypesForTests; import de.monticore.types3.util.SymTypeBoxingVisitor; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static de.monticore.types.check.SymTypeExpressionFactory.*; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests.*; -import static org.junit.Assert.assertEquals; +import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; +import static de.monticore.types.check.SymTypeExpressionFactory.createIntersection; +import static de.monticore.types.check.SymTypeExpressionFactory.createPrimitive; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeArray; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeVariable; +import static de.monticore.types.check.SymTypeExpressionFactory.createUnion; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class SymTypeBoxingVisitorTest extends AbstractTypeTest { +public class SymTypeBoxingVisitorTest extends AbstractMCTest { SymTypeBoxingVisitor visitor = new SymTypeBoxingVisitor(); @@ -38,7 +45,6 @@ public void boxPrimitives() { check(_booleanSymType, "java.lang.Boolean"); check(_byteSymType, "java.lang.Byte"); check(_charSymType, "java.lang.Character"); - assertNoFindings(); } @Test @@ -70,7 +76,6 @@ public void boxCollections() { "java.util.List"); check(createGenerics(_unboxedMapSymType.getTypeInfo(), _intSymType, _doubleSymType), "java.util.Map"); - assertNoFindings(); } @Test @@ -106,7 +111,7 @@ public void boxComplexTypes() { public void check(SymTypeExpression unboxed, String expectedBoxedName) { SymTypeExpression boxed = visitor.calculate(unboxed); assertNoFindings(); - Assertions.assertEquals(expectedBoxedName, boxed.printFullName()); + assertEquals(expectedBoxedName, boxed.printFullName()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeCompatibilityTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeCompatibilityTest.java index 601785ac99..ae29fcf779 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeCompatibilityTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeCompatibilityTest.java @@ -5,6 +5,8 @@ import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsGlobalScope; import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsScope; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsScope; @@ -18,14 +20,13 @@ import de.monticore.types.check.SymTypeOfObject; import de.monticore.types.check.SymTypeOfRegEx; import de.monticore.types.check.SymTypeVariable; -import de.monticore.types3.util.DefsTypesForTests; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; +import static de.monticore.types3.util.DefsTypesForTests.*; import static de.monticore.types.check.SymTypeExpressionFactory.createFunction; import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; import static de.monticore.types.check.SymTypeExpressionFactory.createIntersection; @@ -38,9 +39,10 @@ import static de.monticore.types.check.SymTypeExpressionFactory.createTypeVariable; import static de.monticore.types.check.SymTypeExpressionFactory.createUnion; import static de.monticore.types.check.SymTypeExpressionFactory.createWildcard; -import static de.monticore.types3.util.DefsTypesForTests.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class SymTypeCompatibilityTest extends AbstractTypeTest { +public class SymTypeCompatibilityTest extends AbstractMCTest { protected ICombineExpressionsWithLiteralsScope scope; @@ -54,211 +56,208 @@ public void init() { @Test public void isCompatiblePrimitives() { - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _doubleSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _floatSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _longSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _byteSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_booleanSymType, _booleanSymType)); - - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _doubleSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _floatSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _longSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _intSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _charSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _shortSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_doubleSymType, _booleanSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_floatSymType, _doubleSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, _floatSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, _longSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, _intSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, _charSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, _shortSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_floatSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_floatSymType, _booleanSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_longSymType, _doubleSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_longSymType, _floatSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, _longSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, _intSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, _charSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, _shortSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_longSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_longSymType, _booleanSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, _doubleSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, _floatSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, _longSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, _intSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, _charSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, _shortSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, _booleanSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_charSymType, _doubleSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_charSymType, _floatSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_charSymType, _longSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_charSymType, _intSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_charSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_charSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_charSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_charSymType, _booleanSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_shortSymType, _doubleSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_shortSymType, _floatSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_shortSymType, _longSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_shortSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_shortSymType, _charSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_shortSymType, _shortSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_shortSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_shortSymType, _booleanSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_byteSymType, _doubleSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_byteSymType, _floatSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_byteSymType, _longSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_byteSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_byteSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_byteSymType, _shortSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_byteSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_byteSymType, _booleanSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _personSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_booleanSymType, _BooleanSymType)); - assertNoFindings(); + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _doubleSymType)); + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _floatSymType)); + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _longSymType)); + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _intSymType)); + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _charSymType)); + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _shortSymType)); + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _byteSymType)); + assertTrue(SymTypeRelations.isCompatible(_booleanSymType, _booleanSymType)); + + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _doubleSymType)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _floatSymType)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _longSymType)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _intSymType)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _charSymType)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _shortSymType)); + assertTrue(SymTypeRelations.isCompatible(_doubleSymType, _byteSymType)); + assertFalse(SymTypeRelations.isCompatible(_doubleSymType, _booleanSymType)); + + assertFalse(SymTypeRelations.isCompatible(_floatSymType, _doubleSymType)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, _floatSymType)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, _longSymType)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, _intSymType)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, _charSymType)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, _shortSymType)); + assertTrue(SymTypeRelations.isCompatible(_floatSymType, _byteSymType)); + assertFalse(SymTypeRelations.isCompatible(_floatSymType, _booleanSymType)); + + assertFalse(SymTypeRelations.isCompatible(_longSymType, _doubleSymType)); + assertFalse(SymTypeRelations.isCompatible(_longSymType, _floatSymType)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, _longSymType)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, _intSymType)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, _charSymType)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, _shortSymType)); + assertTrue(SymTypeRelations.isCompatible(_longSymType, _byteSymType)); + assertFalse(SymTypeRelations.isCompatible(_longSymType, _booleanSymType)); + + assertFalse(SymTypeRelations.isCompatible(_intSymType, _doubleSymType)); + assertFalse(SymTypeRelations.isCompatible(_intSymType, _floatSymType)); + assertFalse(SymTypeRelations.isCompatible(_intSymType, _longSymType)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, _intSymType)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, _charSymType)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, _shortSymType)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, _byteSymType)); + assertFalse(SymTypeRelations.isCompatible(_intSymType, _booleanSymType)); + + assertFalse(SymTypeRelations.isCompatible(_charSymType, _doubleSymType)); + assertFalse(SymTypeRelations.isCompatible(_charSymType, _floatSymType)); + assertFalse(SymTypeRelations.isCompatible(_charSymType, _longSymType)); + assertFalse(SymTypeRelations.isCompatible(_charSymType, _intSymType)); + assertTrue(SymTypeRelations.isCompatible(_charSymType, _charSymType)); + assertFalse(SymTypeRelations.isCompatible(_charSymType, _shortSymType)); + assertFalse(SymTypeRelations.isCompatible(_charSymType, _byteSymType)); + assertFalse(SymTypeRelations.isCompatible(_charSymType, _booleanSymType)); + + assertFalse(SymTypeRelations.isCompatible(_shortSymType, _doubleSymType)); + assertFalse(SymTypeRelations.isCompatible(_shortSymType, _floatSymType)); + assertFalse(SymTypeRelations.isCompatible(_shortSymType, _longSymType)); + assertFalse(SymTypeRelations.isCompatible(_shortSymType, _intSymType)); + assertFalse(SymTypeRelations.isCompatible(_shortSymType, _charSymType)); + assertTrue(SymTypeRelations.isCompatible(_shortSymType, _shortSymType)); + assertTrue(SymTypeRelations.isCompatible(_shortSymType, _byteSymType)); + assertFalse(SymTypeRelations.isCompatible(_shortSymType, _booleanSymType)); + + assertFalse(SymTypeRelations.isCompatible(_byteSymType, _doubleSymType)); + assertFalse(SymTypeRelations.isCompatible(_byteSymType, _floatSymType)); + assertFalse(SymTypeRelations.isCompatible(_byteSymType, _longSymType)); + assertFalse(SymTypeRelations.isCompatible(_byteSymType, _intSymType)); + assertFalse(SymTypeRelations.isCompatible(_byteSymType, _charSymType)); + assertFalse(SymTypeRelations.isCompatible(_byteSymType, _shortSymType)); + assertTrue(SymTypeRelations.isCompatible(_byteSymType, _byteSymType)); + assertFalse(SymTypeRelations.isCompatible(_byteSymType, _booleanSymType)); + + assertFalse(SymTypeRelations.isCompatible(_booleanSymType, _personSymType)); + assertTrue(SymTypeRelations.isCompatible(_booleanSymType, _BooleanSymType)); } @Test public void isSubTypePrimitives() { - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _doubleSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _floatSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _longSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _byteSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_booleanSymType, _booleanSymType)); - - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_doubleSymType, _doubleSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _floatSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _longSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _booleanSymType)); - - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_floatSymType, _doubleSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_floatSymType, _floatSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _longSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _booleanSymType)); - - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_longSymType, _doubleSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_longSymType, _floatSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_longSymType, _longSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _booleanSymType)); - - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _doubleSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _floatSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _longSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _booleanSymType)); - - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _doubleSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _floatSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _longSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _intSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _charSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_charSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_charSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_charSymType, _booleanSymType)); - - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _doubleSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _floatSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _longSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_shortSymType, _charSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _shortSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_shortSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_shortSymType, _booleanSymType)); - - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _doubleSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _floatSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _longSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_byteSymType, _charSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _shortSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _byteSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_byteSymType, _booleanSymType)); - - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _personSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _BooleanSymType)); - assertNoFindings(); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _doubleSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _floatSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _longSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _intSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _charSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _shortSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _byteSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_booleanSymType, _booleanSymType)); + + assertTrue(SymTypeRelations.isSubTypeOf(_doubleSymType, _doubleSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _floatSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _longSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _intSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _charSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _shortSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _byteSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_doubleSymType, _booleanSymType)); + + assertTrue(SymTypeRelations.isSubTypeOf(_floatSymType, _doubleSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_floatSymType, _floatSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _longSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _intSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _charSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _shortSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _byteSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_floatSymType, _booleanSymType)); + + assertTrue(SymTypeRelations.isSubTypeOf(_longSymType, _doubleSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_longSymType, _floatSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_longSymType, _longSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _intSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _charSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _shortSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _byteSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_longSymType, _booleanSymType)); + + assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _doubleSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _floatSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _longSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _intSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _charSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _shortSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _byteSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _booleanSymType)); + + assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _doubleSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _floatSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _longSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _intSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_charSymType, _charSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_charSymType, _shortSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_charSymType, _byteSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_charSymType, _booleanSymType)); + + assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _doubleSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _floatSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _longSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _intSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_shortSymType, _charSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_shortSymType, _shortSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_shortSymType, _byteSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_shortSymType, _booleanSymType)); + + assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _doubleSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _floatSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _longSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _intSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_byteSymType, _charSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _shortSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_byteSymType, _byteSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_byteSymType, _booleanSymType)); + + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _personSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _BooleanSymType)); } @Test public void isCompatibleObjects() { - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, _personSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, _studentSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, _csStudentSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, _teacherSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_studentSymType, _personSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_studentSymType, _studentSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_studentSymType, _csStudentSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_studentSymType, _teacherSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, _personSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, _studentSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_csStudentSymType, _csStudentSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, _teacherSymType)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(_teacherSymType, _personSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_teacherSymType, _studentSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_teacherSymType, _csStudentSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_teacherSymType, _teacherSymType)); + assertTrue(SymTypeRelations.isCompatible(_personSymType, _personSymType)); + assertTrue(SymTypeRelations.isCompatible(_personSymType, _studentSymType)); + assertTrue(SymTypeRelations.isCompatible(_personSymType, _csStudentSymType)); + assertTrue(SymTypeRelations.isCompatible(_personSymType, _teacherSymType)); + + assertFalse(SymTypeRelations.isCompatible(_studentSymType, _personSymType)); + assertTrue(SymTypeRelations.isCompatible(_studentSymType, _studentSymType)); + assertTrue(SymTypeRelations.isCompatible(_studentSymType, _csStudentSymType)); + assertFalse(SymTypeRelations.isCompatible(_studentSymType, _teacherSymType)); + + assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, _personSymType)); + assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, _studentSymType)); + assertTrue(SymTypeRelations.isCompatible(_csStudentSymType, _csStudentSymType)); + assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, _teacherSymType)); + + assertFalse(SymTypeRelations.isCompatible(_teacherSymType, _personSymType)); + assertFalse(SymTypeRelations.isCompatible(_teacherSymType, _studentSymType)); + assertFalse(SymTypeRelations.isCompatible(_teacherSymType, _csStudentSymType)); + assertTrue(SymTypeRelations.isCompatible(_teacherSymType, _teacherSymType)); // String - Assertions.assertTrue(SymTypeRelations.isCompatible(_boxedString, _boxedString)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_boxedString, _unboxedString)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_unboxedString, _boxedString)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_unboxedString, _unboxedString)); + assertTrue(SymTypeRelations.isCompatible(_boxedString, _boxedString)); + assertTrue(SymTypeRelations.isCompatible(_boxedString, _unboxedString)); + assertTrue(SymTypeRelations.isCompatible(_unboxedString, _boxedString)); + assertTrue(SymTypeRelations.isCompatible(_unboxedString, _unboxedString)); // diverse types - Assertions.assertFalse(SymTypeRelations.isCompatible(_personSymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible(_personSymType, _intSymType)); + assertFalse(SymTypeRelations.isCompatible( _personSymType, createTypeArray(_personSymType, 1))); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( _personSymType, createTypeArray(_personSymType, 0))); - Assertions.assertFalse(SymTypeRelations.isCompatible(_personSymType, _unboxedMapSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_personSymType, _BooleanSymType)); - assertNoFindings(); + assertFalse(SymTypeRelations.isCompatible(_personSymType, _unboxedMapSymType)); + assertFalse(SymTypeRelations.isCompatible(_personSymType, _BooleanSymType)); } @Test public void isCompatibleRegEx() { SymTypeOfRegEx regEx1 = createTypeRegEx("gr(a|e)y"); SymTypeOfRegEx regEx2 = createTypeRegEx("gr(e|a)y"); - Assertions.assertTrue(SymTypeRelations.isCompatible(regEx1, regEx1)); - Assertions.assertTrue(SymTypeRelations.isCompatible(regEx2, regEx1)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_unboxedString, regEx1)); - Assertions.assertTrue(SymTypeRelations.isCompatible(regEx1, _unboxedString)); + assertTrue(SymTypeRelations.isCompatible(regEx1, regEx1)); + assertTrue(SymTypeRelations.isCompatible(regEx2, regEx1)); + assertTrue(SymTypeRelations.isCompatible(_unboxedString, regEx1)); + assertTrue(SymTypeRelations.isCompatible(regEx1, _unboxedString)); } @Test @@ -267,10 +266,10 @@ public void isCompatibleRegExOnlyJavaLangString() { BasicSymbolsMill.globalScope().remove(_unboxedString.getTypeInfo()); SymTypeOfRegEx regEx1 = createTypeRegEx("gr(a|e)y"); SymTypeOfRegEx regEx2 = createTypeRegEx("gr(e|a)y"); - Assertions.assertTrue(SymTypeRelations.isCompatible(regEx1, regEx1)); - Assertions.assertTrue(SymTypeRelations.isCompatible(regEx2, regEx1)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_boxedString, regEx1)); - Assertions.assertTrue(SymTypeRelations.isCompatible(regEx1, _boxedString)); + assertTrue(SymTypeRelations.isCompatible(regEx1, regEx1)); + assertTrue(SymTypeRelations.isCompatible(regEx2, regEx1)); + assertTrue(SymTypeRelations.isCompatible(_boxedString, regEx1)); + assertTrue(SymTypeRelations.isCompatible(regEx1, _boxedString)); } @Test @@ -279,7 +278,7 @@ public void isCompatibleRegExToStringSuperTypes() { // just to test if String supertypes are taken care of for RegEx _unboxedString.getTypeInfo().addSuperTypes(_personSymType); SymTypeOfRegEx regEx1 = createTypeRegEx("gr(a|e)y"); - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, regEx1)); + assertTrue(SymTypeRelations.isCompatible(_personSymType, regEx1)); } @Test @@ -300,27 +299,26 @@ public void isCompatibleGenerics() { SymTypeOfGenerics linkedListOfPerson = createGenerics(_linkedListSymType.getTypeInfo(), _personSymType); - Assertions.assertTrue(SymTypeRelations.isCompatible(listOfPerson, listOfPerson)); - Assertions.assertTrue(SymTypeRelations.isCompatible(listOfPerson, subPersonList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(listOfPerson, linkedListOfPerson)); - - Assertions.assertFalse(SymTypeRelations.isCompatible(listOfInt, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(listOfInt, listOfBoolean)); - Assertions.assertFalse(SymTypeRelations.isCompatible(listOfBoolean, listOfInt)); - Assertions.assertFalse(SymTypeRelations.isCompatible(listOfBoolean, listOfPerson)); - Assertions.assertFalse(SymTypeRelations.isCompatible(listOfPerson, listOfBoolean)); - Assertions.assertFalse(SymTypeRelations.isCompatible(listOfBoolean, subPersonList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(subPersonList, listOfPerson)); - assertNoFindings(); + assertTrue(SymTypeRelations.isCompatible(listOfPerson, listOfPerson)); + assertTrue(SymTypeRelations.isCompatible(listOfPerson, subPersonList)); + assertTrue(SymTypeRelations.isCompatible(listOfPerson, linkedListOfPerson)); + + assertFalse(SymTypeRelations.isCompatible(listOfInt, _intSymType)); + assertFalse(SymTypeRelations.isCompatible(listOfInt, listOfBoolean)); + assertFalse(SymTypeRelations.isCompatible(listOfBoolean, listOfInt)); + assertFalse(SymTypeRelations.isCompatible(listOfBoolean, listOfPerson)); + assertFalse(SymTypeRelations.isCompatible(listOfPerson, listOfBoolean)); + assertFalse(SymTypeRelations.isCompatible(listOfBoolean, subPersonList)); + assertFalse(SymTypeRelations.isCompatible(subPersonList, listOfPerson)); } @Test public void isSubTypeGenericsDoNotIgnoreTypeArguments() { //s. https://git.rwth-aachen.de/monticore/monticore/-/issues/2977 // Test if we do not ignore TypeVariables in the description of the supertypes. - // e.g., given HashMap extends Map + // e.g., given LinkedHashMap extends Map // do not ignore the identity of the variables, e.g., do not allow - // Map x = new HashMap(); + // Map x = new LinkedHashMap(); SymTypeOfGenerics iSMap = createGenerics( _boxedMapSymType.getTypeInfo(), _IntegerSymType, _boxedString); SymTypeOfGenerics iSHashMap = createGenerics( @@ -328,78 +326,75 @@ public void isSubTypeGenericsDoNotIgnoreTypeArguments() { SymTypeOfGenerics sIHashMap = createGenerics( _hashMapSymType.getTypeInfo(), _boxedString, _IntegerSymType); - Assertions.assertTrue(SymTypeRelations.isCompatible(iSMap, iSHashMap)); - Assertions.assertFalse(SymTypeRelations.isCompatible(iSMap, sIHashMap)); - assertNoFindings(); + assertTrue(SymTypeRelations.isCompatible(iSMap, iSHashMap)); + assertFalse(SymTypeRelations.isCompatible(iSMap, sIHashMap)); } @Test public void isCompatibleUnions() { - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createUnion(_personSymType, _carSymType), _personSymType )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createUnion(_personSymType, _carSymType), createUnion(_personSymType, _carSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( _personSymType, createUnion(_studentSymType, _teacherSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( _personSymType, createUnion(_studentSymType, _carSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createUnion(_studentSymType, _teacherSymType), _personSymType )); - assertNoFindings(); } @Test public void IsCompatibleIntersections() { - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createIntersection(_personSymType, _carSymType), createIntersection(_personSymType, _carSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( _personSymType, createIntersection(_studentSymType, _teacherSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( _personSymType, createIntersection(_personSymType, _carSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createIntersection(_teachableSymType, _personSymType), createUnion(_childSymType, _studentSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createIntersection(_personSymType, _carSymType), _personSymType )); - assertNoFindings(); } @Test public void isCompatibleTuples() { - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createTuple(_personSymType, _intSymType), createTuple(_personSymType, _intSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createTuple(_personSymType, _intSymType), createTuple(_studentSymType, _intSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createTuple(_studentSymType, _intSymType), createTuple(_personSymType, _intSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createTuple(_carSymType, _intSymType), createTuple(_personSymType, _intSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createTuple(_personSymType, _intSymType), createTuple(_personSymType, _intSymType, _intSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createTuple(_personSymType, _intSymType, _intSymType), createTuple(_personSymType, _intSymType) )); @@ -407,60 +402,58 @@ public void isCompatibleTuples() { @Test public void isCompatibleFunctions() { - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createFunction(_personSymType), createFunction(_personSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createFunction(_personSymType, _intSymType), createFunction(_personSymType, _intSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createFunction(_personSymType, List.of(_intSymType), true), createFunction(_personSymType, List.of(_intSymType), true) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createFunction(_personSymType, _intSymType), createFunction(_studentSymType, _intSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createFunction(_personSymType, _intSymType), createFunction(_personSymType, _longSymType) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createFunction(_personSymType, _intSymType), createFunction(_personSymType, List.of(_longSymType), true) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createFunction(_personSymType, _intSymType, _intSymType), createFunction(_personSymType, List.of(_intSymType), true) )); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible( createFunction(_personSymType), createFunction(_personSymType, List.of(_intSymType), true) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createFunction(_personSymType), createFunction(_carSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createFunction(_studentSymType, _intSymType), createFunction(_personSymType, _intSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createFunction(_personSymType, _longSymType), createFunction(_personSymType, _intSymType) )); - Assertions.assertFalse(SymTypeRelations.isCompatible( + assertFalse(SymTypeRelations.isCompatible( createFunction(_personSymType, List.of(_intSymType), true), createFunction(_personSymType, _intSymType) )); - - assertNoFindings(); } @Test public void isCompatibleNumericsAndSIUnits() { - Assertions.assertFalse(SymTypeRelations.isCompatible(_s_SISymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, _s_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_s_SISymType, _intSymType)); + assertFalse(SymTypeRelations.isCompatible(_intSymType, _s_SISymType)); // TBD: SIUnit of dimension one } @@ -468,12 +461,12 @@ public void isCompatibleNumericsAndSIUnits() { public void isCompatibleNumericsAndNumericsWithSIUnits() { SymTypeOfNumericWithSIUnit deg_float_SISymType = createNumericWithSIUnit(_deg_SISymType, _floatSymType); - Assertions.assertFalse(SymTypeRelations.isCompatible(_s_int_SISymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, _s_int_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_deg_int_SISymType, _intSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_intSymType, _deg_int_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(deg_float_SISymType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, deg_float_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_s_int_SISymType, _intSymType)); + assertFalse(SymTypeRelations.isCompatible(_intSymType, _s_int_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_deg_int_SISymType, _intSymType)); + assertTrue(SymTypeRelations.isCompatible(_intSymType, _deg_int_SISymType)); + assertTrue(SymTypeRelations.isCompatible(deg_float_SISymType, _intSymType)); + assertFalse(SymTypeRelations.isCompatible(_intSymType, deg_float_SISymType)); } @Test @@ -483,80 +476,80 @@ public void isCompatibleNumericWithSIUnits() { SymTypeOfNumericWithSIUnit deg_float_SISymType = createNumericWithSIUnit(_deg_SISymType, _floatSymType); - Assertions.assertTrue(SymTypeRelations.isCompatible(_s_int_SISymType, _s_int_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_Ohm_int_SISymType, _Ohm_int_SISymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_s_int_SISymType, _A_int_SISymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_A_int_SISymType, _s_int_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_deg_int_SISymType, _rad_int_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_rad_int_SISymType, _deg_int_SISymType)); - - Assertions.assertTrue(SymTypeRelations.isCompatible(s_float_SISymType, _s_int_SISymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_s_int_SISymType, s_float_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(deg_float_SISymType, _rad_int_SISymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_rad_int_SISymType, deg_float_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_s_int_SISymType, _s_int_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_Ohm_int_SISymType, _Ohm_int_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_s_int_SISymType, _A_int_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_A_int_SISymType, _s_int_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_deg_int_SISymType, _rad_int_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_rad_int_SISymType, _deg_int_SISymType)); + + assertTrue(SymTypeRelations.isCompatible(s_float_SISymType, _s_int_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_s_int_SISymType, s_float_SISymType)); + assertTrue(SymTypeRelations.isCompatible(deg_float_SISymType, _rad_int_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_rad_int_SISymType, deg_float_SISymType)); } @Test public void isCompatibleSIUnits() { - Assertions.assertTrue(SymTypeRelations.isCompatible(_s_SISymType, _s_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_Ohm_SISymType, _Ohm_SISymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_s_SISymType, _A_SISymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_A_SISymType, _s_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_deg_SISymType, _rad_SISymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_rad_SISymType, _deg_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_s_SISymType, _s_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_Ohm_SISymType, _Ohm_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_s_SISymType, _A_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_A_SISymType, _s_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_deg_SISymType, _rad_SISymType)); + assertTrue(SymTypeRelations.isCompatible(_rad_SISymType, _deg_SISymType)); // cannot combine SIUnits with NumericWithSIUnits - Assertions.assertFalse(SymTypeRelations.isCompatible(_s_SISymType, _s_int_SISymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_s_int_SISymType, _s_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_s_SISymType, _s_int_SISymType)); + assertFalse(SymTypeRelations.isCompatible(_s_int_SISymType, _s_SISymType)); } @Test public void isSubTypeBottom() { // bottom is subType of EVERY other type - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _bottomType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _intSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _booleanSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _IntegerSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _personSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _nullSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _unboxedListSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _unboxedListSymType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _linkedListSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _bottomType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _intSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _booleanSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _IntegerSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _personSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _nullSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _unboxedListSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _unboxedListSymType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _linkedListSymType)); // bottom is never the superType except for bottom itself - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_IntegerSymType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_personSymType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_nullSymType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_unboxedListSymType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_unboxedListSymType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_linkedListSymType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_intSymType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_booleanSymType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_IntegerSymType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_personSymType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_nullSymType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_unboxedListSymType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_unboxedListSymType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_linkedListSymType, _bottomType)); } @Test public void isSubTypeTop() { // top is superType of EVERY other type - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_topType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_booleanSymType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_IntegerSymType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_personSymType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_nullSymType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_unboxedListSymType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_unboxedListSymType, _topType)); - Assertions.assertTrue(SymTypeRelations.isSubTypeOf(_linkedListSymType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_bottomType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_topType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_intSymType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_booleanSymType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_IntegerSymType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_personSymType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_nullSymType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_unboxedListSymType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_unboxedListSymType, _topType)); + assertTrue(SymTypeRelations.isSubTypeOf(_linkedListSymType, _topType)); // top is never the subType except for top itself - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _bottomType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _intSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _booleanSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _IntegerSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _personSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _nullSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _unboxedListSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _unboxedListSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_topType, _linkedListSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _bottomType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _intSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _booleanSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _IntegerSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _personSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _nullSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _unboxedListSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _unboxedListSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_topType, _linkedListSymType)); } @Test @@ -588,60 +581,58 @@ public void isCompatibleTypeVariable() { // unbounded type variable are like existential types: // we don't know enough to do pretty much anything with it - Assertions.assertTrue(SymTypeRelations.isCompatible(unboundedTVar, unboundedTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(unboundedTVar, unbounded2TVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(unboundedTVar, _personSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_personSymType, unboundedTVar)); + assertTrue(SymTypeRelations.isCompatible(unboundedTVar, unboundedTVar)); + assertFalse(SymTypeRelations.isCompatible(unboundedTVar, unbounded2TVar)); + assertFalse(SymTypeRelations.isCompatible(unboundedTVar, _personSymType)); + assertFalse(SymTypeRelations.isCompatible(_personSymType, unboundedTVar)); // we can assign variables if we know their upper bound - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, subStudentTVar)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_studentSymType, subStudentTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, subStudentTVar)); + assertTrue(SymTypeRelations.isCompatible(_personSymType, subStudentTVar)); + assertTrue(SymTypeRelations.isCompatible(_studentSymType, subStudentTVar)); + assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, subStudentTVar)); // we cannot really assign to variable if we only know their upper bounds - Assertions.assertFalse(SymTypeRelations.isCompatible(subStudentTVar, _personSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(subStudentTVar, _studentSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(subStudentTVar, _csStudentSymType)); + assertFalse(SymTypeRelations.isCompatible(subStudentTVar, _personSymType)); + assertFalse(SymTypeRelations.isCompatible(subStudentTVar, _studentSymType)); + assertFalse(SymTypeRelations.isCompatible(subStudentTVar, _csStudentSymType)); // we can assign to variables if we know their lower bound - Assertions.assertFalse(SymTypeRelations.isCompatible(superStudentTVar, _personSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(superStudentTVar, _studentSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(superStudentTVar, _csStudentSymType)); + assertFalse(SymTypeRelations.isCompatible(superStudentTVar, _personSymType)); + assertTrue(SymTypeRelations.isCompatible(superStudentTVar, _studentSymType)); + assertTrue(SymTypeRelations.isCompatible(superStudentTVar, _csStudentSymType)); // we cannot really assign variables if we only know their lower bounds - Assertions.assertFalse(SymTypeRelations.isCompatible(_personSymType, superStudentTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_studentSymType, superStudentTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, superStudentTVar)); + assertFalse(SymTypeRelations.isCompatible(_personSymType, superStudentTVar)); + assertFalse(SymTypeRelations.isCompatible(_studentSymType, superStudentTVar)); + assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, superStudentTVar)); // two single bounded variables - Assertions.assertTrue(SymTypeRelations.isCompatible(superStudentTVar, subStudentTVar)); - Assertions.assertTrue(SymTypeRelations.isCompatible(superPersonTVar, subStudentTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(superStudentTVar, subPersonTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(subPersonTVar, subStudentTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(subStudentTVar, subPersonTVar)); + assertTrue(SymTypeRelations.isCompatible(superStudentTVar, subStudentTVar)); + assertTrue(SymTypeRelations.isCompatible(superPersonTVar, subStudentTVar)); + assertFalse(SymTypeRelations.isCompatible(superStudentTVar, subPersonTVar)); + assertFalse(SymTypeRelations.isCompatible(subPersonTVar, subStudentTVar)); + assertFalse(SymTypeRelations.isCompatible(subStudentTVar, subPersonTVar)); // in case of upper AND lower bound set, // we can assign and assign to the type variable // assign to: - Assertions.assertFalse(SymTypeRelations.isCompatible(superSSubCsSTVar, _personSymType)); - Assertions.assertFalse(SymTypeRelations.isCompatible(superSSubCsSTVar, _studentSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(superSSubCsSTVar, _csStudentSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(superSSubCsSTVar, _firstSemesterCsStudentSymType)); + assertFalse(SymTypeRelations.isCompatible(superSSubCsSTVar, _personSymType)); + assertFalse(SymTypeRelations.isCompatible(superSSubCsSTVar, _studentSymType)); + assertTrue(SymTypeRelations.isCompatible(superSSubCsSTVar, _csStudentSymType)); + assertTrue(SymTypeRelations.isCompatible(superSSubCsSTVar, _firstSemesterCsStudentSymType)); // assign: - Assertions.assertTrue(SymTypeRelations.isCompatible(_personSymType, superSSubCsSTVar)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_studentSymType, superSSubCsSTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, superSSubCsSTVar)); - Assertions.assertFalse(SymTypeRelations.isCompatible(_firstSemesterCsStudentSymType, superSSubCsSTVar)); - - assertNoFindings(); + assertTrue(SymTypeRelations.isCompatible(_personSymType, superSSubCsSTVar)); + assertTrue(SymTypeRelations.isCompatible(_studentSymType, superSSubCsSTVar)); + assertFalse(SymTypeRelations.isCompatible(_csStudentSymType, superSSubCsSTVar)); + assertFalse(SymTypeRelations.isCompatible(_firstSemesterCsStudentSymType, superSSubCsSTVar)); } @Test public void isCompatibleTypeVariableRecursive() { // check that we can handle recursively defined generics, // e.g., A> - Assertions.assertTrue(SymTypeRelations.isCompatible(_simpleCrtSymType, _simpleCrtSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_graphSymType, _graphSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_graphNodeSymType, _graphNodeSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible(_graphEdgeSymType, _graphEdgeSymType)); + assertTrue(SymTypeRelations.isCompatible(_simpleCrtSymType, _simpleCrtSymType)); + assertTrue(SymTypeRelations.isCompatible(_graphSymType, _graphSymType)); + assertTrue(SymTypeRelations.isCompatible(_graphNodeSymType, _graphNodeSymType)); + assertTrue(SymTypeRelations.isCompatible(_graphEdgeSymType, _graphEdgeSymType)); } @Test @@ -675,26 +666,24 @@ public void isCompatibleUpperBoundedGenerics() { createWildcard(true, _personSymType) ); - Assertions.assertFalse(SymTypeRelations.isCompatible(pList, sList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(sList, pList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(pList, sSubList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(sList, sSubList)); - - Assertions.assertTrue(SymTypeRelations.isCompatible(pSubList, pList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(pSubList, sList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(pSubList, pSubList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(pSubList, sSubList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(sSubList, pList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSubList, sList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(sSubList, pSubList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSubList, sSubList)); - - Assertions.assertTrue(SymTypeRelations.isCompatible(pSubList, pSubLinkedList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(pSubList, sSubLinkedList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(sSubList, pSubLinkedList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSubList, sSubLinkedList)); - - assertNoFindings(); + assertFalse(SymTypeRelations.isCompatible(pList, sList)); + assertFalse(SymTypeRelations.isCompatible(sList, pList)); + assertFalse(SymTypeRelations.isCompatible(pList, sSubList)); + assertFalse(SymTypeRelations.isCompatible(sList, sSubList)); + + assertTrue(SymTypeRelations.isCompatible(pSubList, pList)); + assertTrue(SymTypeRelations.isCompatible(pSubList, sList)); + assertTrue(SymTypeRelations.isCompatible(pSubList, pSubList)); + assertTrue(SymTypeRelations.isCompatible(pSubList, sSubList)); + assertFalse(SymTypeRelations.isCompatible(sSubList, pList)); + assertTrue(SymTypeRelations.isCompatible(sSubList, sList)); + assertFalse(SymTypeRelations.isCompatible(sSubList, pSubList)); + assertTrue(SymTypeRelations.isCompatible(sSubList, sSubList)); + + assertTrue(SymTypeRelations.isCompatible(pSubList, pSubLinkedList)); + assertTrue(SymTypeRelations.isCompatible(pSubList, sSubLinkedList)); + assertFalse(SymTypeRelations.isCompatible(sSubList, pSubLinkedList)); + assertTrue(SymTypeRelations.isCompatible(sSubList, sSubLinkedList)); } @Test @@ -728,36 +717,34 @@ public void isCompatibleLowerBoundedGenerics() { createWildcard(false, _personSymType) ); - Assertions.assertFalse(SymTypeRelations.isCompatible(pList, sList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(sList, pList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(pList, sSuperList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(sList, sSuperList)); - - Assertions.assertTrue(SymTypeRelations.isCompatible(pSuperList, pList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(pSuperList, sList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(pSuperList, pSuperList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(pSuperList, sSuperList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSuperList, pList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSuperList, sList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSuperList, pSuperList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSuperList, sSuperList)); - - Assertions.assertTrue(SymTypeRelations.isCompatible(pSuperList, pSuperLinkedList)); - Assertions.assertFalse(SymTypeRelations.isCompatible(pSuperList, sSuperLinkedList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSuperList, pSuperLinkedList)); - Assertions.assertTrue(SymTypeRelations.isCompatible(sSuperList, sSuperLinkedList)); - - assertNoFindings(); + assertFalse(SymTypeRelations.isCompatible(pList, sList)); + assertFalse(SymTypeRelations.isCompatible(sList, pList)); + assertFalse(SymTypeRelations.isCompatible(pList, sSuperList)); + assertFalse(SymTypeRelations.isCompatible(sList, sSuperList)); + + assertTrue(SymTypeRelations.isCompatible(pSuperList, pList)); + assertFalse(SymTypeRelations.isCompatible(pSuperList, sList)); + assertTrue(SymTypeRelations.isCompatible(pSuperList, pSuperList)); + assertFalse(SymTypeRelations.isCompatible(pSuperList, sSuperList)); + assertTrue(SymTypeRelations.isCompatible(sSuperList, pList)); + assertTrue(SymTypeRelations.isCompatible(sSuperList, sList)); + assertTrue(SymTypeRelations.isCompatible(sSuperList, pSuperList)); + assertTrue(SymTypeRelations.isCompatible(sSuperList, sSuperList)); + + assertTrue(SymTypeRelations.isCompatible(pSuperList, pSuperLinkedList)); + assertFalse(SymTypeRelations.isCompatible(pSuperList, sSuperLinkedList)); + assertTrue(SymTypeRelations.isCompatible(sSuperList, pSuperLinkedList)); + assertTrue(SymTypeRelations.isCompatible(sSuperList, sSuperLinkedList)); } @Test public void nullCompatibilityAndSubTyping() { - Assertions.assertFalse(SymTypeRelations.isCompatible(_intSymType, createTypeOfNull())); - Assertions.assertTrue(SymTypeRelations.isCompatible(_IntegerSymType, createTypeOfNull())); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(createTypeOfNull(), _personSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_personSymType, createTypeOfNull())); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_s_SISymType, _nullSymType)); - Assertions.assertFalse(SymTypeRelations.isSubTypeOf(_s_int_SISymType, _nullSymType)); + assertFalse(SymTypeRelations.isCompatible(_intSymType, createTypeOfNull())); + assertTrue(SymTypeRelations.isCompatible(_IntegerSymType, createTypeOfNull())); + assertFalse(SymTypeRelations.isSubTypeOf(createTypeOfNull(), _personSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_personSymType, createTypeOfNull())); + assertFalse(SymTypeRelations.isSubTypeOf(_s_SISymType, _nullSymType)); + assertFalse(SymTypeRelations.isSubTypeOf(_s_int_SISymType, _nullSymType)); } /** @@ -785,8 +772,8 @@ public void isCompatibleSuperTypeOfBoxed() { createGenerics(iterableSym, _boxedListSymType.getArgument(0)) )); - Assertions.assertTrue(SymTypeRelations.isCompatible(comparableInteger, _IntegerSymType)); - Assertions.assertTrue(SymTypeRelations.isCompatible( + assertTrue(SymTypeRelations.isCompatible(comparableInteger, _IntegerSymType)); + assertTrue(SymTypeRelations.isCompatible( createGenerics(iterableSym, _IntegerSymType), createGenerics(_unboxedListSymType.getTypeInfo(), _intSymType) )); diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeExpressionComparatorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeExpressionComparatorTest.java new file mode 100644 index 0000000000..0b94b641a2 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeExpressionComparatorTest.java @@ -0,0 +1,57 @@ +// (c) https://github.com/MontiCore/monticore +package de.monticore.types3; + +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.types.check.SymTypeExpression; +import de.monticore.types3.util.SymTypeExpressionGenerator; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class SymTypeExpressionComparatorTest extends AbstractMCTest { + + @Test + public void symTypeExpressionComparatorMonkeyTest1() { + // for Primitives + BasicSymbolsMill.init(); + BasicSymbolsMill.initializePrimitives(); + + SymTypeExpressionGenerator symTypeExpressionGenerator = + new SymTypeExpressionGenerator(); + List randomTypes = symTypeExpressionGenerator + .createSymTypeExpressions(10000, 5, 5, true); + assertNoFindings(); + + // remove all duplicates + // since we test the comparator, we cannot use sorting here, + // thus, keep amount/complexity low + List uniqueTypes = new ArrayList<>(randomTypes.size()); + for (SymTypeExpression t : randomTypes) { + if (uniqueTypes.stream().noneMatch(uT -> uT.deepEquals(t))) { + uniqueTypes.add(t); + } + } + assertNoFindings(); + + // sort into set using the comparator + Set uniqueTypesSorted = new TreeSet<>(uniqueTypes); + assertNoFindings(); + + // check explicitly with == + Set vanished = uniqueTypesSorted.stream() + .filter(uT -> uniqueTypes.stream().noneMatch(uT2 -> uT == uT2)) + .collect(Collectors.toSet()); + + assertEquals(Collections.emptySet(), vanished); + } + +} diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeLeastUpperBoundTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeLeastUpperBoundTest.java index 457484d971..6042aad884 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeLeastUpperBoundTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeLeastUpperBoundTest.java @@ -4,28 +4,29 @@ import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsScope; -import de.monticore.types.check.SymTypeExpression; +import de.monticore.runtime.junit.AbstractMCTest; import de.monticore.types3.util.DefsTypesForTests; -import org.junit.jupiter.api.Assertions; +import de.monticore.types.check.SymTypeExpression; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Optional; -import static de.monticore.types.check.SymTypeExpressionFactory.createBottomType; -import static de.monticore.types.check.SymTypeExpressionFactory.createIntersection; -import static de.monticore.types.check.SymTypeExpressionFactory.createTypeArray; -import static de.monticore.types.check.SymTypeExpressionFactory.createUnion; -import static de.monticore.types3.util.DefsTypesForTests._DoubleSymType; -import static de.monticore.types3.util.DefsTypesForTests._IntegerSymType; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; import static de.monticore.types3.util.DefsTypesForTests._carSymType; import static de.monticore.types3.util.DefsTypesForTests._childSymType; import static de.monticore.types3.util.DefsTypesForTests._csStudentSymType; +import static de.monticore.types3.util.DefsTypesForTests._DoubleSymType; +import static de.monticore.types3.util.DefsTypesForTests._IntegerSymType; import static de.monticore.types3.util.DefsTypesForTests._personSymType; import static de.monticore.types3.util.DefsTypesForTests._studentSymType; -import static org.junit.Assert.assertEquals; +import static de.monticore.types.check.SymTypeExpressionFactory.createBottomType; +import static de.monticore.types.check.SymTypeExpressionFactory.createIntersection; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeArray; +import static de.monticore.types.check.SymTypeExpressionFactory.createUnion; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class SymTypeLeastUpperBoundTest extends AbstractTypeTest { +public class SymTypeLeastUpperBoundTest extends AbstractMCTest { protected ICombineExpressionsWithLiteralsScope scope; @@ -64,6 +65,6 @@ protected void checkLub(SymTypeExpression type, String expectedPrint) { Optional lubOpt = SymTypeRelations.leastUpperBound(type); String printed = lubOpt.map(SymTypeExpression::printFullName).orElse(""); assertNoFindings(); - Assertions.assertEquals(expectedPrint, printed); + assertEquals(expectedPrint, printed); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeNormalizeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeNormalizeVisitorTest.java index cba913f14b..8ead0cf963 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeNormalizeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeNormalizeVisitorTest.java @@ -2,17 +2,19 @@ package de.monticore.types3; import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.types.check.SymTypeExpression; import de.monticore.types.check.SymTypeOfIntersection; import de.monticore.types.check.SymTypeOfUnion; -import de.monticore.types3.util.DefsTypesForTests; import de.monticore.types3.util.SymTypeNormalizeVisitor; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; +import static de.monticore.types3.util.DefsTypesForTests.*; import static de.monticore.types.check.SymTypeExpressionFactory.createBottomType; import static de.monticore.types.check.SymTypeExpressionFactory.createFunction; import static de.monticore.types.check.SymTypeExpressionFactory.createIntersection; @@ -24,10 +26,9 @@ import static de.monticore.types.check.SymTypeExpressionFactory.createTypeArray; import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; import static de.monticore.types.check.SymTypeExpressionFactory.createUnion; -import static de.monticore.types3.util.DefsTypesForTests.*; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class SymTypeNormalizeVisitorTest extends AbstractTypeTest { +public class SymTypeNormalizeVisitorTest extends AbstractMCTest { SymTypeNormalizeVisitor visitor; @@ -343,7 +344,7 @@ public void normalizeNumericWithSIUnits() { public void check(SymTypeExpression type, String expectedPrint) { SymTypeExpression normalized = visitor.calculate(type); assertNoFindings(); - Assertions.assertEquals(expectedPrint, normalized.printFullName()); + assertEquals(expectedPrint, normalized.printFullName()); } public void check(SymTypeExpression type, SymTypeExpression expectedType) { diff --git a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeUnboxingVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeUnboxingVisitorTest.java index c5a3f8f1ea..c8b6c38352 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/SymTypeUnboxingVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/SymTypeUnboxingVisitorTest.java @@ -3,25 +3,26 @@ import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.expressions.combineexpressionswithliterals._symboltable.ICombineExpressionsWithLiteralsGlobalScope; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols._symboltable.TypeSymbol; import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol; import de.monticore.types.check.SymTypeExpression; -import de.monticore.types3.util.DefsTypesForTests; import de.monticore.types3.util.SymTypeUnboxingVisitor; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static de.monticore.runtime.junit.MCAssertions.assertNoFindings; +import static de.monticore.types3.util.DefsTypesForTests.*; import static de.monticore.types.check.SymTypeExpressionFactory.createFunction; import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; import static de.monticore.types.check.SymTypeExpressionFactory.createTypeArray; import static de.monticore.types.check.SymTypeExpressionFactory.createTypeObject; import static de.monticore.types.check.SymTypeExpressionFactory.createTypeVariable; import static de.monticore.types.check.SymTypeExpressionFactory.createUnion; -import static de.monticore.types3.util.DefsTypesForTests.*; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class SymTypeUnboxingVisitorTest extends AbstractTypeTest { +public class SymTypeUnboxingVisitorTest extends AbstractMCTest { SymTypeUnboxingVisitor visitor = new SymTypeUnboxingVisitor(); @@ -42,7 +43,6 @@ public void unboxPrimitives() { check(_BooleanSymType, "boolean"); check(_ByteSymType, "byte"); check(_CharacterSymType, "char"); - assertNoFindings(); } @Test @@ -74,7 +74,6 @@ public void unboxCollections() { "List"); check(createGenerics(_boxedMapSymType.getTypeInfo(), _IntegerSymType, _DoubleSymType), "Map"); - assertNoFindings(); } @Test @@ -110,7 +109,7 @@ public void unboxComplexTypes() { public void check(SymTypeExpression boxed, String expectedUnboxedName) { SymTypeExpression unboxed = visitor.calculate(boxed); assertNoFindings(); - Assertions.assertEquals(expectedUnboxedName, unboxed.printFullName()); + assertEquals(expectedUnboxedName, unboxed.printFullName()); } } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/TupleExpressionsTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/TupleExpressionsTypeVisitorTest.java index 628c79ca8d..d09cd03254 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/TupleExpressionsTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/TupleExpressionsTypeVisitorTest.java @@ -3,12 +3,10 @@ import org.junit.jupiter.api.Test; -import java.io.IOException; - public class TupleExpressionsTypeVisitorTest extends AbstractTypeVisitorTest { @Test - public void deriveFromTupleExpressionTest() throws IOException { + public void deriveFromTupleExpressionTest() { // simple checkExpr("(1,1)", "(int, int)"); checkExpr("(1, 1)", "(int, int)"); @@ -23,7 +21,13 @@ public void deriveFromTupleExpressionTest() throws IOException { } @Test - public void bracketExpressionIsNotATupleTest() throws IOException { + public void deriveFromTupleExpressionCTTITest() { + checkExpr("([], [1])", "(List, List)", "(List, List)"); + checkExpr("(([], [1]), 1)", "((List, List), int)", "((List, List), int)"); + } + + @Test + public void bracketExpressionIsNotATupleTest() { checkExpr("(1)", "int"); checkExpr("((1,1))", "(int, int)"); } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/UglyExpressionsTypeVisitorTest.java b/monticore-grammar/src/test/java/de/monticore/types3/UglyExpressionsTypeVisitorTest.java index fb774f281a..a7bcd70b37 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/UglyExpressionsTypeVisitorTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/UglyExpressionsTypeVisitorTest.java @@ -1,11 +1,11 @@ package de.monticore.types3; +import de.monticore.types3.util.DefsVariablesForTests; import de.monticore.symbols.oosymbols.OOSymbolsMill; import de.monticore.symbols.oosymbols._symboltable.IOOSymbolsGlobalScope; import de.monticore.symbols.oosymbols._symboltable.IOOSymbolsScope; import de.monticore.symbols.oosymbols._symboltable.MethodSymbol; import de.monticore.types.check.SymTypeExpressionFactory; -import de.monticore.types3.util.DefsVariablesForTests; import de.monticore.types3.util.OOWithinTypeBasicSymbolsResolver; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -142,6 +142,14 @@ public void testGenericConstructorClassCreatorExpression() throws IOException { checkExpr("new List()", "List", "List"); checkExpr("new List(1)", "List", "List"); checkExpr("new List(1)", "List"); + + checkExpr("new List<>()", "List", "List"); + checkExpr("new List<>(1)", "List", "List"); + checkExpr("new List<>(1)", "List"); + + checkExpr("new List()", "List", "List"); + checkExpr("new List(1)", "List", "List"); + checkExpr("new List(1)", "List"); } @Test diff --git a/monticore-grammar/src/test/java/de/monticore/types3/streams/StreamSymTypeFactoryTest.java b/monticore-grammar/src/test/java/de/monticore/types3/streams/StreamSymTypeFactoryTest.java index f95df69a71..1b4a5925f4 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/streams/StreamSymTypeFactoryTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/streams/StreamSymTypeFactoryTest.java @@ -1,32 +1,25 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.streams; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.symbols.basicsymbols._symboltable.IBasicSymbolsGlobalScope; import de.monticore.types.check.SymTypeOfGenerics; import de.monticore.types.mccollectiontypes.types3.util.MCCollectionSymTypeFactory; import de.monticore.types.mccollectiontypes.types3.util.MCCollectionTypeRelations; -import de.monticore.types3.AbstractTypeTest; -import de.monticore.types3.util.DefsTypesForTests; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static de.monticore.types3.util.DefsTypesForTests._boxedListSymType; -import static de.monticore.types3.util.DefsTypesForTests._boxedMapSymType; import static de.monticore.types3.util.DefsTypesForTests._boxedOptionalSymType; import static de.monticore.types3.util.DefsTypesForTests._boxedSetSymType; -import static de.monticore.types3.util.DefsTypesForTests._floatSymType; import static de.monticore.types3.util.DefsTypesForTests._intSymType; import static de.monticore.types3.util.DefsTypesForTests._unboxedListSymType; -import static de.monticore.types3.util.DefsTypesForTests._unboxedMapSymType; import static de.monticore.types3.util.DefsTypesForTests._unboxedOptionalSymType; import static de.monticore.types3.util.DefsTypesForTests._unboxedSetSymType; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; -public class StreamSymTypeFactoryTest extends AbstractTypeTest { +public class StreamSymTypeFactoryTest extends AbstractMCTest { MCCollectionTypeRelations collectionTypeRelations; diff --git a/monticore-grammar/src/test/java/de/monticore/types3/streams/StreamTypeRelationsTest.java b/monticore-grammar/src/test/java/de/monticore/types3/streams/StreamTypeRelationsTest.java index 21ee2fce4c..b466f110b6 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/streams/StreamTypeRelationsTest.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/streams/StreamTypeRelationsTest.java @@ -1,18 +1,18 @@ // (c) https://github.com/MontiCore/monticore package de.monticore.types3.streams; +import de.monticore.runtime.junit.AbstractMCTest; +import de.monticore.types3.util.DefsTypesForTests; import de.monticore.symbols.basicsymbols.BasicSymbolsMill; import de.monticore.types.check.SymTypeExpressionFactory; import de.monticore.types.mccollectiontypes.types3.MCCollectionSymTypeRelations; -import de.monticore.types3.AbstractTypeTest; -import de.monticore.types3.util.DefsTypesForTests; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; +import static de.monticore.runtime.junit.MCAssertions.assertHasFindingStartingWith; import static de.monticore.types3.util.DefsTypesForTests._boxedListSymType; import static de.monticore.types3.util.DefsTypesForTests._boxedMapSymType; import static de.monticore.types3.util.DefsTypesForTests._boxedOptionalSymType; @@ -28,7 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; -public class StreamTypeRelationsTest extends AbstractTypeTest { +public class StreamTypeRelationsTest extends AbstractMCTest { @BeforeEach public void init() { @@ -81,11 +81,15 @@ public void recognizeNonLists() { _unboxedListSymType.setArgumentList(Collections.emptyList()); _boxedListSymType.setArgumentList(Collections.emptyList()); assertFalse(MCCollectionSymTypeRelations.isList(_unboxedListSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isList(_boxedListSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedListSymType.setArgumentList(List.of(_intSymType, _intSymType)); _boxedListSymType.setArgumentList(List.of(_intSymType, _intSymType)); assertFalse(MCCollectionSymTypeRelations.isList(_unboxedListSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isList(_boxedListSymType)); + assertHasFindingStartingWith("0xFD1C4"); } @Test @@ -107,11 +111,15 @@ public void recognizeNonSets() { _unboxedSetSymType.setArgumentList(Collections.emptyList()); _boxedSetSymType.setArgumentList(Collections.emptyList()); assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedSetSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isSet(_boxedSetSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedSetSymType.setArgumentList(List.of(_intSymType, _intSymType)); _boxedSetSymType.setArgumentList(List.of(_intSymType, _intSymType)); assertFalse(MCCollectionSymTypeRelations.isSet(_unboxedSetSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isSet(_boxedSetSymType)); + assertHasFindingStartingWith("0xFD1C4"); } @Test @@ -133,11 +141,15 @@ public void recognizeNonOptionals() { _unboxedOptionalSymType.setArgumentList(Collections.emptyList()); _boxedOptionalSymType.setArgumentList(Collections.emptyList()); assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedOptionalSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedOptionalSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedOptionalSymType.setArgumentList(List.of(_intSymType, _intSymType)); _boxedOptionalSymType.setArgumentList(List.of(_intSymType, _intSymType)); assertFalse(MCCollectionSymTypeRelations.isOptional(_unboxedOptionalSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isOptional(_boxedOptionalSymType)); + assertHasFindingStartingWith("0xFD1C4"); } @Test @@ -159,17 +171,23 @@ public void recognizeNonMaps() { _unboxedMapSymType.setArgumentList(Collections.emptyList()); _boxedMapSymType.setArgumentList(Collections.emptyList()); assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedMapSymType.setArgumentList(List.of(_intSymType)); _boxedMapSymType.setArgumentList(List.of(_intSymType)); assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); _unboxedMapSymType.setArgumentList( List.of(_intSymType, _intSymType, _intSymType)); _boxedMapSymType.setArgumentList( List.of(_intSymType, _intSymType, _intSymType)); assertFalse(MCCollectionSymTypeRelations.isMap(_unboxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); assertFalse(MCCollectionSymTypeRelations.isMap(_boxedMapSymType)); + assertHasFindingStartingWith("0xFD1C4"); } @Test diff --git a/monticore-grammar/src/test/java/de/monticore/types3/util/CombineExpressionsWithLiteralsTypeTraverserFactory.java b/monticore-grammar/src/test/java/de/monticore/types3/util/CombineExpressionsWithLiteralsTypeTraverserFactory.java index 0d88454964..d738f12baf 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/util/CombineExpressionsWithLiteralsTypeTraverserFactory.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/util/CombineExpressionsWithLiteralsTypeTraverserFactory.java @@ -7,15 +7,16 @@ import de.monticore.expressions.combineexpressionswithliterals.CombineExpressionsWithLiteralsMill; import de.monticore.expressions.combineexpressionswithliterals._visitor.CombineExpressionsWithLiteralsTraverser; import de.monticore.expressions.commonexpressions.types3.CommonExpressionsCTTIVisitor; -import de.monticore.expressions.commonexpressions.types3.CommonExpressionsTypeIdAsConstructorTypeVisitor; +import de.monticore.expressions.commonexpressions.types3.CommonExpressionsTypeIdAsConstructorCTTIVisitor; import de.monticore.expressions.commonexpressions.types3.CommonExpressionsTypeVisitor; import de.monticore.expressions.commonexpressions.types3.util.CommonExpressionsLValueRelations; import de.monticore.expressions.expressionsbasis.types3.ExpressionBasisCTTIVisitor; -import de.monticore.expressions.expressionsbasis.types3.ExpressionBasisTypeIdAsConstructorTypeVisitor; +import de.monticore.expressions.expressionsbasis.types3.ExpressionBasisTypeIdAsConstructorCTTIVisitor; import de.monticore.expressions.expressionsbasis.types3.ExpressionBasisTypeVisitor; import de.monticore.expressions.javaclassexpressions.types3.JavaClassExpressionsTypeVisitor; import de.monticore.expressions.lambdaexpressions.types3.LambdaExpressionsTypeVisitor; import de.monticore.expressions.streamexpressions.types3.StreamExpressionsTypeVisitor; +import de.monticore.expressions.tupleexpressions.types3.TupleExpressionsCTTIVisitor; import de.monticore.expressions.tupleexpressions.types3.TupleExpressionsTypeVisitor; import de.monticore.expressions.uglyexpressions.types3.UglyExpressionsCTTIVisitor; import de.monticore.expressions.uglyexpressions.types3.UglyExpressionsTypeVisitor; @@ -100,7 +101,7 @@ public CombineExpressionsWithLiteralsTraverser createTraverserForOO( return traverser; } - public MapBasedTypeCheck3 initTypeCheck3ForOO() { + public static MapBasedTypeCheck3 initTypeCheck3ForOO() { OOWithinScopeBasicSymbolsResolver.init(); OOWithinTypeBasicSymbolsResolver.init(); TypeVisitorOperatorCalculator.init(); @@ -108,7 +109,8 @@ public MapBasedTypeCheck3 initTypeCheck3ForOO() { CommonExpressionsLValueRelations.init(); Type4Ast type4Ast = new Type4Ast(); InferenceContext4Ast ctx4Ast = new InferenceContext4Ast(); - ITraverser traverser = createTraverserForOO(type4Ast, ctx4Ast); + ITraverser traverser = new CombineExpressionsWithLiteralsTypeTraverserFactory() + .createTraverserForOO(type4Ast, ctx4Ast); // sets itself as delegate return new TypeCheck3Impl(traverser, type4Ast, ctx4Ast); } @@ -135,14 +137,15 @@ public CombineExpressionsWithLiteralsTraverser createTraverserForOOWithConstruct return traverser; } - public MapBasedTypeCheck3 initTypeCheck3ForOOWithConstructors() { + public static MapBasedTypeCheck3 initTypeCheck3ForOOWithConstructors() { OOWithinScopeBasicSymbolsResolver.init(); OOWithinTypeBasicSymbolsResolver.init(); TypeVisitorOperatorCalculator.init(); TypeContextCalculator.init(); Type4Ast type4Ast = new Type4Ast(); InferenceContext4Ast ctx4Ast = new InferenceContext4Ast(); - ITraverser traverser = createTraverserForOOWithConstructors(type4Ast, ctx4Ast); + ITraverser traverser = new CombineExpressionsWithLiteralsTypeTraverserFactory() + .createTraverserForOOWithConstructors(type4Ast, ctx4Ast); // sets itself as delegate return new TypeCheck3Impl(traverser, type4Ast, ctx4Ast); } @@ -197,6 +200,9 @@ else if (visitors.cTTISetExpressions != null) { if (visitors.derTupleExpressions != null) { visitors.derTupleExpressions.setType4Ast(type4Ast); } + else if (visitors.cTTITupleExpressions != null) { + visitors.cTTITupleExpressions.setType4Ast(type4Ast); + } if (visitors.derUglyExpressions != null) { visitors.derUglyExpressions.setType4Ast(type4Ast); } @@ -259,6 +265,9 @@ protected void setContext4Ast(VisitorList visitors, InferenceContext4Ast ctx4Ast if (visitors.cTTISetExpressions != null) { visitors.cTTISetExpressions.setContext4Ast(ctx4Ast); } + if (visitors.cTTITupleExpressions != null) { + visitors.cTTITupleExpressions.setContext4Ast(ctx4Ast); + } if (visitors.cTTIUglyExpressions != null) { visitors.cTTIUglyExpressions.setContext4Ast(ctx4Ast); } @@ -277,7 +286,7 @@ protected VisitorList constructVisitorsCTTI() { visitors.derOptionalOperators = new OptionalOperatorsTypeVisitor(); visitors.cTTISetExpressions = new SetExpressionsCTTIVisitor(); visitors.derStreamExpressions = new StreamExpressionsTypeVisitor(); - visitors.derTupleExpressions = new TupleExpressionsTypeVisitor(); + visitors.cTTITupleExpressions = new TupleExpressionsCTTIVisitor(); visitors.cTTIUglyExpressions = new UglyExpressionsCTTIVisitor(); visitors.derOfMCCommonLiterals = new MCCommonLiteralsTypeVisitor(); visitors.derSIUnitLiterals = new SIUnitLiteralsTypeVisitor(); @@ -330,9 +339,8 @@ protected VisitorList constructVisitorsNoCTTI() { * initializes additional logic for languages that have access to OO Symbols */ protected VisitorList constructVisitorsForOO() { - VisitorList visitors = constructVisitorsNoCTTI(); - visitors.derCommonExpressions = - new CommonExpressionsTypeIdAsConstructorTypeVisitor(); + VisitorList visitors = constructVisitorsCTTI(); + // as of 7.7.0, no special visitors are required return visitors; } @@ -342,10 +350,12 @@ protected VisitorList constructVisitorsForOO() { */ protected VisitorList constructVisitorsForOOWithConstructors() { VisitorList visitors = constructVisitorsForOO(); - visitors.derCommonExpressions = - new CommonExpressionsTypeIdAsConstructorTypeVisitor(); - visitors.derExpressionBasis = - new ExpressionBasisTypeIdAsConstructorTypeVisitor(); + visitors.derCommonExpressions = null; + visitors.cTTICommonExpressions = + new CommonExpressionsTypeIdAsConstructorCTTIVisitor(); + visitors.derExpressionBasis = null; + visitors.cTTIExpressionBasis = + new ExpressionBasisTypeIdAsConstructorCTTIVisitor(); return visitors; } @@ -408,6 +418,10 @@ else if (visitors.cTTISetExpressions != null) { if (visitors.derTupleExpressions != null) { traverser.add4TupleExpressions(visitors.derTupleExpressions); } + else if (visitors.cTTITupleExpressions != null) { + traverser.add4TupleExpressions(visitors.cTTITupleExpressions); + traverser.setTupleExpressionsHandler(visitors.cTTITupleExpressions); + } if (visitors.derUglyExpressions != null) { traverser.add4UglyExpressions(visitors.derUglyExpressions); } @@ -493,6 +507,8 @@ protected static class VisitorList { public TupleExpressionsTypeVisitor derTupleExpressions; + public TupleExpressionsCTTIVisitor cTTITupleExpressions; + public UglyExpressionsTypeVisitor derUglyExpressions; public UglyExpressionsCTTIVisitor cTTIUglyExpressions; diff --git a/monticore-grammar/src/test/java/de/monticore/types3/util/DefsTypesForTests.java b/monticore-grammar/src/test/java/de/monticore/types3/util/DefsTypesForTests.java index 7ddd645178..96e53d5bdb 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/util/DefsTypesForTests.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/util/DefsTypesForTests.java @@ -35,6 +35,7 @@ import static de.monticore.types.check.SymTypeExpressionFactory.createBottomType; import static de.monticore.types.check.SymTypeExpressionFactory.createGenerics; +import static de.monticore.types.check.SymTypeExpressionFactory.createGenericsDeclaredType; import static de.monticore.types.check.SymTypeExpressionFactory.createNumericWithSIUnit; import static de.monticore.types.check.SymTypeExpressionFactory.createPrimitive; import static de.monticore.types.check.SymTypeExpressionFactory.createSIUnit; @@ -47,7 +48,9 @@ * offers one Symbol-Infrastructure * including Scopes etc. that is used to provide relevant Symbols. * This infrastructure can be used for testing + * @deprecated Use the test fixture instead */ +@Deprecated(forRemoval = true) public class DefsTypesForTests { /** @@ -174,32 +177,32 @@ public static TypeSymbol type(String name) { IBasicSymbolsScope scope = BasicSymbolsMill.scope(); scope.setShadowing(true); return BasicSymbolsMill.typeSymbolBuilder() - .setSpannedScope(scope) - .setName(name) - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .build(); + .setSpannedScope(scope) + .setName(name) + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .build(); } public static TypeSymbol type(String name, - List superTypeList) { + List superTypeList) { TypeSymbol ts = type(name); ts.setSuperTypesList(superTypeList); return ts; } public static TypeSymbol type(String name, - List superTypeList, - List typeVariableList) { + List superTypeList, + List typeVariableList) { TypeSymbol ts = type(name, superTypeList); typeVariableList.forEach(tv -> inScope(ts.getSpannedScope(), tv)); return ts; } public static TypeSymbol type(String name, - List superTypeList, - List typeVariableList, - List functionList, - List variableList) { + List superTypeList, + List typeVariableList, + List functionList, + List variableList) { TypeSymbol ts = type(name, superTypeList, typeVariableList); functionList.forEach(fs -> inScope(ts.getSpannedScope(), fs)); variableList.forEach(vs -> inScope(ts.getSpannedScope(), vs)); @@ -212,33 +215,33 @@ public static OOTypeSymbol oOtype(String name) { IOOSymbolsScope scope = OOSymbolsMill.scope(); scope.setShadowing(true); return OOSymbolsMill.oOTypeSymbolBuilder() - .setSpannedScope(scope) - .setName(name) - .setIsPublic(true) - .setIsStatic(true) - .build(); + .setSpannedScope(scope) + .setName(name) + .setIsPublic(true) + .setIsStatic(true) + .build(); } public static OOTypeSymbol oOtype(String name, - List superTypeList) { + List superTypeList) { OOTypeSymbol ts = oOtype(name); ts.setSuperTypesList(superTypeList); return ts; } public static OOTypeSymbol oOtype(String name, - List superTypeList, - List typeVariableList) { + List superTypeList, + List typeVariableList) { OOTypeSymbol ts = oOtype(name, superTypeList); typeVariableList.forEach(tv -> inScope(ts.getSpannedScope(), tv)); return ts; } public static OOTypeSymbol oOtype(String name, - List superTypeList, - List typeVariableList, - List methodList, - List fieldList) { + List superTypeList, + List typeVariableList, + List methodList, + List fieldList) { OOTypeSymbol ts = oOtype(name, superTypeList, typeVariableList); methodList.forEach(fs -> inScope(ts.getSpannedScope(), fs)); fieldList.forEach(vs -> inScope(ts.getSpannedScope(), vs)); @@ -252,102 +255,102 @@ public static TypeVarSymbol typeVariable(String name) { } public static TypeVarSymbol typeVariable(String name, - List superTypeList) { + List superTypeList) { return BasicSymbolsMill.typeVarSymbolBuilder() - .setName(name) - .setSuperTypesList(superTypeList) - .setSpannedScope(BasicSymbolsMill.scope()) - .build(); + .setName(name) + .setSuperTypesList(superTypeList) + .setSpannedScope(BasicSymbolsMill.scope()) + .build(); } // create FunctionSymbols (some defaults apply) public static FunctionSymbol function(String name, SymTypeExpression returnType, - SymTypeExpression... argumentTypes) { + SymTypeExpression... argumentTypes) { return function(name, returnType, List.of(argumentTypes)); } public static FunctionSymbol function(String name, SymTypeExpression returnType, - List argumentTypes) { + List argumentTypes) { return function(name, returnType, argumentTypes, false); } public static FunctionSymbol function(String name, SymTypeExpression returnType, - List argumentTypes, boolean elliptic) { + List argumentTypes, boolean elliptic) { IBasicSymbolsScope scope = BasicSymbolsMill.scope(); scope.setOrdered(true); scope.setShadowing(true); for (int i = 0; i < argumentTypes.size(); i++) { scope.add( - BasicSymbolsMill.variableSymbolBuilder() - .setType(argumentTypes.get(i)) - .setName("arg" + i) - .build() + BasicSymbolsMill.variableSymbolBuilder() + .setType(argumentTypes.get(i)) + .setName("arg" + i) + .build() ); } return BasicSymbolsMill.functionSymbolBuilder() - .setSpannedScope(scope) - .setName(name) - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setType(returnType) - .setIsElliptic(elliptic) - .build(); + .setSpannedScope(scope) + .setName(name) + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setType(returnType) + .setIsElliptic(elliptic) + .build(); } // create MethodSymbols (some defaults apply) public static MethodSymbol method(String name, SymTypeExpression returnType, - SymTypeExpression... argumentTypes) { + SymTypeExpression... argumentTypes) { return method(name, returnType, List.of(argumentTypes)); } public static MethodSymbol method(String name, SymTypeExpression returnType, - List argumentTypes) { + List argumentTypes) { return method(name, returnType, argumentTypes, false); } public static MethodSymbol method(String name, SymTypeExpression returnType, - List argumentTypes, boolean elliptic) { + List argumentTypes, boolean elliptic) { IOOSymbolsScope scope = OOSymbolsMill.scope(); scope.setOrdered(true); scope.setShadowing(true); for (int i = 0; i < argumentTypes.size(); i++) { scope.add( - OOSymbolsMill.fieldSymbolBuilder() - .setType(argumentTypes.get(i)) - .setName("arg" + i) - .build() + OOSymbolsMill.fieldSymbolBuilder() + .setType(argumentTypes.get(i)) + .setName("arg" + i) + .build() ); } return OOSymbolsMill.methodSymbolBuilder() - .setSpannedScope(scope) - .setName(name) - .setType(returnType) - .setIsElliptic(elliptic) - .setIsPublic(true) - .setIsStatic(false) - .build(); + .setSpannedScope(scope) + .setName(name) + .setType(returnType) + .setIsElliptic(elliptic) + .setIsPublic(true) + .setIsStatic(false) + .build(); } // create VariableSymbols (some defaults apply) public static VariableSymbol variable(String name, SymTypeExpression type) { return BasicSymbolsMill.variableSymbolBuilder() - .setName(name) - .setAccessModifier(AccessModifier.ALL_INCLUSION) - .setType(type) - .build(); + .setName(name) + .setAccessModifier(AccessModifier.ALL_INCLUSION) + .setType(type) + .build(); } // create FieldSymbols (some defaults apply) public static FieldSymbol field(String name, SymTypeExpression type) { return OOSymbolsMill.fieldSymbolBuilder() - .setName(name) - .setType(type) - .setIsPublic(true) - .setIsStatic(false) - .build(); + .setName(name) + .setType(type) + .setIsPublic(true) + .setIsStatic(false) + .build(); } /*********************************************************************/ @@ -398,21 +401,21 @@ public static void set_thePrimitives() { BasicSymbolsMill.initializePrimitives(); } _intSymType = createPrimitive( - typeSymbolsScope.resolveType(BasicSymbolsMill.INT).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.INT).get()); _charSymType = createPrimitive( - typeSymbolsScope.resolveType(BasicSymbolsMill.CHAR).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.CHAR).get()); _booleanSymType = createPrimitive( - typeSymbolsScope.resolveType(BasicSymbolsMill.BOOLEAN).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.BOOLEAN).get()); _doubleSymType = createPrimitive( - typeSymbolsScope.resolveType(BasicSymbolsMill.DOUBLE).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.DOUBLE).get()); _floatSymType = createPrimitive( - typeSymbolsScope.resolveType(BasicSymbolsMill.FLOAT).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.FLOAT).get()); _longSymType = createPrimitive( - typeSymbolsScope.resolveType(BasicSymbolsMill.LONG).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.LONG).get()); _byteSymType = createPrimitive( - typeSymbolsScope.resolveType(BasicSymbolsMill.BYTE).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.BYTE).get()); _shortSymType = createPrimitive( - typeSymbolsScope.resolveType(BasicSymbolsMill.SHORT).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.SHORT).get()); } /*********************************************************************/ @@ -441,21 +444,21 @@ public static void set_boxedPrimitives() { IBasicSymbolsScope langScope = createJavaLangScope(); // create boxed primitives _IntegerSymType = - createTypeObject(inScope(langScope, type("Integer"))); + createTypeObject(inScope(langScope, type("Integer"))); _CharacterSymType = - createTypeObject(inScope(langScope, type("Character"))); + createTypeObject(inScope(langScope, type("Character"))); _BooleanSymType = - createTypeObject(inScope(langScope, type("Boolean"))); + createTypeObject(inScope(langScope, type("Boolean"))); _DoubleSymType = - createTypeObject(inScope(langScope, type("Double"))); + createTypeObject(inScope(langScope, type("Double"))); _FloatSymType = - createTypeObject(inScope(langScope, type("Float"))); + createTypeObject(inScope(langScope, type("Float"))); _LongSymType = - createTypeObject(inScope(langScope, type("Long"))); + createTypeObject(inScope(langScope, type("Long"))); _ByteSymType = - createTypeObject(inScope(langScope, type("Byte"))); + createTypeObject(inScope(langScope, type("Byte"))); _ShortSymType = - createTypeObject(inScope(langScope, type("Short"))); + createTypeObject(inScope(langScope, type("Short"))); } /*********************************************************************/ @@ -472,7 +475,7 @@ public static void set_unboxedObjects() { BasicSymbolsMill.initializeString(); } _unboxedString = createTypeObject( - typeSymbolsScope.resolveType(BasicSymbolsMill.STRING).get()); + typeSymbolsScope.resolveType(BasicSymbolsMill.STRING).get()); } /*********************************************************************/ @@ -515,8 +518,8 @@ public static void set_unboxedOptionalSymType() { IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); TypeVarSymbol optVar = typeVariable("T"); _unboxedOptionalSymType = createGenerics( - inScope(gs, type("Optional", List.of(), List.of(optVar))), - createTypeVariable(optVar) + inScope(gs, type("Optional", List.of(), List.of(optVar))), + createTypeVariable(optVar) ); } @@ -524,8 +527,8 @@ public static void set_unboxedSetSymType() { IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); TypeVarSymbol setVar = typeVariable("T"); _unboxedSetSymType = createGenerics( - inScope(gs, type("Set", List.of(), List.of(setVar))), - createTypeVariable(setVar) + inScope(gs, type("Set", List.of(), List.of(setVar))), + createTypeVariable(setVar) ); } @@ -533,8 +536,8 @@ public static void set_unboxedListSymType() { IBasicSymbolsGlobalScope gs = BasicSymbolsMill.globalScope(); TypeVarSymbol listVar = typeVariable("T"); _unboxedListSymType = createGenerics( - inScope(gs, type("List", List.of(), List.of(listVar))), - createTypeVariable(listVar) + inScope(gs, type("List", List.of(), List.of(listVar))), + createTypeVariable(listVar) ); } @@ -543,8 +546,8 @@ public static void set_unboxedMapSymType() { TypeVarSymbol mapVar1 = typeVariable("T"); TypeVarSymbol mapVar2 = typeVariable("U"); _unboxedMapSymType = createGenerics( - inScope(gs, type("Map", List.of(), List.of(mapVar1, mapVar2))), - createTypeVariable(mapVar1), createTypeVariable(mapVar2) + inScope(gs, type("Map", List.of(), List.of(mapVar1, mapVar2))), + createTypeVariable(mapVar1), createTypeVariable(mapVar2) ); } @@ -568,24 +571,24 @@ public static void set_boxedCollections() { IBasicSymbolsScope utilScope = inScope(javaScope, scope("util")); TypeVarSymbol optVar = typeVariable("OptT"); _boxedOptionalSymType = createGenerics( - inScope(utilScope, type("Optional", List.of(), List.of(optVar))), - createTypeVariable(optVar) + inScope(utilScope, type("Optional", List.of(), List.of(optVar))), + createTypeVariable(optVar) ); TypeVarSymbol setVar = typeVariable("SetT"); _boxedSetSymType = createGenerics( - inScope(utilScope, type("Set", List.of(), List.of(setVar))), - createTypeVariable(setVar) + inScope(utilScope, type("Set", List.of(), List.of(setVar))), + createTypeVariable(setVar) ); TypeVarSymbol listVar = typeVariable("ListT"); _boxedListSymType = createGenerics( - inScope(utilScope, type("List", List.of(), List.of(listVar))), - createTypeVariable(listVar) + inScope(utilScope, type("List", List.of(), List.of(listVar))), + createTypeVariable(listVar) ); TypeVarSymbol mapVar1 = typeVariable("KeyT"); TypeVarSymbol mapVar2 = typeVariable("ValueT"); _boxedMapSymType = createGenerics( - inScope(utilScope, type("Map", List.of(), List.of(mapVar1, mapVar2))), - createTypeVariable(mapVar1), createTypeVariable(mapVar2) + inScope(utilScope, type("Map", List.of(), List.of(mapVar1, mapVar2))), + createTypeVariable(mapVar1), createTypeVariable(mapVar2) ); } @@ -632,65 +635,65 @@ public static void set_streams() { } else { Log.trace("Stream could not be resolved," - + " skipping its usual initialization", - "DefsTypesForTests" + + " skipping its usual initialization", + "DefsTypesForTests" ); TypeVarSymbol streamVar = typeVariable("StreamT"); _StreamSymType = createGenerics( - inScope(gs, type("Stream", List.of(), List.of(streamVar))), - createTypeVariable(streamVar) + inScope(gs, type("Stream", List.of(), List.of(streamVar))), + createTypeVariable(streamVar) ); TypeVarSymbol eventStreamVar = typeVariable("EventStreamT"); SymTypeExpression eventStreamSuperType = createGenerics( - _StreamSymType.getTypeInfo(), - List.of(createTypeVariable(eventStreamVar)) - ); + _StreamSymType.getTypeInfo(), + List.of(createTypeVariable(eventStreamVar)) + ); _EventStreamSymType = createGenerics( - inScope(gs, type( - "EventStream", - List.of(eventStreamSuperType), - List.of(eventStreamVar) - )), - createTypeVariable(eventStreamVar) + inScope(gs, type( + "EventStream", + List.of(eventStreamSuperType), + List.of(eventStreamVar) + )), + createTypeVariable(eventStreamVar) ); TypeVarSymbol syncStreamVar = typeVariable("SyncStreamT"); SymTypeExpression syncStreamSuperType = createGenerics( - _StreamSymType.getTypeInfo(), - List.of(createTypeVariable(syncStreamVar)) + _StreamSymType.getTypeInfo(), + List.of(createTypeVariable(syncStreamVar)) ); _SyncStreamSymType = createGenerics( - inScope(gs, type( - "SyncStream", - List.of(syncStreamSuperType), - List.of(syncStreamVar) - )), - createTypeVariable(syncStreamVar) + inScope(gs, type( + "SyncStream", + List.of(syncStreamSuperType), + List.of(syncStreamVar) + )), + createTypeVariable(syncStreamVar) ); TypeVarSymbol toptStreamVar = typeVariable("ToptStreamT"); SymTypeExpression toptStreamSuperType = createGenerics( - _StreamSymType.getTypeInfo(), - List.of(createTypeVariable(toptStreamVar)) + _StreamSymType.getTypeInfo(), + List.of(createTypeVariable(toptStreamVar)) ); _ToptStreamSymType = createGenerics( - inScope(gs, type( - "ToptStream", - List.of(toptStreamSuperType), - List.of(toptStreamVar) - )), - createTypeVariable(toptStreamVar) + inScope(gs, type( + "ToptStream", + List.of(toptStreamSuperType), + List.of(toptStreamVar) + )), + createTypeVariable(toptStreamVar) ); TypeVarSymbol untimedStreamVar = typeVariable("UntimedStreamT"); SymTypeExpression untimedStreamSuperType = createGenerics( - _StreamSymType.getTypeInfo(), - List.of(createTypeVariable(untimedStreamVar)) + _StreamSymType.getTypeInfo(), + List.of(createTypeVariable(untimedStreamVar)) ); _UntimedStreamSymType = createGenerics( - inScope(gs, type( - "UntimedStream", - List.of(untimedStreamSuperType), - List.of(untimedStreamVar) - )), - createTypeVariable(untimedStreamVar) + inScope(gs, type( + "UntimedStream", + List.of(untimedStreamSuperType), + List.of(untimedStreamVar) + )), + createTypeVariable(untimedStreamVar) ); } } @@ -722,8 +725,8 @@ public static void set_genericsRecursive() { // SimpleCrt> TypeVarSymbol crtVar = typeVariable("CrtT"); _simpleCrtSymType = createGenerics( - inScope(gs, type("SimpleCrt", List.of(), List.of(crtVar))), - createTypeVariable(crtVar) + inScope(gs, type("SimpleCrt", List.of(), List.of(crtVar))), + createTypeVariable(crtVar) ); crtVar.addSuperTypes(_simpleCrtSymType); @@ -736,36 +739,38 @@ public static void set_genericsRecursive() { SymTypeVariable nodeEdgeVar = createTypeVariable(typeVariable("NodeE")); nodeSymbol.getSpannedScope().add(nodeNodeVar.getTypeVarSymbol()); nodeSymbol.getSpannedScope().add(nodeEdgeVar.getTypeVarSymbol()); + //class Edge , E extends Edge> + SymTypeVariable edgeNodeVar = createTypeVariable(typeVariable("EdgeN")); + SymTypeVariable edgeEdgeVar = createTypeVariable(typeVariable("EdgeE")); + edgeSymbol.getSpannedScope().add(edgeNodeVar.getTypeVarSymbol()); + edgeSymbol.getSpannedScope().add(edgeEdgeVar.getTypeVarSymbol()); + //class Graph, E extends Edge> + SymTypeVariable graphNodeVar = createTypeVariable(typeVariable("GraphN")); + SymTypeVariable graphEdgeVar = createTypeVariable(typeVariable("GraphE")); + graphSymbol.getSpannedScope().add(graphNodeVar.getTypeVarSymbol()); + graphSymbol.getSpannedScope().add(graphEdgeVar.getTypeVarSymbol()); + // TypeVar superTypes nodeNodeVar.getTypeVarSymbol().addSuperTypes(createGenerics( nodeSymbol, List.of(nodeNodeVar, nodeEdgeVar) )); nodeEdgeVar.getTypeVarSymbol().addSuperTypes(createGenerics( edgeSymbol, List.of(nodeNodeVar, nodeEdgeVar) )); - _graphNodeSymType = createGenerics(nodeSymbol, nodeNodeVar, nodeEdgeVar); - //class Edge , E extends Edge> - SymTypeVariable edgeNodeVar = createTypeVariable(typeVariable("EdgeN")); - SymTypeVariable edgeEdgeVar = createTypeVariable(typeVariable("EdgeE")); - edgeSymbol.getSpannedScope().add(edgeNodeVar.getTypeVarSymbol()); - edgeSymbol.getSpannedScope().add(edgeEdgeVar.getTypeVarSymbol()); edgeNodeVar.getTypeVarSymbol().addSuperTypes(createGenerics( nodeSymbol, List.of(edgeNodeVar, edgeEdgeVar) )); edgeEdgeVar.getTypeVarSymbol().addSuperTypes(createGenerics( edgeSymbol, List.of(edgeNodeVar, edgeEdgeVar) )); - _graphEdgeSymType = createGenerics(edgeSymbol, edgeNodeVar, edgeEdgeVar); - //class Graph, E extends Edge> - SymTypeVariable graphNodeVar = createTypeVariable(typeVariable("GraphN")); - SymTypeVariable graphEdgeVar = createTypeVariable(typeVariable("GraphE")); - graphSymbol.getSpannedScope().add(graphNodeVar.getTypeVarSymbol()); - graphSymbol.getSpannedScope().add(graphEdgeVar.getTypeVarSymbol()); graphNodeVar.getTypeVarSymbol().addSuperTypes(createGenerics( nodeSymbol, List.of(graphNodeVar, graphEdgeVar) )); graphEdgeVar.getTypeVarSymbol().addSuperTypes(createGenerics( edgeSymbol, List.of(graphNodeVar, graphEdgeVar) )); + // finally create SymTypeExpressions + _graphNodeSymType = createGenerics(nodeSymbol, nodeNodeVar, nodeEdgeVar); + _graphEdgeSymType = createGenerics(edgeSymbol, edgeNodeVar, edgeEdgeVar); _graphSymType = createGenerics(graphSymbol, graphNodeVar, graphEdgeVar); } @@ -804,19 +809,19 @@ public static void set_objectTypes() { _personSymType = createTypeObject(inScope(gs, type("Person"))); _teachableSymType = createTypeObject(inScope(gs, type("Teachable"))); _studentSymType = createTypeObject(inScope(gs, - type("Student", List.of(_personSymType, _teachableSymType))) + type("Student", List.of(_personSymType, _teachableSymType))) ); _csStudentSymType = createTypeObject(inScope(gs, - type("CsStudent", List.of(_studentSymType))) + type("CsStudent", List.of(_studentSymType))) ); _firstSemesterCsStudentSymType = createTypeObject(inScope(gs, - type("FirstSemesterCsStudent", List.of(_csStudentSymType))) + type("FirstSemesterCsStudent", List.of(_csStudentSymType))) ); _childSymType = createTypeObject(inScope(gs, - type("Child", List.of(_personSymType, _teachableSymType))) + type("Child", List.of(_personSymType, _teachableSymType))) ); _teacherSymType = createTypeObject(inScope(gs, - type("Teacher", List.of(_personSymType))) + type("Teacher", List.of(_personSymType))) ); _carSymType = createTypeObject(inScope(gs, type("Car"))); _schoolSymType = createTypeObject(inScope(gs, type("School"))); @@ -840,13 +845,13 @@ public static void set_objectTypes() { public static void set_specialObjectTypes() { IBasicSymbolsScope langScope = createJavaLangScope(); _ObjectSymType = - createTypeObject(inScope(langScope, type("Object"))); + createTypeObject(inScope(langScope, type("Object"))); _ThrowableSymType = - createTypeObject(inScope(langScope, type("Throwable"))); + createTypeObject(inScope(langScope, type("Throwable"))); _VoidSymType = - createTypeObject(inScope(langScope, type("Void"))); + createTypeObject(inScope(langScope, type("Void"))); _AutoClosableSymType = - createTypeObject(inScope(langScope, type("AutoClosable"))); + createTypeObject(inScope(langScope, type("AutoClosable"))); } /*********************************************************************/ @@ -862,26 +867,26 @@ public static void set_specialObjectTypes() { public static void set_generics() { IBasicSymbolsScope utilScope = - _boxedListSymType.getTypeInfo().getEnclosingScope(); + _boxedListSymType.getTypeInfo().getEnclosingScope(); TypeVarSymbol listVar = typeVariable("LinkedListT"); - _linkedListSymType = createGenerics( - inScope(utilScope, type("LinkedList", - List.of(createGenerics(_boxedListSymType.getTypeInfo(), - createTypeVariable(listVar))), - List.of(listVar) - )) + _linkedListSymType = createGenericsDeclaredType( + inScope(utilScope, type("LinkedList", + List.of(createGenerics(_boxedListSymType.getTypeInfo(), + createTypeVariable(listVar))), + List.of(listVar) + )) ); TypeVarSymbol mapKVar = typeVariable("HashMapK"); TypeVarSymbol mapVVar = typeVariable("HashMapV"); - _hashMapSymType = createGenerics( - inScope(utilScope, type("HashMap", - List.of(createGenerics( - _boxedMapSymType.getTypeInfo(), - createTypeVariable(mapKVar), - createTypeVariable(mapVVar)) - ), - List.of(mapKVar, mapVVar)) - ) + _hashMapSymType = createGenericsDeclaredType( + inScope(utilScope, type("HashMap", + List.of(createGenerics( + _boxedMapSymType.getTypeInfo(), + createTypeVariable(mapKVar), + createTypeVariable(mapVVar)) + ), + List.of(mapKVar, mapVVar)) + ) ); } @@ -899,18 +904,18 @@ public static void set_generics() { public static void set_specialGenerics() { IBasicSymbolsScope langScope = createJavaLangScope(); TypeVarSymbol classVar = typeVariable("T"); - _ClassSymType = createGenerics( - inScope(langScope, type("Class", - Collections.emptyList(), - List.of(classVar) - )) + _ClassSymType = createGenericsDeclaredType( + inScope(langScope, type("Class", + Collections.emptyList(), + List.of(classVar) + )) ); TypeVarSymbol IterableVar = typeVariable("T"); - _IterableSymType = createGenerics( - inScope(langScope, type("Iterable", - Collections.emptyList(), - List.of(classVar) - )) + _IterableSymType = createGenericsDeclaredType( + inScope(langScope, type("Iterable", + Collections.emptyList(), + List.of(classVar) + )) ); } diff --git a/monticore-grammar/src/test/java/de/monticore/types3/util/DefsVariablesForTests.java b/monticore-grammar/src/test/java/de/monticore/types3/util/DefsVariablesForTests.java index 9c8899a87c..46c21411cf 100644 --- a/monticore-grammar/src/test/java/de/monticore/types3/util/DefsVariablesForTests.java +++ b/monticore-grammar/src/test/java/de/monticore/types3/util/DefsVariablesForTests.java @@ -25,7 +25,9 @@ * if specific variables are needed * (e.g., specific generics or two variables of the same type), * they ought to be added in the specific test. + * @deprecated Use the test fixtures instead */ +@Deprecated(forRemoval = true) public class DefsVariablesForTests { /** @@ -131,13 +133,13 @@ public static void set_boxedObjects(IBasicSymbolsScope scope) { public static void set_unboxedCollections(IBasicSymbolsScope scope) { _intUnboxedOptionalVarSym = inScope(scope, variable("varintOptional", - createGenerics(_unboxedOptionalSymType.getTypeInfo(), _intSymType))); + createGenerics(_unboxedOptionalSymType.getTypeInfo(), _intSymType))); _intUnboxedSetVarSym = inScope(scope, variable("varintSet", - createGenerics(_unboxedSetSymType.getTypeInfo(), _intSymType))); + createGenerics(_unboxedSetSymType.getTypeInfo(), _intSymType))); _intUnboxedListVarSym = inScope(scope, variable("varintList", - createGenerics(_unboxedListSymType.getTypeInfo(), _intSymType))); + createGenerics(_unboxedListSymType.getTypeInfo(), _intSymType))); _intUnboxedMapVarSym = inScope(scope, variable("varintMap", - createGenerics(_unboxedMapSymType.getTypeInfo(), _intSymType, _intSymType))); + createGenerics(_unboxedMapSymType.getTypeInfo(), _intSymType, _intSymType))); } /* @@ -154,13 +156,13 @@ public static void set_unboxedCollections(IBasicSymbolsScope scope) { public static void set_boxedCollections(IBasicSymbolsScope scope) { _boxedOptionalVarSym = inScope(scope, variable("varintBoxedOptional", - createGenerics(_boxedOptionalSymType.getTypeInfo(), _intSymType))); + createGenerics(_boxedOptionalSymType.getTypeInfo(), _intSymType))); _boxedSetVarSym = inScope(scope, variable("varintBoxedSet", - createGenerics(_boxedSetSymType.getTypeInfo(), _intSymType))); + createGenerics(_boxedSetSymType.getTypeInfo(), _intSymType))); _boxedListVarSym = inScope(scope, variable("varintBoxedList", - createGenerics(_boxedListSymType.getTypeInfo(), _intSymType))); + createGenerics(_boxedListSymType.getTypeInfo(), _intSymType))); _boxedMapVarSym = inScope(scope, variable("varintBoxedMap", - createGenerics(_boxedMapSymType.getTypeInfo(), _intSymType, _intSymType))); + createGenerics(_boxedMapSymType.getTypeInfo(), _intSymType, _intSymType))); } /* @@ -179,15 +181,15 @@ public static void set_boxedCollections(IBasicSymbolsScope scope) { public static void set_streams(IBasicSymbolsScope scope) { _intStreamVarSym = inScope(scope, variable("varintStream", - createGenerics(_StreamSymType.getTypeInfo(), _intSymType))); + createGenerics(_StreamSymType.getTypeInfo(), _intSymType))); _intEventStreamVarSym = inScope(scope, variable("varintEventStream", - createGenerics(_EventStreamSymType.getTypeInfo(), _intSymType))); + createGenerics(_EventStreamSymType.getTypeInfo(), _intSymType))); _intSyncStreamVarSym = inScope(scope, variable("varintSyncStream", - createGenerics(_SyncStreamSymType.getTypeInfo(), _intSymType))); + createGenerics(_SyncStreamSymType.getTypeInfo(), _intSymType))); _intToptStreamVarSym = inScope(scope, variable("varintToptStream", - createGenerics(_ToptStreamSymType.getTypeInfo(), _intSymType))); + createGenerics(_ToptStreamSymType.getTypeInfo(), _intSymType))); _intUntimedStreamVarSym = inScope(scope, variable("varintUntimedStream", - createGenerics(_UntimedStreamSymType.getTypeInfo(), _intSymType))); + createGenerics(_UntimedStreamSymType.getTypeInfo(), _intSymType))); } /* @@ -214,23 +216,23 @@ public static void set_streams(IBasicSymbolsScope scope) { public static void set_objectTypes(IBasicSymbolsScope scope) { _personVarSym = inScope(scope, variable("varPerson", - createTypeObject(_personSymType.getTypeInfo()))); + createTypeObject(_personSymType.getTypeInfo()))); _teachableVarSym = inScope(scope, variable("varTeachable", - createTypeObject(_teachableSymType.getTypeInfo()))); + createTypeObject(_teachableSymType.getTypeInfo()))); _studentVarSym = inScope(scope, variable("varStudent", - createTypeObject(_studentSymType.getTypeInfo()))); + createTypeObject(_studentSymType.getTypeInfo()))); _csStudentVarSym = inScope(scope, variable("varCsStudent", - createTypeObject(_csStudentSymType.getTypeInfo()))); + createTypeObject(_csStudentSymType.getTypeInfo()))); _firstSemesterCsStudentVarSym = inScope(scope, variable("varFirstSemesterCsStudent", - createTypeObject(_firstSemesterCsStudentSymType.getTypeInfo()))); + createTypeObject(_firstSemesterCsStudentSymType.getTypeInfo()))); _childVarSym = inScope(scope, variable("varChild", - createTypeObject(_childSymType.getTypeInfo()))); + createTypeObject(_childSymType.getTypeInfo()))); _teacherVarSym = inScope(scope, variable("varTeacher", - createTypeObject(_teacherSymType.getTypeInfo()))); + createTypeObject(_teacherSymType.getTypeInfo()))); _carVarSym = inScope(scope, variable("varCar", - createTypeObject(_carSymType.getTypeInfo()))); + createTypeObject(_carSymType.getTypeInfo()))); _schoolVarSym = inScope(scope, variable("varSchool", - createTypeObject(_schoolSymType.getTypeInfo()))); + createTypeObject(_schoolSymType.getTypeInfo()))); } /* @@ -244,9 +246,9 @@ public static void set_objectTypes(IBasicSymbolsScope scope) { public static void set_generics(IBasicSymbolsScope scope) { _intLinkedListVarSym = inScope(scope, variable("varintLinkedList", - createGenerics(_linkedListSymType.getTypeInfo(), _intSymType))); + createGenerics(_linkedListSymType.getTypeInfo(), _intSymType))); _intHashMapVarSym = inScope(scope, variable("varintHashMap", - createGenerics(_hashMapSymType.getTypeInfo(), _intSymType, _intSymType))); + createGenerics(_hashMapSymType.getTypeInfo(), _intSymType, _intSymType))); } /* diff --git a/monticore-grammar/src/test/java/de/monticore/types3/util/SymTypeExpressionGenerator.java b/monticore-grammar/src/test/java/de/monticore/types3/util/SymTypeExpressionGenerator.java new file mode 100644 index 0000000000..ac57af9000 --- /dev/null +++ b/monticore-grammar/src/test/java/de/monticore/types3/util/SymTypeExpressionGenerator.java @@ -0,0 +1,170 @@ +// (c) https://github.com/MontiCore/monticore +package de.monticore.types3.util; + +import de.monticore.symbols.basicsymbols.BasicSymbolsMill; +import de.monticore.types.check.SymTypeExpression; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static de.monticore.types.check.SymTypeExpressionFactory.createFunction; +import static de.monticore.types.check.SymTypeExpressionFactory.createInferenceVariable; +import static de.monticore.types.check.SymTypeExpressionFactory.createIntersection; +import static de.monticore.types.check.SymTypeExpressionFactory.createObscureType; +import static de.monticore.types.check.SymTypeExpressionFactory.createPrimitive; +import static de.monticore.types.check.SymTypeExpressionFactory.createTuple; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeArray; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeOfNull; +import static de.monticore.types.check.SymTypeExpressionFactory.createTypeVoid; +import static de.monticore.types.check.SymTypeExpressionFactory.createUnion; +import static de.monticore.types.check.SymTypeExpressionFactory.createWildcard; + +/** + * A generator to generate random SymTypeExpressions for testing purposes. + *