/// <summary> /// Create a refinement of the specified type /// </summary> /// <param name="childType">A <see cref="DomainClassInfo"/> of the current type if <paramref name="nameUsageType"/> is set. /// Otherwise, the <see cref="DomainClassInfo.BaseDomainClass"/> must equal the current <see cref="ModelElement.GetDomainClass">DomainClass</see>.</param> /// <param name="nameUsageType">The type to associate with the <see cref="NameUsage"/> property. Can be <see langword="null"/></param> /// <returns>A new <see cref="NameGenerator"/> of the specified type</returns> private NameGenerator CreateRefinement(DomainClassInfo childType, Type nameUsageType) { DomainClassInfo nameGeneratorClass = GetDomainClass(); Debug.Assert(childType == nameGeneratorClass || childType.BaseDomainClass == nameGeneratorClass); ReadOnlyCollection <DomainPropertyInfo> properties = nameGeneratorClass.AllDomainProperties; PropertyAssignment[] propertyAssignments = new PropertyAssignment[properties.Count + (nameUsageType == null ? -1 : 0)]; Partition partition = Partition; int i = 0; foreach (DomainPropertyInfo property in properties) { if (property.Id != NameUsageDomainPropertyId) { propertyAssignments[i] = new PropertyAssignment(property.Id, property.GetValue(this)); ++i; } else if (nameUsageType != null) { propertyAssignments[i] = new PropertyAssignment(property.Id, ObjectModel.NameUsage.TranslateToNameUsageIdentifier(partition.DomainDataDirectory.FindDomainClass(nameUsageType))); ++i; } } NameGenerator retVal = (NameGenerator)Store.GetDomainModel(childType.DomainModel.Id).CreateElement(partition, childType.ImplementationClass, propertyAssignments); retVal.RefinesGenerator = this; return(retVal); }
public override void Visit(PropertyAssignment node) { result = (node.Expression != null) ? new PropertyAssignment(node.Name, GetCloneOf(node.Expression)) : new PropertyAssignment(node.Name, GetCloneOf(node.GetFunction), GetCloneOf(node.SetFunction)) ; }
public static object GetPropertyValue(PropertyAssignment assignment, PropType type) { switch (type) { case PropType.Number: return(assignment.GetValue <int>()); case PropType.Decimal: return(assignment.GetValue <float>()); case PropType.Boolean: return(assignment.GetValue <bool>()); case PropType.Actor: return(assignment.GetValue <string>()); case PropType.Sound: return(assignment.GetValue <string>()); case PropType.ParticleEffect: return(assignment.GetValue <string>()); case PropType.CardDeck: return(assignment.GetValue <string[]>() ?? new string[0]); case PropType.String: return(assignment.GetValue <string>()); case PropType.Prefab: return(assignment.GetValue <string>()); case PropType.ActorGroup: return(assignment.GetValue <string>()); case PropType.Image: return(assignment.GetValue <string>()); case PropType.Color: return(assignment.GetValue <string>()); case PropType.Enum: return(assignment.GetValue <string>()); case PropType.NumberArray: return(assignment.GetValue <int[]>() ?? new int[0]); case PropType.ActorArray: case PropType.StringArray: case PropType.EnumArray: return(assignment.GetValue <string[]>() ?? new string[0]); default: throw new System.Exception($"Didn't expect to get property of type {type}. Property var name: {assignment.propertyName}"); } }
/// <summary> /// Gets the property assignments based on the element this proto element represents. /// </summary> /// <param name="partition">Partition to use.</param> /// <param name="elementId">Id to assign to the IdPropertyAssignment.</param> /// <returns>Array of property assignments.</returns> public PropertyAssignment[] GetPropertyAssignments(Partition partition, Guid elementId) { if (partition == null) { throw new System.ArgumentNullException("partition"); } int length = properties.Count + 1; PropertyAssignment[] propertyAssignmentArr = new PropertyAssignment[length]; for (int i = 0; i < properties.Count; i++) { ModelProtoPropertyValue protoPropertyValue = (ModelProtoPropertyValue)properties[i]; DomainPropertyInfo domainPropertyInfo = partition.DomainDataDirectory.FindDomainProperty(protoPropertyValue.DomainPropertyId); propertyAssignmentArr[i] = new PropertyAssignment(protoPropertyValue.DomainPropertyId, protoPropertyValue.PropertyValue); } propertyAssignmentArr[properties.Count] = new PropertyAssignment(ElementFactory.IdPropertyAssignment, elementId); return(propertyAssignmentArr); }
/// <summary> /// DScript prints an allowlist before each list with five or more elements /// </summary> public override void VisitPropertyAssignment(PropertyAssignment node) { if (IsInObjectLiteralContext) { var initializer = node.Initializer; if (initializer != null && initializer.Kind == TypeScript.Net.Types.SyntaxKind.ArrayLiteralExpression) { var arrayLiteral = initializer.Cast <IArrayLiteralExpression>(); if (arrayLiteral.Elements.Count >= 5) { // unless it is the first var parentArray = node.Parent.TryCast <IObjectLiteralExpression>(); if (parentArray != null && parentArray.Properties[0] != node) { // Add a newline before each array literals with 5 or more elements. Writer.AdditionalNewLine(); } } } } base.VisitPropertyAssignment(node); }
/// <summary> /// Gets the property assignments based on the element this proto element represents. /// </summary> /// <param name="partition">Partition to use.</param> /// <param name="elementId">Id to assign to the IdPropertyAssignment.</param> /// <returns>Array of property assignments.</returns> public PropertyAssignment[] GetPropertyAssignments(Partition partition, Guid elementId) { if (partition == null) throw new System.ArgumentNullException("partition"); int length = properties.Count + 1; PropertyAssignment[] propertyAssignmentArr = new PropertyAssignment[length]; for (int i = 0; i < properties.Count; i++) { ModelProtoPropertyValue protoPropertyValue = (ModelProtoPropertyValue)properties[i]; DomainPropertyInfo domainPropertyInfo = partition.DomainDataDirectory.FindDomainProperty(protoPropertyValue.DomainPropertyId); propertyAssignmentArr[i] = new PropertyAssignment(protoPropertyValue.DomainPropertyId, protoPropertyValue.PropertyValue); } propertyAssignmentArr[properties.Count] = new PropertyAssignment(ElementFactory.IdPropertyAssignment, elementId); return propertyAssignmentArr; }
public override void Visit(PropertyAssignment node) { throw new NotImplementedException(); }
/// <summary> /// Generages the <see cref="ConceptType"/> objects along with any relationships that they have and adds them to the /// model. /// </summary> /// <param name="factTypeMappings">A dictionary of all the final decided FactTypeMapping objects.</param> private void GenerateConceptTypes(FactTypeMappingDictionary factTypeMappings) { ORMModel model = this.ORMModel; LinkedElementCollection<ObjectType> modelObjectTypes = model.ObjectTypeCollection; AbstractionModel oialModel = this.AbstractionModel; // For each object type in the model... foreach (ObjectType objectType in modelObjectTypes) { if (ShouldIgnoreObjectType(objectType)) { continue; } // If it should have a conctpt type... if (ObjectTypeIsConceptType(objectType, factTypeMappings)) { // Create the ConceptType object. PropertyAssignment name = new PropertyAssignment(ConceptType.NameDomainPropertyId, objectType.Name); ConceptType conceptType = new ConceptType(Store, name); ConceptTypeIsForObjectType conceptTypeIsForObjectType = new ConceptTypeIsForObjectType(conceptType, objectType); // Add it to the model. oialModel.ConceptTypeCollection.Add(conceptType); // If this conceptType is for a ValueType... if (objectType.IsValueType) { InformationTypeFormat valueTypeInformationTypeFormat = InformationTypeFormatIsForValueType.GetInformationTypeFormat(objectType); RoleAssignment conceptTypeRole = new RoleAssignment(InformationType.ConceptTypeDomainRoleId, conceptType); RoleAssignment informationTypeFormat = new RoleAssignment(InformationType.InformationTypeFormatDomainRoleId, valueTypeInformationTypeFormat); RoleAssignment[] roleAssignments = { conceptTypeRole, informationTypeFormat }; PropertyAssignment isMandatory = new PropertyAssignment(InformationType.IsMandatoryDomainPropertyId, true); PropertyAssignment informationTypeNameProperty = new PropertyAssignment(InformationType.NameDomainPropertyId, String.Concat(objectType.Name, "Value")); PropertyAssignment[] informationTypePropertyAssignments = { isMandatory, informationTypeNameProperty }; // ConceptType for conceptType gets an InformationType that references InformationTypeFormat for conceptType. InformationType informationType = new InformationType(Store, roleAssignments, informationTypePropertyAssignments); PropertyAssignment uniquenessNameProperty = new PropertyAssignment(Uniqueness.NameDomainPropertyId, String.Concat(objectType.Name, "Uniqueness")); PropertyAssignment isPreferred = new PropertyAssignment(Uniqueness.IsPreferredDomainPropertyId, true); PropertyAssignment[] uniquenessPropertyAssignments = { uniquenessNameProperty, isPreferred }; // Uniqueness constraint Uniqueness uniqueness = new Uniqueness(Store, uniquenessPropertyAssignments); UniquenessIncludesConceptTypeChild uniquenessIncludesConceptTypeChild = new UniquenessIncludesConceptTypeChild(uniqueness, informationType); conceptType.UniquenessCollection.Add(uniqueness); } } } }
/// <summary> /// Generates the <see cref="Uniqueness"/> objects for the <see cref="AbstractionModel"/>. /// </summary> /// <param name="factTypeMappings">The decided <see cref="FactTypeMapping"/> objects.</param> private void GenerateUniqueness(FactTypeMappingDictionary factTypeMappings) { // TODO: clean this up. AbstractionModel oialModel = this.AbstractionModel; // For each concept type in the model... foreach (ConceptType conceptType in oialModel.ConceptTypeCollection) { ObjectType objectType = ConceptTypeIsForObjectType.GetObjectType(conceptType); // For each role played by its object type... foreach (Role role in objectType.PlayedRoleCollection) { if (ShouldIgnoreFactType(role.BinarizedFactType)) { continue; } Role oppositeRole = role.OppositeRoleAlwaysResolveProxy.Role; // For each constraint on the opposite role... foreach (ConstraintRoleSequence constraintRoleSequence in oppositeRole.ConstraintRoleSequenceCollection) { UniquenessConstraint uninquenessConstraint = constraintRoleSequence as UniquenessConstraint; // If it is a uniqueness constraint... if (uninquenessConstraint != null && uninquenessConstraint.Modality == ConstraintModality.Alethic) { if (UniquenessIsForUniquenessConstraint.GetUniqueness(uninquenessConstraint) != null) { continue; } bool hasFactTypeThatShouldBeIgnored = false; bool allChildrenMapTowardObjectType = true; IList<FactType> factTypes = new List<FactType>(); foreach (Role childRole in uninquenessConstraint.RoleCollection) { FactType binarizedFactType = childRole.BinarizedFactType; if (ShouldIgnoreFactType(binarizedFactType)) { hasFactTypeThatShouldBeIgnored = true; break; } FactTypeMapping factTypeMapping = factTypeMappings[binarizedFactType]; if (factTypeMapping.TowardsRole != childRole.OppositeRoleAlwaysResolveProxy.Role) { allChildrenMapTowardObjectType = false; break; } else { factTypes.Add(binarizedFactType); } } if (hasFactTypeThatShouldBeIgnored) { continue; } if (allChildrenMapTowardObjectType) { IList<ConceptTypeChild> conceptTypeChildren = new List<ConceptTypeChild>(); bool skipThisUniquenessConstraint = false; foreach (FactType factType in factTypes) { bool childWasAssimilation = false; bool missedChild = true; foreach (ConceptTypeChild conceptTypeChild in ConceptTypeChildHasPathFactType.GetConceptTypeChild(factType)) { if (conceptTypeChild.Parent != conceptType) { // This ConceptTypeChild is of a different ConceptType, so go on to the next ConceptTypeChild. continue; } if (conceptTypeChild is ConceptTypeAssimilatesConceptType) { childWasAssimilation = true; break; } missedChild = false; conceptTypeChildren.Add(conceptTypeChild); } if (childWasAssimilation) { skipThisUniquenessConstraint = true; break; } if (missedChild) { // We couldn't find a ConceptTypeChild for this FactType, so just bail out. skipThisUniquenessConstraint = true; break; } } if (!skipThisUniquenessConstraint) { PropertyAssignment name = new PropertyAssignment(Uniqueness.NameDomainPropertyId, uninquenessConstraint.Name); PropertyAssignment isPreferred = new PropertyAssignment(Uniqueness.IsPreferredDomainPropertyId, uninquenessConstraint.IsPreferred); PropertyAssignment[] propertyAssignments = { name, isPreferred }; // Create uniquenesss Uniqueness uniqueness = new Uniqueness(Store, propertyAssignments); uniqueness.ConceptType = conceptType; new UniquenessIsForUniquenessConstraint(uniqueness, uninquenessConstraint); foreach (ConceptTypeChild conceptTypeChild in conceptTypeChildren) { UniquenessIncludesConceptTypeChild uniquenessIncludesConceptTypeChild = new UniquenessIncludesConceptTypeChild(uniqueness, conceptTypeChild); } } } } } } } }
/// <summary> /// Constructor. /// </summary> /// <param name="partition">Partition of the store where element is to be created.</param> /// <param name="propertyAssignments">New element property assignments.</param> protected DomainModelElement(Partition partition, PropertyAssignment[] propertyAssignments) : base(partition, propertyAssignments) { }
// evaluate starts evaluation with fresh environment public static ExpressionValue Evaluate(Expression exp, Valuation env) { switch (exp.ExpressionType) { case ExpressionType.Constant: return(exp as ExpressionValue); case ExpressionType.Variable: // Look up variable in environment; we assume // that value is found try { return(env.Variables[exp.expressionID]); } catch (KeyNotFoundException) { throw new EvaluatingException("Access the non existing variable: " + exp.expressionID); } catch (Exception ex) { throw new EvaluatingException("Variable evaluation exception for variable '" + exp.expressionID + "':" + ex.Message); } case ExpressionType.Record: { Expression[] ass = ((Record)exp).Associations; ExpressionValue[] values = new ExpressionValue[ass.Length]; for (int i = 0; i < ass.Length; i++) { //rv.Put(association.Property, store.Extend(Eval(association.Expression, env))); //rv.Put(Eval(association, env)); values[i] = Evaluate(ass[i], env); #if !OPTIMAL_FOR_EXP if (values[i] == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } #endif } RecordValue rv = new RecordValue(values); return(rv); } case ExpressionType.PrimitiveApplication: // First evaluate the first argument, then the second, and // then evaluate using evalPrimAppl. { PrimitiveApplication newexp = exp as PrimitiveApplication; ExpressionValue x1 = Evaluate(newexp.Argument1, env); Debug.Assert(x1 != null); #if !OPTIMAL_FOR_EXP if (x1 == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } #endif return(EvalPrimAppl(newexp, x1, newexp.Argument2, env)); } case ExpressionType.Assignment: { //Assign the rhs to lhs String lhs = ((Assignment)exp).LeftHandSide; Expression rhs = ((Assignment)exp).RightHandSide; ExpressionValue rhsV = Evaluate(rhs, env); #if !OPTIMAL_FOR_EXP if (rhsV == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } Valuation.CheckVariableRange(lhs, rhsV); #endif env.Variables[lhs] = rhsV; return(rhsV); } case ExpressionType.PropertyAssignment: { try { PropertyAssignment pa = (PropertyAssignment)exp; RecordValue rec = (RecordValue)Evaluate(pa.RecordExpression, env); IntConstant pro = (IntConstant)Evaluate(pa.PropertyExpression, env); ExpressionValue rhs = Evaluate(pa.RightHandExpression, env); //rec.Put(pro.PropertyName, store.Extend(rhs)); int index = pro.Value; if (index < 0) { throw new NegativeArraySizeException("Access negative index " + index + " for variable " + pa.RecordExpression.ToString()); } else if (index >= rec.Associations.Length) { throw new IndexOutOfBoundsException("Index " + index + " is out of range for variable " + pa.RecordExpression.ToString()); } #if !OPTIMAL_FOR_EXP if (rhs == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } Valuation.CheckVariableRange(pa.RecordExpression.ToString(), rhs); #endif rec.Associations[index] = rhs; //Note:Important!!! must recalculate the ID here, otherwise ID is obsolete and the verification result is wrong rec.GetID(); return(rhs); } catch (InvalidCastException ex) { throw new RuntimeException("Invalid Cast Exception for " + exp + ": " + ex.Message.Replace("PAT.Common.Classes.Expressions.ExpressionClass.", "")); } } case ExpressionType.If: // Conditionals are evaluated by evaluating the then-part or // else-part depending of the result of evaluating the condition. { ExpressionValue cond = Evaluate(((If)exp).Condition, env); if (((BoolConstant)cond).Value) { return(Evaluate(((If)exp).ThenPart, env)); } else if (((If)exp).ElsePart != null) { return(Evaluate(((If)exp).ElsePart, env)); } else { return(null); } } case ExpressionType.Sequence: // firstPart;secondPart Expression fP = ((Sequence)exp).FirstPart; Expression sP = ((Sequence)exp).SecondPart; Evaluate(fP, env); return(Evaluate(sP, env)); case ExpressionType.While: Expression test = ((While)exp).Test; Expression body = ((While)exp).Body; // the value of test may not be a Value. // here we assume it is always a Value, which // may cause run time exception due to non-Value. if (((BoolConstant)Evaluate(test, env)).Value) { // test is ture Evaluate(body, env); // body serves to change the store return(Evaluate(exp, env)); // evaluate the While again } else { return(null); } case ExpressionType.StaticMethodCall: try { StaticMethodCall methodCall = (StaticMethodCall)exp; if (methodCall.Arguments.Length > 0) { ChannelQueue queue; string cname = null; if ((methodCall.Arguments[0] is Variable)) { cname = (methodCall.Arguments[0] as Variable).ExpressionID; } else if (methodCall.Arguments[0] is PrimitiveApplication) { PrimitiveApplication pa = (methodCall.Arguments[0] as PrimitiveApplication); ExpressionValue ind = Evaluate(pa.Argument2, env); cname = pa.Argument1 + "[" + ind + "]"; } switch (methodCall.MethodName) { case Common.Classes.Ultility.Constants.cfull: if (env.Channels.TryGetValue(cname, out queue)) { return(new BoolConstant(queue.IsFull())); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } case Common.Classes.Ultility.Constants.cempty: if (env.Channels.TryGetValue(cname, out queue)) { return(new BoolConstant(queue.IsEmpty())); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } case Common.Classes.Ultility.Constants.ccount: if (env.Channels.TryGetValue(cname, out queue)) { return(new IntConstant(queue.Count)); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } case Common.Classes.Ultility.Constants.csize: if (env.Channels.TryGetValue(cname, out queue)) { return(new IntConstant(queue.Size)); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } case Common.Classes.Ultility.Constants.cpeek: if (env.Channels.TryGetValue(cname, out queue)) { if (queue.Count == 0) { throw new IndexOutOfBoundsException("Channel " + cname + "'s buffer is empty!"); } return(new RecordValue(queue.Peek())); } else { throw new RuntimeException("Channel " + cname + " is not used in the model. Therefore it is meaningless to query channel information using " + methodCall + "."); } } } object[] paras = new object[methodCall.Arguments.Length]; for (int i = 0; i < paras.Length; i++) { ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env); paras[i] = GetValueFromExpression(x1); } string key = methodCall.MethodName + paras.Length; if (Common.Utility.Utilities.CSharpMethods.ContainsKey(key)) { object resultv = Common.Utility.Utilities.CSharpMethods[key].Invoke(null, paras); if (Common.Utility.Utilities.CSharpMethods[key].ReturnType.Name == "Void") { return(null); } if (resultv is bool) { return(new BoolConstant((bool)resultv)); } else if (resultv is int || resultv is short || resultv is byte || resultv is double) { return(new IntConstant(Convert.ToInt32(resultv))); } else if (resultv is int[]) { int[] list = resultv as int[]; ExpressionValue[] vals = new ExpressionValue[list.Length]; for (int i = 0; i < vals.Length; i++) { vals[i] = new IntConstant(list[i]); } return(new RecordValue(vals)); } else if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } return(new NullConstant()); //the following check is not necessary, since we will only keep bool, int and int[] methods //else //{ // throw new Expressions.ExpressionClass.RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your methods."); //} } throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library."); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { RuntimeException exception = new RuntimeException("Exception happened at expression " + exp + ": " + ex.InnerException.Message); exception.InnerStackTrace = ex.InnerException.StackTrace; throw exception; } else { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } case ExpressionType.ClassMethodCall: try { ClassMethodCall methodCall = (ClassMethodCall)exp; ExpressionValue variable = env.Variables[methodCall.Variable]; if (variable == null) { throw new RuntimeException("Exception happened at expression " + exp + ": variable " + methodCall.Variable + "'s value is null"); } object[] paras = new object[methodCall.Arguments.Length]; for (int i = 0; i < paras.Length; i++) { ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env); paras[i] = GetValueFromExpression(x1); } MethodInfo methodInfo = variable.GetType().GetMethod(methodCall.MethodName); if (methodInfo != null) { object resultv = methodInfo.Invoke(variable, BindingFlags.InvokeMethod, null, paras, CultureInfo.InvariantCulture); if (methodInfo.ReturnType.Name == "Void") { return(null); } if (resultv is bool) { return(new BoolConstant((bool)resultv)); } else if (resultv is int || resultv is short || resultv is byte || resultv is double) { return(new IntConstant(Convert.ToInt32(resultv))); } else if (resultv is int[]) { int[] list = resultv as int[]; ExpressionValue[] vals = new ExpressionValue[list.Length]; for (int i = 0; i < vals.Length; i++) { vals[i] = new IntConstant(list[i]); } return(new RecordValue(vals)); } else if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } else if (resultv == null) { return(new NullConstant()); } //return null; //the following check is not necessary, since we will only keep bool, int and int[] methods throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + methodCall.ToString() + "."); } throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library."); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { RuntimeException exception = new RuntimeException("Exception happened at expression " + exp + ": " + ex.InnerException.Message); exception.InnerStackTrace = ex.InnerException.StackTrace; throw exception; } else { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } case ExpressionType.ClassMethodCallInstance: try { ClassMethodCallInstance methodCall = (ClassMethodCallInstance)exp; ExpressionValue variable = Evaluate(methodCall.Variable, env); object[] paras = new object[methodCall.Arguments.Length]; for (int i = 0; i < paras.Length; i++) { ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env); paras[i] = GetValueFromExpression(x1); } MethodInfo methodInfo = variable.GetType().GetMethod(methodCall.MethodName); if (methodInfo != null) { object resultv = methodInfo.Invoke(variable, paras); if (methodInfo.ReturnType.Name == "Void") { return(null); } if (resultv is bool) { return(new BoolConstant((bool)resultv)); } else if (resultv is int || resultv is short || resultv is byte || resultv is double) { return(new IntConstant(Convert.ToInt32(resultv))); } else if (resultv is int[]) { int[] list = resultv as int[]; ExpressionValue[] vals = new ExpressionValue[list.Length]; for (int i = 0; i < vals.Length; i++) { vals[i] = new IntConstant(list[i]); } return(new RecordValue(vals)); } else if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } else if (resultv == null) { return(new NullConstant()); } //return null; //the following check is not necessary, since we will only keep bool, int and int[] methods throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + methodCall.ToString() + "."); } throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library."); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { RuntimeException exception = new RuntimeException("Exception happened at expression " + exp + ": " + ex.InnerException.Message); exception.InnerStackTrace = ex.InnerException.StackTrace; throw exception; } else { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } case ExpressionType.ClassProperty: try { ClassProperty property = (ClassProperty)exp; ExpressionValue variable = Evaluate(property.Variable, env); PropertyInfo propertyInfo = variable.GetType().GetProperty(property.PropertyName); object resultv = null; if (propertyInfo != null) { resultv = propertyInfo.GetValue(variable, null); } else { FieldInfo fieldInfo = variable.GetType().GetField(property.PropertyName); if (fieldInfo != null) { resultv = fieldInfo.GetValue(variable); } } if (resultv != null) { if (resultv is bool) { return(new BoolConstant((bool)resultv)); } else if (resultv is int || resultv is short || resultv is byte || resultv is double) { return(new IntConstant(Convert.ToInt32(resultv))); } else if (resultv is int[]) { int[] list = resultv as int[]; ExpressionValue[] vals = new ExpressionValue[list.Length]; for (int i = 0; i < vals.Length; i++) { vals[i] = new IntConstant(list[i]); } return(new RecordValue(vals)); } else if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } //else if (resultv == null) //{ // return new NullConstant(); //} //return null; //the following check is not necessary, since we will only keep bool, int and int[] methods throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + property.ToString() + "."); } throw new RuntimeException("Invalid Property Accessing: " + property + "! Make sure you have defined the method in the library."); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { RuntimeException exception = new RuntimeException("Exception happened at expression " + exp + ": " + ex.InnerException.Message); exception.InnerStackTrace = ex.InnerException.StackTrace; throw exception; } else { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } case ExpressionType.ClassPropertyAssignment: { try { ClassPropertyAssignment pa = (ClassPropertyAssignment)exp; ExpressionValue rhs = Evaluate(pa.RightHandExpression, env); #if !OPTIMAL_FOR_EXP if (rhs == null) { throw new RuntimeException("Invalid expression assignment: " + exp); } #endif ClassProperty property = pa.ClassProperty; ExpressionValue variable = Evaluate(property.Variable, env); PropertyInfo propertyInfo = variable.GetType().GetProperty(property.PropertyName); if (propertyInfo != null) { propertyInfo.SetValue(variable, GetValueFromExpression(rhs), null); } else { FieldInfo fieldInfo = variable.GetType().GetField(property.PropertyName); if (fieldInfo != null) { fieldInfo.SetValue(variable, GetValueFromExpression(rhs)); } else { throw new RuntimeException("Invalid expression assignment: " + exp); } } return(rhs); } catch (InvalidCastException ex) { throw new RuntimeException("Invalid Cast Exception for " + exp + ": " + ex.Message.Replace("PAT.Common.Classes.Expressions.ExpressionClass.", "")); } } case ExpressionType.Let: LetDefinition definition = exp as LetDefinition; ExpressionValue rhv = Evaluate(definition.RightHandExpression, env); env.ExtendDestructive(definition.Variable, rhv); return(null); case ExpressionType.NewObjectCreation: try { NewObjectCreation methodCall = (NewObjectCreation)exp; object[] paras = new object[methodCall.Arguments.Length]; for (int i = 0; i < paras.Length; i++) { ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env); paras[i] = GetValueFromExpression(x1); } Type classType; if (Common.Utility.Utilities.CSharpDataType.TryGetValue(methodCall.ClassName, out classType)) { object resultv = Activator.CreateInstance(classType, paras); if (resultv is ExpressionValue) { return(resultv as ExpressionValue); } //return null; //the following check is not necessary, since we will only keep bool, int and int[] methods throw new RuntimeException("Only object of class inheriting from ExpressionValue can be created. Please check your statement: " + methodCall.ToString() + "."); } throw new RuntimeException("Invalid Object Creation: " + methodCall + "! Make sure you have defined the class in the library."); } catch (Exception ex) { throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message); } //case ExpressionType.UserDefinedDataType: // return exp as ; /* case ExpressionType.Let: * // Evaluate body with respect to environment extended by binding of leftHand to rightHand * { * Valuation newenv = env.GetVariableClone(); * foreach (LetDefinition def in ((Let) exp).Definitions) * { * Value rhv = Evaluate(def.RightHandExpression, env); * //newenv = Extend(newenv, def.Variable, rhv); * //newenv = newenv.Extend(def.Variable, rhv); * newenv.ExtendDestructive(def.Variable, rhv); * } * return Evaluate(((Let) exp).Body, newenv); * } * case ExpressionType.Fun: * return new FunValue(env, ((Fun) exp).Formals, ((Fun) exp).Body); * case ExpressionType.RecFun: * // For recursive functions, we need to place an environment * // in the function that has a binding of the function variable * // to the function itself. For this, we obtain a clone of the * // environment, making sure that a destructive change will * // not have any effect on the original environment. Then, we * // place the clone in the function value. After that, we * // destructively change the environment by a binding of the * // function variable to the constructed function value. * { * Valuation newEnv = env.GetVariableClone(); // (Valuation)env.Clone(); * Value result = new FunValue(newEnv, ((RecFun) exp).Formals, ((RecFun) exp).body); * //ExtendDestructive(newEnv, ((RecFun)exp).FunVar, result); * newEnv.ExtendDestructive(((RecFun) exp).FunVar, result); * return result; * } * case ExpressionType.Application: * // Apply the function value resulting from evaluating the operator * // (we assume that this is a function value) to * // the value resulting from evaluating the operand. * // Note that we do not need to distinguish functions from * // recursive functions. Both are represented by function values, * // recursive functions have a binding of their function variable * // to themselves in their environment. * { * FunValue fun = (FunValue) Evaluate(((Application) exp).Operator, env); * Valuation newenv = (Valuation) fun.Valuation; * * List<Expression> ops = ((Application) exp).Operands; * List<string> fe = fun.Formals; * * for (int i = 0; i < ops.Count; i++) * { * Value argvalue = Evaluate(ops[i], env); * //newenv = Extend(newenv, fe[i], argvalue); * newenv = newenv.Extend((String) fe[i], argvalue); * } * return Evaluate(fun.Body, newenv); * }*/ } // (exp instanceof NotUsed) // NotUsed is used as argument2 of PrimitiveApplication. // We assume the resulting value will not be used, // thus any value will do, here. return(new BoolConstant(true)); }
public static SubProcessElement CreateSubProcessElement(string subProcessName, Partition partition, ProcessOverview.Process process, SubProcess subProcess, ModelBusReference subProcessReference) { var childReferenceProperty = new PropertyAssignment(SubProcessElement.SubProcessRefDomainPropertyId, null); var nameProperty = new PropertyAssignment(SubProcessElement.NameDomainPropertyId, subProcessName); var subProcessElement = new ProcessOverview.SubProcessElement(partition, nameProperty, childReferenceProperty); subProcessElement.VisioId = subProcess.VisioId.ToString().ToLower(); subProcessElement.SubProcessRef = subProcessReference; process.BTSubProcess.Add(subProcessElement); return subProcessElement; }
//for assignment attached with events only public static Value Evaluate(Expression expression, Environment env) { Stack <Expression> workingStack = new Stack <Expression>(16); Stack <Value> valueStack = new Stack <Value>(16); workingStack.Push(expression); bool firstMeet = true; while (workingStack.Count > 0) { Expression expr = workingStack.Pop(); if (expr == null) { firstMeet = false; expr = workingStack.Pop(); } else { firstMeet = true; } switch (expr.ExpressionType) { case ExpressionType.Variable: try { string varName = ((Variable)expr).VarName; valueStack.Push(env[varName]); break; } catch (KeyNotFoundException) { throw new EvaluatingException("Access the non existing variable: " + (expr as Variable).VarName); } catch (Exception ex) { throw new EvaluatingException("Variable evaluation exception for variable '" + (expr as Variable).VarName + "':" + ex.Message); } case ExpressionType.BoolConstant: valueStack.Push(new BoolValue(((BoolConstant)expr).BoolValue)); break; case ExpressionType.IntConstant: valueStack.Push(new IntValue(((IntConstant)expr).IntValue)); break; case ExpressionType.Record: int size = ((Record)expr).Associations.Length; if (firstMeet) { workingStack.Push(expr); workingStack.Push(null); Expression[] ass = ((Record)expr).Associations; for (int i = 0; i < size; i++) { workingStack.Push(ass[i]); } } else { Value[] values = new Value[size]; for (int i = 0; i < size; i++) { values[i] = valueStack.Pop(); } RecordValue rv = new RecordValue(values); valueStack.Push(rv); } break; case ExpressionType.PrimitiveApplication: PrimitiveApplication newexp = ((PrimitiveApplication)expr); if (firstMeet) { workingStack.Push(expr); workingStack.Push(null); workingStack.Push(newexp.Argument1); if (newexp.Argument2 != null) { workingStack.Push(newexp.Argument2); } } else { Value x1 = valueStack.Pop(); Value x2 = null; if (newexp.Argument2 != null) { x2 = valueStack.Pop(); } valueStack.Push(EvalPrimAppl(newexp.Operator, x1, x2)); } break; case ExpressionType.Assignment: String lhs = ((Assignment)expr).LeftHandSide; if (firstMeet) { workingStack.Push(expr); workingStack.Push(null); workingStack.Push(((Assignment)expr).RightHandSide); } else { env[lhs] = valueStack.Pop(); } break; case ExpressionType.PropertyAssignment: PropertyAssignment pa = (PropertyAssignment)expr; if (firstMeet) { workingStack.Push(expr); workingStack.Push(null); workingStack.Push(pa.RecordExpression); workingStack.Push(pa.PropertyExpression); workingStack.Push(pa.RightHandExpression); } else { RecordValue rec = (RecordValue)valueStack.Pop(); IntValue pro = (IntValue)valueStack.Pop(); Value rhs = valueStack.Pop(); rec.Values[pro.Value] = rhs; } break; case ExpressionType.If: if (firstMeet) { workingStack.Push(expr); workingStack.Push(null); workingStack.Push(((If)expr).Condition); } else { BoolValue cond = valueStack.Pop() as BoolValue; if (cond.Value) { //return Evaluate(((If)expr).ThenPart, env, VariablesToWrite, VariablesToRead); workingStack.Push(((If)expr).ThenPart); } else if (((If)expr).ElsePart != null) { //return Evaluate(((If)expr).ElsePart, env, VariablesToWrite, VariablesToRead); workingStack.Push(((If)expr).ElsePart); } } break; case ExpressionType.Sequence: workingStack.Push(((Sequence)expr).FirstPart); workingStack.Push(((Sequence)expr).SecondPart); break; case ExpressionType.While: if (firstMeet) { workingStack.Push(expr); workingStack.Push(null); workingStack.Push(((While)expr).Test); } else { BoolValue cond = valueStack.Pop() as BoolValue; if (cond.Value) { workingStack.Push(expr); workingStack.Push(((While)expr).Body); } } break; } } if (valueStack.Count > 0) { return(valueStack.Pop()); } else { return(null); } }
/// <summary> /// Binarizes the unary <see cref="FactType"/> specified by <paramref name="unaryFactType"/>, defaulting /// to using open-world assumption. The caller is responsible for making sure <paramref name="unaryFactType"/> /// is in fact a unary fact type. /// </summary> public static void BinarizeUnary(FactType unaryFactType, INotifyElementAdded notifyAdded) { Partition partition = unaryFactType.Partition; Store store = partition.Store; IHasAlternateOwner <FactType> toAlternateOwner; IAlternateElementOwner <FactType> alternateFactTypeOwner = (null == (toAlternateOwner = unaryFactType as IHasAlternateOwner <FactType>)) ? null : toAlternateOwner.AlternateOwner; LinkedElementCollection <RoleBase> roleCollection = unaryFactType.RoleCollection; Debug.Assert(roleCollection.Count == 1, "Unaries should only have one role."); Role unaryRole = (Role)roleCollection[0]; string implicitBooleanValueTypeName = GetImplicitBooleanValueTypeName(unaryRole); // UNDONE: We are using open-world assumption now // Setup the mandatory constraint (for closed-world assumption) //MandatoryConstraint mandatoryConstraint = MandatoryConstraint.CreateSimpleMandatoryConstraint(unaryRole); //mandatoryConstraint.Model = unaryFactType.Model; //if (notifyAdded != null) //{ // notifyAdded.ElementAdded(mandatoryConstraint, true); //} // Setup the uniqueness constraint (to make the newly binarized FactType valid) if (unaryRole.SingleRoleAlethicUniquenessConstraint == null) { UniquenessConstraint uniquenessConstraint = UniquenessConstraint.CreateInternalUniquenessConstraint(unaryFactType); uniquenessConstraint.RoleCollection.Add(unaryRole); if (notifyAdded != null) { notifyAdded.ElementAdded(uniquenessConstraint, true); } } // Setup the boolean role (to make the FactType a binary) Role implicitBooleanRole = new Role(partition, null); implicitBooleanRole.Name = unaryRole.Name; // Setup the boolean value type (because the boolean role needs a role player) IAlternateElementOwner <ObjectType> alternateObjectTypeOwner = null; DomainClassInfo alternateCtor = (null != alternateFactTypeOwner && null != (alternateObjectTypeOwner = alternateFactTypeOwner as IAlternateElementOwner <ObjectType>)) ? alternateObjectTypeOwner.GetOwnedElementClassInfo(typeof(ObjectType)) : null; PropertyAssignment implicitBooleanProperty = new PropertyAssignment(ObjectType.IsImplicitBooleanValueDomainPropertyId, true); ObjectType implicitBooleanValueType = (alternateCtor != null) ? (ObjectType)partition.ElementFactory.CreateElement(alternateCtor, implicitBooleanProperty) : new ObjectType(partition, implicitBooleanProperty); Dictionary <object, object> contextInfo = store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo; object duplicateNamesKey = ORMModel.AllowDuplicateNamesKey; bool removeDuplicateNamesKey = false; object duplicateSignaturesKey = ORMModel.BlockDuplicateReadingSignaturesKey; bool addDuplicateSignaturesKey = false; try { if (!contextInfo.ContainsKey(duplicateNamesKey)) { contextInfo[duplicateNamesKey] = null; removeDuplicateNamesKey = true; } if (contextInfo.ContainsKey(duplicateSignaturesKey)) { contextInfo[duplicateSignaturesKey] = null; addDuplicateSignaturesKey = true; } implicitBooleanValueType.Name = implicitBooleanValueTypeName; if (alternateCtor != null) { ((IHasAlternateOwner <ObjectType>)implicitBooleanValueType).AlternateOwner = alternateObjectTypeOwner; } else { implicitBooleanValueType.Model = unaryFactType.ResolvedModel; } if (notifyAdded != null) { notifyAdded.ElementAdded(implicitBooleanValueType, true); } } finally { if (removeDuplicateNamesKey) { contextInfo.Remove(duplicateNamesKey); } if (addDuplicateSignaturesKey) { contextInfo[duplicateSignaturesKey] = null; } } implicitBooleanValueType.DataType = store.ElementDirectory.FindElements <TrueOrFalseLogicalDataType>(false)[0]; // Set value constraint on implicit boolean ValueType for open-world assumption ValueTypeValueConstraint implicitBooleanValueConstraint = implicitBooleanValueType.ValueConstraint = new ValueTypeValueConstraint(partition, null); // Add the true-only ValueRange to the value constraint for open-world assumption implicitBooleanValueConstraint.ValueRangeCollection.Add(new ValueRange(partition, new PropertyAssignment(ValueRange.MinValueDomainPropertyId, bool.TrueString), new PropertyAssignment(ValueRange.MaxValueDomainPropertyId, bool.TrueString))); // Make the boolean value type the role player for the implicit boolean role implicitBooleanRole.RolePlayer = implicitBooleanValueType; // Add the boolean role to the FactType roleCollection.Add(implicitBooleanRole); if (notifyAdded != null) { notifyAdded.ElementAdded(implicitBooleanRole, true); } }
public override void Visit(PropertyAssignment node) { throw new InvalidOperationException(); }
public CSharpSyntaxNode Convert(PropertyAssignment node) { return(SyntaxFactory .Argument(node.Initializer.ToCsNode <ExpressionSyntax>()) .WithNameColon(SyntaxFactory.NameColon(node.Name.Text))); }
/// <summary> /// Override default values used to create the initial state of the object. /// </summary> private static PropertyAssignment[] GenerateDefaultValues(params PropertyAssignment[] propertyAssignments) { PropertyAssignment[] properties = propertyAssignments; string nameUsage = null; int casingOptionIndex = -1; int spacingOptionIndex = -1; for (int i = 0; i < properties.Length; ++i) { PropertyAssignment assignment = properties[i]; Guid propertyId = assignment.PropertyId; if (propertyId == NameGenerator.CasingOptionDomainPropertyId) { casingOptionIndex = i; } else if (propertyId == NameGenerator.NameUsageDomainPropertyId) { nameUsage = (string)assignment.Value; } else if (propertyId == NameGenerator.SpacingFormatDomainPropertyId) { spacingOptionIndex = i; } } if (nameUsage == null) { if (spacingOptionIndex != -1) { properties[spacingOptionIndex] = new PropertyAssignment(NameGenerator.SpacingFormatDomainPropertyId, NameGeneratorSpacingFormat.Remove); } } else if (casingOptionIndex != -1) { if (nameUsage == "RelationalColumn") { properties[casingOptionIndex] = new PropertyAssignment(NameGenerator.CasingOptionDomainPropertyId, NameGeneratorCasingOption.Camel); } else if (nameUsage == "RelationalTable") { properties[casingOptionIndex] = new PropertyAssignment(NameGenerator.CasingOptionDomainPropertyId, NameGeneratorCasingOption.Pascal); } } return properties; }
public void TestPropertyAssignment() { PropertyAssignment node = new PropertyAssignment(GetStringId(), GetExpression1(), DefaultLineInfo); CheckSerializationRoundTrip(node); }
public override void Visit(PropertyAssignment node) { VisitNode(node.Expression); Visit((Node)node); }
public override void Visit(PropertyAssignment node) { }
/// <summary> /// Creates a new instance of the DomainModelLink class. /// </summary> /// <param name="partition">The Partition instance containing this ElementLink</param> /// <param name="roleAssignments">A set of role assignments for roleplayer initialization</param> /// <param name="propertyAssignments">A set of attribute assignments for attribute initialization</param> protected DomainModelLink(Partition partition, RoleAssignment[] roleAssignments, PropertyAssignment[] propertyAssignments) : base(partition, roleAssignments, propertyAssignments) { }
public const double MINIMUM_DIFFERENCE = 0.000001; //0.000001; public static void TestIsBooleanExpression(Expression p, IToken ID1, string expression, Valuation valuation, Dictionary <string, Expression> ConstantDatabase) { if (ConstantDatabase.Count > 0) { p = p.ClearConstant(ConstantDatabase); } if (p is PrimitiveApplication) { string Operator = (p as PrimitiveApplication).Operator; if (Operator == "+" || Operator == "-" || Operator == "*" || Operator == "/" || Operator == "~" || Operator == "." || Operator == "mod") //Operator == "." || { throw new ParsingException("The expression " + p + " " + expression + " must be a boolean expression!", ID1); } else if (Operator == "||" || Operator == "&&" || Operator == "!") { //recursive test the component inside TestIsBooleanExpression((p as PrimitiveApplication).Argument1, ID1, expression, valuation, ConstantDatabase); if ((p as PrimitiveApplication).Argument2 != null) { TestIsBooleanExpression((p as PrimitiveApplication).Argument2, ID1, expression, valuation, ConstantDatabase); } } else if (Operator == ">=" || Operator == "<=" || Operator == ">" || Operator == "<") { //recursive test the component inside TestIsIntExpression((p as PrimitiveApplication).Argument1, ID1, expression, valuation, ConstantDatabase); if ((p as PrimitiveApplication).Argument2 != null) { TestIsIntExpression((p as PrimitiveApplication).Argument2, ID1, expression, valuation, ConstantDatabase); } } } else if (p is Variable) { if (valuation != null && valuation.Variables != null && valuation.Variables.ContainsKey(p.ExpressionID) && !(valuation.Variables[p.ExpressionID] is BoolConstant)) { throw new ParsingException(string.Format(Resources.The_variable__0__must_be_a_boolean_variable_, p + " " + expression), ID1); } } else if (p is StaticMethodCall) { StaticMethodCall call = p as StaticMethodCall; switch (call.MethodName) { case Common.Classes.Ultility.Constants.cfull: case Common.Classes.Ultility.Constants.cempty: return; } string key = call.MethodName + call.Arguments.Length; if (Utilities.CSharpMethods.ContainsKey(key)) { if (Utilities.CSharpMethods[key].ReturnType.Name == "Boolean") { return; } } else { throw new ParsingException(string.Format("The call {0} is not defined.", call.MethodName), ID1); } throw new ParsingException(string.Format(Resources.The_static_method_call__0__must_return_a_boolean_value_, p), ID1); } else if (p is ClassMethodCall) { ClassMethodCall call = p as ClassMethodCall; if (valuation.Variables.ContainsKey(call.Variable)) { MethodInfo methodInfo = valuation.Variables[call.Variable].GetType().GetMethod(call.MethodName); if (methodInfo != null) { if (methodInfo.ReturnType.Name == "Boolean") { return; } } } else { throw new ParsingException(string.Format("The call {0} may not be defined for variable {1}.", call.MethodName, call.Variable), ID1); } throw new ParsingException(string.Format(Resources.The_static_method_call__0__must_return_a_boolean_value_, p), ID1); } else if (p is Assignment) { Assignment assign = p as Assignment; TestIsBooleanExpression(assign.RightHandSide, ID1, expression, valuation, ConstantDatabase); } else if (p is PropertyAssignment) { PropertyAssignment assign = p as PropertyAssignment; TestIsBooleanExpression(assign.RightHandExpression, ID1, expression, valuation, ConstantDatabase); } else if (!(p is BoolConstant) && !(p is If) && !(p is While)) { throw new ParsingException(string.Format(Resources.The_expression__0__must_be_a_boolean_expression_, p + " " + expression), ID1); } }
/// <summary> /// Constructor /// </summary> /// <param name="partition">Partition where new link is to be created.</param> /// <param name="roleAssignments">List of relationship role assignments.</param> /// <param name="propertyAssignments">List of properties assignments to set on the new link.</param> public FactTypeMapsTowardsRole(Partition partition, RoleAssignment[] roleAssignments, PropertyAssignment[] propertyAssignments) : base(partition, roleAssignments, propertyAssignments) { }
public static string GenerateLaTexString(Expression exp) { switch (exp.ExpressionType) { case ExpressionType.Variable: return(exp.ToString()); case ExpressionType.Constant: if (exp is BoolConstant) { return(((BoolConstant)exp).Value.ToString()); } else { return(exp.ToString()); } case ExpressionType.Record: { Record record = exp as Record; StringBuilder sb = new StringBuilder("["); for (int i = 0; i < record.Associations.Length - 1; i++) { Expression con = record.Associations[i]; sb.Append(GenerateLaTexString(con) + ", "); } sb.Append(GenerateLaTexString(record.Associations[record.Associations.Length - 1])); sb.Append("]"); return(sb.ToString()); } case ExpressionType.PrimitiveApplication: // First evaluate the first argument, then the second, and // then evaluate using evalPrimAppl. { PrimitiveApplication newexp = exp as PrimitiveApplication; if (newexp.Argument2 == null) { if (newexp.Operator == "~") { return("-" + GenerateLaTexString(newexp.Argument1)); } else { return(newexp.Operator + GenerateLaTexString(newexp.Argument1)); } } else { if (newexp.Operator == ".") { return(GenerateLaTexString(newexp.Argument1) + "[" + GenerateLaTexString(newexp.Argument2) + "]"); } else if (newexp.Operator == "mod") { return("(" + GenerateLaTexString(newexp.Argument1) + " \\% " + GenerateLaTexString(newexp.Argument2) + ")"); } else { string op = ""; switch (newexp.Operator) { case "&&": op = @"\land"; break; case "||": op = @"\lor"; break; case "==": op = @"=="; break; case "!=": op = @"\neq"; break; case ">=": op = @"\geq"; break; case "<=": op = @"\leq"; break; case "\\": op = @"\backslash"; break; default: op = newexp.Operator; break; } return("(" + GenerateLaTexString(newexp.Argument1) + " " + op + " " + GenerateLaTexString(newexp.Argument2) + ")"); } } } case ExpressionType.Assignment: { Assignment assign = exp as Assignment; return(assign.LeftHandSide + " = " + GenerateLaTexString(assign.RightHandSide) + ";"); } case ExpressionType.PropertyAssignment: { PropertyAssignment pa = (PropertyAssignment)exp; return(GenerateLaTexString(pa.RecordExpression) + "[" + GenerateLaTexString(pa.PropertyExpression) + "]=" + GenerateLaTexString(pa.RightHandExpression) + ";"); } case ExpressionType.If: // Conditionals are evaluated by evaluating the then-part or // else-part depending of the result of evaluating the condition. { If ifC = (If)exp; if (ifC.ElsePart != null) { return(" if (" + GenerateLaTexString(ifC.Condition) + ") \\{" + GenerateLaTexString(ifC.ThenPart) + "\\} else \\{" + GenerateLaTexString(ifC.ElsePart) + "\\}"); } else { return(" if (" + GenerateLaTexString(ifC.Condition) + ") \\{" + GenerateLaTexString(ifC.ThenPart) + "\\}"); } } case ExpressionType.Sequence: return(GenerateLaTexString(((Sequence)exp).FirstPart) + ";" + GenerateLaTexString(((Sequence)exp).SecondPart)); case ExpressionType.While: return("while (" + GenerateLaTexString(((While)exp).Test) + ") \\{" + GenerateLaTexString(((While)exp).Body) + "\\}"); case ExpressionType.StaticMethodCall: StaticMethodCall call = exp as StaticMethodCall; StringBuilder strbui = new StringBuilder("call(" + call.MethodName + ","); for (int i = 0; i < call.Arguments.Length; i++) { if (i == call.Arguments.Length - 1) { strbui.Append(call.Arguments[i].ToString()); } else { strbui.Append(call.Arguments[i] + ",~"); } } strbui.Append(")"); return(strbui.ToString()); } return(""); }
/// <summary> /// Generates the appropriate <see cref="ConceptTypeChild">concept type children</see> in <paramref name="parentConceptType"/> /// for <paramref name="factTypeMapping"/>. /// </summary> /// <param name="factTypeMappings"> /// The set of all decided <see cref="FactTypeMapping">fact type mappings</see>. /// </param> /// <param name="parentConceptType"> /// The <see cref="ConceptType"/> into which <see cref="ConceptTypeChild">concept type children</see> should be generated. /// </param> /// <param name="parentConceptTypeHasDeepAway"> /// Test if the parent concept type has a deep mapping away from it. Handles some cyclic cases by making a potential assimilation /// into a reference. Delay calculated because this is not always needed. /// </param> /// <param name="factTypeMapping"> /// The <see cref="FactTypeMapping"/> for which <see cref="ConceptTypeChild">concept type children</see> should be generated. /// </param> /// <param name="factTypePath"> /// The path of <see cref="FactType">fact types</see> leading from <paramref name="parentConceptType"/> to <paramref name="factTypeMapping"/> /// </param> /// <param name="isMandatorySoFar"> /// Indicates whether every step in <paramref name="factTypePath"/> is mandatory for the parent concept type (towards object type). /// </param> private static void GenerateConceptTypeChildrenForFactTypeMapping(FactTypeMappingDictionary factTypeMappings, ConceptType parentConceptType, ref bool? parentConceptTypeHasDeepAway, FactTypeMapping factTypeMapping, List<FactType> factTypePath, bool isMandatorySoFar) { // Push the current fact type onto the path. factTypePath.Add(factTypeMapping.FactType); bool isMandatory = isMandatorySoFar && (factTypeMapping.TowardsRoleMandatory); ConceptTypeChild newConceptTypeChild; ConceptType fromConceptType = ConceptTypeIsForObjectType.GetConceptType(factTypeMapping.FromObjectType); if (fromConceptType != null) { // The mapping is coming from a concept type, so we will create a concept type reference to it. // Set up the property assignments that are common to both kinds of concept type references. PropertyAssignment isMandatoryPropertyAssignment = new PropertyAssignment(ConceptTypeChild.IsMandatoryDomainPropertyId, isMandatory); string name = ResolveRoleName(factTypeMapping.FromRole); string oppositeName = ResolveRoleName(factTypeMapping.TowardsRole); // UNDONE: Yes, these are backwards, but they need to remain so for compatibility reasons until we do a file format change. PropertyAssignment namePropertyAssignment = new PropertyAssignment(ConceptTypeChild.NameDomainPropertyId, oppositeName); PropertyAssignment oppositeNamePropertyAssignment = new PropertyAssignment(ConceptTypeReferencesConceptType.OppositeNameDomainPropertyId, name); if (factTypeMapping.MappingDepth == MappingDepth.Deep) { // Since this is a deep mapping, we will create a concept type assimilation for it. SubtypeFact subtypeFact = factTypeMapping.FactType as SubtypeFact; // UNDONE: The handling here for IsPreferredForParent and IsPreferredForTarget may not be correct // if we have more than one fact type in the fact type path. bool isPreferredForTarget; if (subtypeFact != null) { // For subtype assimilations, IsPreferredForTarget matches the ProvidesPreferredIdentifier // property of the ORM subtype fact. isPreferredForTarget = subtypeFact.ProvidesPreferredIdentifier; } else { // For non-subtype assimilations, IsPreferredForTarget is true if the role played by the object // type corresponding to the parent concept type has the preferred identifying uniqueness constraint // for the target concept type. isPreferredForTarget = factTypeMapping.TowardsRole.SingleRoleAlethicUniquenessConstraint.IsPreferred; } bool isPreferredForParent = factTypeMapping.IsFromPreferredIdentifier; // The IsPreferredForParent property on concept type assimilations indicates that the assimilation, on its own, // provides the preferred identifier for the assimilating concept type. Although the IsFromPreferredIdentifier // property on the fact type mapping will be true even if the from role is part of a multi-role preferred identifier, // ORM currently doesn't allow a role with a single role alethic uniqueness constraint (which is required for this to // be a deep mapping) to be part of any other uniqueness constraint. However, this may change in the future as our // handling of derivations, implications, equivalences, and logical rules becomes more sophisticated. We assert here // in order to make this case easier to catch if it happens, since this method may need to be adjusted in that case // to ensure that it continues to produce correct results. Debug.Assert(!isPreferredForParent || factTypeMapping.FromRole.SingleRoleAlethicUniquenessConstraint.IsPreferred); newConceptTypeChild = new ConceptTypeAssimilatesConceptType(parentConceptType.Partition, new RoleAssignment[] { new RoleAssignment(ConceptTypeAssimilatesConceptType.AssimilatorConceptTypeDomainRoleId, parentConceptType), new RoleAssignment(ConceptTypeAssimilatesConceptType.AssimilatedConceptTypeDomainRoleId, fromConceptType) }, new PropertyAssignment[] { isMandatoryPropertyAssignment, namePropertyAssignment, oppositeNamePropertyAssignment, new PropertyAssignment(ConceptTypeAssimilatesConceptType.RefersToSubtypeDomainPropertyId, subtypeFact != null), new PropertyAssignment(ConceptTypeAssimilatesConceptType.IsPreferredForParentDomainPropertyId, isPreferredForParent), new PropertyAssignment(ConceptTypeAssimilatesConceptType.IsPreferredForTargetDomainPropertyId, isPreferredForTarget), }); } else { Debug.Assert(factTypeMapping.MappingDepth == MappingDepth.Shallow, "Collapse mappings should not come from object types that have a concept type."); // Since this is a shallow mapping, we will create a concept type relation for it. newConceptTypeChild = new ConceptTypeRelatesToConceptType(parentConceptType.Partition, new RoleAssignment[] { new RoleAssignment(ConceptTypeRelatesToConceptType.RelatingConceptTypeDomainRoleId, parentConceptType), new RoleAssignment(ConceptTypeRelatesToConceptType.RelatedConceptTypeDomainRoleId, fromConceptType) }, new PropertyAssignment[] { isMandatoryPropertyAssignment, namePropertyAssignment, oppositeNamePropertyAssignment }); } } else { // The mapping is not coming from a concept type, meaning that we either need an information // type for an atomic value type (which will already have an information type format created // for it), or we need to collapse the preferred identifier of an entity type or structured // value type. InformationTypeFormat fromInformationTypeFormat = InformationTypeFormatIsForValueType.GetInformationTypeFormat(factTypeMapping.FromObjectType); if (fromInformationTypeFormat != null) { // We have an information type format, which means that we need to create an information type. string name = ResolveRoleName(factTypeMapping.FromRole); newConceptTypeChild = new InformationType(parentConceptType.Partition, new RoleAssignment[] { new RoleAssignment(InformationType.ConceptTypeDomainRoleId, parentConceptType), new RoleAssignment(InformationType.InformationTypeFormatDomainRoleId, fromInformationTypeFormat) }, new PropertyAssignment[] { new PropertyAssignment(ConceptTypeChild.IsMandatoryDomainPropertyId, isMandatory), new PropertyAssignment(ConceptTypeChild.NameDomainPropertyId, name) }); } else { // We do not have an information type format, which means that we need to collapse the fact // types in the preferred identifier of the FromObjectType into the parent concept type. newConceptTypeChild = null; UniquenessConstraint preferredIdentifier = factTypeMapping.FromObjectType.PreferredIdentifier; Debug.Assert(preferredIdentifier != null); foreach (Role preferredIdentifierRole in preferredIdentifier.RoleCollection) { // NOTE: We don't need the ShouldIgnoreFactType filter here, because we would have ignored // this object type if we were ignoring any of the fact types in its preferred identifier. FactType preferredIdentifierFactType = preferredIdentifierRole.BinarizedFactType; FactTypeMapping preferredIdentifierFactTypeMapping = factTypeMappings[preferredIdentifierFactType]; if (preferredIdentifierFactType == factTypeMapping.FactType) { // We just got back to the fact that we were already mapping. This should only happen // when the object type has a single fact type in its preferred identifier and it is // deeply mapped away from the object type. Debug.Assert(preferredIdentifier.RoleCollection.Count == 1 && preferredIdentifierFactTypeMapping.MappingDepth == MappingDepth.Deep); // UNDONE: For now, we just ignore this fact type entirely. What we should be doing is: // 1) If everything along the path is mandatory, then we're done, since we know that instances of the parent // concept type always identify an instance of the object type that we're trying to map. // 2) Otherwise, check if there are any other relationships that would allow use to derive whether an instance // of the parent concept type identifies an instance of the object type that we're trying to map. Examples // of things that would allow us to do this would be a mandatory role played by the object type that we're // we're trying to map that gets absorbed into some concept type. The reference to an instance of this concept // type from it allows us to tell if this instance identifies an instance of the object type. // 3) If no other relationship allows us to derive this information, we need to add a boolean information type // that indicates for each instance of the parent concept type whether it identifies an instance of the object // type that we're trying to map. break; } // If we have a single fact type in the preferred identifier, it might be mapped // deeply away from the object type that we are collapsing. For this case, we need // to create a "fake" mapping and process it instead. if (preferredIdentifierFactTypeMapping.TowardsRole == preferredIdentifierRole) { // Make sure this is actually the situation we are trying to handle, since it shouldn't be possible in any other scenario. Debug.Assert(preferredIdentifier.RoleCollection.Count == 1 && preferredIdentifierFactTypeMapping.MappingDepth == MappingDepth.Deep); // UNDONE: Would we ever want to use a depth other than shallow here? Probably not, but it might be worth looking in to. FactTypeMappingFlags currentFlags = preferredIdentifierFactTypeMapping.Flags; preferredIdentifierFactTypeMapping = new FactTypeMapping(preferredIdentifierFactType, preferredIdentifierFactTypeMapping.TowardsRole, preferredIdentifierFactTypeMapping.FromRole, (currentFlags & FactTypeMappingFlags.Subtype) | GetFlags(false, 0 != (currentFlags & FactTypeMappingFlags.TowardsValueType), 0 != (currentFlags & FactTypeMappingFlags.TowardsRoleMandatory), 0 != (currentFlags & FactTypeMappingFlags.TowardsRoleImpliedMandatory), 0 != (currentFlags & FactTypeMappingFlags.FromValueType), 0 != (currentFlags & FactTypeMappingFlags.FromRoleMandatory), 0 != (currentFlags & FactTypeMappingFlags.FromRoleImpliedMandatory))); } else if (preferredIdentifierFactTypeMapping.MappingDepth == MappingDepth.Deep) { // Handle cyclic deep mapping scenario with collapsed entities. // The primary scenario here is: // 1) B is a subtype of A and identified by A's identifier // 2) A and B participate in an objectified 1-1 FactType // 3) The uniqueness constraint on the A role is the preferred identifier // 4) The A role is mandatory // In this case, without this code, you get an assimilation mapping B into A // and mapping A into B. We fix this case by forwarding a shallow mapping, // which generates a reference instad of an assimilation. if (!parentConceptTypeHasDeepAway.HasValue) { ObjectType objectType = ConceptTypeIsForObjectType.GetObjectType(parentConceptType); foreach (Role role in ConceptTypeIsForObjectType.GetObjectType(parentConceptType).PlayedRoleCollection) { FactType factType; FactTypeMapping testMapping; if (null != (factType = role.BinarizedFactType) && factTypeMappings.TryGetValue(factType, out testMapping) && testMapping.MappingDepth == MappingDepth.Deep && testMapping.FromObjectType == objectType) { preferredIdentifierFactTypeMapping = new FactTypeMapping(preferredIdentifierFactType, preferredIdentifierFactTypeMapping.FromRole, preferredIdentifierFactTypeMapping.TowardsRole, preferredIdentifierFactTypeMapping.Flags & ~FactTypeMappingFlags.DeepMapping); parentConceptTypeHasDeepAway = true; break; } } if (!parentConceptTypeHasDeepAway.HasValue) { parentConceptTypeHasDeepAway = false; } } else if (parentConceptTypeHasDeepAway.Value) { preferredIdentifierFactTypeMapping = new FactTypeMapping(preferredIdentifierFactType, preferredIdentifierFactTypeMapping.FromRole, preferredIdentifierFactTypeMapping.TowardsRole, preferredIdentifierFactTypeMapping.Flags & ~FactTypeMappingFlags.DeepMapping); } } GenerateConceptTypeChildrenForFactTypeMapping(factTypeMappings, parentConceptType, ref parentConceptTypeHasDeepAway, preferredIdentifierFactTypeMapping, factTypePath, isMandatory); } } } // If we created a new concept type child, populate its fact type path. if (newConceptTypeChild != null) { foreach (FactType pathFactType in factTypePath) { ConceptTypeChildHasPathFactType conceptTypeChildHasPathFactType = new ConceptTypeChildHasPathFactType(newConceptTypeChild, pathFactType); } } // Pop the current fact type off of the path. Debug.Assert(factTypePath[factTypePath.Count - 1] == factTypeMapping.FactType, "Fact type path stack is corrupt."); factTypePath.RemoveAt(factTypePath.Count - 1); }
// TODO rewrite as just.. ToAssignment(PropEditor editable) public static PropertyAssignment ToAssignment(PropEditor editable) { var assign = new PropertyAssignment(); assign.propertyName = editable.propDef.variableName; switch (editable.propType) { case PropType.Number: assign.SetValue <int>((int)editable.data); break; case PropType.Decimal: assign.SetValue <float>((float)editable.data); break; case PropType.Boolean: assign.SetValue <bool>((bool)editable.data); break; case PropType.String: assign.SetValue <string>((string)editable.data); break; case PropType.CardDeck: assign.SetValue <string[]>((string[])editable.data); break; case PropType.Actor: if (editable.data == null) { assign.SetValue <string>(null); } else { assign.SetValue <string>((string)editable.data); } break; case PropType.Sound: assign.SetValue <string>((string)editable.data); break; case PropType.ParticleEffect: assign.SetValue <string>((string)editable.data); break; case PropType.Prefab: assign.SetValue <string>((string)editable.data); break; case PropType.ActorGroup: assign.SetValue <string>((string)editable.data); break; case PropType.Image: assign.SetValue <string>((string)editable.data); break; case PropType.Color: assign.SetValue <string>((string)editable.data); break; case PropType.Enum: assign.SetValue <string>((string)editable.data); break; case PropType.NumberArray: assign.SetValue <int[]>((int[])editable.data); break; case PropType.StringArray: case PropType.EnumArray: case PropType.ActorArray: assign.SetValue <string[]>((string[])editable.data); break; default: throw new System.NotImplementedException(); } return(assign); }
/// <summary> /// Generates the <see cref="InformationTypeFormat"/> objects and adds them to the model. /// </summary> private void GenerateInformationTypeFormats() { ORMModel model = this.ORMModel; IEnumerable<ObjectType> modelValueTypes = model.ValueTypeCollection; AbstractionModel oialModel = this.AbstractionModel; // For each ValueType in the model... foreach (ObjectType valueType in modelValueTypes) { if (ShouldIgnoreObjectType(valueType)) { continue; } // Create InformationTypeFormat. PropertyAssignment namePropertyAssignment = new PropertyAssignment(InformationTypeFormat.NameDomainPropertyId, valueType.Name); InformationTypeFormat informationTypeFormat = new InformationTypeFormat(Store, namePropertyAssignment); InformationTypeFormatIsForValueType informationTypeFormatIsForValueType = new InformationTypeFormatIsForValueType(informationTypeFormat, valueType); // TODO: information type format data types // Add it to the model. oialModel.InformationTypeFormatCollection.Add(informationTypeFormat); } }
public override void Visit(PropertyAssignment node) { VisitNode(node.Expression); Visit((Node)node); WriteEdge(node, node.Expression, "expression"); }
/// <nodoc /> public virtual void Visit(PropertyAssignment propertyAssignment) { }
public InitialPropertyExpansionBranch(Store store, PropertyAssignment[] assignments) { myDirectory = store.DomainDataDirectory; myAssignments = assignments; }