Abstract base class for evaluation values. * @author tkoenig *
java this.elements = new ArrayList<Data>();
Data class with derived type information (anonym product). * @author tkoenig *
java final ConstructorTypeExpression conTypeExpr = new ConstructorTypeExpression( model); final Iterator<Data> iterator = this.getElements().iterator(); while (iterator.hasNext()) { conTypeExpr.getParts().add(iterator.next().getType(model)); } return conTypeExpr;
Data class for concrete type values. * @author tkoenig *
java super(); this.type = type;
java return this.type;
constructor. * * @param type
Class to evaluate expressions. * @author tkoenig *
java this.model = model;
java return this.evaluateHelper(evaluableFunction, new DerivedTypeData());
java return evaluableFunction .accept(new FunctionExpressionVisitorWithResult<Data>() { @Override public Data handleTypedProjection( final TypedProjection typedProjection) { return this.handleAbstractProjection(typedProjection); } @Override public Data handleTypedIdentity( final TypedIdentity typedIdentity) { return previousData; } @Override public Data handleTypedFinalMap( final TypedFinalMap typedFinalMap) { return new DerivedTypeData(); } @Override public Data handleTypedConstructorFunctionExpression( final TypedConstructorFunctionExpression typedConstructorFunctionExpression) throws ModelException { return this .handleAbstractConstructorFunctionExpression(typedConstructorFunctionExpression); } @Override public Data handleSumFunctionExpression( final SumFunctionExpression sumFunctionExpression) { final Iterator<FunctionExpression> iterator = sumFunctionExpression .getParts().iterator(); while (iterator.hasNext()) { final FunctionExpression expr = iterator.next(); // if(expr.getDomain() // previousData.getType(Evaluator.this.model)){ // return Evaluator.this.evaluateHelper(expr, // previousData); // } } // TODO: ModelException ist doof in diesem Visitor!!! return new DerivedTypeData(); } @Override public Data handleSequentialFunctionExpression( final SequentialFunctionExpression sequentialFunctionExpression) throws ModelException { final Iterator<FunctionExpression> iterator = sequentialFunctionExpression .getParts().iterator(); Data value = previousData; while (iterator.hasNext()) { value = Evaluator.this.evaluateHelper( iterator.next(), value); } return value; } @Override public Data handleProjection(final Projection projection) { return this.handleAbstractProjection(projection); } @Override public Data handleProductFunctionExpression( final ProductFunctionExpression productFunctionExpression) throws ModelException { final Data ret = new DerivedTypeData(); final Iterator<FunctionExpression> iterator = productFunctionExpression .getParts().iterator(); while (iterator.hasNext()) { ret.getElements().add( Evaluator.this.evaluateHelper( iterator.next(), previousData)); } return ret; } @Override public Data handleNamedFunctionReference( final NamedFunctionReference namedFunctionReference) throws ModelException { // TODO no implementation yed. return null; } @Override public Data handleIdentity(final Identity identity) { return previousData; } @Override public Data handleFinalMap(final FinalMap finalMap) { return new DerivedTypeData(); } @Override public Data handleConstructorFunctionExpression( final ConstructorFunctionExpression constructorFunctionExpression) throws ModelException { return this .handleAbstractConstructorFunctionExpression(constructorFunctionExpression); } /** * Behavior of typed and non-typed constructor expression * are actual equivalent. * * @param previousData * @param typedConstructorFunctionExpression * @return * @throws ModelException */ private Data handleAbstractConstructorFunctionExpression( final AbstractConstructorFunctionExpression typedConstructorFunctionExpression) throws ModelException { return new TypedData(typedConstructorFunctionExpression .getCoDomain(previousData .getType(Evaluator.this.model))); } /** * Behavior of typed and non-typed projection are actual * equivalent. * * @param abstrProjection * @return */ private Data handleAbstractProjection( final AbstractProjection abstrProjection) { final Iterator<Data> it = previousData.getElements() .iterator(); Data currentData = null; int i = 0; while (it.hasNext()) { currentData = it.next(); if (i == abstrProjection.getOffset()) { return currentData; } i++; } // TODO: ModelException ist doof in diesem Visitor!!! return new DerivedTypeData(); } });
Construktor.
Operation to evaluate list of evaluable functional expressions. * * @param evaluableFunction * @return Data with evaluated expressions. * @throws ModelException
An superclass for all Exceptions that can occour in Operations in the model.
java super(message); this.object = object; java return this.object; Returns the corrupt {@link CodeContainable}.
Default constructor with message. * * @param message
Accepts a {@link ModelExceptionVisitor}.
Exception that occours if tried to apply an {@link de.fhdw.lomf.model.Projection} on an Type that has no Components.
java super(message, object);
java visitor.handleNoProjectionableTypeException(this);
Exception indicating that the requested offset in an Projection is out of the bounds given by the elements of the type.
java super(message, object);
java visitor.handleProjectionIndexOutOfBoundsException(this);
java super(ExceptionConstants.AMBIGUOUS_BINDING + contextType.print(), object);
java visitor.handleAmbiguousBindingException(this);
Constructor.
java super(ExceptionConstants.MISSING_BINDING + domain.print(), sum);
java visitor.handleMissingBindingException(this);
Constructor.
Exception indicates that the CoDomain and Domain in an {@link de.fhdw.lomf.model.SequentialFunctionExpression} doesn't match.
java super(message, object);
java visitor.handleSequenceDomainCodomainMissmatchException(this);
A visitor to get the type of a ModelException.
Represents an error that occurs if a symbol is missing. @author tkoenig
java super(object, ExceptionConstants.MISSING_SYMBOL + symbol); java return ModelErrorType.ERROR;
constructor. * @param object * @param symbol
A visitor to check the type of the FunctionExpression with a return value. * @param <T> type of the return value. *
Adapter for a {@link TypeExpressionVisitor}.
Visitor for {@link de.fhdw.lomf.model.TypeExpression} hierarchy.
Default implementation for {@link TypeExpressionVisitor}.
java this.defaultHandling(visitee);
java this.defaultHandling(visitee);
java this.defaultHandling(visitee);
java this.defaultHandling(visitee);
java this.defaultHandling(visitee);
java this.defaultHandling(visitee);
Visitor for {@link de.fhdw.lomf.model.TypeOrder} hierarchy.
A visitor to check the type of the FunctionExpression.
Default visitor for {@link FunctionExpression}.
java this.defaultHandling(typedFinalMap);
java this.defaultHandling(finalMap);
java this.defaultHandling(identity);
java this.defaultHandling(typedIdentity);
java this.defaultHandling(namedFunctionReference);
java this.defaultHandling(projection);
java this.defaultHandling(typedProjection);
java this.defaultHandling(typedConstructorFunctionExpression);
java this.defaultHandling(sequentialFunctionExpression);
java this.defaultHandling(productFunctionExpression);
java this.defaultHandling(constructorFunctionExpression);
java this.defaultHandling(sumFunctionExpression);
Abstract class for all Errors that can occur due model-checking. *
java super(); this.object = object; this.errorMessage = errorMessage; java if (this.object instanceof CodeContainableWithName) { return ((CodeContainableWithName) this.object).getName(); } else if (this.object instanceof ObjectWithTypeNameReference) { return ((ObjectWithTypeNameReference) this.object).getTypeName(); } else { return ""; } java final int prime = 31; int result = 1; result = prime * result + ((this.errorMessage == null) ? 0 : this.errorMessage.hashCode()); result = prime * result + ((this.object == null) ? 0 : this.object.hashCode()); return result;
java if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final ModelError other = (ModelError) obj; if (!this.errorMessage.equals(other.errorMessage)) { return false; } if (this.object == null) { if (other.object != null) { return false; } } else if (!this.object.equals(other.object)) { return false; } return true; java final String name = this.getName(); return name.length() == 0 ? this.getErrorMessage() : this .getErrorMessage() + " " + name; java return this.getObject().getTokens();
Returns the {@link ModelErrorType} of this error. * * @return
Creates new Error corresponding to the given {@link CodeContainable} * object and given <errorMessage>. * * @param object * @param errorMessage
Enumeration for defining the Type of an Model Error. Be careful when adding new Type, due the ordinal is used for compare.
Error indicating a name conflict between a type and a function. @author Sönke *
java super(object, "Conflicting names"); java return ModelErrorType.ERROR;
Creates new {@link NameConflictError}. * * @param object
Represents an error that occurs, if there are ambiguous bindings for a type.
java super(object, errorMessage); java return ModelErrorType.ERROR;
Constructor.
Error indicates that between two methods f1 and f2 for the same function f with the property domain(f1) <=(abstract) domain(f2) that codomain(f1) !<=(abstract) codomain(f2).
java super(object, "The codomain has to be less or equal: " + lessOrEqualThan.toString() + "."); java return ModelErrorType.ERROR;
Constructor to create a {@link CoDomainIsNotSubTypeError}. * @param object * @param lessOrEqualThan
Represent an error, when the codomain of the function is not greater or equal than the codomain of the method.
java super(object, errorMessage); java return ModelErrorType.ERROR;
Constructor to create a CoDomainMissmatchError.
Indicates a error, when two methods f1 and f2 for same function f have the same domain.
java super(object, "A function to the same name has the same domain."); java return ModelErrorType.ERROR;
Constructor to create a {@link DomainConflictError}.
Represent an error, when the domain of a method is not greater or equal than the domain of a function.
java super(object, errorMessage); java return ModelErrorType.ERROR;
Constructor to create a DomainMissmatchError.
Indicates a error, that an empty product was found.
java super(object, "An empty product is not allowed."); java return ModelErrorType.ERROR;
Creates a {@link EmptyProductError}.
This error indicates that a empty SumFunctionExpression was found.
java super(object, "An empty sum is not allowed."); java return ModelErrorType.ERROR;
Creates a {@link EmptySumError}.
{@link ModelError} for evaluable expressions that are not sequential.
java super(object, "The expression has to be sequential."); java return ModelErrorType.ERROR;
Constructor.
{@link ModelError} for evaluable expressions that do not start with a final map.
java super(object, "Expression does not start from nothing."); java return ModelErrorType.ERROR;
Constructor.
Represents an error that occurs if a binding for a type is missing.
java super(object, errorMessage); java return ModelErrorType.ERROR;
Constructor.
Error indicating an missing function.
java super(source, "Missing coecer from " + source.getName() + " to " + target.getName()); java return ModelErrorType.ERROR;
Creates a new {@link MissingCoercerError}.
Error indicating an missing function.
java super(object, "Missing function"); java return ModelErrorType.ERROR;
Creates a new {@link MissingFunctionError}. * * @param object
Error indicating a missing type.
java super(object, "Missing type"); java return ModelErrorType.ERROR;
Creates new {@link MissingTypeError}. * * @param object
Comparator for {@link ModelError}s. Compares their {@link ModelErrorType}s.
java this.direction = direction;
java final int result = arg0.getErrorType().compareTo(arg1.getErrorType()); return this.direction ? result : result * -1;
Creates new {@link ModelErrorComparator} with the given <direction>. * direction == true --> Ascending order direction == false --> Descending * order. * * @param direction
Error that occours if tried to apply an {@link de.fhdw.lomf.model.Projection} on an Type that has no Components.
java super(object, errorMessage); java return ModelErrorType.ERROR;
Constructor to create a {@link NoProjectionableTypeError}.
Indicates that a product contains only one part.
java super(object, "The product contains only one part."); java return ModelErrorType.ERROR;
Creates a {@link ProductContainsOnePartError}.
An Error indicating that the offset from an Projection was greater or less than the bounds of an Projection.
java super(object, errorMessage); java return ModelErrorType.ERROR;
Default Constructor. * * @param object * @param errorMessage
An error indicating that two succeeding functions in an {@link de.fhdw.lomf.model.SequentialFunctionExpression} have an Doman-CoDomain missmatch, ie the codomain of the preceding one is not <= the domain of the following.
java super(object, errorMessage); java return ModelErrorType.ERROR;
Default Constructor. * * @param object * @param errorMessage
This error indicates a SequentialFunctionExpression that ends with a FinalMap or TypedFinalMap.
java super(object, "At this position is a final-symbol not allowed."); java return ModelErrorType.ERROR;
Creates a {@link SequenceEndWithFinalMapError}.
This error indicates that a SumFunctionExpression with only one part was found.
java super(object, "The sum contains only one part."); java return ModelErrorType.STYLE;
Creates a {@link SumContainsOnePartError}.
{@link ModelError}, that indicates, that an implicit sum had summands, that did not start with an identity expression.
java super(object, "Summand in sum does not start with identity expression"); java return ModelErrorType.ERROR;
Constructor.
Error that indicates that a hierarchy is symmetric.
java super(from, "The hierarchy between the type " + from.getName() + " and the type " + to.getName() + " is symmetric."); java return ModelErrorType.ERROR;
Creates a new {@link SymmetricHierarchyError}.
{@link ModelError}, that indicates, that an implicit sum more than summands, that started with an untyped identity.
java super(object, "There were multiple summands starting with a untyped identity."); java return ModelErrorType.ERROR;
Constructor.
Abstraction for {@link ConstructorFunctionExpression} and {@link TypedConstructorFunctionExpression}.
java super(tokens, parts, belongsToModel); java return Symbols.SEPARATOR_SYMBOL; java return Symbols.CONSTRUCTOR_START_SYMBOL; java if (this.getParts().isEmpty()) { return new SumOfAllTypesExpression(this.getModel()); } final SumTypeExpression domainType = new SumTypeExpression( new LinkedList<Token>(), this.getDomainIntersection(), this.getModel()); return domainType.concretize(false); java final Set<TypeExpression> domain = new HashSet<TypeExpression>(); final ConcretizedTypeToSetOfSubTypesConverter converter = new ConcretizedTypeToSetOfSubTypesConverter(); final Iterator<FunctionExpression> parts = this.getParts().iterator(); final ValueWrapper<Boolean> foundSpecial = new ValueWrapper<Boolean>(); foundSpecial.setValue(Boolean.FALSE); final ValueWrapper<SumOfAllTypesExpression> sumOfAllTypes = new ValueWrapper<SumOfAllTypesExpression>(); final List<SumOfAllNaryProducts> sumOfAllNArayProducts = new ArrayList<SumOfAllNaryProducts>(); boolean collectionWasFilled = false; while (parts.hasNext()) { final TypeExpression currentDomain = parts.next().getDomain(); this.handleSpecialTypes(sumOfAllTypes, sumOfAllNArayProducts, foundSpecial, currentDomain); if (foundSpecial.getValue().equals(Boolean.TRUE)) { continue; } else { if (!collectionWasFilled) { collectionWasFilled = true; domain.addAll(converter.convert(currentDomain)); } else { domain.retainAll(converter.convert(currentDomain)); } } } // Handling of untyped products final SumOfAllNaryProducts biggestProduct = this.getBiggestProduct(sumOfAllNArayProducts); if (biggestProduct != null) { if (domain.isEmpty()) { final Set<TypeExpression> singleSet = new HashSet<TypeExpression>(); singleSet.add(biggestProduct); return singleSet; } for (final TypeExpression currentDomainPart : domain) { // If there is one part, that is not a subtype of the biggest product, // the intersection automatically will be empty. Otherwise, if all parts // are a subtype of the biggest product, we can ignore the product if (!biggestProduct.isSuperTypeOf(currentDomainPart, true)) { return new HashSet<TypeExpression>(); } } } //Handling of sum-of-all-types // If there is just a sum-of-all-types, we have to return it. // Otherwise, we can ignore it if (sumOfAllTypes.getValue() != null && domain.isEmpty()) { final Set<TypeExpression> singleSet = new HashSet<TypeExpression>(); singleSet.add(sumOfAllTypes.getValue()); return singleSet; } return domain;
java domain.accept(new TypeExpressionAdapter() { @Override public void handle(final SumOfAllTypesExpression visitee) { if (sumOfAllTypes.getValue() == null) { sumOfAllTypes.setValue(visitee); } foundSpecial.setValue(Boolean.TRUE); } @Override public void handle(final SumOfAllNaryProducts visitee) { sumOfAllNArayProducts.add(visitee); foundSpecial.setValue(Boolean.TRUE); } });
java SumOfAllNaryProducts biggest = null; for (final SumOfAllNaryProducts current : sumOfAllNArayProducts) { if (biggest == null || current.getComponentCount() > biggest.getComponentCount()) { biggest = current; } } return biggest;
The constructor.
Abstraction over {@link FinalMap} and {@link TypedFinalMap}.
java super(tokens, belongsToModel);
java return new ConstructorTypeExpression(new LinkedList<TypeExpression>(), this.getModel());
Abstraction für {@link Identity} and {@link TypedIdentity}.
java super(tokens, belongsToModel);
java return domainContext;
Represents an abstract model. java this.errors = new HashMap<Class<? extends ModelError>, Collection<ModelError>>(); java return this.errors.size() == 0;
java Collection<ModelError> values = this.errors.get(error.getClass()); if (values == null) { values = new ArrayList<ModelError>(); this.errors.put(error.getClass(), values); } values.add(error);
java final Collection<ModelError> result = this.errors.get(errorClass); if (result != null) { return result; } else { return Collections.emptySet(); }
java for (final ModelError error : this.getErrors()) { if (error.getErrorType().equals(type)) { return true; } } return false;
Constructor.
Returns a Collection of Lists of Functions. Each Function within one List * has the same identifier. Returns a List of all Functions with the given name. If no function with * the given name exits an empty list will be returned. * * @param name * the name of the {@link Function} * @return a {@link List} with all {@link Function}s corresponding to * <code>name</code> * * TODO #27153: This function is only called in testcases. Check if * this method can be moved to testclass. Gets an operation by its name. * * @param name * @return The operation.
Returns a Collection of all the {@link Type}s within the {@link Model}. * * @return Returns {@link Type} Object for the given type name of <code>null</code> * if no type with that name exists. ****** Pretty Printing. ******************************************************************************* Returns the {@link CoercerHierarchy} for this model. Returns <code>true</code> iff the Model contains no erroneous * {@link Type}s. Otherwise <code>false</code> is returned. Adds a {@link TypeOrFunction} to the Model. Accept operation for visitor pattern.
Returns all errors in the model with the given {@link Class} errorClass.
Returns true, iff at least one {@link ModelError} with the given {@link ModelErrorType} is contained * in this models errors.
Represents an object, that contains the {@link Model} to which <code>this</code> object belongs.
java this.model = model;
Constructor to create a {@link AbstractModelContainable}.
Abstraction for {@link Projection} and {@link TypedProjection}.
java super(tokens, belongsToModel); this.offset = offset;
java final SumTypeExpression result = new SumTypeExpression(this.getModel()); final ValueWrapper<ModelException> exceptionHolder = new ValueWrapper<ModelException>(); domainContext.accept(new TypeExpressionVisitor() { @Override public void handle(final SumOfAllNaryProducts visitee) { if (AbstractProjection.this.getOffset() < visitee.getComponentCount()) { result.addElement(new SumOfAllTypesExpression(AbstractProjection.this.getModel())); } else { exceptionHolder.setValue( new NoProjectionableTypeException( "The projection offset is out of bounds in " + visitee.print(), AbstractProjection.this)); } } @Override public void handle(final SumOfAllTypesExpression visitee) { exceptionHolder.setValue( new NoProjectionableTypeException( visitee.print() + " has no projections.", AbstractProjection.this)); } @Override public void handle(final NamedTypeReference visitee) { final Type type = visitee.refersTo(); if (type.isAbstract()) { final TypeExpression concretes = visitee.concretize(false); this.tryInner(concretes); } else { final TypeExpression definition = type.getType(); this.tryInner(definition); } } @Override public void handle(final FunctionTypeExpression visitee) { //TODO FunctionType } @Override public void handle(final ConstructorTypeExpression visitee) { if (AbstractProjection.this.getOffset() > visitee.getSize() - 1 || AbstractProjection.this.getOffset() < 0) { exceptionHolder.setValue( new ProjectionIndexOutOfBoundsException( ExceptionConstants.PROJECTION_INDEX_OUT_OF_BOUNDS + visitee.print(), AbstractProjection.this)); } else { int pos = 0; for (final TypeExpression part : visitee.getParts()) { if (!(pos == AbstractProjection.this.getOffset())) { pos++; continue; } result.addElement(part); break; } } } private void tryInner(final TypeExpression innerExpression) { try { final TypeExpression summandCoDomain = AbstractProjection.this.getCoDomain(innerExpression); summandCoDomain.accept(new TypeExpressionVisitor() { @Override public void handle(final SumOfAllNaryProducts visitee) { result.addElement(visitee); } @Override public void handle(final SumOfAllTypesExpression visitee) { result.addElement(visitee); } @Override public void handle(final NamedTypeReference visitee) { result.addElement(visitee); } @Override public void handle(final FunctionTypeExpression visitee) { result.addElement(visitee); } @Override public void handle(final ConstructorTypeExpression visitee) { result.addElement(visitee); } @Override public void handle(final SumTypeExpression visitee) { for (final TypeExpression current : visitee) { result.addElement(current); } } }); } catch (final ModelException e) { exceptionHolder.setValue(e); } } @Override public void handle(final SumTypeExpression visitee) { for (final TypeExpression summand : visitee) { this.tryInner(summand); if (exceptionHolder.getValue() != null) { break; } } } }); if (exceptionHolder.getValue() != null) { throw exceptionHolder.getValue(); } return result.size() == 1 ? result.iterator().next() : result;
Abstraction of all atomic {@link FunctionExpression}. *
java super(tokens, belongsToModel);
Abstract class for all atomic type expressions.
java super(tokens, belongsToModel);
Helper class for building bindings.
java super(); this.functions = functions; this.self = self; this.model = self.getModel(); this.binding = new HashMap<TypeExpression, List<FunctionOrFunctionExpression>>();
java final TypeExpression concreteType = domainContext.concretize(false); if (!this.hasBindingFor(concreteType)) { this.buildBinding(concreteType); this.analyseBinding(); } return this.getCoDomainFor(concreteType);
java final AtomicBoolean result = new AtomicBoolean(); concreteType.accept(new TypeExpressionDefaultVisitor() { @Override public void handle(final SumTypeExpression visitee) { final Iterator<TypeExpression> types = visitee.iterator(); while (types.hasNext()) { final TypeExpression typeExpression = types.next(); this.defaultHandling(typeExpression); if (!result.get()) { return; } } } @Override public void defaultHandling(final TypeExpression typeExpression) { result.set(BindingBuilder.this.binding.containsKey(typeExpression)); } }); return result.get();
java final Map<TypeExpression, List<FunctionOrFunctionExpression>> newBinding = new HashMap<TypeExpression, List<FunctionOrFunctionExpression>>(); domainContext.accept(new TypeExpressionDefaultVisitor() { @Override public void defaultHandling(final TypeExpression typeExpression) { this.singleTypehandling(typeExpression); } @Override public void handle(final SumTypeExpression sum) { for (final TypeExpression currentDomainContext : sum) { this.singleTypehandling(currentDomainContext); } } private void singleTypehandling(final TypeExpression currentDomainContext) { final List<FunctionOrFunctionExpression> currentCandidates = new ArrayList<FunctionOrFunctionExpression>(); newBinding.put(currentDomainContext, currentCandidates); WithoutEffect: for (final FunctionOrFunctionExpression currentFunction : BindingBuilder.this.functions) { final TypeExpression currentDomain = currentFunction.getDomain(); if (currentDomain.isSuperTypeOf(currentDomainContext, false)) { final Iterator<FunctionOrFunctionExpression> oldCandidates = currentCandidates.iterator(); while (oldCandidates.hasNext()) { final TypeExpression currentOldDomain = oldCandidates.next().getDomain(); if (currentOldDomain.isProperSuperTypeOf(currentDomain)) { oldCandidates.remove(); } if (currentDomain.isProperSuperTypeOf(currentOldDomain)) { continue WithoutEffect; } } currentCandidates.add(currentFunction); } } } }); this.binding.putAll(newBinding); java for (final Map.Entry<TypeExpression, List<FunctionOrFunctionExpression>> currentEntry : this.binding.entrySet()) { final List<FunctionOrFunctionExpression> currentBindings = currentEntry.getValue(); if (currentBindings.isEmpty()) { throw new MissingBindingException(currentEntry.getKey(), this.self); } if (currentBindings.size() > 1) { throw new AmbiguousBindingException(currentEntry.getKey(), this.self); } //TODO ML find dead code }
java final HashSet<TypeExpression> coDomainParts = new LinkedHashSet<TypeExpression>(); final ValueWrapper<ModelException> exceptionWrapper = new ValueWrapper<ModelException>(); concreteType.accept(new TypeExpressionDefaultVisitor() { @Override public void handle(final SumTypeExpression visitee) { for (final TypeExpression subtype : visitee) { this.defaultHandling(subtype); } } @Override public void defaultHandling(final TypeExpression typeExpression) { final List<FunctionOrFunctionExpression> list = BindingBuilder.this.binding.get(typeExpression); assert list.size() == 1; try { coDomainParts.add(list.get(0).getCoDomain(typeExpression)); } catch (final ModelException e) { exceptionWrapper.setValue(e); } } }); if (exceptionWrapper.getValue() != null) { throw exceptionWrapper.getValue(); } return new SumTypeExpression(new LinkedList<Token>(), coDomainParts, this.model).concretize(false); java final Set<TypeExpression> domain = new HashSet<TypeExpression>(); for (final FunctionOrFunctionExpression function : this.functions) { domain.add(function.getDomain()); } return new SumTypeExpression(new LinkedList<Token>(), domain, this.model) .concretize(false);
Constructor.
Hierarchy containing all available coercers between concrete types. *
java super(belongsToModel); this.coercers = new HashMap<Type, Map<Type, FunctionExpression>>();
java if (!this.coercers.containsKey(source)) { this.coercers.put(source, new HashMap<Type, FunctionExpression>()); } final Map<Type, FunctionExpression> values = this.coercers.get(source); values.put(target, coercer);
java for (final TypeOrder typeOrder : type.getHierarchies()) { typeOrder.accept(new TypeOrderVisitor() { @Override public void handle(final Specialization visitee) { if (visitee.hasCoercer()) { CoercerHierarchy.this.addCoercer(type, visitee.getRefersTo(), visitee.getCoercer()); } } @Override public void handle(final Generalization visitee) { if (visitee.hasCoercer()) { CoercerHierarchy.this.addCoercer(visitee.getRefersTo(), type, visitee.getCoercer()); } } }); }
java return Collections .unmodifiableMap(this.coercers.containsKey(type) ? this.coercers .get(type) : new HashMap<Type, FunctionExpression>(0));
java for (final Type type : types) { this.addCoercersFromType(type); } this.createTransitiveClosure(); java boolean hasChanged; final Map<Type, FunctionExpression> newCoercers = new HashMap<Type, FunctionExpression>(); do { hasChanged = false; for (final Entry<Type, Map<Type, FunctionExpression>> sourceEntry : this.coercers .entrySet()) { for (final Entry<Type, FunctionExpression> targetEntry : sourceEntry .getValue().entrySet()) { // Check if there is a coercer that starts at the end of // this coercer if (!this.coercers.containsKey(targetEntry.getKey())) { continue; } this.addTransitiveCoercer(newCoercers, sourceEntry.getKey(), targetEntry.getKey()); } if (!newCoercers.isEmpty()) { sourceEntry.getValue().putAll(newCoercers); newCoercers.clear(); hasChanged = true; } } } while (hasChanged);
java for (final Entry<Type, FunctionExpression> targetEntry : this.coercers .get(target).entrySet()) { // Check if it is not contained already if (this.containsCoercer(source, targetEntry.getKey())) { continue; } final List<FunctionExpression> parts = new LinkedList<FunctionExpression>(); // Add the coercer from the sourceType to the target type (ie. // A-->B) parts.add(this.getCoercer(source, target)); // Add the coercer from the targetEntry (i.e. B-->C) parts.add(targetEntry.getValue()); final SequentialFunctionExpression transitiveCoercer = new SequentialFunctionExpression( new LinkedList<Token>(), parts, this.getModel()); newCoercers.put(targetEntry.getKey(), transitiveCoercer); }
java return this.coercers.containsKey(source) && this.coercers.get(source).containsKey(target);
java return this.coercers.get(source).get(target); Creates and adds the transitive closure for the coercers.
Constructor for new empty {@link CoercerHierarchy}.
Adds the coercer with the given {@link Type} source and given * {@link Type} target to this hierarchy. * * @param source * @param target * @param coercer
Adds all coercers to this hierarchy, that are defined in the * {@link TypeOrder} contained in the given {@link Type}. * * @param type
Returns a read-only {@link Map} of all type-indexed coercers for the * given source {@code type}. * * @param type * @return
Returns true, iff this hierarchy contains an coercer from the given * source to the given target. * * @param source * @param target * @return
Returns the coercer from the given {@link Type} source to the given * {@link Type} target. * * @param source * @param target * @return
* Adds all coercers to this hierarchy from all the given types by calling * the {@link addCoercersFromType} method. * * @param types
Creates and adds an derived, transitive, coercer between the source and * the target of the target. * * @param newCoercers * @param source * @param target
Represents the Function thats defined by a Constructor.
java super(tokens, parts, belongsToModel);
java this(new LinkedList<Token>(), parts, belongsToModel);
java visitor.handleConstructorFunctionExpression(this);
java return visitor.handleConstructorFunctionExpression(this);
java final List<TypeExpression> parts = new LinkedList<TypeExpression>(); for (final FunctionExpression function : this.getParts()) { final TypeExpression currentCoDomain = function .getCoDomain(domainContext); parts.add(currentCoDomain); } return new ConstructorTypeExpression(new LinkedList<Token>(), parts, this.getModel()).concretize(false); java return Symbols.CONSTRUCTOR_END_SYMBOL;
A type expression that represents an Constructor.
java this(tokens, new LinkedList<TypeExpression>(), belongsToModel);
java this(new LinkedList<TypeExpression>(), belongsToModel);
java this(new LinkedList<Token>(), parts, belongsToModel);
java super(tokens, new LinkedList<TypeExpression>(parts), belongsToModel); java return Symbols.CONSTRUCTOR_END_SYMBOL; java return Symbols.CONSTRUCTOR_START_SYMBOL;
java assert visitor != null; visitor.handle(this);
java if (this.size() == 0) { return this; } final SumTypeExpression result = new SumTypeExpression(this.getModel()); final TypeExpression firstAsConcrete = this.iterator().next().concretize(includeAbstractTypes); final ConstructorTypeExpression rest = this.copy(); final Iterator<TypeExpression> firstInRestRemover = rest.iterator(); firstInRestRemover.next(); firstInRestRemover.remove(); final TypeExpression restAsConcrete = rest.concretize(includeAbstractTypes); firstAsConcrete.accept(new TypeExpressionVisitor() { @Override public void handle(final SumOfAllNaryProducts visitee) { this.firstInVariant(visitee, restAsConcrete); } @Override public void handle(final SumOfAllTypesExpression visitee) { this.firstInVariant(visitee, restAsConcrete); } @Override public void handle(final NamedTypeReference visitee) { this.firstInVariant(visitee, restAsConcrete); } @Override public void handle(final FunctionTypeExpression visitee) { this.firstInVariant(visitee, restAsConcrete); } @Override public void handle(final ConstructorTypeExpression visitee) { this.firstInVariant(visitee, restAsConcrete); } @Override public void handle(final SumTypeExpression visitee) { for (final TypeExpression summand : visitee) { this.firstInVariant(summand, restAsConcrete); } } private void firstInVariant(final TypeExpression first, final TypeExpression rest) { rest.accept(new TypeExpressionVisitor() { @Override public void handle(final SumOfAllNaryProducts visitee) { this.createPair(visitee); } @Override public void handle(final SumOfAllTypesExpression visitee) { this.createPair(visitee); } @Override public void handle(final NamedTypeReference visitee) { this.createPair(visitee); } @Override public void handle(final FunctionTypeExpression visitee) { this.createPair(visitee); } @Override public void handle(final ConstructorTypeExpression constructor) { result.addElement(constructor.addAsFirstElementInCopy(first)); } @Override public void handle(final SumTypeExpression visitee) { for (final TypeExpression summand : visitee) { firstInVariant(first, summand); } } private void createPair(final TypeExpression visitee) { final LinkedList<TypeExpression> parts = new LinkedList<TypeExpression>(); parts.add(first); parts.add(visitee); final ConstructorTypeExpression pair = new ConstructorTypeExpression(parts, ConstructorTypeExpression.this.getModel()); result.addElement(pair); } }); } }); return result.getSize() == 1 ? result.iterator().next() : result;
java final LinkedList<TypeExpression> parts = new LinkedList<TypeExpression>(); if (!first.isEmptyProduct()) { parts.add(first); } for (final TypeExpression typeExpression : this) { if (!typeExpression.isEmptyProduct()) { parts.add(typeExpression); } } return new ConstructorTypeExpression(parts, this.getModel());
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final ConstructorTypeExpression that = (ConstructorTypeExpression) obj; //ML Shall be redesigned into head-controlled loop!!! if (this.size() != that.size()) { return false; } if (this.isEmpty()) { return true; } final Iterator<TypeExpression> thisElementIterator = this.iterator(); assert thisElementIterator != null; final Iterator<TypeExpression> thatElementIterator = that.iterator(); assert thatElementIterator != null; do { final TypeExpression thisElement = thisElementIterator.next(); assert thisElement != null; final TypeExpression thatElement = thatElementIterator.next(); assert thatElement != null; if (!thisElement.equals(thatElement)) { return false; } } while (thisElementIterator.hasNext()); return true; java final int prime = 31; int result = 1; for (final TypeExpression element : this) { assert element != null; result = prime * result + element.hashCode(); } return result;
java assert subType != null; /** * Visitor for Checking Constructor super type. */ class IsConstructorTypeSuperTypeOfVisitor implements TypeExpressionVisitor { private boolean result = true; @Override public void handle(final SumTypeExpression visitee) { for (final TypeExpression typeExpression : visitee) { if (!ConstructorTypeExpression.this.isSuperTypeOf(typeExpression)) { this.result = false; break; } } } @Override public void handle(final ConstructorTypeExpression visitee) { if (visitee.getSize() == ConstructorTypeExpression.this.getSize()) { final Iterator<TypeExpression> me = ConstructorTypeExpression.this.iterator(); final Iterator<TypeExpression> you = visitee.iterator(); while (me.hasNext()) { final TypeExpression currentMe = me.next(); final TypeExpression currentYou = you.next(); if (!currentMe.isSuperTypeOf(currentYou)) { this.result = false; break; } } } else { this.result = false; } } @Override public void handle(final FunctionTypeExpression visitee) { //TODO ML FunctionTypeExpression in Type Checker } @Override public void handle(final NamedTypeReference visitee) { this.result = false; } @Override public void handle(final SumOfAllTypesExpression visitee) { this.result = false; } @Override public void handle(final SumOfAllNaryProducts visitee) { this.result = false; } } final IsConstructorTypeSuperTypeOfVisitor visitor = new IsConstructorTypeSuperTypeOfVisitor(); subType.accept(visitor); return visitor.result; java final LinkedList<TypeExpression> partsCopy = new LinkedList<TypeExpression>(); for (final TypeExpression typeExpression : this) { partsCopy.add(typeExpression); } return new ConstructorTypeExpression(this.getTokens(), partsCopy, this.getModel()); java return this.isEmpty();
Represents a model that contains evaluable {@link FunctionExpression} and another model, that functions as a typing model.
java super(); this.typeModel = typeModel; this.evaluableFunctions = new ArrayList<FunctionExpression>(); java return this.typeModel.hashCode(); java return this.typeModel.getFunctions();
java return this.typeModel.getFunctions(name);
java return this.typeModel.getOperation(name); java return this.typeModel.getTypes();
java return this.typeModel.getType(typeName); java return this.typeModel.print(); java return this.typeModel.getCoercerHierarchy();
java visitor.handle(this);
java this.evaluableFunctions.addAll(evaluationExpression);
Creates a new evaluable model.
Adds all expressions to the model.
Represents the morphism to the final object. * *
java super(tokens, belongsToModel); java return Symbols.FINAL_SYMBOL;
java visitor.handleFinalMap(this);
java return visitor.handleFinalMap(this); java return new SumOfAllTypesExpression(this.getModel()); java return this.print();
Creates new finalMap with start and endPosition. * * @param startPosition * @param endPosition
Representation for an function that has an type and method.
java super(tokens, name); assert type != null; this.type = type; assert method != null; this.method = method; java return this.method;
java assert visitor != null; visitor.handleFunction(this); java return Symbols.FUNCTION_SYMBOL + Symbols.STANDARD_WHITE_SPACE + this.getName() + Symbols.STANDARD_WHITE_SPACE + this.getType().print() + Symbols.DEFINE_BY_SYMBOL + "\n" + this.getMethod().print() + Symbols.SELECTION_END_SYMBOL + "\n"; java return this.getName() + this.getType() + Symbols.DEFINE_BY_SYMBOL + this.getMethod(); java final int prime = 31; int result = 1; final String name = this.getName(); assert name != null; result = prime * result + name.hashCode(); assert this.method != null; result = prime * result + this.method.hashCode(); assert this.type != null; result = prime * result + this.type.hashCode(); return result;
java if (this == obj) { return true; } assert obj != null; if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } final Function that = (Function) obj; final String thisName = this.getName(); assert thisName != null; final String thatName = that.getName(); assert thatName != null; if (!thisName.equals(thatName)) { return false; } assert this.method != null; assert that.method != null; if (!this.method.equals(that.method)) { return false; } assert this.type != null; assert that.type != null; if (!this.type.equals(that.type)) { return false; } return true; java return this.getType().getDomainType();
java return this.getType().getCoDomainType(); Returns the method for this function. * * @return
Creates an new Function. * * @param name * Name of this function. * @param type * The type of this function. * @param method * The method for this function.
A comparator to compare {@link Function}s. @author Stefan K. Christian
java assert left != null; assert right != null; if (!left.getName().equals(right.getName())) { return left.getName().compareTo(right.getName()); } return this.methodComparator.compare(left, right);
Abstract type for all FunctionExpressions with start and endPosition.
java super(belongsToModel); this.tokens = tokens; Returns a String representation of this functionExpression. * * @return
Creates new {@link FunctionExpression} with given start- and endPosition. * * @param startPosition * @param endPosition
Accepts a {@link FunctionExpressionVisitor}.
A comparator to compare {@link Function} methods. @author Stefan K. Christian
java assert left != null; assert right != null; assert left.getName().equals(right.getName()); assert left.getType() != null; assert left.getType().getDomainType() != null; final TypeExpression leftDomainType = left.getType().getDomainType(); assert leftDomainType != null; assert right.getType() != null; assert right.getType().getDomainType() != null; final TypeExpression rightDomainType = right.getType().getDomainType(); assert rightDomainType != null; final boolean isSuperType = leftDomainType.isSuperTypeOf(rightDomainType, true); final boolean isSubType = rightDomainType.isSuperTypeOf(leftDomainType, true); if (isSuperType && isSubType) { return 0; } if (isSuperType) { return -1; } return 1;
Common interface for Function and FunctionExpressions. Returns the {@link TypeExpression} that represents the domain of this * {@link FunctionExpression}. * * @return
Representation of an functionType that has an domain and coDomain.
java super(tokens, belongsToModel); this.domainType = domainType; this.coDomainType = coDomainType; java return this.coDomainType; java return Symbols.FUNCTION_TYPE_START_SYMBOL + this.getDomainType().print() + Symbols.ARROW_SYMBOL + this.getCoDomainType().print() + Symbols.FUNCTION_TYPE_END_SYMBOL;
java visitor.handle(this);
java return this;
java return this.equals(subType); java final int prime = 31; int result = 1; assert this.domainType != null; result = prime * result + this.domainType.hashCode(); assert this.coDomainType != null; result = prime * result + this.coDomainType.hashCode(); return result;
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final FunctionTypeExpression that = (FunctionTypeExpression) obj; assert this.domainType != null; assert that.domainType != null; if (!this.domainType.equals(that.domainType)) { return false; } assert this.coDomainType != null; assert that.coDomainType != null; if (!this.coDomainType.equals(that.coDomainType)) { return false; } return true; Returns the coDomain of this {@link FunctionTypeExpression}. * * @return
Creates new {@link FunctionTypeExpression} with given start and * endPositions and given domain and coDomain. * * @param startPosition * @param endPosition * @param domainType * @param coDomainType
Represents generalization of types. *
java super(tokens, typeName, coercer); java return Symbols.GENERALIZES_SYMBOL;
java visitor.handle(this);
Identity function.
java super(tokens, belongsToModel); java return Symbols.IDENTITY_SYMBOL;
java visitor.handleIdentity(this);
java return visitor.handleIdentity(this); java return new SumOfAllTypesExpression(this.getModel());
Constructs new Identity function within the given start- and endPosition. * * @param startPosition * @param endPosition
FunctionExpression that consists of a list of FunctionExpressions.
java super(tokens, belongsToModel); this.parts = parts; java return this.parts.size(); java return this.parts.iterator(); java return this.printStartSymbol() + this.printParts() + this.printEndSymbol(); java final StringBuilder result = new StringBuilder(); final Iterator<FunctionExpression> partsIterator = this.iterator(); while (partsIterator.hasNext()) { result.append(partsIterator.next().print()); result.append(partsIterator.hasNext() ? this.getSeperatorSymbol() : ""); } return result.toString(); java final int prime = 31; int result = 1; for (final FunctionExpression part : this.parts) { assert part != null; result = prime * result + part.hashCode(); } return result;
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final ListFunctionExpression that = (ListFunctionExpression) obj; assert this.parts != null; assert that.parts != null; if (this.parts.size() != that.parts.size()) { return false; } if (this.parts.isEmpty()) { return true; } final Iterator<FunctionExpression> thisPartIterator = this.parts.iterator(); assert thisPartIterator != null; final Iterator<FunctionExpression> thatPartIterator = that.parts.iterator(); assert thatPartIterator != null; do { final FunctionExpression thisPart = thisPartIterator.next(); assert thisPart != null; final FunctionExpression thatPart = thatPartIterator.next(); assert thatPart != null; if (!thisPart.equals(thatPart)) { return false; } } while (thisPartIterator.hasNext()); return true; Returns the count of the {@link FunctionExpression}-parts. Returns the end-Symbol representing the end of this * ListFunctionExpression. * * @return Returns the seperatorSymbol between the parts of this * ListFunctionExpression. Returns the start-Symbol representing the start of this * ListFunctionExpression.
Constructor for new ListFunctionExpression with given start- and * endPosition and parts.
An abstract type expression that consists of a list of {@link TypeExpression} .
java super(tokens, belongsToModel); assert parts != null; this.parts = parts; java return this.parts.iterator(); java return this.parts.size(); java return this.printStartSymbol() + this.printParts() + this.printEndSymbol(); java final StringBuilder result = new StringBuilder(); final Iterator<TypeExpression> partIterator = this.iterator(); while (partIterator.hasNext()) { result.append(partIterator.next().print()); result.append(partIterator.hasNext() ? Symbols.SEPARATOR_SYMBOL : ""); } return result.toString(); java return this.parts.size();
java assert element != null; this.parts.add(element); java return this.parts.isEmpty();
java assert element != null; return this.parts.contains(element);
java assert elements != null; return this.parts.containsAll(elements); Creates a copy. Returns the part-{@link TypeExpression}-count. Returns the endSymbol of this expression. * * @return Returns the startSymbol of this expression. * * @return Returns the size of the List. Returns <code>true</code> iff <code>this.size() == 0</code>. Otherwise * <code>false</code>. Adds a new {@link TypeExpression} to the {@link ListTypeExpression}.
Returns <code>true</code> iff the {@link ListTypeExpression} contains the * {@link TypeExpression}.
Creates new {@link ListTypeExpression} with the given start and * endPositiona and parts. * * @param startPosition * @param endPosition * @param parts
Returns <code>true</code> iff the {@link ListTypeExpression} contains all * of the {@link TypeExpression}s.
Class representig the Model. java this.types = new HashMap<String, Type>(); this.coercerHierarchy = new CoercerHierarchy(this); this.operationsByName = new HashMap<String, Operation>();
java section.accept(new TypeOrFunctionVisitor() { @Override public void handleFunction(final Function function) { Model.this.addFunction(function); } @Override public void handleType(final Type type) { Model.this.addType(type); } });
java if (this.types.containsKey(type.getName())) { this.addError(new NameConflictError(type)); this.addError(new NameConflictError(this.types.get(type.getName()))); } else { this.types.put(type.getName(), type); }
java assert function != null; final String functionName = function.getName(); assert functionName != null; assert !functionName.isEmpty(); Operation operation = this.operationsByName.get(functionName); if (operation == null) { operation = new Operation(functionName); this.operationsByName.put(functionName, operation); } operation.addFunction(function); java final Set<List<Function>> functions = new HashSet<List<Function>>(); for (final Entry<String, Operation> operationByName : this.operationsByName.entrySet()) { assert operationByName != null; final Operation operation = operationByName.getValue(); assert operation != null; functions.add(new ArrayList<Function>(operation.getFunctions())); } return functions;
java assert name != null; assert !name.isEmpty(); final Operation operation = this.operationsByName.get(name); if (operation != null) { return new ArrayList<Function>(operation.getFunctions()); } return Collections.emptyList();
java assert name != null; assert !name.isEmpty(); return this.operationsByName.get(name);
java return this.types.get(typeName); java final StringBuilder result = new StringBuilder(); for (final TypeOrFunction current : this.getSections()) { result.append("\n" + current.print()); } return result.toString(); java final Set<TypeOrFunction> result = new TreeSet<TypeOrFunction>(); for (final TypeOrFunction current : this.types.values()) { result.add(current); } for (final List<Function> current : this.getFunctions()) { for (final Function currentFunction : current) { result.add(currentFunction); } } return result;
java visitor.handle(this);
Constructor.
Interface for classes that contain a model reference. Returns the {@link Model} to that <code>this</code> {@link AbstractModelContainable} belongs.
Interface for visitor pattern.
Reference to a function with given name.
java super(tokens, belongsToModel); this.name = name; this.refersTo = new ArrayList<Function>(); this.bindindBuilder = new BindingBuilder(this.refersTo, this);
java this(new LinkedList<Token>(), name, belongsToModel); java return this.name; java return this.getName(); java return !this.refersTo.isEmpty(); java return this.refersTo;
java this.refersTo.clear(); this.refersTo.addAll(refersTo);
java visitor.handleNamedFunctionReference(this);
java return visitor.handleNamedFunctionReference(this); java return this.bindindBuilder.getDomain();
java return this.bindindBuilder.getCoDomain(domainContext); Returns true iff there is at least one method {@link Function} in * refersTo. Returns the list of {@link Function} this Reference is referring to.
Creates a new Reference for Function with given name without syntactical position.
Creates a new Reference for Function with given name.
Sets the list of {@link Function} this Reference is referring to.
Reference to the type with the given name. * @author Sönke
java super(tokens, belongsToModel); assert name != null; assert !name.isEmpty(); this.name = name;
java super(new LinkedList<Token>(), belongsToModel); assert name != null; assert !name.isEmpty(); this.name = name; java return this.getName(); java return this.refersTo != null; java return this.refersTo;
java assert refersTo != null; this.refersTo = refersTo;
java assert visitor != null; visitor.handle(this);
java final SumTypeExpression sum = new SumTypeExpression(new LinkedList<Token>(), this.getModel()); if (this.refersTo != null) { for (final Type type : this.refersTo.getSubTypes()) { if (includeAbstractTypes || !type.isAbstract()) { final NamedTypeReference newElement = new NamedTypeReference(new LinkedList<Token>(), type.getName(), this.getModel()); newElement.setRefersTo(type); sum.addElement(newElement); } } } return sum.size() == 1 ? sum.iterator().next() : sum; java assert this.name != null; assert !this.name.isEmpty(); return this.name.hashCode();
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final NamedTypeReference that = (NamedTypeReference) obj; assert this.name != null; assert that.name != null; return this.name.equals(that.name);
java class IsNamedTypeSuperTypeOfVisitor implements TypeExpressionVisitor { private boolean result = true; @Override public void handle(SumTypeExpression visitee) { for (TypeExpression typeExpression : visitee) { if (!NamedTypeReference.this.isSuperTypeOf(typeExpression)) { result = false; break; } } } @Override public void handle(ConstructorTypeExpression visitee) { if (visitee.getSize() == 1) { result = NamedTypeReference.this.isSuperTypeOf(visitee.getParts().iterator().next()); } else { result = false; } } @Override public void handle(FunctionTypeExpression visitee) { //TODO FunctionType } @Override public void handle(NamedTypeReference visitee) { result = NamedTypeReference.this.refersTo.getSubTypes().contains(visitee.refersTo); } @Override public void handle(SumOfAllTypesExpression visitee) { result = false; } @Override public void handle(SumOfAllNaryProducts visitee) { result = false; } } final IsNamedTypeSuperTypeOfVisitor visitor = new IsNamedTypeSuperTypeOfVisitor(); subType.accept(visitor); return visitor.result; Returns true iff the type is set, this reference is referring to. * * @return Returns the {@link Type} this refernece is referring to. * * @return
Creates new Reference to the type with given name. * * @param startPosition * @param endPosition * @param name
Sets the {@link Type} this reference is referring to. * * @param refersTo
Creates new Reference to the type with given name. * * @param startPosition * @param endPosition * @param name
The {@link Operation} associates a given set of {@link Function}s with all of their domains possible concrete sub-types. This is done in a way that guarantees a concrete {@link TypeExpression} to be associated with its most specialized {@link Function} counterpart. In case of two {@link Function}s being incomparable on their domains, there will be an attempt to establish an order using their co-domains.
java assert name != null; this.name = name;
java assert name != null; this.name = name; assert functions != null; this.setFunctions(functions); java return this.state.size();
java assert functions != null; this.state.setFunctions(functions);
java assert functions != null; this.state.addFunctions(functions);
java assert function != null; assert function.getName().equals(this.name); this.state.setFunction(function);
java assert function != null; assert function.getName().equals(this.name); this.state.addFunction(function); java return Collections.unmodifiableSet(this.internalFunctions);
java assert type != null; return this.state.getFunction(type);
java assert function != null; assert type != null; assert subTypes != null; assert functionsByConcreteType != null; assert concreteTypesByFunction != null; assert associatedConcreteTypesByFunction != null; concreteTypesByFunction.put(function, subTypes); /* * Create remaining concrete sub-types set from the original sub-types * set provide */ final Deque<TypeExpression> remainingConcreteSubTypes = new LinkedList<TypeExpression>(subTypes); final Set<TypeExpression> typesToSkip = new HashSet<TypeExpression>(); final Set<TypeExpression> associatedConcreteTypes = new HashSet<TypeExpression>(); // Repeat until there are no more sub-types remaining do { final TypeExpression currentConcreteSubType = remainingConcreteSubTypes.poll(); assert currentConcreteSubType != null; /* * Check whether the current concrete type is marked for skip; if * so, just skip it. */ if (typesToSkip.contains(currentConcreteSubType)) { typesToSkip.remove(currentConcreteSubType); continue; } /* * Get the current known functions associated with the current * concrete sub-type */ SortedSet<Function> concreteSubTypeAssociatedFunctions = functionsByConcreteType.get(currentConcreteSubType); /* * Check whether the function is the first function that gets * associated with the current concrete type */ if (concreteSubTypeAssociatedFunctions == null) { /* * Create a new sorted set to hold associated functions; * additional functions will be sorted by their co-domain */ concreteSubTypeAssociatedFunctions = new TreeSet<Function>(new DomainCoDomainComparator()); concreteSubTypeAssociatedFunctions.add(function); /* * Set the new map containing the first function as the concrete * sub-types associations */ functionsByConcreteType.put(currentConcreteSubType, concreteSubTypeAssociatedFunctions); /* * Remember the current concrete sub-type to be associated with * the function */ associatedConcreteTypes.add(currentConcreteSubType); continue; } /* * Prepare for iteration over the existing functions associated with * the concrete type */ final Iterator<Function> concreteSubTypeAssociatedFunctionIterator = concreteSubTypeAssociatedFunctions.iterator(); // Iterate through the previously associated functions while (concreteSubTypeAssociatedFunctionIterator.hasNext()) { final Function otherFunction = concreteSubTypeAssociatedFunctionIterator.next(); assert otherFunction.getType() != null; assert otherFunction.getType().getDomainType() != null; final TypeExpression otherDomainType = otherFunction.getType().getDomainType(); /* * Check whether the functions domain is either a super type, * sub type, or non-comparable type to the current other * functions domain */ if (type.isSuperTypeOf(otherDomainType, true)) { final Set<TypeExpression> otherConcreteSubTypes = concreteTypesByFunction.get(otherFunction); assert otherConcreteSubTypes != null; assert !otherConcreteSubTypes.isEmpty(); /* * The functions domain is a super-type to the current other * functions domain; therefore it is a super-type to all * other concrete types that the other function might be * associated with; a check of those types would be a waste * of time */ typesToSkip.addAll(otherConcreteSubTypes); } else { boolean otherHasDomainSuperType = false; if (otherDomainType.isSuperTypeOf(type, true)) { otherHasDomainSuperType = true; /* * The current function is more concrete than a function * within mapping for the current concrete type; * therefore remove the other function from the types * mapping */ concreteSubTypeAssociatedFunctionIterator.remove(); } /* * Add the current concrete type to the types that the * current function is associated with */ associatedConcreteTypes.add(currentConcreteSubType); /* * Retrieve the other functions associated types as a basis * for an intersection with the current functions concrete * domain sub types */ final Set<TypeExpression> intersectingConcreteTypes = new HashSet<TypeExpression>(associatedConcreteTypesByFunction.get(otherFunction)); /* * Remember the other functions number of associated * concrete types for later comparison */ final int otherNumberOfAssociatedConcreteTypes = intersectingConcreteTypes.size(); /* * Intersect the other functions associated set of concrete * types with the set of concrete sub types of the current * functions domain; as it is known that this function is * more concrete for this type, this function is also more * concrete for all types found within the functions sub * types that are also part of the other functions * associated types set */ intersectingConcreteTypes.retainAll(subTypes); /* * Remember all intersecting types now being associated with * the new function */ associatedConcreteTypes.addAll(intersectingConcreteTypes); /* * Types of the intersection can be added/substituted in a * bulk operation; therefore mark those types for removal */ typesToSkip.addAll(intersectingConcreteTypes); if (!otherHasDomainSuperType) { for (final TypeExpression concreteType : intersectingConcreteTypes) { final SortedSet<Function> functions = functionsByConcreteType.get(concreteType); // Add the new function functions.add(function); } continue; } for (final TypeExpression concreteType : intersectingConcreteTypes) { final SortedSet<Function> currentConcreteTypeAssociatedFunctions = functionsByConcreteType.get(concreteType); /* * Remove the old function first; this is important as * comparison is done on co-domain and both functions * could have the same co-domain while the new function * is more concrete in terms of its domain being a * sub-type of the old functions domain */ currentConcreteTypeAssociatedFunctions.remove(otherFunction); // Substitute the new function currentConcreteTypeAssociatedFunctions.add(function); } /* * Check whether the other function has no associations * left; if there are still some associations left, just * remove the current intersection; if there are no * associations left, remove the function completely */ if (intersectingConcreteTypes.size() != otherNumberOfAssociatedConcreteTypes) { associatedConcreteTypesByFunction.get(otherFunction).removeAll( intersectingConcreteTypes); } else { associatedConcreteTypesByFunction.remove(otherFunction); } } } functionsByConcreteType.put(currentConcreteSubType, concreteSubTypeAssociatedFunctions); } while (!remainingConcreteSubTypes.isEmpty()); // Remember the functions associations if any if (associatedConcreteTypes.size() > 0) { associatedConcreteTypesByFunction.put(function, associatedConcreteTypes); }
Constructor that takes a function name as its only parameter. All added * functions will be assumed to be {@link Function}s under the defined name. * * @param name
Gets the size of the {@link Operation}. * * @return The size of the {@link Operation} Gets all functions that are currently part of this operation. * * @return All functions that are currently part of this operation Sets the {@link Function} to create the {@link Operation} from. * * @param function
Adds/introduces a {@link Function} to the existing {@link Operation}. * * @param function
Gets the {@link Function} that is associated with the given * {@link TypeExpression}. * * @param type * The {@link TypeExpression} that a {@link Function} is searched * for. * @return
Constructor that takes a function name and a {@code Set} of * {@link Function}s. All added functions will be assumed to be * {@link Function}s under the defined name. * * @param name * @param functions
Sets the {@link Function}s to create the {@link Operation} from. * * @param functions
Adds/introduces {@link Function}s to the existing {@link Operation}. * * @param functions
Introduces new {@link Function}s to the {@link Operation}. * * @param function * The {@link Function} to be introduced to the {@link Operation} * @param type * The concretized domain of the {@link Function} * @param subTypes * The {@code Set} of sub-types that are the result of the * concretized
A comparator to compare {@link Function}s co-domains.
java assert left != null; assert right != null; assert left.getName().equals(right.getName()); assert left.getType() != null; assert left.getType().getCoDomainType() != null; final TypeExpression leftCoDomainType = left.getType().getCoDomainType(); assert leftCoDomainType != null; assert right.getType() != null; assert right.getType().getCoDomainType() != null; final TypeExpression rightCoDomainType = right.getType().getCoDomainType(); assert rightCoDomainType != null; final boolean isCoDomainSuperType = leftCoDomainType.isSuperTypeOf(rightCoDomainType, true); final boolean isCoDomainSubType = rightCoDomainType.isSuperTypeOf(leftCoDomainType, true); // Check whether both co-domains are equal if (isCoDomainSuperType && isCoDomainSubType) { return 0; } // Check whether the left co-domain is a super-type of the right one if (isCoDomainSuperType) { return 1; } // Check whether the left co-domain is a sub-type of the right one if (isCoDomainSubType) { return -1; } /* * At this point there is no other criteria to generate an order of * the two functions; therefore both functions may be assumed to be * equal */ return 0;
The {@link Operation}s abstract internal {@link State}.
The {@link Operation}s {@link CachedState}. java return Operation.this.internalFunctionsByConcreteType.size();
java Operation.this.state = new UncachedState(); Operation.this.state.setFunctions(functions);
java Operation.this.state = new UncachedState(); Operation.this.state.addFunctions(functions);
java Operation.this.state = new UncachedState(); Operation.this.state.setFunction(function);
java Operation.this.state = new UncachedState(); Operation.this.state.addFunction(function);
java assert type != null; final SortedSet<Function> functions = Operation.this.internalFunctionsByConcreteType.get(type); if (functions != null) { return functions.first(); } return null;
The {@link Operation}s {@link UncachedState}. java this.calculateFunctionAssociations(); Operation.this.state = new CachedState(); return Operation.this.state.size();
java assert functions != null; Operation.this.internalFunctions.clear(); this.addFunctions(functions);
java assert functions != null; for (final Function function : functions) { assert function != null; this.addFunction(function); }
java assert function != null; Operation.this.internalFunctions.clear(); this.addFunction(function);
java assert function != null; assert function.getName().equals(Operation.this.name); Operation.this.internalFunctions.add(function);
java assert type != null; this.calculateFunctionAssociations(); Operation.this.state = new CachedState(); return Operation.this.state.getFunction(type); java final ConcretizedTypeToSetOfSubTypesConverter converter = new ConcretizedTypeToSetOfSubTypesConverter(); Operation.this.internalFunctionsByConcreteType.clear(); final Map<Function, Set<TypeExpression>> concreteTypesByFunction = new HashMap<Function, Set<TypeExpression>>(); final Map<Function, Set<TypeExpression>> associatedConcreteTypesByFunction = new HashMap<Function, Set<TypeExpression>>(); for (final Function function : Operation.this.internalFunctions) { assert function != null; assert function.getType() != null; assert function.getType().getDomainType() != null; final TypeExpression concretizedDomain = function.getType().getDomainType().concretize(false); Operation.calculateFunctionAssociations(function, concretizedDomain, converter.convert(concretizedDomain), Operation.this.internalFunctionsByConcreteType, concreteTypesByFunction, associatedConcreteTypesByFunction); }
Representation of an product function i.e. <f,g>.
java super(tokens, parts, belongsToModel); java return Symbols.PARALLEL_END_SYMBOL; java return Symbols.PARALLEL_START_SYMBOL; java return Symbols.SEPARATOR_SYMBOL;
java visitor.handleProductFunctionExpression(this);
java return visitor.handleProductFunctionExpression(this); java final int prime = 31; int result = 1; final List<FunctionExpression> parts = this.getParts(); assert parts != null; for (final FunctionExpression part : parts) { assert part != null; result = prime * result + part.hashCode(); } return result;
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final ProductFunctionExpression that = (ProductFunctionExpression) obj; final List<FunctionExpression> thisParts = this.getParts(); final List<FunctionExpression> thatParts = that.getParts(); assert thisParts != null; assert thatParts != null; if (thisParts.size() != thatParts.size()) { return false; } if (thisParts.isEmpty()) { return true; } final Iterator<FunctionExpression> thisPartIterator = thisParts .iterator(); assert thisPartIterator != null; final Iterator<FunctionExpression> thatPartIterator = thatParts .iterator(); assert thatPartIterator != null; do { final FunctionExpression thisPart = thisPartIterator.next(); assert thisPart != null; final FunctionExpression thatPart = thatPartIterator.next(); assert thatPart != null; if (!thisPart.equals(thatPart)) { return false; } } while (thisPartIterator.hasNext()); return true; java final List<TypeExpression> domain = new LinkedList<TypeExpression>(); for (final FunctionExpression part : this.getParts()) { domain.add(part.getDomain()); } final ConstructorTypeExpression domainType = new ConstructorTypeExpression( new LinkedList<Token>(), domain, this.getModel()); return domainType.concretize(false);
java final List<TypeExpression> parts = new LinkedList<TypeExpression>(); int offset = 0; Projection projection; for (final FunctionExpression part : this.getParts()) { projection = new Projection(new LinkedList<Token>(), offset, this.getModel()); parts.add(part.getCoDomain(projection.getCoDomain(domainContext))); offset++; } return new ConstructorTypeExpression(new LinkedList<Token>(), parts, this.getModel()) .concretize(false);
Creates new productFunctionExpression with the given start and endPosition * and parts. * * @param startPosition * @param endPosition * @param parts
Represents the application of an projection in a product with a given offset.
java super(tokens, offset, belongsToModel); java return Symbols.IDENTITY_SYMBOL + this.getOffset();
java visitor.handleProjection(this);
java return visitor.handleProjection(this); java final int prime = 31; int result = 1; result = prime * result + this.getOffset(); return result;
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final Projection other = (Projection) obj; if (this.getOffset() != other.getOffset()) { return false; } return true; java return new SumOfAllNaryProducts(new LinkedList<Token>(), this.getOffset() + 1, this.getModel()); java return this.print();
Creates a new Projection with the given start- and endPosition and * offset.
Expression representing an sequential function expression. ie. f.g
java super(tokens, parts, belongsToModel);
java visitor.handleSequentialFunctionExpression(this);
java return visitor.handleSequentialFunctionExpression(this);
java final Iterator<FunctionExpression> it = this.getParts().iterator(); assert it.hasNext(); FunctionExpression lastFunction = it.next(); TypeExpression lastCoDomain = domainContext; while (it.hasNext()) { lastCoDomain = lastFunction.getCoDomain(lastCoDomain); final FunctionExpression current = it.next(); final TypeExpression currentDomain = current.getDomain(); if (!currentDomain.isSuperTypeOf(lastCoDomain, false)) { final List<FunctionExpression> parts = new LinkedList<FunctionExpression>(); parts.add(lastFunction); parts.add(current); final Deque<Token> tokens = new LinkedList<Token>(); tokens.addAll(lastFunction.getTokens()); tokens.addAll(current.getTokens()); final SequentialFunctionExpression seq = new SequentialFunctionExpression( tokens, parts, this.getModel()); throw new SequenceDomainCodomainMissmatchException( "Domain/Codomain mismatch: " + lastFunction.print() + " provides " + lastCoDomain.print() + " :: " + current.print() + " needs " + currentDomain.print(), seq); } lastFunction = current; } return lastFunction.getCoDomain(lastCoDomain).concretize(false); java assert this.getParts().size() > 0; return this.getParts().get(0).getDomain().concretize(false); java return Symbols.STANDARD_WHITE_SPACE; java return ""; java return "";
Creates new {@link SequentialFunctionExpression} with the given start and * endPositions and the given parts. * * @param startPosition * @param endPosition * @param parts
Represents Specialization of types. @author Sönke *
java super(tokens, typeName, coercer); java return Symbols.SPECIALIZES_SYMBOL;
java visitor.handle(this);
Representation of an SumFunction with a list of parts.
java super(tokens, parts, belongsToModel); this.bindingBuilder = new BindingBuilder(parts, this);
java this(new LinkedList<Token>(), parts, belongsToModel);
java this(new LinkedList<FunctionExpression>(), belongsToModel); java return Symbols.CHOICE_END_SYMBOL; java return Symbols.CHOICE_START_SYMBOL; java return Symbols.SEPARATOR_SYMBOL;
java visitor.handleSumFunctionExpression(this);
java return visitor.handleSumFunctionExpression(this); java return this.bindingBuilder.getDomain();
java return this.bindingBuilder.getCoDomain(domainContext);
Creates an empty SumFunctionExpression with no position.
Creates an new SumFunctionExpression with the given start- and * endPosition and the given {@link FunctionExpression} parts.
Creates an new SumFunctionExpression with no position.
Anonymous type that represents the sum of all types that have at least n projections.
java super(tokens, belongsToModel); this.componentCount = componentCount; java return "SumOfAll" + this.componentCount + "-aryProducts";
java visitor.handle(this);
java return this;
java final CheckSuperTypeVisitor visitor = new CheckSuperTypeVisitor(); subType.accept(visitor); return visitor.getResult(); java final int prime = 31; int result = 1; result = prime * result + this.getComponentCount(); return result;
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final SumOfAllNaryProducts other = (SumOfAllNaryProducts) obj; if (this.getComponentCount() != other.getComponentCount()) { return false; } return true;
Creates new SumOfAllNaryProducts with the given tokens and the given * componentCount. * * @param tokens * @param componentCount
An Visitor that checks if this {@link SumOfAllNaryProducts} is * superTypeof the visited TypeExpression.
java for (final TypeExpression part : visitee.getParts()) { if (!SumOfAllNaryProducts.this.isSuperTypeOf(part)) { this.result = false; return; } } this.result = true;
java this.result = visitee.getParts().size() >= SumOfAllNaryProducts.this.componentCount;
java this.result = false;
java final Type type = visitee.refersTo(); if (type.isAbstract()) { final TypeExpression concretes = visitee.concretize(false); this.result = SumOfAllNaryProducts.this.isSuperTypeOf(concretes); } else { final TypeExpression definition = type.getType(); this.result = SumOfAllNaryProducts.this.isSuperTypeOf(definition); }
java this.result = false;
java this.result = visitee.getComponentCount() >= SumOfAllNaryProducts.this.componentCount;
The Type that represents the Sum of all Types available in this system.
java super(new LinkedList<Token>(), belongsToModel); java return "";
java visitor.handle(this);
java return this;
java return true; java final int prime = 31; int result = 1; result = prime * result + super.hashCode(); return result;
java if (this == obj) { return true; } assert obj != null; return this.getClass() == obj.getClass(); java return true;
TypeExpression representing an sum Type i.e. A + B.
java super(new LinkedList<Token>(), new LinkedHashSet<TypeExpression>(parts), belongsToModel);
java super(new LinkedList<Token>(), new LinkedHashSet<TypeExpression>(), belongsToModel);
java super(tokens, new LinkedHashSet<TypeExpression>(), belongsToModel);
java super(tokens, new LinkedHashSet<TypeExpression>(parts), belongsToModel); java return Symbols.CHOICE_END_SYMBOL; java return Symbols.CHOICE_START_SYMBOL;
java assert visitor != null; visitor.handle(this);
java if (this.isEmpty()) { return this; } final SumTypeExpression result = new SumTypeExpression(this.getModel()); for (final TypeExpression typeExpression : this) { typeExpression.concretize(includeAbstractTypes).accept(new AddToSumTypeExpressionVisitor(result)); } for (TypeExpression typeExpression : result) { if (typeExpression.isSumOfAllTypesExpression()) { return typeExpression; //ML20130814 } } return result.size() == 1 ? result.iterator().next() : result;
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final SumTypeExpression that = (SumTypeExpression) obj; //ML Shall be redesigned into head-controlled loop!!! if (this.size() != that.size()) { return false; } if (this.isEmpty()) { return true; } final Iterator<TypeExpression> thisElementIterator = this.iterator(); assert thisElementIterator != null; do { final TypeExpression thisElement = thisElementIterator.next(); assert thisElement != null; if (!that.contains(thisElement)) { return false; } } while (thisElementIterator.hasNext()); //ML20130816 Second iterator added! final Iterator<TypeExpression> thatElementIterator = that.iterator(); assert thatElementIterator != null; do { final TypeExpression thatElement = thatElementIterator.next(); assert thatElement != null; if (!this.contains(thatElement)) { return false; } } while (thisElementIterator.hasNext()); return true; java final int prime = 31; int result = 1; /* * In order to guarantee an order-independent hash code, the elements * need to be sorted for its calculation. Currently it is assumed that * the base set itself is sorted. */ for (final TypeExpression element : this) { assert element != null; result = prime * result + element.hashCode(); } return result;
java final IsSuperTypeOfTypeExpressionVisitor visitor = new IsSuperTypeOfTypeExpressionVisitor(this); subType.accept(visitor); return visitor.isSuperType(); java final LinkedHashSet<TypeExpression> partsCopy = new LinkedHashSet<TypeExpression>(); for (TypeExpression typeExpression : this) { partsCopy.add(typeExpression); } return new SumTypeExpression(this.getTokens(), partsCopy, this.getModel());
Creates a new empty {@link SumTypeExpression} with no position. * ML20130814
Creates a new {@link SumTypeExpression} with no position. * ML20130814
Creates a new empty {@link SumTypeExpression} with the position given by * the tokens.
Creates an new SumTypeExpression with the position given by the tokens * and the given {@link TypeExpression} parts.
Adds the {@link TypeExpression} to the given sum.
java this.sum = sum;
java for (final TypeExpression typeExpression : visitee) { this.sum.addElement(typeExpression); }
java this.handleOthers(visitee);
java this.handleOthers(visitee);
java this.handleOthers(visitee);
java this.sum.addElement(visitee);
java this.handleOthers(visitee);
java this.handleOthers(visitee);
Checks if an given {@link SumTypeExpression} includes the * {@link TypeExpression} or all Elements of another * {@link SumTypeExpression}.
java this.superType = superType; this.isSuperType = true;
java for (final TypeExpression typeExpression : visitee) { if (!this.superType.isSuperTypeOf(typeExpression)) { this.isSuperType = false; break; } }
java for (TypeExpression typeExpression : this.superType.getParts()) { if (typeExpression.isSuperTypeOf(visitee)) { return; } } this.isSuperType = false;
java this.isSuperType = this.superType.contains(visitee); java return this.isSuperType;
java this.isSuperType = false;
java this.isSuperType = false;
Class that represents a type in lomf2.
java super(tokens, name); this.type = type; this.hierarchies = hierarchies; this.subTypes = new HashSet<Type>();
java this(tokens, name, null, hierarchies); java return this.type == null; java return this.subTypes;
java this.subTypes.addAll(types); java return (this.isAbstract() ? Symbols.ABSTRACT_SYMBOL + Symbols.STANDARD_WHITE_SPACE : "") + Symbols.TYPE_SYMBOL + Symbols.STANDARD_WHITE_SPACE + this.getName() + (this.isAbstract() ? "" : this.getType().print()) + this.printHierarchies() + Symbols.SELECTION_END_SYMBOL + "\n"; java final StringBuilder result = new StringBuilder(); for (final TypeOrder current : this.hierarchies) { result.append(current.print()); } return result.toString(); java return this.getName();
java visitor.handleType(this); java final int prime = 31; int result = 1; final String name = this.getName(); assert name != null; result = prime * result + name.hashCode(); return result;
java if (this == obj) { return true; } assert obj != null; if (this.getClass() != obj.getClass()) { return false; } final TypeOrFunction that = (TypeOrFunction) obj; final String thisName = this.getName(); assert thisName != null; final String thatName = that.getName(); assert thatName != null; if (!thisName.equals(thatName)) { return false; } return true; Returns true iff this type is an abstract type, ie. the * {@link ListTypeExpression} attribute type is not set. Returns a {@link Set} of subtypes of <code>this</code> {@link Type}.
Constructor for an new concrete type with the given start- and * endPosition, name, type Hierarchy objects <hierarchies> and the given * {@link ListTypeExpression} type. * * @param startPosition * @param endPosition * @param name * @param type * @param hierarchies
Creates an new abstract Type with the given start- and endPosition, name * and {@link TypeOrder} hierarchies. * * @param startPosition * @param endPosition * @param name * @param hierarchies
Adds all elements of the assigned {@link Set} of subtypes ( * <code>subTypes</code>) to <code>this</code> {@link Set} of subtypes.
Abstract representation of all Expressions representing an type.
java super(belongsToModel); this.tokens = tokens;
java return this.concretize(includeAbstractTypes).isSuperTypeOf(subtype.concretize(includeAbstractTypes));
java return this.isSuperTypeOf(subType) && !subType.isSuperTypeOf(this); java return this.print(); java return false; java return false; Returns an well formated sourceCode of the represented type. Returns a new {@link TypeExpression} in a normalized format which * contains either only concrete Types (includeAbstractTypes == * <code>false</code>) or concrete and abstract Types (includeAbstractTypes * == <code>true</code>).
ML20130814. if includeAbstractTypes == <code>true</code> this function returns * <code>true</code> iff "subtype" is a member of the set of subtypes of * this {@link TypeExpression}; otherwise it returns <code>false</code>. * <p/> * <p/> * if includeAbstractTypes == <code>false</code> this function returns * <code>true</code> iff all concrete subtypes of "subtype" are subtypes of * this {@link TypeExpression}; otherwise it returns <code>false</code>.
Returns <code>true</code> iff the actual concrete {@link TypeExpression} * is an super type of the given subType.
ML20130815.
Creates an new TypeExpression with the given start- and endPosition. * * @param startPosition * @param endPosition
Entrypoint for {@link TypeExpressionVisitor}.
A comparator to compare {@link AnonymousType}s by their hash code. @author Stefan K. Christian
java assert left != null; assert right != null; final int leftHashCode = left.hashCode(); final int rightHashCode = right.hashCode(); return leftHashCode == rightHashCode ? 0 : leftHashCode < rightHashCode ? -1 : 1;
Supertype for types or functions. *
java this.tokens = tokens; this.name = name;
java assert other != null; int thisStart = 0; int otherStart = 0; if (!this.getTokens().isEmpty()) { thisStart = this.getTokens().getFirst().getPosition(); } if (!other.getTokens().isEmpty()) { otherStart = other.getTokens().getFirst().getPosition(); } return Integer.valueOf(thisStart).compareTo(otherStart); Returns well formated source-code representation of this object. * * @return Accept method for {@link TypeOrFunctionVisitor}-visitor. * * @param visitor
Creates a new TypeOrFunction Object with the given start- and endPosition * and name Attributes. * * @param startPosition * @param endPosition * @param name
Visitor interface for {@link TypeOrFunction} Hierarchy. @author Sönke *
Representation for a ConstructorFunctionExpression with given {@link Type} informations.
java super(tokens, parts, belongsToModel); this.refersTo = refersTo; java return Symbols.CONSTRUCTOR_END_SYMBOL + Symbols.TYPE_DELIMITER + this.refersTo.getName(); java return this.refersTo;
java visitor.handleTypedConstructorFunctionExpression(this);
java return visitor.handleTypedConstructorFunctionExpression(this); java final int prime = 31; int result = 1; result = prime * result + super.hashCode(); result = prime * result + this.refersTo.hashCode(); return result;
java if (this == obj) { return true; } assert obj != null; if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } final TypedConstructorFunctionExpression that = (TypedConstructorFunctionExpression) obj; if (!this.refersTo.equals(that.refersTo)) { return false; } return true;
java final NamedTypeReference type = new NamedTypeReference(this.refersTo().getName(), this.getModel()); type.setRefersTo(this.refersTo()); return type; Returns the refersTo attribute.
Constructs a new {@link TypedConstructorFunctionExpression} with given * start- and endPosition, parts and a {@link Type} which it refers to.
Morphism to final object with given domain.
java super(tokens, belongsToModel); this.typeName = typeName; java return Symbols.TYPED_FINAL_SYMBOL + this.getTypeName(); java return this.typeName != null; java return this.refersTo;
java this.refersTo = refersTo;
java visitor.handleTypedFinalMap(this);
java return visitor.handleTypedFinalMap(this); java final NamedTypeReference type = new NamedTypeReference(this.refersTo().getName(), this.getModel()); type.setRefersTo(this.refersTo()); return type; Returns true if the typeName is set. * * @return Returns the attribute referesTo. * * @return Sets the attribute refersTo. * * @param refersTo
Creates new FinalTypedMap with given start and endPosition and the given * typeName as domain. * * @param startPosition * @param endPosition * @param typeName
Identity function with given {@link Type} for the domain.
java super(tokens, belongsToModel); this.typeName = typeName; java return Symbols.TYPED_IDENTITY_SYMBOL + this.getTypeName(); java return this.typeName != null; java return this.refersTo;
java this.refersTo = refersTo;
java visitor.handleTypedIdentity(this);
java return visitor.handleTypedIdentity(this); java final NamedTypeReference type = new NamedTypeReference(new LinkedList<Token>(), this.refersTo().getName(), this.getModel()); type.setRefersTo(this.refersTo()); return type; Returns true if this type typedIdentity has a typeDefinition. * * @return Returns the refersTo attribute. * * @return Sets the refersTo attribute. * * @param refersTo
Constructs a new TypedIdentity with given start- and endPosition and * typeName.
Projection function with given {@link Type} for the domain.
java super(tokens, offset, belongsToModel); this.typeName = typeName; java return Symbols.IDENTITY_SYMBOL + this.getOffset() + Symbols.TYPE_DELIMITER + this.getTypeName(); java return this.typeName != null; java return this.refersTo;
java this.refersTo = refersTo;
java visitor.handleTypedProjection(this);
java return visitor.handleTypedProjection(this); java final int prime = 31; int result = 1; result = prime * result + super.hashCode(); result = prime * result + this.typeName.hashCode(); return result;
java if (this == obj) { return true; } assert obj != null; if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } final TypedProjection other = (TypedProjection) obj; if (!this.typeName.equals(other.typeName)) { return false; } return true; java final NamedTypeReference type = new NamedTypeReference( new LinkedList<Token>(), this.refersTo().getName(), this.getModel()); type.setRefersTo(this.refersTo()); return type; Returns true if this TypedProjection has a typeName set. * * @return Returns the refersTo attribute. * Sets the refersTo attribute. * * @param refersTo
Constructs a new TypedProjection with given start- and endPosition, * offset and typeName.
Represents an order between {@link Type} Objects.
java this.tokens = tokens; this.typeName = typeName; this.coercer = coercer; java return "\n" + this.printSymbol() + Symbols.STANDARD_WHITE_SPACE + this.getTypeName() + (this.hasCoercer() ? Symbols.DEFINE_BY_SYMBOL + Symbols.STANDARD_WHITE_SPACE + this.getCoercer().print() : ""); java return this.coercer != null; Returns well formated sourceCode representation of this TypeOrder. Returns <code>true</code> iff the {@link TypeOrder} has a coercer * {@link FunctionExpression}. Otherwise <code>false</code>. Returns the Symbol representing this TypeOrder. * * @return Entrypoint for the {@link TypeOrderVisitor}.
Creates an new TypeOrder with the given start- and endPosition, for the * given typeName and with the given {@link FunctionExpression} coercer. * * @param typeName * @param coercer
Class that represents a {@link Token} constructed by the {@link Scanner}.
java this.position = position; java return this.getPosition() + this.getBruttoLength(); Returns the {@link String} representation of the {@link Token}. Returns the ending position of the Token in the scanned file. Returns the length of the the Token in the scanned file. Method that accepts an {@link TokenVisitor}.
Abstract constructor of {@link Token}s. * @param position starting position of the {@link Token}.
Visitor that handles RealSymbolTokens.
Visitor that handles KeyWordTokens.
Visitor that handles BaseTypeSymbolTokens.
Visitor that handles BlindTokens.
Visitor that handles ValueTokens.
Visitor that handles CommentTokens.
Visitor that handles Tokens.
Visitor that handles SymbolTokens.
Visitor that handles HierarchyKeyWordTokens.
Token representing the end of a Token. @author Sönke *
java super(position); java return Symbols.CONSTRUCTOR_END_SYMBOL.length(); java return Symbols.CONSTRUCTOR_END_SYMBOL;
java visitor.handleConstructorEndSymbolToken(this);
Creates new {@link ConstructorEndSymbolToken} with the given position.
Token representing an abstract symbol: 'abstract'. @author Sönke *
java super(position); java return Symbols.ABSTRACT_SYMBOL.length(); java return Symbols.ABSTRACT_SYMBOL;
java visitor.handleAbstractSymbolToken(this);
Creates new {@link AbstractSymbolToken} with the given <position>. * * @param position
Token representing the Arrow "-->". @author Sönke *
java super(position); java return Symbols.ARROW_SYMBOL.length(); java return Symbols.ARROW_SYMBOL;
java visitor.handleArrowSymbolToken(this);
Creates new ArrowSymbolToken with the given <position>. * * @param position
A base-type symbol.
java super(position);
java visitor.handleBaseTypeSymbolToken(this);
A blind token.
java super(position, value);
java visitor.handleBlindToken(this);
A cardinal symbol.
java super(position); java return Symbols.CARDINAL_SYMBOL.length(); java return Symbols.CARDINAL_SYMBOL;
java visitor.handleCardinalSymbolToken(this);
Constructs a {@link CardinalSymbolToken}. * @see Token
Token representing the end of a choice: '}'. @author Sönke *
java super(position); java return Symbols.CHOICE_END_SYMBOL.length(); java return Symbols.CHOICE_END_SYMBOL;
java visitor.handleChoiceEndSymbolToken(this);
Creates new ChoiseEndSymbolToken with the given position. * * @param position
Token representing the start of a choise: '{'. @author Sönke *
java super(position); java return Symbols.CHOICE_START_SYMBOL.length(); java return Symbols.CHOICE_START_SYMBOL;
java visitor.handleChoiceStartSymbolToken(this);
Creates new {@link ChoiceStartSymbolToken} with the given <position>. * * @param position
Token representing a comment. @author Sönke *
java super(position, value);
java visitor.handleCommentToken(this);
Token representing the start of a constructor. @author Sönke *
java super(position); java return Symbols.CONSTRUCTOR_START_SYMBOL.length(); java return Symbols.CONSTRUCTOR_START_SYMBOL;
java visitor.handleConstructorStartSymbolToken(this);
Creates new {@link ConstructorStartSymbolToken} with the given * <position>. * * @param position
Token representing the definedBy symbol: '::='. @author Sönke *
java super(position); java return Symbols.DEFINE_BY_SYMBOL.length(); java return Symbols.DEFINE_BY_SYMBOL;
java visitor.handleDefineBySymbolToken(this);
Creates new DefineBySymbolToken with the given <position>. * * @param position
Representation of an end token.
java super(position); java return 0; java return "";
java visitor.handleEndToken(this);
Constructs an {@link EndToken}. * @see Token
Token representing the final map: '!'. @author Sönke *
java super(position); java return Symbols.FINAL_SYMBOL.length(); java return Symbols.FINAL_SYMBOL;
java visitor.handleFinalSymbolToken(this);
Creates new FinalSymbolToken with the given <position>. * * @param position
Token representing a function signature start: 'function'. @author Sönke *
java super(position); java return Symbols.FUNCTION_SYMBOL.length(); java return Symbols.FUNCTION_SYMBOL;
java visitor.handleFunctionSymbolToken(this);
Creates new {@link FunctionSymbolToken} with given <position>. * * @param position
Token representing the End of a FunctionType: ']'. @author Sönke *
java super(position); java return Symbols.FUNCTION_TYPE_END_SYMBOL.length(); java return Symbols.FUNCTION_TYPE_END_SYMBOL;
java visitor.handleFunctionTypeEndSymbolToken(this);
Creates new FunctionTypeEndSymbol with the given <position>. * * @param position
Scanner for source-Code of LOMF-2. *
java assert toBeScanned != null; theScannerProjectionState = new ScannerIdentityOrProjectionState(this); theScannerFinalState = new ScannerFinalState(this); theScannerCommentState = new ScannerCommentState(this); theScannerLineCommentState = new ScannerLineCommentState(this); theScannerWhiteSpaceState = new ScannerWhiteSpaceState(this); theScannerIdentifierState = new ScannerIdentifierState(this); theScannerStandardState = new ScannerStandardState(this); theScannerTypedProjectionState = new ScannerTypedIdentityOrProjectionState( this); this.toBeScanned = new StringBuilder(toBeScanned); length = toBeScanned.length(); position = 0; ok = true; state = theScannerStandardState; result = new TokenStream(); result.append(new StartToken(position));
java this.state = state; state.reset(position);
java final int delta = symbol.length(); skip(delta);
java position += count; java return toBeScanned.substring(position, position + 1);
java return toBeScanned.substring(startPosition, position);
java result.append(t); java final int inputLength = toBeScanned.length(); while (position < inputLength) { state.scan(); } state.finalToken(inputLength); result.append(new EndToken(position)); return result;
java if (symbol.length() > length - position) { return false; } return toBeScanned.substring(position, position + symbol.length()) .equals(symbol); java return isWhiteSpace(toBeScanned.charAt(position));
java return Character.isWhitespace(character); java final char next = toBeScanned.charAt(position); return Character.isDigit(next); java int maximalLength; final int restLength = toBeScanned.length() - position; maximalLength = restLength <= ScannerConstants.MAX_SYMBOL_LENGTH ? restLength : ScannerConstants.MAX_SYMBOL_LENGTH; final String inspect = toBeScanned.substring(position, position + maximalLength).toString(); return this.startsWithSymbol(inspect);
java return inspect.startsWith(Symbols.CONSTRUCTOR_END_SYMBOL) || inspect.startsWith(Symbols.CONSTRUCTOR_START_SYMBOL) || inspect.startsWith(Symbols.CHOICE_START_SYMBOL) || inspect.startsWith(Symbols.CHOICE_END_SYMBOL) || inspect.startsWith(Symbols.PARALLEL_START_SYMBOL) || inspect.startsWith(Symbols.PARALLEL_END_SYMBOL) || inspect.startsWith(Symbols.FUNCTION_TYPE_START_SYMBOL) || inspect.startsWith(Symbols.FUNCTION_TYPE_END_SYMBOL) || inspect.startsWith(Symbols.COMMENT_START_SYMBOL) || inspect.startsWith(Symbols.LINE_COMMENT_START_SYMBOL) || inspect.startsWith(Symbols.SEPARATOR_SYMBOL) || inspect.startsWith(Symbols.ARROW_SYMBOL) || inspect.startsWith(Symbols.SELECTION_END_SYMBOL) || inspect.startsWith(Symbols.DEFINE_BY_SYMBOL) || inspect.startsWith(Symbols.IDENTITY_SYMBOL) || inspect.startsWith(Symbols.TYPED_FINAL_SYMBOL) || inspect.startsWith(Symbols.FINAL_SYMBOL); java return theScannerProjectionState; java return theScannerStandardState; java return theScannerIdentifierState; java return length; Returns the character at the current position of the scanner. * * @return Appends the given {@link Token} <t> to the result. * * @param t
Processes the toBeScanned input set in this Scanner and returns the * resulting {@link TokenStream}. * * @return * @throws ScannerException Returns true, iff the currentPosition of the scanner is a whitespace. * * @return Returns true, iff the character at the current position is a digit. * * @return Returns true, iff the character at the current position is a symbol, * thats defined in {@link Symbols}. * * @return Returns the {@link ScannerIdentityOrProjectionState}. Returns the {@link ScannerStandardState}. Returns the {@link ScannerIdentifierState}. Returns the length.
Creates new Scanner for the given <toBeScanned> sourceCode. * * @param toBeScanned * sourceCode to be scanned.
Skips the symbol by skipping its length count characters in the input. * * @param symbol
Skips <count> characters by incrementing the position by the count. * * @param count
Returns the substring of the toBeScanned from the given <startPosition> * to the current position of the scanner. * * @param startPosition * @return
Returns true if the String at the current scanner position equals the * given String <symbol>. * * @param symbol * @return
Returns true if the given <character> is a whitespace. * * @param character * @return
Checks the assigned parameter <code>inspect</code> after * standard-symbols.
Sets the {@link ScannerState} of this scanner. * * @param state
java super(SCANNER_EXPRESSION_PREFIX + message, position);
Creates new {@link ScannerException} with the given message and position. * * @param message * @param position
The {@link TokenStream} is the result returned by the {@link Scanner} after processing the sourceCode. java this.tokenStream = new ArrayList<Token>(); java final TokenStream stream = new TokenStream(); stream.append(new EndToken(0)); stream.append(new StartToken(0)); return stream;
java this.tokenStream.add(t);
java this.tokenStream.addAll(stream.tokenStream); java return this.tokenStream.iterator(); java final TokenStream result = new TokenStream(); for (int i = this.tokenStream.size() - 1; i >= 0; i--) { result.append(this.tokenStream.get(i)); } return result;
java final Iterator<Token> tokenIterator = this.tokenStream.iterator(); Token current = new StartToken(0); while (tokenIterator.hasNext()) { current = tokenIterator.next(); final int currentStartPosition = current.getPosition(); final int currentEndPosition = currentStartPosition + current.getBruttoLength() - 1; if (currentStartPosition <= position && currentEndPosition >= position) { return current; } } return current; java // Tokenstream shall not be empty final Token result = this.tokenStream.get(0); this.tokenStream.remove(0); return result; java // Tokenstream shall not be empty final int last = this.tokenStream.size() - 1; final Token result = this.tokenStream.get(last); this.tokenStream.remove(last); return result; java return this.tokenStream.size(); java if (this.tokenStream.size() > 1) { return this.tokenStream.get(this.tokenStream.size() - 2); // last // token // is // endtoken!!! } return this.tokenStream.get(0); // endtoken java if (this.tokenStream.size() > 1) { this.tokenStream.remove(this.tokenStream.size() - 2); } java final StringBuilder buffer = new StringBuilder(); final Iterator<Token> tokens = this.iterator(); while (tokens.hasNext()) { final Token current = tokens.next(); buffer.append(current.getContents()); } return buffer;
Creates new, empty, {@link TokenStream}. Creates and returns an new, empty, TokenStream. * * @return Append the given {@link Token} to this stream. * * @param t
Appends all Tokens from the given {@link TokenStream} to this token * Stream. * * @param stream
Iterator for the tokens in this token Stream. * * @return Returns this token Stream in reversed Order. Removes and returns the firstToken from this {@link TokenStream}. * * @return Removes and returns the last Token from this {@link TokenStream}. * * @return Returns the length of this tokenStream, ie. the count of tokens in it. * * @return Returns the last significant? token. * * @return Removes the last significant? token. Returns an String representation of the contained tokens. * * @return Returns the token from this stream at the given position. * * @param position * @return
Representation of a {@link RealSymbolToken}.
java super(position);
java visitor.handleRealSymbolToken(this);
Representation of a {@link KeyWordToken}.
java super(position);
java visitor.handleKeyWordToken(this);
A valued token.
java super(position); this.value = value; java return this.value.length(); java return this.value; java return this.value;
java visitor.handleValueToken(this); Returns the value of this {@link Token}. Returns the netto value of this {@link Token}. Returns the netto position of this {@link Token}.
Accepts a {@link ValueTokenVisitor}.
Abstract constructor of {@link ValueToken}. * @param value {@link String} representation of this {@link Token} * @see Token
Token representing the start of a FunctionType: '['.
java super(position); java return Symbols.FUNCTION_TYPE_START_SYMBOL.length(); java return Symbols.FUNCTION_TYPE_START_SYMBOL;
java visitor.handleFunctionTypeStartSymbolToken(this);
Creates new {@link FunctionTypeStartSymbolToken} with the given * <position>. * * @param position
Token representing a Generalization: 'generalizes'. @author Sönke *
java super(position); java return Symbols.GENERALIZES_SYMBOL.length(); java return Symbols.GENERALIZES_SYMBOL;
java visitor.handleGeneralizesSymbolToken(this);
Creates new {@link GeneralizesSymbolToken} with the given <position>. * * @param position
A identifier token.
java super(position, value); java return this.getBruttoValue(); java return this.getPosition();
java visitor.handleIdentifierToken(this);
Constructs a {@link IdentifierToken}. * @param value {@link String} representation of this token. * @see Token
Token representing the identity function: '.'. @author Sönke *
java super(position); java return Symbols.IDENTITY_SYMBOL.length(); java return Symbols.IDENTITY_SYMBOL;
java visitor.handleIdentitySymbolToken(this);
Creates new {@link IdentitySymbolToken} with the given <position>. * * @param position
Token representing a line comment: '//'. @author Sönke *
java super(position, value); java final String brutto = this.getBruttoValue(); return brutto.substring(Symbols.LINE_COMMENT_START_SYMBOL.length(), brutto.length() - Symbols.RETURN_SYMBOL.length()); java return this.getPosition() + Symbols.LINE_COMMENT_START_SYMBOL.length();
java visitor.handleLineCommentToken(this);
Creates new {@link LineCommentToken} with the given <position>. * * @param position
Token representing the End of parallel functions: '>'. @author Sönke *
java super(position); java return Symbols.PARALLEL_END_SYMBOL.length(); java return Symbols.PARALLEL_END_SYMBOL;
java visitor.handleParallelEndSymbolToken(this);
Creates new {@link ParallelEndSymbolToken} with the given <position>. * * @param position
Token representing the start of parallel functions: '<'. @author Sönke *
java super(position); java return Symbols.PARALLEL_START_SYMBOL.length(); java return Symbols.PARALLEL_START_SYMBOL;
java visitor.handleParallelStartSymbolToken(this);
Creates new {@link ParallelStartSymbolToken} with the given <position>. * * @param position
Token representing a projection: '.'. @author Sönke *
java super(position, value); java final String brutto = this.getBruttoValue(); return brutto.substring(Symbols.IDENTITY_SYMBOL.length(), brutto.length()); java return this.getPosition() + Symbols.IDENTITY_SYMBOL.length();
java visitor.handleProjectionToken(this);
Creates new {@link ProjectionToken} with the given <position> and * <value>. * * @param position
State indicating this scanner processes an comment.
java super(scanner); java if (this.getScanner().startsWith(Symbols.COMMENT_END_SYMBOL)) { this.getScanner().advancePosition(Symbols.COMMENT_END_SYMBOL); this.getScanner().appendToken( new StandardCommentToken(this.getStartPosition(), this.getScanner() .getSubString(this.getStartPosition()))); this.getScanner().setState(this.getScanner().getTheScannerStandardState()); return; } this.getScanner().skip(1);
java this.getScanner() .appendToken( new StandardCommentToken(this.getStartPosition(), this.getScanner() .getSubString(this.getStartPosition()) + Symbols.COMMENT_END_SYMBOL)); throw new ScannerException(UNLIMITED_COMMENT_TEXT, this.getStartPosition());
Constants for the scanner. *
State indicating this scanner processen an final symbol.
java super(scanner);
java this.getScanner().appendToken( new TypedFinalSymbolToken(this.getStartPosition(), this.getScanner() .getSubString(this.getStartPosition()))); java if (!this.getScanner().startsWithSymbol() && !this.getScanner().startsWithWhiteSpace()) { this.getScanner().skip(1); } else { this.getScanner().appendToken( new TypedFinalSymbolToken(this.getStartPosition(), this.getScanner() .getSubString(this.getStartPosition()))); this.getScanner().setState(this.getScanner().getTheScannerStandardState()); }
State indicating this scanner is scanning an identifiere.
java super(scanner);
java this.appendKeyWordTokenOrIdentifier(); java if (this.getScanner().startsWithWhiteSpace()) { this.appendKeyWordTokenOrIdentifier(); this.getScanner().setState(this.getScanner().getTheScannerWhiteSpaceState()); return; } if (this.getScanner().startsWithSymbol()) { this.appendKeyWordTokenOrIdentifier(); this.getScanner().setState(this.getScanner().getTheScannerStandardState()); return; } this.getScanner().skip(1); java final String value = this.getScanner().getSubString(this.getStartPosition()); if (value.equals(Symbols.ABSTRACT_SYMBOL)) { this.getScanner().appendToken( new AbstractSymbolToken(this.getStartPosition())); return; } if (value.equals(Symbols.SPECIALIZES_SYMBOL)) { this.getScanner().appendToken( new SpecializesSymbolToken(this.getStartPosition())); return; } if (value.equals(Symbols.GENERALIZES_SYMBOL)) { this.getScanner().appendToken( new GeneralizesSymbolToken(this.getStartPosition())); return; } if (value.equals(Symbols.TYPE_SYMBOL)) { this.getScanner().appendToken(new TypeSymbolToken(this.getStartPosition())); return; } if (value.equals(Symbols.FUNCTION_SYMBOL)) { this.getScanner().appendToken( new FunctionSymbolToken(this.getStartPosition())); return; } if (value.equals(Symbols.CARDINAL_SYMBOL)) { this.getScanner().appendToken( new CardinalSymbolToken(this.getStartPosition())); return; } if (value.equals(Symbols.STRING_SYMBOL)) { this.getScanner().appendToken(new StringSymbolToken(this.getStartPosition())); return; } this.getScanner() .appendToken(new IdentifierToken(this.getStartPosition(), value));
State indicating scanner scans an Identity or projection.
java super(scanner);
java this.getScanner().appendToken(this.produceToken()); java final String value = this.getScanner().getSubString(this.getStartPosition()); return value.length() == 1 ? new IdentitySymbolToken(this.getStartPosition()) : new ProjectionToken(this.getStartPosition(), value); java if (this.getScanner().startsWithDigit()) { this.getScanner().skip(1); } else if (this.getScanner().startsWith(Symbols.TYPE_DELIMITER)) { this.getScanner().skip(1); this.getScanner().setState( this.getScanner().getTheScannerTypedProjectionState()); this.getScanner().getTheScannerTypedProjectionState().setPosition( this.getStartPosition()); } else { this.getScanner().appendToken(this.produceToken()); this.getScanner().setState(this.getScanner().getTheScannerStandardState()); }
State indicating the scanner scans an LineComment.
java super(scanner); java if (this.getScanner().startsWith(Symbols.RETURN_SYMBOL)) { this.getScanner().advancePosition(Symbols.RETURN_SYMBOL); this.getScanner().appendToken( new LineCommentToken(this.getStartPosition(), this.getScanner() .getSubString(this.getStartPosition()))); this.getScanner().setState(this.getScanner().getTheScannerStandardState()); return; } this.getScanner().skip(1);
java this.getScanner().appendToken( new LineCommentToken(this.getStartPosition(), this.getScanner().getSubString( this.getStartPosition()) + Symbols.RETURN_SYMBOL)); throw new ScannerException(UNLIMITED_COMMENT_TEXT, this.getStartPosition());
The state the scanner is in per default.
java super(scanner); java if (getScanner().startsWith(Symbols.CHOICE_START_SYMBOL)) { getScanner().appendToken( new ChoiceStartSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.CHOICE_START_SYMBOL); return; } if (getScanner().startsWith(Symbols.CHOICE_END_SYMBOL)) { getScanner().appendToken( new ChoiceEndSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.CHOICE_END_SYMBOL); return; } if (getScanner().startsWith(Symbols.PARALLEL_START_SYMBOL)) { getScanner().appendToken( new ParallelStartSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.PARALLEL_START_SYMBOL); return; } if (getScanner().startsWith(Symbols.PARALLEL_END_SYMBOL)) { getScanner().appendToken( new ParallelEndSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.PARALLEL_END_SYMBOL); return; } if (getScanner().startsWith(Symbols.FUNCTION_TYPE_START_SYMBOL)) { getScanner().appendToken( new FunctionTypeStartSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.FUNCTION_TYPE_START_SYMBOL); return; } if (getScanner().startsWith(Symbols.FUNCTION_TYPE_END_SYMBOL)) { getScanner().appendToken( new FunctionTypeEndSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.FUNCTION_TYPE_END_SYMBOL); return; } if (getScanner().startsWith(Symbols.CONSTRUCTOR_START_SYMBOL)) { getScanner().appendToken( new ConstructorStartSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.CONSTRUCTOR_START_SYMBOL); return; } if (getScanner().startsWith(Symbols.CONSTRUCTOR_END_SYMBOL)) { getScanner().appendToken( new ConstructorEndSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.CONSTRUCTOR_END_SYMBOL); return; } if (getScanner().startsWith(Symbols.ARROW_SYMBOL)) { getScanner().appendToken( new ArrowSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.ARROW_SYMBOL); return; } if (getScanner().startsWith(Symbols.SEPARATOR_SYMBOL)) { getScanner().appendToken( new SeparatorSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.SEPARATOR_SYMBOL); return; } if (getScanner().startsWith(Symbols.SELECTION_END_SYMBOL)) { getScanner().appendToken( new SectionEndSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.SELECTION_END_SYMBOL); return; } if (getScanner().startsWith(Symbols.DEFINE_BY_SYMBOL)) { getScanner().appendToken( new DefineBySymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.DEFINE_BY_SYMBOL); return; } if (getScanner().startsWith(Symbols.COMMENT_START_SYMBOL)) { getScanner().setState(getScanner().getTheScannerCommentState()); getScanner().advancePosition(Symbols.COMMENT_START_SYMBOL); return; } if (getScanner().startsWith(Symbols.TYPED_FINAL_SYMBOL)) { getScanner().setState(getScanner().getTheScannerFinalState()); getScanner().advancePosition(Symbols.TYPED_FINAL_SYMBOL); return; } if (getScanner().startsWith(Symbols.FINAL_SYMBOL)) { getScanner().appendToken( new FinalSymbolToken(getScanner().getPosition())); getScanner().advancePosition(Symbols.FINAL_SYMBOL); return; } if (getScanner().startsWith(Symbols.IDENTITY_SYMBOL)) { getScanner().setState(getScanner().getTheScannerProjectionState()); getScanner().advancePosition(Symbols.IDENTITY_SYMBOL); return; } if (getScanner().startsWith(Symbols.LINE_COMMENT_START_SYMBOL)) { getScanner().setState(getScanner().getTheScannerLineCommentState()); getScanner().advancePosition(Symbols.LINE_COMMENT_START_SYMBOL); return; } if (getScanner().startsWithWhiteSpace()) { getScanner().setState(getScanner().getTheScannerWhiteSpaceState()); return; } getScanner().setState(getScanner().getTheScannerIdentifierState());
The object indicating the current state of a {@link Scanner}.
java this.scanner = scanner;
A scanner-state to produce a {@link TypedIdentityToken} or {@link TypedProjectionToken}.
java super(scanner);
java this.getScanner().appendToken(this.produceToken()); java final String value = this.getScanner().getSubString(this.getStartPosition()); if (value.startsWith(Symbols.TYPED_IDENTITY_SYMBOL)) { return new TypedIdentityToken(this.getStartPosition(), value); } else { return new TypedProjectionToken(this.getStartPosition(), value); } java if (this.getScanner().startsWith(Symbols.SEPARATOR_SYMBOL) || this.getScanner().startsWith(Symbols.CONSTRUCTOR_END_SYMBOL) || this.getScanner().startsWith(Symbols.SELECTION_END_SYMBOL) || this.getScanner().startsWith(Symbols.PARALLEL_END_SYMBOL) || this.getScanner().startsWith(Symbols.CHOICE_END_SYMBOL) || this.getScanner().startsWith(Symbols.COMMENT_START_SYMBOL) || this.getScanner().startsWith(Symbols.LINE_COMMENT_START_SYMBOL) || this.getScanner().startsWith(Symbols.IDENTITY_SYMBOL) || this.getScanner().startsWith(Symbols.STANDARD_WHITE_SPACE) || this.getScanner().startsWith(Symbols.RETURN_SYMBOL)) { this.getScanner().appendToken(this.produceToken()); this.getScanner().setState(this.getScanner().getTheScannerStandardState()); } else { this.getScanner().skip(1); }
State indicating this scanner scans an WhiteSpace.
java super(scanner); java if (this.getScanner().startsWithWhiteSpace()) { this.getScanner().skip(1); return; } this.getScanner().appendToken( new WhiteSpaceToken(this.getStartPosition(), this.getScanner().getSubString( this.getStartPosition()))); this.getScanner().setState(this.getScanner().getTheScannerStandardState());
java this.getScanner().appendToken( new WhiteSpaceToken(this.getStartPosition(), this.getScanner().getSubString( this.getStartPosition())));
Token representing the end of a section: ';'. @author Sönke *
java super(position); java return Symbols.SELECTION_END_SYMBOL.length(); java return Symbols.SELECTION_END_SYMBOL;
java visitor.handleSectionEndSymbolToken(this);
Creates new {@link SectionEndSymbolToken} with the given <position>. * * @param position
Token representing a Seperator symbol: ','. @author Sönke *
java super(position); java return Symbols.SEPARATOR_SYMBOL.length(); java return Symbols.SEPARATOR_SYMBOL;
java visitor.handleSeparatorSymbolToken(this);
Creates new {@link SeparatorSymbolToken} with the given <position>. * * @param position
Token reprenting the Specialization of types: 'specializes'. @author Sönke *
java super(position); java return Symbols.SPECIALIZES_SYMBOL.length(); java return Symbols.SPECIALIZES_SYMBOL;
java visitor.handleSpecializesSymbolToken(this);
Creates new {@link SpecializesSymbolToken} with the given <position>. * * @param position
A standard comment token.
java super(position, value); java final String brutto = this.getBruttoValue(); return brutto.substring(Symbols.COMMENT_START_SYMBOL.length(), brutto.length() - Symbols.COMMENT_END_SYMBOL.length()); java return this.getPosition() + Symbols.COMMENT_START_SYMBOL.length();
java visitor.handleStandardCommentToken(this);
Constructs a {@link StandardCommentToken}. * @param value {@link String} representation of this {@link Token}.
The start {@link Token} of a {@link TokenStream}.
java super(position); java return 0; java return "";
java visitor.handleStartToken(this);
Constructs a {@link StartToken}. * @see Token
Token representing the String-Symbol: 'String'. @author Sönke *
java super(position); java return Symbols.STRING_SYMBOL.length(); java return Symbols.STRING_SYMBOL;
java visitor.handleStringSymbolToken(this);
Creates new {@link StringSymbolToken} with the given <position>. * * @param position
Represents a {@link SymbolToken}.
java super(position);
java visitor.handleSymbolToken(this);
Abstract token for hierarchy definition tokens. @author Sönke *
java super(position);
java visitor.handleTypeHierarchyKeyWordToken(this);
Token representing Type declaration start: 'type'. @author Sönke *
java super(position); java return Symbols.TYPE_SYMBOL.length(); java return Symbols.TYPE_SYMBOL;
java visitor.handleTypeSymbolToken(this);
Creates new TypeSymbolToken with the given <position>. * * @param position * @param value
Token representing TypedFinalMap: '!-'. @author Sönke *
java super(position, value); java return this.getPosition() + Symbols.TYPED_FINAL_SYMBOL.length(); java return this.getBruttoValue().substring(Symbols.TYPED_FINAL_SYMBOL.length(), this.getBruttoValue().length());
java visitor.handleTypedFinalSymbolToken(this);
Creates new TypedFinalSymbolToken with the given <position>. * * @param position * @param value
Identity function token with given name for the domain.
java super(position, value); java final String brutto = this.getBruttoValue(); return brutto.substring(brutto.indexOf(Symbols.TYPE_DELIMITER) + 1, brutto.length()); java return this.getPosition() + Symbols.TYPED_IDENTITY_SYMBOL.length();
java visitor.handleTypedIdentityToken(this);
Constructs a new TypedIdentityToken with given position * value.
Projection function token with given name for the domain.
java super(position, value); java final String brutto = this.getBruttoValue(); return brutto.substring(Symbols.IDENTITY_SYMBOL.length(), brutto.indexOf(Symbols.TYPE_DELIMITER)); java return this.getPosition() + this.getBruttoValue().indexOf(Symbols.TYPE_DELIMITER); java final String brutto = this.getBruttoValue(); return brutto.substring(brutto.indexOf(Symbols.TYPE_DELIMITER) + 1, brutto.length());
java visitor.handleTypedProjectionToken(this);
Constructs a new TypedProjectionToken with given position * value.
Returns the name of the type of the typed projection. * @return The name of the type.
Scanner state for representing scanning an value.
java super(scanner);
java this.startPosition = position;
java this.startPosition = position;
Creates new state for the given {@link Scanner}. * * @param scanner
Sets the startPosition of this state. * * @param position
Token representing a single whitespace. *
java super(position, value); java return this.getBruttoValue(); java return this.getPosition();
java visitor.handleWhiteSpaceToken(this);
Creates new {@link WhiteSpaceToken} at the given position. * * @param position * @param value
Container for all constant Symbols for the scanner. *
Represents a Object that can be contained in the source code.
Represents named Objects with Positions within the TokenStream.
An Entry in the Parsers Map for the last Tokens. Needed due for one startToken there can be more than one observers. java super(); this.tokens = new LinkedList<Token>(); // this.tokens.add(startToken); this.count = 1;
java this.tokens.add(token); java return this.count; java this.count++; java this.count--;
Creates new {@link LastTokensMapEntry} with the given startToken. * * @param tokens Appends the given Token to this Entry. * * @param token
Returns the count of observers for this entry. * * @return Increments the observer-count by one. Decrements the observer-count by one.
java super(PARSER_EXCEPTION_PREFIX + message, position);
Creates new {@link ParserException} with the given message and position. * * @param message * @param position
Parser of a {@link TokenStream}.
java this.tokenStream = tokenStream.iterator(); java this.skip(); this.skip(); this.skip(); this.skip(); this.skip(); this.skip(); java this.last = this.current; this.current = this.next; this.next = this.behindNext; this.behindNext = this.behindBehindNext; this.behindBehindNext = this.behindBehindBehindNext; this.behindBehindBehindNext = this.behindBehindBehindBehindNext; this.getNextToken(); java return this.last; java return this.next; java return this.behindBehindNext; java return this.behindBehindBehindNext; java return this.behindBehindBehindBehindNext; java if (this.tokenStream.hasNext()) { this.behindBehindBehindBehindNext = this.tokenStream.next(); } Routine to set all {@link Token}s like <code>last</code>, * <code>current</code>, <code>next</code>, <code>behindNext</code> and so * on. Skips to the next {@link Token}s. Returns the last "current" {@link Token}. After initialization it returns * null. Returns the next {@link Token}. Returns the behindBehindNext {@link Token}. Returns the behindBehindBehindNext {@link Token}. Returns the behindBehindBehindBehindNext {@link Token}.
Constructs a {@link ParserTokenStream}. * * @param tokenStream * a {@link TokenStream}.
LOMF2's Parser.
java this.lastTokens = new HashMap<Token, LastTokensMapEntry>(); this.toBeParsed = toBeParsed; this.toBeParsed.start(); this.toBeParsed.skip(); // Start token java return this.parseSections();
java return "Symbol \"" + symbol + "\" expected!"; java final Model result = new Model(); while (!(this.currentToken() instanceof EndToken)) { final TypeOrFunction section = this.parseSection(result); result.add(section); } return result;
java final ArrayList<FunctionExpression> result = new ArrayList<FunctionExpression>(); while (!(this.currentToken() instanceof EndToken)) { final FunctionExpression expr = this.parseFunctionExpression(model); this.parseSectionEndSymbolToken(); result.add(expr); } return result;
java if (this.currentToken() instanceof AbstractSymbolToken) { return this.parseAbstractTypeSection(model); } if (this.currentToken() instanceof TypeSymbolToken) { return this.parseTypeSection(model); } return this.parseFunctionSection(model);
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); this.parseAbstractSymbolToken(); this.parseTypeSymbolToken(); final String name = this.parseIdentifier(); final List<TypeOrder> hierarchies = this.parseTypeOrders(false, model); // final int endPosition = this.currentToken().getEndPosition(); this.parseSectionEndSymbolToken(); return new Type(this.getLastTokens(startToken), name, hierarchies);
java final List<TypeOrder> result = new ArrayList<TypeOrder>(); while (this.currentToken() instanceof TypeHierarchyKeyWordToken) { final TypeOrder current = this.parseTypeOrder(coercersAllowed, model); result.add(current); } return result;
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); boolean specialization = false; if (this.currentToken() instanceof SpecializesSymbolToken) { this.parseSpecializationSymbolToken(); specialization = true; } else { this.parseGeneralizationSymbolToken(); } // int endPosition = this.currentPosition(); final String nameOfGeneralType = this.parseIdentifier(); FunctionExpression coercer = null; if (coercersAllowed && this.currentToken() instanceof DefineBySymbolToken) { this.parseDefineBySymbol(); coercer = this.parseFunctionExpression(model); } // endPosition = coercer == null ? endPosition : // coercer.getEndPosition(); if (specialization) { return new Specialization(this.getLastTokens(startToken), nameOfGeneralType, coercer); } return new Generalization(this.getLastTokens(startToken), nameOfGeneralType, coercer);
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); this.parseTypeSymbolToken(); final String name = this.parseIdentifier(); final ListTypeExpression type = this.parseComposedTypeExpression(false, false, false, model); final List<TypeOrder> hierarchies = this.parseTypeOrders(true, model); // final int endPosition = this.currentToken().getEndPosition(); this.parseSectionEndSymbolToken(); return new Type(this.getLastTokens(startToken), name, type, hierarchies);
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); final FunctionExpression expression = this.parseSingleFunctionExpression(model); if (this.currentToken() instanceof SectionEndSymbolToken) { return expression; } final List<FunctionExpression> parts = new ArrayList<FunctionExpression>(); parts.add(expression); final ParseFunctionExpressionVisitor visitor = new ParseFunctionExpressionVisitor(expression, parts, model); this.currentToken().accept(visitor); visitor.checkException(); // while (this.currentToken() instanceof ExpressionStartSymbol) { // expression = this.parseSingleFunctionExpression(); // parts.add(expression); // } // final int endPosition = this.currentToken().getEndPosition(); return new SequentialFunctionExpression(this.getLastTokens(startToken), parts, model);
java if (this.currentToken() instanceof ChoiceStartSymbolToken) { return this.parseComposedExpression(Parser.SUM_EXPRESSION_INDICATOR, model); } if (this.currentToken() instanceof ConstructorStartSymbolToken) { return this.parseComposedExpression(Parser.CONSTRUCTOR_EXPRESSION_INDICATOR, model); } if (this.currentToken() instanceof ParallelStartSymbolToken) { return this.parseComposedExpression(Parser.PARALLEL_EXPRESSION_INDICATOR, model); } if (this.currentToken() instanceof ProjectionToken) { return this.parseProjection(model); } if (this.currentToken() instanceof TypedProjectionToken) { return this.parseTypedProjection(model); } if (this.currentToken() instanceof IdentifierToken) { return this.parseNamedFunctionReference(model); } if (this.currentToken() instanceof IdentitySymbolToken) { return this.parseIdentity(model); } if (this.currentToken() instanceof TypedIdentityToken) { return this.parseTypedIdentity(model); } if (this.currentToken() instanceof TypedFinalSymbolToken) { return this.parseTypedFinalSymbolToken(model); } if (this.currentToken() instanceof FinalSymbolToken) { return this.parseFinalSymbolToken(model); } throw new ParserException(Parser.UNKNOWN_EXPRESSION_MSG, this.currentPosition());
java // final int startPosition = this.currentPosition(); // final int endPosition = this.currentToken().getEndPosition(); final String name = this.parseIdentifier(); return new NamedFunctionReference(this.getCurrentTokenAsDeque(), name, model);
java if (this.currentToken() instanceof TypedFinalSymbolToken) { // final int startPosition = this.currentPosition(); // final int endPosition = this.currentToken().getEndPosition(); final TypedFinalSymbolToken currentFinalSymbolToken = (TypedFinalSymbolToken) this.currentToken(); this.skipToken(); return new TypedFinalMap(this.getCurrentTokenAsDeque(), currentFinalSymbolToken.getNettoValue(), model); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.TYPED_FINAL_SYMBOL), this.currentPosition()); }
java if (this.currentToken() instanceof FinalSymbolToken) { // final int startPosition = this.currentPosition(); // final int endPosition = this.currentToken().getEndPosition(); this.skipToken(); return new FinalMap(this.getCurrentTokenAsDeque(), model); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.TYPED_FINAL_SYMBOL), this.currentPosition()); }
java if (this.currentToken() instanceof IdentitySymbolToken) { // final int startPosition = this.currentPosition(); // final int endPosition = this.currentToken().getEndPosition(); this.skipToken(); return new Identity(this.getCurrentTokenAsDeque(), model); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.IDENTITY_SYMBOL), this.currentPosition()); }
java if (this.currentToken() instanceof TypedIdentityToken) { // final int startPosition = this.currentPosition(); // final int endPosition = this.currentToken().getEndPosition(); final TypedIdentityToken current = (TypedIdentityToken) this.currentToken(); this.skipToken(); return new TypedIdentity(this.getCurrentTokenAsDeque(), current.getNettoValue(), model); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.IDENTITY_SYMBOL), this.currentPosition()); }
java if (this.currentToken() instanceof ProjectionToken) { // final int startPosition = this.currentPosition(); // final int endPosition = this.currentToken().getEndPosition(); final int projectionNumber = new Integer(((ProjectionToken) this.currentToken()).getNettoValue()); this.skipToken(); return new Projection(this.getCurrentTokenAsDeque(), projectionNumber, model); } else { throw new ParserException("Projection symbol expected!", this.currentPosition()); }
java if (this.currentToken() instanceof TypedProjectionToken) { // final int startPosition = this.currentPosition(); // final int endPosition = this.currentToken().getEndPosition(); final TypedProjectionToken token = (TypedProjectionToken) this.currentToken(); final int projectionNumber = new Integer(token.getNettoValue()); this.skipToken(); return new TypedProjection(this.getCurrentTokenAsDeque(), projectionNumber, token.getTypeName(), model); } else { throw new ParserException("Projection symbol expected!", this.currentPosition()); }
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); switch (indicator) { case Parser.SUM_EXPRESSION_INDICATOR : this.parseChoiceStartSymbolToken(); break; case Parser.PARALLEL_EXPRESSION_INDICATOR : this.parseParallelStartSymbolToken(); break; case Parser.CONSTRUCTOR_EXPRESSION_INDICATOR : this.parseConstructorStartSymbolToken(); break; default : throw new ParserException(Parser.UNKNOWN_COMPOSITE_MSG, this.currentPosition()); } final List<FunctionExpression> parts = new ArrayList<FunctionExpression>(); if (!(this.currentToken() instanceof ChoiceEndSymbolToken) && !(this.currentToken() instanceof ParallelEndSymbolToken) && !(this.currentToken() instanceof ConstructorEndSymbolToken)) { parts.add(this.parseFunctionExpression(model)); while (this.currentToken() instanceof SeparatorSymbolToken) { this.parseSeparatorSymbolToken(); parts.add(this.parseFunctionExpression(model)); } } // final int endPosition = this.currentToken().getEndPosition(); switch (indicator) { case Parser.SUM_EXPRESSION_INDICATOR : this.parseChoiceEndSymbolToken(); return new SumFunctionExpression(this.getLastTokens(startToken), parts, model); case Parser.PARALLEL_EXPRESSION_INDICATOR : this.parseParallelEndSymbolToken(); return new ProductFunctionExpression(this.getLastTokens(startToken), parts, model); case Parser.CONSTRUCTOR_EXPRESSION_INDICATOR : this.parseConstructorEndSymbolToken(); return new ConstructorFunctionExpression(this.getLastTokens(startToken), parts, model); default : throw new ParserException(Parser.UNKNOWN_COMPOSITE_MSG, this.currentPosition()); }
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); this.parseFunctionSymbol(); final String name = this.parseIdentifier(); final FunctionTypeExpression type = this.parseFunctionType(model); this.parseDefineBySymbol(); final FunctionExpression method = this.parseFunctionExpression(model); // final int endPosition = this.currentToken().getEndPosition(); this.parseSectionEndSymbolToken(); return new Function(this.getLastTokens(startToken), name, type, method);
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); this.parseFunctionTypeStartSymbol(); final TypeExpression domainType = this.parseTypeExpression(true, model); this.parseArrowSymbol(); final TypeExpression coDomainType = this.parseTypeExpression(false, model); // final int endPosition = this.currentToken().getEndPosition(); this.parseFunctionTypeEndSymbol(); return new FunctionTypeExpression(this.getLastTokens(startToken), domainType, coDomainType, model);
java if (this.currentToken() instanceof ConstructorStartSymbolToken) { return this.parseComposedTypeExpression(withFunctionTypes, false, true, model); } if (this.currentToken() instanceof ChoiceStartSymbolToken) { return this.parseComposedTypeExpression(withFunctionTypes, true, true, model); } if (withFunctionTypes && this.currentToken() instanceof FunctionTypeStartSymbolToken) { return this.parseFunctionType(model); } return this.parseNamedTypeReference(model);
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); final String name = this.parseIdentifier(); return new NamedTypeReference(this.getLastTokens(startToken), name, model);
java // final int startPosition = this.currentPosition(); final Token startToken = this.currentToken(); this.registerForLastTokens(startToken); final List<TypeExpression> parts = new ArrayList<TypeExpression>(); if (sum) { this.parseChoiceStartSymbolToken(); } else { this.parseConstructorStartSymbolToken(); } if (!(this.currentToken() instanceof ChoiceEndSymbolToken) && !(this.currentToken() instanceof ConstructorEndSymbolToken)) { parts.add(recursive ? this.parseTypeExpression(withFunctionTypes, model) : this.parseNamedTypeReference(model)); while (this.currentToken() instanceof SeparatorSymbolToken) { this.parseSeparatorSymbolToken(); parts.add(recursive ? this.parseTypeExpression(withFunctionTypes, model) : this.parseNamedTypeReference(model)); } } // final int endPosition = this.currentToken().getEndPosition(); if (sum) { this.parseChoiceEndSymbolToken(); } else { this.parseConstructorEndSymbolToken(); } return sum ? new SumTypeExpression(this.getLastTokens(startToken), parts, model) : new ConstructorTypeExpression(this.getLastTokens(startToken), parts, model); java if (this.currentToken() instanceof AbstractSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.ABSTRACT_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof SpecializesSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.SPECIALIZES_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof GeneralizesSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.GENERALIZES_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof FunctionTypeStartSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.FUNCTION_TYPE_START_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof FunctionTypeEndSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.FUNCTION_TYPE_END_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof ParallelStartSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.PARALLEL_START_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof ParallelEndSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.PARALLEL_END_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof ArrowSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.ARROW_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof IdentifierToken) { final String result = ((IdentifierToken) this.currentToken()).getContents(); this.skipToken(); return result; } else { throw new ParserException(Parser.IDENTIFIER_EXPECTED_MSG, this.currentPosition()); } java if (this.currentToken() instanceof FunctionSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.FUNCTION_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof TypeSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.TYPE_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof SectionEndSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.SELECTION_END_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof ConstructorStartSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.CONSTRUCTOR_START_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof ConstructorEndSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.CONSTRUCTOR_END_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof SeparatorSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.SEPARATOR_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof ChoiceStartSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.CHOICE_START_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof ChoiceEndSymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.CHOICE_END_SYMBOL), this.currentPosition()); } java if (this.currentToken() instanceof DefineBySymbolToken) { this.skipToken(); } else { throw new ParserException(Parser.getExpectedMessage(Symbols.DEFINE_BY_SYMBOL), this.currentPosition()); } java final Token result = this.toBeParsed.getCurrent(); if (result instanceof BlindToken) { this.skipToken(); return this.currentToken(); } return result; java return this.toBeParsed.getCurrent().getPosition(); java for (final LastTokensMapEntry entry : this.lastTokens.values()) { entry.appendToken(this.toBeParsed.getCurrent()); } this.toBeParsed.skip();
java final LastTokensMapEntry entry = this.lastTokens.get(startToken); assert entry != null; if (entry.getCount() == 1) { this.lastTokens.remove(startToken); } else { entry.decrementCount(); } return entry.getTokens();
java LastTokensMapEntry entry = this.lastTokens.get(startToken); if (entry == null) { entry = new LastTokensMapEntry(); this.lastTokens.put(startToken, entry); } else { entry.incrementCount(); } java final Deque<Token> token = new LinkedList<Token>(); token.add(this.toBeParsed.getCurrent()); return token;
Constructor.
Creates a new {@link Model}, for the {@link ParserTokenStream}. Different entry-point for parsing functionexpressions.
Parses FunctionExpressions.
java this.expression = expression; this.parts = parts; this.parserException = null; this.model = model; java if (this.parserException != null) { throw this.parserException; }
java symbolToken.accept(new SymbolTokenVisitor() { @Override public void handleRealSymbolToken(final RealSymbolToken realSymbolToken) { realSymbolToken.accept(new RealSymbolTokenVisitor() { @Override public void handleSeparatorSymbolToken(final SeparatorSymbolToken separatorSymbolToken) { } @Override public void handleSectionEndSymbolToken(final SectionEndSymbolToken sectionEndSymbolToken) { } @Override public void handleParallelStartSymbolToken( final ParallelStartSymbolToken parallelStartSymbolToken) { ParseFunctionExpressionVisitor.this. handleExpressionStartSymbolToken(parallelStartSymbolToken); } @Override public void handleParallelEndSymbolToken(final ParallelEndSymbolToken parallelEndSymbolToken) { } @Override public void handleIdentitySymbolToken(final IdentitySymbolToken identitySymbolToken) { ParseFunctionExpressionVisitor.this.handleExpressionStartSymbolToken(identitySymbolToken); } @Override public void handleFunctionTypeStartSymbolToken( final FunctionTypeStartSymbolToken functionTypeStartSymbolToken) { } @Override public void handleFunctionTypeEndSymbolToken( final FunctionTypeEndSymbolToken functionTypeEndSymbolToken) { } @Override public void handleFinalSymbolToken(final FinalSymbolToken finalSymbolToken) { ParseFunctionExpressionVisitor.this.handleExpressionStartSymbolToken(finalSymbolToken); } @Override public void handleDefineBySymbolToken(final DefineBySymbolToken defineBySymbolToken) { } @Override public void handleConstructorStartSymbolToken( final ConstructorStartSymbolToken constructorStartSymbolToken) { ParseFunctionExpressionVisitor.this. handleExpressionStartSymbolToken(constructorStartSymbolToken); } @Override public void handleConstructorEndSymbolToken( final ConstructorEndSymbolToken constructorEndSymbolToken) { } @Override public void handleChoiceStartSymbolToken(final ChoiceStartSymbolToken choiceStartSymbolToken) { ParseFunctionExpressionVisitor.this. handleExpressionStartSymbolToken(choiceStartSymbolToken); } @Override public void handleChoiceEndSymbolToken(final ChoiceEndSymbolToken choiceEndSymbolToken) { } @Override public void handleArrowSymbolToken(final ArrowSymbolToken arrowSymbolToken) { } }); } @Override public void handleKeyWordToken(final KeyWordToken keyWordToken) { } });
java valueToken.accept(new ValueTokenVisitor() { @Override public void handleTypedProjectionToken(final TypedProjectionToken typedProjectionToken) { ParseFunctionExpressionVisitor.this.handleExpressionStartSymbolToken(typedProjectionToken); } @Override public void handleTypedIdentityToken(final TypedIdentityToken typedIdentityToken) { ParseFunctionExpressionVisitor.this.handleExpressionStartSymbolToken(typedIdentityToken); } @Override public void handleTypedFinalSymbolToken(final TypedFinalSymbolToken typedFinalSymbolToken) { ParseFunctionExpressionVisitor.this.handleExpressionStartSymbolToken(typedFinalSymbolToken); } @Override public void handleProjectionToken(final ProjectionToken projectionToken) { ParseFunctionExpressionVisitor.this.handleExpressionStartSymbolToken(projectionToken); } @Override public void handleIdentifierToken(final IdentifierToken identifierToken) { ParseFunctionExpressionVisitor.this.handleExpressionStartSymbolToken(identifierToken); } @Override public void handleBlindToken(final BlindToken blindToken) { } });
java try { this.expression = Parser.this.parseSingleFunctionExpression(this.model); this.parts.add(this.expression); Parser.this.currentToken().accept(this); } catch (final ParserException e) { this.parserException = e; }
Abstract class for all Modelchecker. * @author tkoenig *
java assert model != null; this.model = model; this.prepareTasks();
java final Set<ModelCheckerTask> instantiatedTasks = new HashSet<ModelCheckerTask>(); try { for (final Class<? extends ModelCheckerTask> taskClass : inTaskClasses) { final Constructor<? extends ModelCheckerTask> constructor = taskClass .getDeclaredConstructor(AbstractModel.class); instantiatedTasks.add(constructor.newInstance(this.model)); } } catch (final Exception ex) { throw new RuntimeException(ex); } return instantiatedTasks; java if (this.getTaskClasses().isEmpty()) { return; } final Set<Class<? extends ModelCheckerTask>> taskClassesCopy = new HashSet<Class<? extends ModelCheckerTask>>( this.getTaskClasses()); final Set<ModelCheckerTask> instantiatedTasks = this .instantiateTasks(taskClassesCopy); Set<ModelCheckerTask> currentTaskGroup = new HashSet<ModelCheckerTask>(); do { for (final ModelCheckerTask instantiatedTask : instantiatedTasks) { final Set<Class<? extends ModelCheckerTask>> predecessorTaskClasses = new HashSet<Class<? extends ModelCheckerTask>>(instantiatedTask.getPredecessorTaskClasses()); predecessorTaskClasses.retainAll(taskClassesCopy); if (predecessorTaskClasses.isEmpty()) { currentTaskGroup.add(instantiatedTask); } } for (final ModelCheckerTask currentTask : currentTaskGroup) { taskClassesCopy.remove(currentTask.getClass()); } this.taskGroups.add(currentTaskGroup); instantiatedTasks.removeAll(currentTaskGroup); currentTaskGroup = new HashSet<ModelCheckerTask>(); } while (!taskClassesCopy.isEmpty()); java /* * Execute each set of tasks that can be executed parallel in given * order. */ for (final Set<ModelCheckerTask> currentTaskGroup : this.taskGroups) { try { /* * Invoke all tasks asynchronously but block until all current * tasks are done. */ final List<Future<ModelCheckerTask.Result>> completedTasks = this.executers .invokeAll(currentTaskGroup); // Handle the completed tasks results for (final Future<ModelCheckerTask.Result> completedTask : completedTasks) { this.handleCompletedTask(completedTask); } } catch (final InterruptedException ex) { throw new RuntimeException("A task execution failed.", ex); } if (this.model.hasErrorType(ModelErrorType.ERROR)) { return; } }
java assert completedTask != null; try { final ModelCheckerTask.Result result = completedTask.get(); result.getErrors(); // none-sense } catch (final InterruptedException ex) { throw new RuntimeException( "The retrieval of a completed tasks result unexpectedly interrupted a thread.", ex); } catch (final ExecutionException ex) { throw new RuntimeException( "The retrieval of a completed tasks result unexpectedly caused an execution to fail.", ex); } java super.finalize(); assert this.executers != null; // Disable new tasks from being submitted this.executers.shutdown(); try { // Wait a while for existing tasks to terminate if (this.executers.awaitTermination(10, TimeUnit.SECONDS)) { return; } // Cancel currently executing tasks this.executers.shutdownNow(); // Wait a while for tasks to respond to being canceled if (!this.executers.awaitTermination(10, TimeUnit.SECONDS)) { System.err.println("Executer pool did not terminate."); } } catch (final InterruptedException ex) { // (Re-)Cancel if current thread also interrupted this.executers.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); }
Constructor.
Performs all registered {@link CheckTask}'s on the Model. Returns the types of Tasks, needed by the ModelChecker. * * @return
Checks the coDomain of a {@link FunctionTypeExpression}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); CoDomainCheckerTask.PREDECESSOR_TASK_CLASSES.add(HierarchyCheckerTask.class);
java super(model); java return Collections.unmodifiableSet(CoDomainCheckerTask.PREDECESSOR_TASK_CLASSES);
java final CoDomainChecker visitor = new CoDomainChecker(); functionTypeExpression.getCoDomainType().accept(visitor);
Constructor to create a {@link CoDomainCheckerTask}.
A visitor to check the coDomain of a {@link FunctionTypeExpression}.
java if (visitee.isEmpty()) { CoDomainCheckerTask.this.getModel().addError(new EmptySumError(visitee)); return; } if (visitee.size() == 1) { CoDomainCheckerTask.this.getModel().addError(new SumContainsOnePartError(visitee)); } this.handleListTypeExpression(visitee);
java if (visitee.isEmpty()) { CoDomainCheckerTask.this.getModel().addError(new EmptyProductError(visitee)); return; } this.handleListTypeExpression(visitee);
java final Iterator<TypeExpression> it = list.iterator(); while (it.hasNext()) { it.next().accept(this); }
This {@link TraversingModelCheckerServiceTask} checks the coercer definitions such that: * If t' is abstract, the (specialization representing) monomorphism is always the set inclusion. If t' is concrete, each concrete type t < t' needs an explicit coercer specification into t' (completeness of concrete coercers): If a concrete type specialises another concrete type directly, the coercer must be provided in the appropriate syntactical clause. Transitivity is given by composition of coercers. (There might be serveral paths. It is not checked if these paths represent the same morphism.) * If an abstract type t specialises a concrete type t', a direct coercer is not required and syntactically impossible. Nevertheless, all concrete (direct or indirect) subtypes t'' of t need a coercer into t'. These coercers can be specified in the definition of t' (if the subtype exists prior to the definition of t') or in the definition of t'' (if t'' becomes a subtype of t after the definition of t'). * This Checks requieres that each TypeOrder between two concrete Types has a coercer. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); CoercerCheckerTask.PREDECESSOR_TASK_CLASSES.add(SubTypeCalculatorTask.class); CoercerCheckerTask.PREDECESSOR_TASK_CLASSES.add(HierarchyCheckerTask.class);
java super(model); java return Collections .unmodifiableSet(CoercerCheckerTask.PREDECESSOR_TASK_CLASSES);
java this.getModel().getCoercerHierarchy().addCoercersFromType(types); // Then check for missing coercers for (final Type type : this.getModel().getTypes()) { if (type.isAbstract()) { continue; } for (final Type subType : type.getSubTypes()) { if (subType.equals(type)) { continue; } if (subType.isAbstract()) { continue; } if (!this.getModel().getCoercerHierarchy() .containsCoercer(subType, type)) { this.getModel().addError( new MissingCoercerError(subType, type)); } } }
Constructor.
This {@link ConstructorGeneratorTask} adds a typed constructor- {@link Function} for each concrete {@link Type} within the Model. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); ConstructorGeneratorTask.PREDECESSOR_TASK_CLASSES .add(GeneralizationReferencerTask.class); ConstructorGeneratorTask.PREDECESSOR_TASK_CLASSES .add(NamedTypeReferenceReferencerTask.class); ConstructorGeneratorTask.PREDECESSOR_TASK_CLASSES .add(SpecializationReferencerTask.class); ConstructorGeneratorTask.PREDECESSOR_TASK_CLASSES .add(TypedFinalMapReferencerTask.class); ConstructorGeneratorTask.PREDECESSOR_TASK_CLASSES .add(TypedIdentityReferencerTask.class); ConstructorGeneratorTask.PREDECESSOR_TASK_CLASSES .add(TypedProjectionReferencerTask.class);
java super(model); java return Collections .unmodifiableSet(ConstructorGeneratorTask.PREDECESSOR_TASK_CLASSES);
java if (!type.isAbstract()) { // Signature final ListTypeExpression domain = type.getType(); final NamedTypeReference codomain = new NamedTypeReference( type.getTokens(), type.getName(), this.getModel()); codomain.setRefersTo(type); final FunctionTypeExpression signature = new FunctionTypeExpression( type.getTokens(), domain, codomain, this.getModel()); // Method final List<FunctionExpression> parts = new ArrayList<FunctionExpression>(); for (int i = 0; i < domain.getSize(); i++) { parts.add(new Projection(new LinkedList<Token>(), i, this.getModel())); } final AbstractConstructorFunctionExpression method = new TypedConstructorFunctionExpression( type.getTokens(), parts, type, this.getModel()); final Function constructor = new Function(type.getTokens(), type.getName(), signature, method); this.getModel().add(constructor); }
Constructor.
Checks a domain of {@link FunctionTypeExpression}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); DomainCheckerTask.PREDECESSOR_TASK_CLASSES.add(HierarchyCheckerTask.class);
java super(model); java return Collections.unmodifiableSet(DomainCheckerTask.PREDECESSOR_TASK_CLASSES);
java final TypeExpression domain = functionTypeExpression.getDomainType(); final DomainChecker visitor = new DomainChecker(); domain.accept(visitor);
Creates a {@link DomainCheckerTask}.
A visitor to check the domain of {@link FunctionTypeExpression}.
java final int size = visitee.getSize(); if (size == 0) { DomainCheckerTask.this.getModel().addError(new EmptySumError(visitee)); return; } else if (size == 1) { DomainCheckerTask.this.getModel().addError(new SumContainsOnePartError(visitee)); } else { this.emptyConstructorAllowed = false; } this.handleListTypeExpression(visitee);
java if (visitee.getSize() == 0) { if (!this.emptyConstructorAllowed) { DomainCheckerTask.this.getModel().addError(new EmptyProductError(visitee)); } return; } else { this.emptyConstructorAllowed = false; } this.handleListTypeExpression(visitee);
java final Iterator<TypeExpression> iterator = listTypeExpression.iterator(); while (iterator.hasNext()) { iterator.next().accept(this); }
A checker to check the following property holds for each pair of methods f1 and f2 for the same function f: domain(f1) <=(abstract) domain(f2) implies codomain(f1) <=(abstract) codomain(f2).
java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); DomainCoDomainSubtypeCheckerTask.PREDECESSOR_TASK_CLASSES .add(CoDomainCheckerTask.class); DomainCoDomainSubtypeCheckerTask.PREDECESSOR_TASK_CLASSES .add(DomainCheckerTask.class);
java super(model); java return Collections .unmodifiableSet(DomainCoDomainSubtypeCheckerTask.PREDECESSOR_TASK_CLASSES);
java for (final List<Function> listOfFunctions : functions) { final int listSize = listOfFunctions.size(); /* * Kleine Optimierung, um zu vermeiden, dass je Funktion immer über die komplette * Liste von Funktionen iteriert werden muss. Dadurch werden zwei Funktion immer nur * einmal verglichen. */ for (int i = 0; i < listSize; i++) { final Function firstFunction = listOfFunctions.get(i); for (int index = i + 1; index < listSize; index++) { final Function secondFunction = listOfFunctions.get(index); if (this.isDomainEqual(firstFunction, secondFunction)) { this.getModel().addError(new DomainConflictError(firstFunction)); this.getModel().addError(new DomainConflictError(secondFunction)); } else if (this.isDomainLess(firstFunction, secondFunction)) { if (!this.isCoDomainLessOrEqual(firstFunction, secondFunction)) { this.addError(secondFunction, firstFunction); } } else if (this.isDomainLess(secondFunction, firstFunction)) { if (!this.isCoDomainLessOrEqual(secondFunction, firstFunction)) { this.addError(firstFunction, secondFunction); } } } } }
java final TypeExpression firstFunctionDomain = this.getDomain(firstFunction); final TypeExpression secondFunctionDomain = this.getDomain(secondFunction); return firstFunctionDomain.concretize(true).equals(secondFunctionDomain.concretize(true));
java final TypeExpression firstFunctionDomain = this.getDomain(firstFunction); final TypeExpression secondFunctionDomain = this.getDomain(secondFunction); return firstFunctionDomain.isSuperTypeOf(secondFunctionDomain, true);
java final TypeExpression firstFunctionCoDomain = this.getCoDomain(firstFunction); final TypeExpression secondFunctionCoDomain = this.getCoDomain(secondFunction); return firstFunctionCoDomain.isSuperTypeOf(secondFunctionCoDomain, true);
java this.getModel().addError(new CoDomainIsNotSubTypeError(errorFunction, other.getType().getCoDomainType()));
java return function.getType().getDomainType();
java return function.getType().getCoDomainType();
Constructor to create a {@link DomainCoDomainSubtypeCheckerTask}.
Returns <code>true</code> iff:<br> * <code>domain(firstFunction).concretize(true).equals(domain(secondFunction).concretize(true)) == true</code><br> * otherwise false.
Returns <code>true</code> iff:<br> * <code>domain(firstFunction).isSuperTypeOf(domain(secondFunction)) == true</code><br> * otherwise false. * * @see TypeExpression#isSuperTypeOf(TypeExpression, boolean)
Returns <code>true</code> iff:<br> * <code>codomain(firstFunction).isSuperTypeOf(codomain(secondFunction)) == true</code><br> * otherwise false. * * @see TypeExpression#isSuperTypeOf(TypeExpression, boolean)
Adds the Model a {@link CoDomainIsNotSubTypeError}.
Returns the domain of the assigned {@link Function}.
Returns the codomain of the assigned {@link Function}.
Tasks for checking that evaluable expressions start with a final map. java PREDECESSOR_TASKS = new HashSet<Class<? extends ModelCheckerTask>>(); PREDECESSOR_TASKS.add(EvaluableFunctionsAreSequentialTask.class);
java super(model); java return PREDECESSOR_TASKS;
java for (final FunctionExpression functionExpression : expressions) { this.checkFunction((SequentialFunctionExpression) functionExpression); }
java final Iterator<FunctionExpression> iterator = expression.iterator(); if (!iterator.hasNext() || !this.isDefinedForEmptyProduct(iterator.next())) { this.getModel().addError(new EvaluableExpressionNotStartingWithFinalMap(expression)); }
java final ConstructorTypeExpression emptyProduct = new ConstructorTypeExpression(this.getModel()); try { expression.getCoDomain(emptyProduct); return true; } catch (final ModelException e) { return false; }
Constructor.
Checker for checking, that every evaluable expression is a sequence.
java super(model); java return Collections.emptySet();
java for (final FunctionExpression expression : expressions) { if (!this.isSequentialExpression(expression)) { this.getModel().addError(new EvaluableExpressionIsNotSequential(expression)); } }
java final ValueWrapper<Boolean> result = new ValueWrapper<Boolean>(); result.setValue(Boolean.FALSE); expression.accept(new FunctionExpressionDefaultVisitor() { @Override public void defaultHandling(final FunctionExpression functionExpression) { } @Override public void handleSequentialFunctionExpression( final SequentialFunctionExpression sequentialFunctionExpression) { result.setValue(Boolean.TRUE); } }); return result.getValue();
Constructor.
Contains necessary tasks to check expressions. @author tkoenig *
java super(model);
Constructor. * @param model
The {@link FunctionTypeConflictDeterminationTask} determines all Function / Type conflicts within the Model. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>();
java super(model); java return Collections .unmodifiableSet(FunctionTypeConflictDeterminationTask.PREDECESSOR_TASK_CLASSES);
java if (!this.getModel().getFunctions(type.getName()).isEmpty()) { this.getModel().addError(new NameConflictError(type)); for (final Function function : this.getModel().getFunctions( type.getName())) { this.getModel().addError(new NameConflictError(function)); } }
Constructor.
The {@link GeneralizationReferencerTask}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); GeneralizationReferencerTask.PREDECESSOR_TASK_CLASSES .add(FunctionTypeConflictDeterminationTask.class);
java super(model); java return Collections .unmodifiableSet(GeneralizationReferencerTask.PREDECESSOR_TASK_CLASSES);
java final Type type = this.getModel().getType(generalization.getTypeName()); if (type == null) { this.getModel().addError(new MissingTypeError(generalization)); } else { generalization.setRefersTo(type); }
Constructor.
The {@link HierarchyCheckerTask} checks that the subtype relation is a hierarchy (antisymmetric).
java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); HierarchyCheckerTask.PREDECESSOR_TASK_CLASSES .add(SubTypeCalculatorTask.class);
java super(model); java return Collections .unmodifiableSet(HierarchyCheckerTask.PREDECESSOR_TASK_CLASSES);
java for (final Type currentSubType : type.getSubTypes()) { if (!currentSubType.equals(type) && currentSubType.getSubTypes().contains(type)) { this.getModel().addError( new SymmetricHierarchyError(type, currentSubType)); } }
Creates a {@link HierarchyCheckerTask}.
The {@link ModelCheckerService} handles the {@link ModelCheckerTask}s which perform checking on the Model, generate elements and set references.
java super(model);
The constructor. * @param model
Abstract class for all Tasks that are checking the model in the {@link ModelCheckerService}.
java this.model = model;
Constructor. * * @param model * The Model the task works on.
Gets a set of {@link ModelCheckerTask} classes that need to be completed * before this one. * * @return A set of {@link ModelCheckerTask} classes
A {@link ModelCheckerTask}'s {@link Result}.
java this.errors.add(error); Adds an error. * * @param error * An error.
A {@link ModelCheckerTask}'s {@link Error}.
The {@link NamedFunctionReferenceReferencerTask} sets all {@link Function} -References within the given Model. If {@link Function}-References refer to a missing {@link Function} a {@link MissingFunctionError} is added to the Model. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); NamedFunctionReferenceReferencerTask.PREDECESSOR_TASK_CLASSES .add(ConstructorGeneratorTask.class);
java super(model); java return Collections .unmodifiableSet(NamedFunctionReferenceReferencerTask.PREDECESSOR_TASK_CLASSES);
java final List<Function> functions = this.getModel().getFunctions(namedFunctionReference.getName()); if (functions.isEmpty()) { this.getModel().addError(new MissingFunctionError(namedFunctionReference)); } else { namedFunctionReference.setRefersTo(functions); }
Constructor.
The {@link NamedTypeReferenceReferencerTask}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); NamedTypeReferenceReferencerTask.PREDECESSOR_TASK_CLASSES .add(FunctionTypeConflictDeterminationTask.class);
java super(model); java return Collections .unmodifiableSet(NamedTypeReferenceReferencerTask.PREDECESSOR_TASK_CLASSES);
java final Type type = this.getModel().getType(namedTypeReference.getName()); if (type == null) { this.getModel().addError(new MissingTypeError(namedTypeReference)); } else { namedTypeReference.setRefersTo(type); }
Constructor.
Abstract checker-task for checking the sets of {@link Type}s and {@link Function}s without iterating recursive over the model.
java super(model); java final Result result = new Result(); this.getModel().accept(new ModelVisitor() { @Override public void handle(final Model model) { //TODO #27153: Needs Refactoring, if Operations are introduced. NonTraversingModelCheckerTask.this.checkFunctions(model.getFunctions(), result); NonTraversingModelCheckerTask.this.checkTypes(model.getTypes(), result); } @Override public void handle(final EvaluableModel evaluableModel) { NonTraversingModelCheckerTask.this.checkEvaluableExpressions( evaluableModel.getEvaluableFunctions(), result); } }); return result;
Checks whether a {@link ProductFunctionExpression} and a {@link ConstructorFunctionExpression} contains at least one part, otherwise an error will be created. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>();
java super(model); java return PREDECESSOR_TASK_CLASSES;
java this.checkPartsSize(productFunctionExpression);
java this.checkPartsSize(constructorFunctionExpression);
java final int size = product.getSize(); if (size == 0) { this.getModel().addError(new EmptyProductError(product)); }
Creates a {@link ProductAndConstructorFunctionExpressionCheckerTask}.
A helper to check that the parts of a {@link ConstructorFunctionExpression} or * {@link ProductFunctionExpression} contains more than one parts.
Checks that a {@link SequentialFunctionExpression} does not end with a {@link FinalMap} or {@link TypedFinalMap} and that a method of a {@link Function} contains only a {@link FinalMap} or {@link TypedFinalMap}, e.g. <code>function x [A-->B] ::= !</code>. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); SequenceDoesNotEndWithFinalMapCheckerTask.PREDECESSOR_TASK_CLASSES .add(HierarchyCheckerTask.class);
java super(model); java return Collections .unmodifiableSet(SequenceDoesNotEndWithFinalMapCheckerTask.PREDECESSOR_TASK_CLASSES);
java final FunctionExpression lastPart = sequentialFunctionExpression.getParts().get(sequentialFunctionExpression.getSize() - 1); lastPart.accept(new FinalMapChecker());
java function.getMethod().accept(new FinalMapChecker());
Constructor.
A visitor to check a {@link FinalMap} or {@link TypedFinalMap}.
java SequenceDoesNotEndWithFinalMapCheckerTask.this.getModel() .addError(new SequenceEndWithFinalMapError(exp));
java this.addError(typedFinalMap);
java this.addError(finalMap);
The {@link SpecializationReferencerTask}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); SpecializationReferencerTask.PREDECESSOR_TASK_CLASSES .add(FunctionTypeConflictDeterminationTask.class);
java super(model); java return Collections .unmodifiableSet(SpecializationReferencerTask.PREDECESSOR_TASK_CLASSES);
java final Type type = this.getModel().getType(specialization.getTypeName()); if (type == null) { this.getModel().addError(new MissingTypeError(specialization)); } else { specialization.setRefersTo(type); }
Constructor.
The {@link SubTypeCalculatorTask} calculates the subtypes for a specific {@link Type}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); SubTypeCalculatorTask.PREDECESSOR_TASK_CLASSES .add(ConstructorGeneratorTask.class);
java super(model); java return Collections .unmodifiableSet(SubTypeCalculatorTask.PREDECESSOR_TASK_CLASSES);
java final Set<Type> res = new HashSet<Type>(); this.calculateSubTypes(type, res); // System.out.println(type.getName() + " : " + res); type.addSubTypes(res);
java if (!subTypes.contains(type)) { subTypes.add(type); for (final TypeOrder currentTypeOrder : type.getHierarchies()) { currentTypeOrder.accept(new TypeOrderVisitor() { @Override public void handle(final Specialization visitee) { // Nothing to do. } /* * type A() generalizes B; --> B is a subtype of A */ @Override public void handle(final Generalization visitee) { final Type subType = visitee.getRefersTo(); // if the generalization does not refer a type, this // generalization will be ignored. if (subType != null) { if (subType.getSubTypes().isEmpty()) { SubTypeCalculatorTask.this.calculateSubTypes( subType, subTypes); } else { subTypes.addAll(subType.getSubTypes()); } } } }); } for (final Type currentType : this.getModel().getTypes()) { if (!currentType.equals(type)) { for (final TypeOrder currentTypeOrder : currentType .getHierarchies()) { currentTypeOrder.accept(new TypeOrderVisitor() { /* * type B() specializes A; --> B is a subtype of A */ @Override public void handle(final Specialization visitee) { final Type referencedType = visitee .getRefersTo(); // if the specialization does not refer a type, // this specialization will be ignored. if (referencedType != null && type.equals(referencedType)) { if (currentType.getSubTypes().isEmpty()) { SubTypeCalculatorTask.this .calculateSubTypes(currentType, subTypes); } else { subTypes.addAll(currentType .getSubTypes()); } } } @Override public void handle(final Generalization visitee) { // Nothing to do. } }); } } } }
Creates a {@link SubTypeCalculatorTask}.
A helper method to calculate the complete set of subtypes for the * assigned {@link Type}.
Checks a {@link SumFunctionExpression}:<br> (1) if <code>{ }</code> (empty sum) a {@link EmptySumError} will be created.<br> (2) if <code>{ .0 }</code> (a sum with only one part) a {@link SumContainsOnePartError} will be created.
java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>();
java super(model); java return PREDECESSOR_TASK_CLASSES;
java if (sumFunctionExpression.getSize() == 0) { this.getModel().addError(new EmptySumError(sumFunctionExpression)); } else if (sumFunctionExpression.getSize() == 1) { this.getModel().addError(new SumContainsOnePartError(sumFunctionExpression)); }
Constructor to create {@link SumFunctionExpressionCheckerTaskTest}.
{@link ModelCheckerTask}, which checks, that all summands in an implicit sum have identity expressions at the beginning. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>();
java super(model); java return PREDECESSOR_TASK_CLASSES;
java final IdentityChecker checker = new IdentityChecker(this.getModel(), result); this.checkForAll(sumFunctionExpression.iterator(), result, checker);
java while (functionExpressionList.hasNext()) { final FunctionExpression currentPart = functionExpressionList.next(); currentPart.accept(visitor); }
Constructor. * * @param model The Model, that shall be checked.
{@link FunctionExpressionVisitor} that decides which expressions are allowed in * the beginning of the summands of a {@link SumFunctionExpression}.
java this.model = model; this.result = result; this.foundIdentity = false; this.inner = false;
java this.model.addError(new SummandDoesNotStartWithIdError(typedProjection));
java this.model.addError(new SummandDoesNotStartWithIdError(typedFinalMap));
java this.model.addError(new SummandDoesNotStartWithIdError(typedConstructorFunctionExpression));
java SummandsAreIdentitiesCheckerTask.this.checkForAll(sumFunctionExpression.iterator(), this.result, this);
java final Iterator<FunctionExpression> sequenceIterator = sequentialFunctionExpression.iterator(); final FunctionExpression first = sequenceIterator.next(); if (this.inner && sequenceIterator.hasNext()) { this.model.addError(new SummandDoesNotStartWithIdError(sequenceIterator.next())); } first.accept(this);
java this.model.addError(new SummandDoesNotStartWithIdError(projection));
java final boolean innerBefore = this.inner; if (!innerBefore) { this.inner = true; } SummandsAreIdentitiesCheckerTask.this.checkForAll(productFunctionExpression.iterator(), this.result, this); if (!innerBefore) { this.inner = false; }
java this.model.addError(new SummandDoesNotStartWithIdError(namedFunctionReference));
java if (this.inner) { return; } if (!this.foundIdentity) { this.foundIdentity = true; } else { this.model.addError(new TooManyIdentitiesError(identity)); }
java this.model.addError(new SummandDoesNotStartWithIdError(finalMap));
java this.model.addError(new SummandDoesNotStartWithIdError(constructorFunctionExpression));
A {@link TraversingModelCheckerServiceTask} iterates over each element of a given Model. For each Element a check method is called. The concrete {@link TraversingModelCheckerServiceTask} can override the check method to "check" the Element or generate other elements.
java super(model); java final Result result = new Result(); this.getModel().accept(new ModelVisitor() { @Override public void handle(final Model model) { for (final Type type : model.getTypes()) { TraversingModelCheckerServiceTask.this.handleType(type, result); } // Functions // TODO #27153: Needs Refactoring, if Operations are introduced. for (final List<Function> functions : model.getFunctions()) { for (final Function function : functions) { TraversingModelCheckerServiceTask.this.handleFunction(function, result); } } } @Override public void handle(final EvaluableModel evaluableModel) { for (final FunctionExpression expression : evaluableModel.getEvaluableFunctions()) { TraversingModelCheckerServiceTask.this.handleFunctionExpression(expression, result); } } }); // return result;
java this.checkType(type, result); for (final TypeOrder to : type.getHierarchies()) { to.accept(new TypeOrderVisitor() { @Override public void handle(final Specialization spezialization) { TraversingModelCheckerServiceTask.this.checkSpecialization(spezialization, result); } @Override public void handle(final Generalization generalization) { TraversingModelCheckerServiceTask.this.checkGeneralization(generalization, result); } }); if (to.hasCoercer()) { this.handleFunctionExpression(to.getCoercer(), result); } } if (!type.isAbstract()) { this.handleTypeExpression(type.getType(), result); }
java this.checkFunction(function, result); this.handleTypeExpression(function.getType(), result); this.handleFunctionExpression(function.getMethod(), result);
java typeExpression.accept(new TypeExpressionVisitor() { private void iterateFurther(final Iterator<TypeExpression> iterator) { while (iterator.hasNext()) { TraversingModelCheckerServiceTask.this.handleTypeExpression(iterator.next(), result); } } @Override public void handle(final NamedTypeReference namedTypeReference) { TraversingModelCheckerServiceTask.this.checkNamedTypeReference(namedTypeReference, result); } @Override public void handle(final FunctionTypeExpression functionTypeExpression) { TraversingModelCheckerServiceTask.this.checkFunctionTypeExpression(functionTypeExpression, result); TraversingModelCheckerServiceTask.this.handleTypeExpression(functionTypeExpression.getDomainType(), result); TraversingModelCheckerServiceTask.this.handleTypeExpression(functionTypeExpression.getCoDomainType(), result); } @Override public void handle(final ConstructorTypeExpression constuctorTypeExpression) { TraversingModelCheckerServiceTask.this.checkConstructorTypeExpression(constuctorTypeExpression, result); this.iterateFurther(constuctorTypeExpression.iterator()); } @Override public void handle(final SumTypeExpression sumTypeExpression) { TraversingModelCheckerServiceTask.this.checkSumTypeExpression(sumTypeExpression, result); this.iterateFurther(sumTypeExpression.iterator()); } @Override public void handle(final SumOfAllTypesExpression visitee) { TraversingModelCheckerServiceTask.this.checkSumOfAllTypes(visitee); } @Override public void handle(final SumOfAllNaryProducts visitee) { TraversingModelCheckerServiceTask.this.checkSumOfAllNaryProducts(visitee); } });
java functionExpression.accept(new FunctionExpressionVisitor() { private void iterateFurther(final Iterator<FunctionExpression> iterator) { while (iterator.hasNext()) { TraversingModelCheckerServiceTask.this.handleFunctionExpression(iterator.next(), result); } } // ListFunctionExpressions @Override public void handleTypedConstructorFunctionExpression( final TypedConstructorFunctionExpression typedConstructorFunctionExpression) { TraversingModelCheckerServiceTask.this.checkTypedConstructorFunctionExpression( typedConstructorFunctionExpression, result); this.iterateFurther(typedConstructorFunctionExpression.iterator()); } @Override public void handleSumFunctionExpression(final SumFunctionExpression sumFunctionExpression) { TraversingModelCheckerServiceTask.this.checkSumFunctionExpression(sumFunctionExpression, result); this.iterateFurther(sumFunctionExpression.iterator()); } @Override public void handleSequentialFunctionExpression( final SequentialFunctionExpression sequentialFunctionExpression) { TraversingModelCheckerServiceTask.this.checkSequentialFunctionExpression( sequentialFunctionExpression, result); this.iterateFurther(sequentialFunctionExpression.iterator()); } @Override public void handleProductFunctionExpression(final ProductFunctionExpression productFunctionExpression) { TraversingModelCheckerServiceTask.this.checkProductFunctionExpression(productFunctionExpression, result); this.iterateFurther(productFunctionExpression.iterator()); } @Override public void handleConstructorFunctionExpression( final ConstructorFunctionExpression constructorFunctionExpression) { TraversingModelCheckerServiceTask.this.checkConstructorFunctionExpression( constructorFunctionExpression, result); this.iterateFurther(constructorFunctionExpression.iterator()); } // AtomicFunctionExpressions @Override public void handleTypedProjection(final TypedProjection typedProjection) { TraversingModelCheckerServiceTask.this.checkTypedProjection(typedProjection, result); } @Override public void handleTypedIdentity(final TypedIdentity typedIdentity) { TraversingModelCheckerServiceTask.this.checkTypedIdentity(typedIdentity, result); } @Override public void handleProjection(final Projection projection) { TraversingModelCheckerServiceTask.this.checkProjection(projection, result); } @Override public void handleNamedFunctionReference(final NamedFunctionReference namedFunctionReference) { TraversingModelCheckerServiceTask.this.checkNamedFunctionReference(namedFunctionReference, result); } @Override public void handleIdentity(final Identity identity) { TraversingModelCheckerServiceTask.this.checkIdentity(identity, result); } @Override public void handleTypedFinalMap(final TypedFinalMap typedFinalMap) { TraversingModelCheckerServiceTask.this.checkTypedFinalMap(typedFinalMap, result); } @Override public void handleFinalMap(final FinalMap finalMap) { TraversingModelCheckerServiceTask.this.checkFinalMap(finalMap, result); } });
This checker checks whether the domain of the method is greater or equal the domain of the function (the method belongs to) and whether the codomain of the function is greater or equal the codomain of the method. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); TypeChecker.PREDECESSOR_TASK_CLASSES .add(DomainCoDomainSubtypeCheckerTask.class);
java super(model); java return Collections .unmodifiableSet(TypeChecker.PREDECESSOR_TASK_CLASSES);
java for (final List<Function> listOfFunctions : functions) { for (final Function function : listOfFunctions) { final FunctionTypeExpression type = function.getType(); final FunctionExpression method = function.getMethod(); final TypeExpression methodDomain = method.getDomain(); final TypeExpression typeDomain = type.getDomainType(); // TODO: true or false? if (!methodDomain.isSuperTypeOf(typeDomain, false)) { this.getModel().addError(new DomainMissmatchError( function, "Method/Function domain mismatch: " + methodDomain.print() + " / " + typeDomain)); } try { // TODO: true or false? final TypeExpression typeCoDomain = type.getCoDomainType(); final TypeExpression methodCoDomain = method.getCoDomain(typeDomain.concretize(false)); if (!typeCoDomain.isSuperTypeOf(methodCoDomain, false)) { this.getModel().addError(new CoDomainMissmatchError( function, "Method/Function co-domain mismatch: " + methodCoDomain.print() + " / " + typeCoDomain)); } } catch (final ModelException e) { e.accept(new ModelExceptionVisitor() { @Override public void handleSequenceDomainCodomainMissmatchException( final SequenceDomainCodomainMissmatchException sequenceDomainCodomainMissmatchException) { TypeChecker.this.getModel().addError(new SequenceDomainCodomainMissmatchError(e.getCodeContainableObject(), e.getMessage())); } @Override public void handleProjectionIndexOutOfBoundsException( final ProjectionIndexOutOfBoundsException projectionIndexOutOfBoundsException) { TypeChecker.this.getModel().addError(new ProjectionIndexOutOfBoundsError(e.getCodeContainableObject(), e.getMessage())); } @Override public void handleNoProjectionableTypeException( final NoProjectionableTypeException noProjectionableTypeException) { TypeChecker.this.getModel().addError(new NoProjectionableTypeError(e.getCodeContainableObject(), e.getMessage())); } @Override public void handleAmbiguousBindingException( AmbiguousBindingException ambiguousBindingException) { TypeChecker.this.getModel().addError(new AmbiguousBindingError(e.getCodeContainableObject(), e.getMessage())); } @Override public void handleMissingBindingException( MissingBindingException missingBindingException) { TypeChecker.this.getModel().addError(new MissingBindingError(e.getCodeContainableObject(), e.getMessage())); } }); } } }
Constructor to create a {@link TypeChecker}.
The {@link TypedFinalMapReferencerTask}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); TypedFinalMapReferencerTask.PREDECESSOR_TASK_CLASSES .add(FunctionTypeConflictDeterminationTask.class);
java super(model); java return Collections .unmodifiableSet(TypedFinalMapReferencerTask.PREDECESSOR_TASK_CLASSES);
java final Type type = this.getModel().getType(typedFinalMap.getTypeName()); if (type == null) { this.getModel().addError(new MissingTypeError(typedFinalMap)); } else { typedFinalMap.setRefersTo(type); }
Constructor.
The {@link TypedIdentityReferencerTask}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); TypedIdentityReferencerTask.PREDECESSOR_TASK_CLASSES .add(FunctionTypeConflictDeterminationTask.class);
java super(model); java return Collections .unmodifiableSet(TypedIdentityReferencerTask.PREDECESSOR_TASK_CLASSES);
java final Type type = this.getModel().getType(typedIdentity.getTypeName()); if (type == null) { this.getModel().addError(new MissingTypeError(typedIdentity)); } else { typedIdentity.setRefersTo(type); }
Constructor.
The {@link TypedProjectionReferencerTask}. java PREDECESSOR_TASK_CLASSES = new HashSet<Class<? extends ModelCheckerTask>>(); TypedProjectionReferencerTask.PREDECESSOR_TASK_CLASSES .add(FunctionTypeConflictDeterminationTask.class);
java super(model); java return Collections .unmodifiableSet(TypedProjectionReferencerTask.PREDECESSOR_TASK_CLASSES);
java final Type type = this.getModel() .getType(typedProjection.getTypeName()); if (type == null) { this.getModel().addError(new MissingTypeError(typedProjection)); } else { typedProjection.setRefersTo(type); }
Constructor.
Abstract class for model builder.
java super(); this.programText = programText; this.prettyText = "Not printed yet!"; java this.prettyText = this.model.print();
java assert this.tokens != null; return this.tokens.getTokenAt(position); java this.tokens = new Scanner(this.programText).scan(); this.model = this.buildModel(new ParserTokenStream(this.tokens));
Constructor.
Formats the model and stores it to the attribute prettyText. Returns the {@link Token} in the {@link TokenStream} at the given * position. * * @pre {@link #build()} has been called before.
Builds a Model based on the program text given while initialized. Template method for building the model from a token stream.
Builds a Model from a given sourceCode. Calls Scanner, Parser and Checker. *
java super(programText);
java final AbstractModel model = new Parser(parserTokenStream).parse(); new ModelCheckerService(model).check(); return model;
A builder for a {@link EvaluableModel}.
java super(programText); this.typeModel = typeModel; this.evaluator = new Evaluator(typeModel);
java final EvaluableModel model = new EvaluableModel(this.typeModel); final List<FunctionExpression> evaluationExpression = new Parser(parserTokenStream).parseEvaluationExpression(model); model.addEvaluableExpressions(evaluationExpression); final ExpressionCheckerService checkerService = new ExpressionCheckerService(model); checkerService.check(); return model; java final EvaluableModel evaluableModel = (EvaluableModel) this.getModel(); final Collection<Data> dataList = new ArrayList<>(); final Iterator<FunctionExpression> iterator = evaluableModel.getEvaluableFunctions().iterator(); while (iterator.hasNext()) { dataList.add(this.evaluator.evaluate(iterator.next())); } return dataList;
Constructor.
Evaluates the evaluable Model. * @throws ModelException
java super(message); this.position = position;
Creates new Exception with given message and position. * * @param message * @param position
java super(message);
Creates new exception with the given message. * * @param message
Objects that have a reference to an type. *
The {@link TypeExpressionToSetOfTypeExpressionConverter} converts the hidden concrete {@link TypeExpression} to a {@code Set} of {@link TypeExpression} representing its sum variant.
java assert typeExpression != null; typeExpression.accept(this); return this.subTypes;
java assert visitee.getParts() != null; assert visitee.getSize() > 0; this.subTypes = this.asSet(visitee.getParts());
java this.subTypes = this.asSet(visitee);
java this.subTypes = this.asSet(visitee);
java this.subTypes = this.asSet(visitee);
java final Set<TypeExpression> set = new HashSet<TypeExpression>(5); set.add(type); return set;
java return new HashSet<TypeExpression>(types);
java assert false;
java assert false; Converts the given {@link TypeExpression} to a {@link Set} of * {@link TypeExpression} Parts..
Convert a single {@link TypeExpression} to a {@code Set} containing the * {@link TypeExpression} as its single element. * * @param type * @return
Convert a {@code Collection} of {@link TypeExpression}s to a unified * {@code Set} containing the {@code Collections}'s elements. * * @param types * @return
Simple utility to wrap primitives. @param <E> the type of ther wrapped value
Provides utility methods for loading resources from the classpath. It uses the current's {@link Thread} context {@link ClassLoader} for all methods {@code *FromClassPath()}. @author Stefan K. Christian java // no instantiation!
java assert classPath != null; return new File(uriFromClassPath(classPath));
java assert classPath != null; final ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); final URL resourceUrl = classLoader.getResource(classPath); if (resourceUrl == null) { throw new FileNotFoundException(classPath); } return resourceUrl.toURI();
java assert cls != null; return cls.getPackage().getName().replaceAll("\\.", "/").concat("/");
Class containing utilities to modify strings. * * java // no instantiation!
java assert s != null; /* * Check whether the provided string is empty. If true, return the empty * string; otherwise proceed. */ if (s.isEmpty()) { return s; } /* * Create a (read-only) character iterator in order to iterate through * the input strings characters. */ final StringCharacterIterator characterIterator = new StringCharacterIterator( s); /* * Create a (writable) output buffer in order to store all * none-whitespace characters of the input string. As the result is * expected to be equal or smaller in length, the output buffer is * created with length(<input string>) capacity. */ final StringBuilder resultBuffer = new StringBuilder(s.length()); /* * At least one character can be expected at this point. Repeat until * the next character is the end of the string. */ do { // Retrieve the current character final char currentCharacter = characterIterator.current(); /* * Check whether the current character is a whitespace character. If * true, continue with the next character; otherwise proceed. */ if (Character.isWhitespace(currentCharacter)) { continue; } // Append the none-whitespace character to the output buffer resultBuffer.append(currentCharacter); } while (characterIterator.next() != CharacterIterator.DONE); // Emit the result return resultBuffer.toString();
java final int size = (int) file.length(); int charsRead = 0; final Reader in = new InputStreamReader(new FileInputStream(file), UTF8); final char[] data = new char[size]; while (in.ready()) { charsRead += in.read(data, charsRead, size - charsRead); } in.close(); final String raw = String.valueOf(data, 0, charsRead); return raw;
collection of constants for exceptions. * @author bbodensieck
collection of constants for button-actions. * @author tkoenig
Utility to mark given Errors within the set {@link JTextComponent} <comp> whith a given {@link Highlighter}. occurrences. *
java this.comp = comp; this.initPainters(); java this.painters = new HashMap<ModelErrorType, HighlightPainter>(); this.painters.put(ModelErrorType.ERROR, new UnderlineHighlightPainter(Color.red)); this.painters.put(ModelErrorType.INFO, new UnderlineHighlightPainter(Color.green)); this.painters.put(ModelErrorType.STYLE, new UnderlineHighlightPainter(Color.blue)); this.painters.put(ModelErrorType.WARNING, new UnderlineHighlightPainter(Color.orange));
java final int firstOffset = -1; final Highlighter highlighter = this.comp.getHighlighter(); // Remove any existing highlights final Highlighter.Highlight[] highlights = highlighter.getHighlights(); for (final Highlight h : highlights) { if (h.getPainter() instanceof UnderlineHighlightPainter) { highlighter.removeHighlight(h); } } // Sort errors first by thier ModelErrorType, so that higher Errors are // marked on top. final SortedMap<ModelErrorType, List<ModelError>> sortedErr = new TreeMap<ModelErrorType, List<ModelError>>(); for (final ModelError modelError : errors) { if (sortedErr.get(modelError.getErrorType()) == null) { sortedErr.put(modelError.getErrorType(), new LinkedList<ModelError>()); } sortedErr.get(modelError.getErrorType()).add(modelError); } for (final Map.Entry<ModelErrorType, List<ModelError>> errorSet : sortedErr.entrySet()) { for (final ModelError error : errorSet.getValue()) { for (final Token token : error.getObject().getTokens()) { try { highlighter.addHighlight(token.getPosition(), token.getEndPosition(), this.getPainter(error)); } catch (final BadLocationException e) { // Nothing to do } } } } return firstOffset;
java return this.painters.get(error.getErrorType()); Removes all old highlights from the text and marks all given ranges. * * @param ranges * @return
Creates new {@link ErrorMarker} to mark Error-Positions in given * {@link JTextComponent} <comp>. <comp>. * * @param comp
Table model for {@link ModelError}s. *
java super(); this.errors = errors; java return this.errors.size(); java return COLUMN_COUNT;
java final ModelError error = this.errors.get(rowIndex); switch (columnIndex) { case COL_STARTPOS: //TODO ML MODIFIED ERROR-OUTPUT return error.getTokens().size() == 0 ? 0 : error.getTokens().getFirst().getPosition(); case COL_OBJECTNAME: return error.getName(); case COL_ERRORNAME: return error.getErrorMessage(); case COL_ERRORTYPE: return error.getErrorType(); default: return "Column not defined."; }
java switch (column) { case COL_STARTPOS: return TextConstants.POSITION_LABEL; case COL_OBJECTNAME: return TextConstants.OBJECT_NAME_LABEL; case COL_ERRORNAME: return TextConstants.ERROR_MESSAGE_LABEL; case COL_ERRORTYPE: return TextConstants.ERROR_TYPE_LABEL; default: return TextConstants.COLUMN_NOT_DEFINED_LABEL; }
java return this.errors.get(row); java final Iterator<ModelError> iterator = this.errors.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } this.fireTableDataChanged();
Creates new TableModel for the given Errors. * * @param errors
Returns the {@link ErrorMessage} at the given <row> in the table. * * @param row * @return
Remove all elements from tableModel and trigger the * TableDataChange-Event.
Class for Highlighting Syntax elements in editor.
java super(); this.textPane = textPane; this.styles = new ArrayList<StyleClass>(); java this.textPane.getDocument().addDocumentListener(this.documentListener); java this.textPane.getDocument().removeDocumentListener(this.documentListener);
java if (e.getLength() != 0) { new Thread(new Runnable() { @Override public void run() { try { final String text = e.getDocument().getText(0, e.getDocument().getLength()); final Scanner scanner = new Scanner(text); final TokenStream tokenStream = scanner.scan(); SyntaxHighlighter.this.highlight(tokenStream.iterator()); } catch (final BadLocationException e1) { } catch (final ScannerException e1) { } } }).start(); }
java final StyleClass styleClass = new StyleClass(); styleClass.clazz = cls; styleClass.style = style; this.insertStyle(styleClass);
java for (int i = 0; i < this.styles.size(); i++) { final StyleClass current = this.styles.get(i); if (current.clazz.isAssignableFrom(styleClass.clazz)) { this.styles.add(i, styleClass); return; } } this.styles.add(styleClass);
java final SimpleAttributeSet defaultAttributes = new SimpleAttributeSet(); StyleConstants.setBold(defaultAttributes, false); StyleConstants.setForeground(defaultAttributes, this.textPane.getForeground()); this.textPane.getStyledDocument().setCharacterAttributes( 0, this.textPane.getStyledDocument().getLength(), defaultAttributes, true); while (tokens.hasNext()) { final Token token = tokens.next(); final AttributeSet style = this.getStyle(token); if (style != null) { this.highlight(token, style); } }
java this.textPane.getStyledDocument().setCharacterAttributes( token.getPosition(), token.getBruttoLength(), style, false);
java // Because of the insert mechanism it's guaranteed that // specific styles are final in front of final general styles. for (final StyleClass style : this.styles) { if (style.clazz.isAssignableFrom(token.getClass())) { return style.style; } } return null; Installs the syntax highlighting. Disables syntax highlighting. Highlights syntax element in the editor.
Creates a new {@link SyntaxHighlighter} for this {@link JTextPane}.
Registers a style for the specific token class.
Represents a set of attributes for a specific kind of token.
collection of constants for view elements. * @author bbodensieck
Painter for UnderliningHiglighter. @author Sönke *
java color = c;
java g.setColor(color == null ? c.getSelectionColor() : color); Rectangle alloc = null; if (offs0 == view.getStartOffset() && offs1 == view.getEndOffset()) { if (bounds instanceof Rectangle) { alloc = (Rectangle) bounds; } else { alloc = bounds.getBounds(); } } else { try { final Shape shape = view.modelToView(offs0, Position.Bias.Forward, offs1, Position.Bias.Backward, bounds); alloc = (shape instanceof Rectangle) ? (Rectangle) shape : shape.getBounds(); } catch (final BadLocationException e) { return null; } } final FontMetrics fm = c.getFontMetrics(c.getFont()); final int baseline = alloc.y + alloc.height - fm.getDescent() + 1; g.drawLine(alloc.x, baseline, alloc.x + alloc.width, baseline); g.drawLine(alloc.x, baseline + 1, alloc.x + alloc.width, baseline + 1); return alloc;
Creates new UnderlineHighligtPainter that uses the given {@link Color} c. * * @param c
Highlighter that underlines given selections. *
java painter = c == null ? SHARED_PAINTER : new UnderlineHighlightPainter(c);
java return addHighlight(startPos, endPos, painter);
java if (!newValue) { throw new IllegalArgumentException( "UnderlineHighlighter only draws layered highlights"); } super.setDrawsLayeredHighlights(true); Convenience method to add a highlight with the default painter. * * @param startPos * @param endPos * @return * @throws BadLocationException
Creates new UnderlineHighliter, that uses the given {@link Color} c. * * @param c
View for displaying and editing sourceCode. *
java super(); initialize(); getTextArea().setText(prettyText); java this.setSize(1000, 800); setContentPane(getJContentPane()); setTitle("Pretty Print");
Creates new PrintView to display the given String <prettyText>. * * @param prettyText
java super(); this.controller = controller; java this.setSize(1000, 800); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setJMenuBar(this.getMyMenuBar()); this.setContentPane(this.getMainSplit()); this.setTitle(TextConstants.TITLE_LABEL); java ((ModelErrorTableModel) this.getErrorTable().getModel()) .removeAllElements(); java if (this.errorContentPane == null) { this.errorContentPane = new JPanel(); final BorderLayout errorContentPaneLayout = new BorderLayout(); this.errorContentPane.setLayout(errorContentPaneLayout); this.errorContentPane.add(this.getJScrollPane1(), BorderLayout.NORTH); } return this.errorContentPane;
java this.syntaxHighlighter.uninstall(); this.getTextArea().setText(contents); this.syntaxHighlighter.install(); java final int length = this.getTextArea().getDocument().getLength(); try { return this.getTextArea().getDocument().getText(0, length); } catch (final BadLocationException e) { return StringUtils.EMPTY; }
java this.setCheckStatus(e.getMessage(), Color.RED);
java this.setCheckStatusWithoutPosition(e); this.getTextArea().setCaretPosition(e.getPosition()); this.getTextArea().getCaret().setVisible(true); this.getTextArea().requestFocus(); this.highlightWrongInput(e);
java final Highlighter highlighter = this.getTextArea().getHighlighter(); try { highlighter.addHighlight(e.getPosition(), e.getPosition() + 1, new DefaultHighlighter.DefaultHighlightPainter(Color.RED)); } catch (final BadLocationException e1) { // FIXME: Logger! }
java this.checkStatusBar.setForeground(color); this.checkStatusBar.setText(message); synchronized (this) { if (this.checkStatusEraser != null && this.checkStatusEraser.isAlive()) { this.checkStatusEraser.interrupt(); } else { this.checkStatusEraser = new Thread(new Runnable() { @Override public void run() { try { synchronized (View.this) { View.this.wait(ERASER_INTERVAL); // @jve:decl-index=0: View.this.checkStatusBar.setText(StringUtils.EMPTY); } } catch (final InterruptedException e) { // TODO: Logger return; } } }); this.checkStatusEraser.start(); } }
java this.getFileStatusBar().setText(message); synchronized (this) { if (this.fileStatusEraser != null && this.fileStatusEraser.isAlive()) { this.fileStatusEraser.interrupt(); } else { this.fileStatusEraser = new Thread(new Runnable() { @Override public void run() { try { synchronized (View.this) { View.this.wait(ERASER_INTERVAL); // @jve:decl-index=0: View.this.fileStatusBar.setText(StringUtils.EMPTY); } } catch (final InterruptedException e) { // TODO: Logger return; } } }); this.fileStatusEraser.start(); } } java if (this.fileToolBar == null) { this.fileStatusBar = new JLabel(); this.fileStatusBar.setText(StringUtils.EMPTY); this.fileToolBar = new JToolBar(); this.fileToolBar.add(this.fileStatusBar); } return this.fileToolBar;
java textAreaToEdit.setFont(new Font("Courier", Font.PLAIN, DEFAULT_FONT_SIZE)); textAreaToEdit.getDocument().addDocumentListener(this.controller); final UndoManager undo = new UndoManager(); final Document doc = textAreaToEdit.getDocument(); // Listen for undo and redo events doc.addUndoableEditListener(new UndoableEditListener() { @Override public void undoableEditHappened(final UndoableEditEvent evt) { undo.addEdit(evt.getEdit()); } }); // Create an undo action and add it to the text component textAreaToEdit.getActionMap().put("Undo", new AbstractAction("Undo") { @Override public void actionPerformed(final ActionEvent evt) { try { if (undo.canUndo()) { undo.undo(); } } catch (final CannotUndoException e) { } } }); // Bind the undo action to ctl-Z textAreaToEdit.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo"); // Create a redo action and add it to the text component textAreaToEdit.getActionMap().put("Redo", new AbstractAction("Redo") { @Override public void actionPerformed(final ActionEvent evt) { try { if (undo.canRedo()) { undo.redo(); } } catch (final CannotRedoException e) { // TODO: Logger } } }); // Bind the redo action to ctl-Y textAreaToEdit.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo"); // DEBUG: tells the the Scanner token and its model objects of the // caret position // this.textArea.addCaretListener(new CaretListener() { // // @Override // public void caretUpdate(final CaretEvent arg0) { // final int position = arg0.getDot(); // if (View.this.builder != null // && View.this.builder.getModel() != null) { // final StringBuilder text = new StringBuilder("Token: "); // text.append(View.this.builder.getTokenAt(position)); // text.append(" Objects: "); // text.append(View.this.builder.getObjectsAt(position)); // View.this.setCheckStatus(text.toString(), Color.BLACK); // } // } // }); java if (this.textArea == null) { this.textArea = new JTextPane(); this.initEditorTextPanel(this.textArea); this.initHighlighter(); } return this.textArea; java this.syntaxHighlighter = new SyntaxHighlighter(this.textArea); final SimpleAttributeSet keywordStyle = new SimpleAttributeSet(); StyleConstants.setBold(keywordStyle, true); StyleConstants.setForeground(keywordStyle, new Color(0x7f, 0x00, 0x55)); this.syntaxHighlighter.registerStyle(KeyWordToken.class, keywordStyle); final SimpleAttributeSet commentStyle = new SimpleAttributeSet(); StyleConstants.setItalic(commentStyle, true); StyleConstants.setForeground(commentStyle, Color.GREEN); this.syntaxHighlighter.registerStyle(CommentToken.class, commentStyle); java if (this.evaluateButton == null) { this.evaluateButton = new JButton(); this.evaluateButton.setText("Evaluate"); this.evaluateButton.setEnabled(false); this.evaluateButton.setActionCommand(ButtonActionConstants.EVALUATE); this.evaluateButton.addActionListener(this.controller); } return this.evaluateButton;
java final int row = this.errorTable.convertRowIndexToModel(this.errorTable.getSelectedRow()); final ModelError error = ((ModelErrorTableModel) this.errorTable.getModel()).getErrorAtRow(row); this.getTextArea().select( error.getObject().getTokens().size() == 0 ? 0 : error .getObject().getTokens().getFirst().getPosition(), error.getObject().getTokens().size() == 0 ? 0 : error .getObject().getTokens().getLast().getEndPosition()); this.getTextArea().requestFocusInWindow(); java if (this.errorTable == null) { this.errorTable = new JTable(); this.errorTable .setSelectionMode(ListSelectionModel.SINGLE_SELECTION); this.errorTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent evt) { View.this.errorSelected(evt); } }); this.errorTable.setModel(new ModelErrorTableModel(Collections.<ModelError>emptyList())); this.errorTable.getColumnModel().getColumn(0).setPreferredWidth(50); this.errorTable.getColumnModel().getColumn(0).setMaxWidth(100); this.errorTable.getColumnModel().getColumn(1) .setPreferredWidth(200); this.errorTable.getColumnModel().getColumn(1).setMinWidth(200); this.errorTable.getColumnModel().getColumn(2) .setPreferredWidth(200); this.errorTable.getColumnModel().getColumn(2).setMinWidth(100); this.errorTable.getTableHeader().setFont( new Font(Font.SANS_SERIF, Font.BOLD, 12)); } return this.errorTable; java if (this.menuBar == null) { this.menuBar = new JMenuBar(); this.menuBar.add(this.getMnFile()); this.menuBar.add(this.getMnOptions()); } return this.menuBar;
java final Font currentFont = this.getTextArea().getFont(); final Font newFont = currentFont.deriveFont(0.0f + currentFont.getSize() + amount); this.getTextArea().setFont(newFont);
java final Font currentFont = this.getTextAreaTesting().getFont(); final Font newFont = currentFont.deriveFont(0.0f + currentFont.getSize() + amount); this.getTextAreaTesting().setFont(newFont); java if (this.tabbedPane == null) { this.tabbedPane = new JTabbedPane(); this.tabbedPane.addTab(TextConstants.MODEL_LABEL, this.getMainPanel()); this.tabbedPane.addTab(TextConstants.TESTING_LABEL, this.getTestingPanel()); } return this.tabbedPane; initialize the view. Remove all elements from <b>errorTable.</b> set the text of parameter to model-textarea. * @param contents
Returns the text of model-textarea. * @return Create a highlight for the complete textual content. * @param e
Create a highlight if necessary. * @param e
Create a highlight for the parameter. * @param e
Setzt die uebergebene <code>message</code> in die Statusleiste der View. * * @param message
Initialize and returns the textarea. This method initializes evaluateButton. * * @return javax.swing.JButton initialize and returns the errortable. * @return
Returns a Tabpane to display model- and testing-Panel. * @return
Constructor for new View. Shows up the openDialog.
Setzt die uebergebene Statusnachricht in der uebegerbenen Farbe. * @param message * @param color
Initialize the parameter <b>textArea</b> and add useful actions * (shortcuts..). <br/> * <b>Precondition:</b> The parameter have to be not null! * * @param textAreaToEdit
Simple controller to handle user interactions. * @author tkoenig * java this.initView(); this.doOpenAction(); this.getView().setVisible(true);
java this.currentFile = new File(filePath); this.initView(); this.loadContentFromFile(); this.getView().setVisible(true); java this.view = new View(this); this.getView().initialize(); this.getView().addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(final java.awt.event.WindowEvent e) { if (ViewController.this.dirty) { ViewController.this.trySaveAction(); } } });
java final String currentActionCommand = e.getActionCommand(); if (currentActionCommand.equals(ButtonActionConstants.CHECK_SYNTAX)) { this.doSyntaxCheck(); } else if (currentActionCommand.equals(ButtonActionConstants.NEW)) { this.doNewAction(); } else if (currentActionCommand.equals(ButtonActionConstants.OPEN)) { this.doOpenAction(); } else if (currentActionCommand.equals(ButtonActionConstants.SAVE)) { this.doSaveAction(); } else if (currentActionCommand.equals(ButtonActionConstants.SAVE_AS)) { this.doSaveAsAction(); } else if (currentActionCommand.equals(ButtonActionConstants.PRINT)) { this.doPrintAction(); } else if (currentActionCommand.equals(ButtonActionConstants.EVALUATE)) { this.doEvaluationAction(); } java if (this.getView().getTabbedPane().getSelectedIndex() == 0) { this.doModelSyntaxCheck(); } else { this.doExpressionSyntaxCheck(); } java this.getView().getTextArea().getHighlighter().removeAllHighlights(); this.builder = new Builder(this.getView().getText()); try { this.builder.build(); if (this.builder.getModel().hasNoErroneousTypesOrFunctions()) { this.getView().setCheckStatus(TextConstants.SYNTAX_OK_MESSAGE, Color.BLACK); this.getView().getPrintButton().setEnabled(true); this.getView().getEvaluateButton().setEnabled(true); } this.refreshErrors(this.builder.getModel()); this.getView().getSyntaxHighlighter() .highlight(this.builder.getTokens()); } catch (final FromTextException e) { // TODO: LOGGER! this.getView().setCheckStatus(e); } java this.getView().getTextAreaTesting().getHighlighter() .removeAllHighlights(); if (this.builder != null && this.builder.getModel() != null) { final AbstractModel checkedModel = this.builder.getModel(); this.evaluableModelBuilder = new EvaluableModelBuilder(this .getView().getTextAreaTesting().getText(), checkedModel); try { this.evaluableModelBuilder.build(); if (this.evaluableModelBuilder.getModel() .hasNoErroneousTypesOrFunctions()) { this.getView().setCheckStatus(TextConstants.SYNTAX_OK_MESSAGE, Color.BLACK); this.getView().getPrintButton().setEnabled(true); this.getView().getEvaluateButton().setEnabled(true); } this.refreshErrors(this.evaluableModelBuilder.getModel()); } catch (final FromTextException e) { this.getView().setCheckStatus(e); } } java if (this.currentFile != null) { final String contents = StringUtils.openFile(this.currentFile); this.getView().setText(contents); this.setDirty(); this.resetBuilder(); } java if (this.dirty) { this.trySaveAction(); } this.currentFile = null; this.getView().setText(StringUtils.EMPTY); this.resetBuilder(); java if (this.dirty) { this.trySaveAction(); } try { if (JFileChooser.APPROVE_OPTION == this.getFileChooser() .showDialog(this.getView(), TextConstants.OPEN_PROGRAM_FILE_MESSAGE)) { this.currentFile = this.getFileChooser().getSelectedFile(); this.getView().removeErrorsFrmTable(); this.loadContentFromFile(); } else { this.getView().setText(StringUtils.EMPTY); this.setDirty(); this.resetBuilder(); } } catch (final IOException e) { // TODO: LOGGER this.getView().setFileStatus(e.getMessage()); } java if (this.evaluableModelBuilder != null) { try { this.evaluableModelBuilder.build(); final String evaluate = this.evaluableModelBuilder.evaluate().toString(); this.getView() .getTextAreaTesting() .setText( this.getView().getTextAreaTesting().getText() + StringUtils.LINE_BREAK + evaluate); } catch (final FromTextException e) { // TODO: Logger! this.getView().setCheckStatus(e); } catch (final ModelException e) { // TODO: Logger! - } // TODO: Do evaluation here }
java try { Files.write(contents, file, Charsets.UTF_8); return true; } catch (final IOException e) { return false; } java if (JFileChooser.APPROVE_OPTION == this.getFileChooser().showDialog( this.getView(), TextConstants.SAVE_AS_PROGRAM_FILE_MESSAGE)) { this.currentFile = this.getFileChooser().getSelectedFile(); this.doSaveAction(); } java if (this.currentFile == null) { this.doSaveAsAction(); } else { if (this.doSaveFile(this.currentFile, this.getView().getTextArea() .getText())) { this.getView().setFileStatus(this.getSavedMessage()); this.dirty = false; this.doSyntaxCheck(); } else { this.getView().setFileStatus(this.getImpossibleSaveMessage()); } } java this.builder.prettyPrint(); new PrintView(this.builder.getPrettyText()).setVisible(true); java final int value = JOptionPane.showConfirmDialog(this.getView(), TextConstants.SAVE_CHANGES_QUESTION, TextConstants.UNSAVED_CHANGES_MESSAGE, JOptionPane.YES_NO_OPTION); switch (value) { case JOptionPane.YES_OPTION: if (this.currentFile != null) { this.doSaveFile(this.currentFile, this.getView().getTextArea() .getText()); } else { this.doSaveAsAction(); } break; case JOptionPane.NO_OPTION: break; default: break; }
java final List<ModelError> errors = new ArrayList<ModelError>( inModel.getErrors()); new ErrorMarker(this.getView().getTextArea()).mark(errors); final ModelErrorTableModel tableModel = new ModelErrorTableModel(errors); this.getView().getErrorTable().setModel(tableModel); final TableRowSorter<ModelErrorTableModel> sorter = new TableRowSorter<ModelErrorTableModel>( tableModel); sorter.setComparator(0, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { return o1.compareTo(o2); } }); this.getView().getErrorTable().setRowSorter(sorter); java return TextConstants.CANNOT_SAVE_LABEL + this.currentFile; java return TextConstants.SAVED_TO_LABEL + this.currentFile.getAbsolutePath(); java this.dirty = true; this.getView().getPrintButton().setEnabled(false); this.getView().getEvaluateButton().setEnabled(false); java this.builder = null; this.getView().setCheckStatus(StringUtils.EMPTY, Color.BLACK);
java this.setDirty();
java this.setDirty();
Default constructor. * * @throws IOException
Create a instance of controller and open selected file. * * @param string * @throws IOException
Initialisiert die Viewschicht. * * @throws IOException Creates and calls a new {@link Builder} for checking the sourceCode. execute syntax check for model-tab. execute syntax check for testing-tab. Reads content from the currentFile and sets its content to the textArea. * * @throws IOException Clear file selection, flags and view-instance. Shows an FileChooser for selection of an input file with sourcCode to * edit. Asks for possibly non-saved Changes to save before, then sets the * text to the content of the selected file. Evaluate entered expression(s). Try to save current file. <br/> * Returns true, iff the save-process complete successful.
Writes the current contents to file. Retrieves pretty formatted SourceCode from {@link Builder} and creates * new PrintView for it. Shows a dialog with "Save changes?"-Question. <br/> * If user confirms, the changes will be saved. refresh entries in error-table. * * @param inModel
Returns a message as string about not successful save-action. * * @return Returns a message as string about successful save-action. * * @return Sets the dirty flag and disables the print button. reset the builder and clear checkstatus-bar.
Simple Class for starting the GUI. * @author Sönke *
java UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (args.length == 1) { new ViewController(args[0]); } else { new ViewController(); }
java
java final Collection<ModelError> modelErrors = new ArrayList<ModelError>(); for (final Collection<ModelError> current : this.errors.values()) { modelErrors.addAll(current); } return modelErrors; java return this.model; java return this.evaluableFunctions; java return this.type; java return this.tokens; java return this.domainType; java return Collections.unmodifiableCollection(this.parts); java return this.types.values(); java return this.coercerHierarchy; java return this.name; java return this.result; java return this.type; java return this.hierarchies; java return this.tokens; java return this.name; java return this.tokens; java return this.typeName; java return this.tokens; java return this.typeName; java return this.typeName; java return this.typeName; java assert this.tokens != null; return this.tokens.iterator(); java return this.model; java return this.prettyText; java if (this.taskClasses == null) { this.taskClasses = new HashSet<Class<? extends ModelCheckerTask>>(); this.taskClasses.add(FunctionTypeConflictDeterminationTask.class); this.taskClasses.add(ConstructorGeneratorTask.class); this.taskClasses.add(NamedFunctionReferenceReferencerTask.class); this.taskClasses.add(GeneralizationReferencerTask.class); this.taskClasses.add(NamedTypeReferenceReferencerTask.class); this.taskClasses.add(SpecializationReferencerTask.class); this.taskClasses.add(TypedFinalMapReferencerTask.class); this.taskClasses.add(TypedProjectionReferencerTask.class); this.taskClasses.add(TypedIdentityReferencerTask.class); this.taskClasses.add(SubTypeCalculatorTask.class); this.taskClasses.add(CoercerCheckerTask.class); this.taskClasses.add(SummandsAreIdentitiesCheckerTask.class); this.taskClasses.add(DomainCoDomainSubtypeCheckerTask.class); this.taskClasses .add(SequenceDoesNotEndWithFinalMapCheckerTask.class); this.taskClasses.add(SumFunctionExpressionCheckerTask.class); this.taskClasses .add(ProductAndConstructorFunctionExpressionCheckerTask.class); this.taskClasses.add(CoDomainCheckerTask.class); this.taskClasses.add(DomainCheckerTask.class); this.taskClasses.add(TypeChecker.class); this.taskClasses.add(EvaluableFunctionsAreSequentialTask.class); this.taskClasses.add(EvaluableExpressionStartFromEmptyProductTask.class); } return this.taskClasses; java if (this.taskClasses == null) { this.taskClasses = new HashSet<Class<? extends ModelCheckerTask>>(); this.taskClasses.add(FunctionTypeConflictDeterminationTask.class); this.taskClasses.add(ConstructorGeneratorTask.class); this.taskClasses.add(NamedFunctionReferenceReferencerTask.class); this.taskClasses.add(GeneralizationReferencerTask.class); this.taskClasses.add(NamedTypeReferenceReferencerTask.class); this.taskClasses.add(SpecializationReferencerTask.class); this.taskClasses.add(TypedFinalMapReferencerTask.class); this.taskClasses.add(TypedIdentityReferencerTask.class); this.taskClasses.add(TypedProjectionReferencerTask.class); this.taskClasses.add(SubTypeCalculatorTask.class); this.taskClasses.add(HierarchyCheckerTask.class); this.taskClasses.add(CoercerCheckerTask.class); this.taskClasses.add(SummandsAreIdentitiesCheckerTask.class); this.taskClasses.add(DomainCoDomainSubtypeCheckerTask.class); this.taskClasses .add(SequenceDoesNotEndWithFinalMapCheckerTask.class); this.taskClasses.add(SumFunctionExpressionCheckerTask.class); this.taskClasses .add(ProductAndConstructorFunctionExpressionCheckerTask.class); this.taskClasses.add(CoDomainCheckerTask.class); this.taskClasses.add(DomainCheckerTask.class); this.taskClasses.add(TypeChecker.class); } return this.taskClasses; java return Collections.unmodifiableSet(this.errors); java return position; java return this.startPosition; java if (jContentPane == null) { jContentPane = new JPanel(); jContentPane.setLayout(new BorderLayout()); jContentPane.add(getScrollPane(), BorderLayout.CENTER); } return jContentPane; java if (scrollPane == null) { scrollPane = new JScrollPane(); scrollPane.setViewportView(getTextArea()); } return scrollPane; java if (textArea == null) { textArea = new JTextArea(); } return textArea; java if (this.jContentPane == null) { this.jContentPane = new JPanel(); this.jContentPane.setLayout(new BorderLayout()); this.jContentPane.add(this.getMainToolBar(), BorderLayout.SOUTH); this.jContentPane.add(this.getFileToolBar(), BorderLayout.NORTH); this.jContentPane.add(this.getTabbedPane(), BorderLayout.CENTER); // this.jContentPane.add(this.getMainPanel(), BorderLayout.CENTER); } return this.jContentPane; java if (this.mainToolBar == null) { this.checkStatusBar = new JLabel(); this.checkStatusBar.setText(StringUtils.EMPTY); this.distanceLabel2 = new JLabel(); this.distanceLabel2.setText(TextConstants.DISTANCE_LABEL); this.mainToolBar = new JToolBar(); this.mainToolBar.add(this.getCheckButton()); this.mainToolBar.add(this.getPrintButton()); this.mainToolBar.add(this.getEvaluateButton()); this.mainToolBar.add(this.distanceLabel2); this.mainToolBar.add(this.checkStatusBar); } return this.mainToolBar; java if (this.checkButton == null) { this.checkButton = new JButton(); this.checkButton.setText(TextConstants.CHECK_LABEL); this.checkButton.setActionCommand(ButtonActionConstants.CHECK_SYNTAX); this.checkButton.addActionListener(this.controller); } return this.checkButton; java if (this.mainPanel == null) { this.mainPanel = new JPanel(); this.mainPanel.setLayout(new BorderLayout()); this.mainPanel.add(this.getTextScrollPane(), BorderLayout.CENTER); } return this.mainPanel; java if (this.textScrollPane == null) { this.textScrollPane = new JScrollPane(); this.textScrollPane.setViewportView(this.getTextArea()); } return this.textScrollPane; java if (this.jScrollPane1 == null) { this.jScrollPane1 = new JScrollPane(); this.jScrollPane1.setViewportView(this.getErrorTable()); } return this.jScrollPane1; java if (this.mainSplit == null) { this.mainSplit = new JSplitPane(); this.mainSplit.setOrientation(JSplitPane.VERTICAL_SPLIT); this.mainSplit.setDividerLocation(600); this.mainSplit.setDividerSize(3); this.mainSplit.setTopComponent(this.getJContentPane()); this.mainSplit.setBottomComponent(this.getErrorPane()); } return this.mainSplit; java if (this.printButton == null) { this.printButton = new JButton(); this.printButton.setText(TextConstants.PRINT_LABEL); this.printButton.setEnabled(false); this.printButton.setActionCommand(ButtonActionConstants.PRINT); this.printButton.addActionListener(this.controller); } return this.printButton; java if (this.mntmNew == null) { this.mntmNew = new JMenuItem(TextConstants.NEW_LABEL); this.mntmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); this.mntmNew.setActionCommand(ButtonActionConstants.NEW.toString()); this.mntmNew.addActionListener(this.controller); } return this.mntmNew; java if (this.mntmOpen == null) { this.mntmOpen = new JMenuItem(TextConstants.OPEN_LABEL); this.mntmOpen.setActionCommand(ButtonActionConstants.OPEN.toString()); this.mntmOpen.addActionListener(this.controller); } return this.mntmOpen; java if (this.mnFile == null) { this.mnFile = new JMenu(TextConstants.FILE_LABEL); this.mnFile.add(this.getMntmNew()); this.mnFile.add(this.getMntmOpen()); this.mnFile.add(this.getMntmSave()); this.mnFile.add(this.getMntmSaveAs()); } return this.mnFile; java if (this.mntmSave == null) { this.mntmSave = new JMenuItem(TextConstants.SAVE_LABEL); this.mntmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); this.mntmSave.setActionCommand(ButtonActionConstants.SAVE.toString()); this.mntmSave.addActionListener(this.controller); } return this.mntmSave; java if (this.mntmSaveAs == null) { this.mntmSaveAs = new JMenuItem(TextConstants.SAVE_AS_LABEL); this.mntmSaveAs.setActionCommand(ButtonActionConstants.SAVE_AS.toString()); this.mntmSaveAs.addActionListener(this.controller); } return this.mntmSaveAs; java if (this.mnOptions == null) { this.mnOptions = new JMenu(TextConstants.EDITOR_LABEL); this.mnOptions.add(this.getMntmLarger()); this.mnOptions.add(this.getMntmNormalSize()); this.mnOptions.add(this.getMntmSmaller()); } return this.mnOptions; java if (this.mntmLarger == null) { this.mntmLarger = new JMenuItem(TextConstants.LARGER_LABEL); this.mntmLarger.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { View.this.increaseEditorFont(2); View.this.increaseTestingPanelFont(2); } }); this.mntmLarger.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_PLUS, InputEvent.CTRL_MASK)); } return this.mntmLarger; java if (this.mntmSmaller == null) { this.mntmSmaller = new JMenuItem(TextConstants.SMALLER_LABEL); this.mntmSmaller.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { View.this.increaseEditorFont(-2); View.this.increaseTestingPanelFont(-2); } }); this.mntmSmaller.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_MINUS, InputEvent.CTRL_MASK)); } return this.mntmSmaller; java if (this.mntmNormalSize == null) { this.mntmNormalSize = new JMenuItem(TextConstants.NORMAL_SIZE_LABEL); this.mntmNormalSize.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final Font currentFont = View.this.getTextArea().getFont(); View.this.getTextArea().setFont( currentFont.deriveFont(0.0f + DEFAULT_FONT_SIZE)); } }); } return this.mntmNormalSize; java if (this.testingPanel == null) { this.testingPanel = new JPanel(); this.testingPanel.setLayout(new BorderLayout()); this.testingPanel.add(this.getTextScrollPaneTesting(), BorderLayout.CENTER); } return this.testingPanel; java if (this.textScrollPaneTesting == null) { this.textScrollPaneTesting = new JScrollPane(); this.textScrollPaneTesting.setViewportView(this.getTextAreaTesting()); } return this.textScrollPaneTesting; java if (this.textAreaTesting == null) { this.textAreaTesting = new JTextPane(); this.initEditorTextPanel(this.textAreaTesting); this.initHighlighter(); } return this.textAreaTesting; java if (this.fileChooser == null) { this.fileChooser = new JFileChooser(); this.fileChooser.setApproveButtonText("Open"); this.fileChooser.setMultiSelectionEnabled(false); } return this.fileChooser;