/// <summary> /// Generates match objects of independents /// </summary> protected void GenerateIndependentsMatchObjects(SourceBuilder sourceCode) { for (int i = 0; i < MatchingPatternClassTypeName.Count; ++i) { if (NestedIndependents[i] == null) { continue; } foreach (KeyValuePair <PatternGraph, bool> nestedIndependent in NestedIndependents[i]) { if (nestedIndependent.Value == false) { continue; // if independent is not nested in iterated with potentially more than one match then matcher-class-based match variables are sufficient, only one match is living at a time } if (nestedIndependent.Key.originalPatternGraph != null) { sourceCode.AppendFrontFormat("{0} {1} = new {0}();\n", nestedIndependent.Key.originalSubpatternEmbedding.matchingPatternOfEmbeddedGraph.GetType().Name + "." + NamesOfEntities.MatchClassName(nestedIndependent.Key.originalPatternGraph.pathPrefix + nestedIndependent.Key.originalPatternGraph.name), NamesOfEntities.MatchedIndependentVariable(nestedIndependent.Key.pathPrefix + nestedIndependent.Key.name)); } else { sourceCode.AppendFrontFormat("{0} {1} = new {0}();\n", MatchingPatternClassTypeName[i] + "." + NamesOfEntities.MatchClassName(nestedIndependent.Key.pathPrefix + nestedIndependent.Key.name), NamesOfEntities.MatchedIndependentVariable(nestedIndependent.Key.pathPrefix + nestedIndependent.Key.name)); } } } }
private int EmitMaybeNullDispatching(SourceBuilder sourceCode, int conditionLevel, int emittedCounter) { if (conditionLevel < DispatchConditions.Length) { sourceCode.AppendFrontFormat("if({0}!=null) {{\n", DispatchConditions[conditionLevel]); sourceCode.Indent(); emittedCounter = EmitMaybeNullDispatching(sourceCode, conditionLevel + 1, emittedCounter); sourceCode.Unindent(); sourceCode.AppendFront("} else {\n"); sourceCode.Indent(); emittedCounter = EmitMaybeNullDispatching(sourceCode, conditionLevel + 1, emittedCounter); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); } else { if (emittedCounter > 0) // first entry are we ourselves, don't call, just nop { sourceCode.AppendFrontFormat("return {0}(actionEnv, maxMatches", SuffixedMatcherNames[emittedCounter]); foreach (string argument in Arguments[emittedCounter]) { sourceCode.AppendFormat(", {0}", argument); } sourceCode.Append(");\n"); } ++emittedCounter; } return(emittedCounter); }
public override void Emit(SourceBuilder sourceCode) { // emit initialization with element mapped from storage string variableContainingStorage = NamesOfEntities.Variable(StorageName); string variableContainingSourceElement = NamesOfEntities.CandidateVariable(SourcePatternElementName); string tempVariableForMapResult = NamesOfEntities.MapWithStorageTemporary(PatternElementName); sourceCode.AppendFrontFormat("if(!{0}.TryGetValue(({1}){2}, out {3})) ", variableContainingStorage, StorageKeyTypeName, variableContainingSourceElement, tempVariableForMapResult); // emit check failed code sourceCode.Append("{\n"); sourceCode.Indent(); CheckFailedOperations.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); // assign the value to the candidate variable, cast it to the variable type string typeOfVariableContainingCandidate = "GRGEN_LGSP." + (IsNode ? "LGSPNode" : "LGSPEdge"); string variableContainingCandidate = NamesOfEntities.CandidateVariable(PatternElementName); sourceCode.AppendFrontFormat("{0} = ({1}){2};\n", variableContainingCandidate, typeOfVariableContainingCandidate, tempVariableForMapResult); }
public void EmitMatchedReset(SourceBuilder builder, bool parallel) { if(parallel) builder.AppendFrontFormat("flagsPerElement{0}[candidate{0}.uniqueId] &= (ushort)~GRGEN_LGSP.LGSPElemFlagsParallel.IS_MATCHED;\n", this.Id); else builder.AppendFrontFormat("candidate{0}.lgspFlags &= ~((uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED);\n", this.Id); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFrontFormat("{0}.{1} match_{2} = new {0}.{1}();\n", RulePatternClassName, NamesOfEntities.MatchClassName(PatternName), MatchName); sourceCode.AppendFrontFormat("match_{0}.SetMatchOfEnclosingPattern({1});\n", MatchName, MatchOfEnclosingPatternName); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFrontFormat("// build match of {0} for patternpath checks\n", PatternGraphName); sourceCode.AppendFrontFormat("if({0}==null) {0} = new {1}.{2}();\n", NamesOfEntities.PatternpathMatch(PatternGraphName), RulePatternClassName, NamesOfEntities.MatchClassName(PatternGraphName)); sourceCode.AppendFrontFormat("{0}._matchOfEnclosingPattern = {1};\n", NamesOfEntities.PatternpathMatch(PatternGraphName), MatchOfNestingPattern); }
public override void Emit(SourceBuilder sourceCode) { if (sourceCode.CommentSourceCode) { sourceCode.AppendFrontFormat("// Variable {0} assigned from expression {1} \n", VariableName, SourceExpression); } // emit declaration of variable initialized with expression sourceCode.AppendFrontFormat("{0} {1} = ({0}){2};\n", VariableType, NamesOfEntities.Variable(VariableName), SourceExpression); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFrontFormat("{0}if({1}.{2} is {3}) {{\n", First ? "" : "else ", MatchObjectName, NestedMatchObjectName, AlternativeCaseMatchTypeName); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0}){2}.{3};\n", AlternativeCaseMatchTypeName, HelperMatchName, MatchObjectName, NestedMatchObjectName); NestedOperationsList.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
public void EmitMatchedCheckAndSet(SourceBuilder builder, bool parallel) { if(parallel) { builder.AppendFrontFormat("List<ushort> flagsPerElement{0} = graph.flagsPerThreadPerElement[threadId];\n", this.Id); builder.AppendFrontFormat("if((flagsPerElement{0}[candidate{0}.uniqueId] & (ushort)GRGEN_LGSP.LGSPElemFlagsParallel.IS_MATCHED) != 0)\n", this.Id); builder.AppendFront("\tcontinue;\n"); builder.AppendFrontFormat("flagsPerElement{0}[candidate{0}.uniqueId] |= (ushort)GRGEN_LGSP.LGSPElemFlagsParallel.IS_MATCHED;\n", this.Id); } else { builder.AppendFrontFormat("if((candidate{0}.lgspFlags & (uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED) != 0)\n", this.Id); builder.AppendFront("\tcontinue;\n"); builder.AppendFrontFormat("candidate{0}.lgspFlags |= (uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED;\n", this.Id); } }
public override void Dump(SourceBuilder builder) { string typeDescr; switch (Type) { case BuildMatchObjectType.Node: typeDescr = "Node"; break; case BuildMatchObjectType.Edge: typeDescr = "Edge"; break; case BuildMatchObjectType.Variable: typeDescr = "Variable"; break; case BuildMatchObjectType.Subpattern: typeDescr = "Subpattern"; break; case BuildMatchObjectType.InlinedSubpattern: typeDescr = "InlinedSubpattern"; break; case BuildMatchObjectType.Iteration: typeDescr = "Iteration"; break; case BuildMatchObjectType.Alternative: typeDescr = "Alternative"; break; case BuildMatchObjectType.Independent: typeDescr = "Independent"; break; default: typeDescr = ">>UNKNOWN<<"; break; } builder.AppendFrontFormat("BuildMatchObject {0} name {1} with {2} within {3}\n", typeDescr, MatchObjectName, PatternElementName, RulePatternClassName); }
public override void Emit(SourceBuilder sourceCode) { if (Type != InitializeFinalizeSubpatternMatchingType.Iteration) { sourceCode.AppendFrontFormat("openTasks.Push(this);\n"); } }
public override void Emit(SourceBuilder sourceCode) { string targetPatternElement = Type == EntityType.Variable ? NamesOfEntities.Variable(TargetPatternElementName) : NamesOfEntities.CandidateVariable(TargetPatternElementName); if (SourcePatternElementUnprefixedName != null) { string sourcePatternElement = NamesOfEntities.MatchName(SourcePatternElementUnprefixedName, Type); sourceCode.AppendFrontFormat("{0} = {1}._{2}; // bubble up (from match)\n", targetPatternElement, NestedMatchOrTaskObjectName, sourcePatternElement); } else { sourceCode.AppendFrontFormat("{0} = {1}.{0}; // bubble up (from task)\n", targetPatternElement, NestedMatchOrTaskObjectName); } }
public void EmitCloning(SourceBuilder source, SequenceGenerator seqGen, String matchListName, String originalToCloneName) { source.AppendFront("if(" + matchesName + ".Count != 0) {\n"); source.Indent(); source.AppendFrontFormat("{0} = ({1}){0}.Clone({2});\n", matchesName, matchesType, originalToCloneName); source.Unindent(); source.AppendFront("}\n"); }
public void EmitAddRange(SourceBuilder source, String matchListName) { source.AppendFront("if(" + matchesName + ".Count != 0) {\n"); source.Indent(); source.AppendFrontFormat("{0}.AddRange({1});\n", matchListName, matchesName); source.Unindent(); source.AppendFront("}\n"); }
public override void Emit(SourceBuilder sourceCode) { // emit check decision string variableContainingCandidate = NamesOfEntities.CandidateVariable(PatternElementName); if (Type == CheckCandidateForTypeType.ByIsAllowedType) { string isAllowedTypeArrayMemberOfRulePattern = IsAllowedArrayName + "_IsAllowedType"; sourceCode.AppendFrontFormat("if(!{0}.{1}[{2}.lgspType.TypeID]) ", RulePatternTypeName, isAllowedTypeArrayMemberOfRulePattern, variableContainingCandidate); } else if (Type == CheckCandidateForTypeType.ByIsMyType) { sourceCode.AppendFrontFormat("if(!{0}.isMyType[{1}.lgspType.TypeID]) ", TypeName, variableContainingCandidate); } else // Type == CheckCandidateForTypeType.ByTypeID) { sourceCode.AppendFront("if("); bool first = true; foreach (string typeID in TypeIDs) { if (first) { first = false; } else { sourceCode.Append(" && "); } sourceCode.AppendFormat("{0}.lgspType.TypeID!={1}", variableContainingCandidate, typeID); } sourceCode.Append(") "); } // emit check failed code sourceCode.Append("{\n"); sourceCode.Indent(); CheckFailedOperations.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
public override void Dump(SourceBuilder builder) { if (Type == PushAndPopSubpatternTaskTypes.Subpattern) { builder.AppendFrontFormat("PopSubpatternTask Subpattern {0} {1}\n", SubpatternElementName, Parallel ? "Parallel" : ""); } else if (Type == PushAndPopSubpatternTaskTypes.Alternative) { builder.AppendFrontFormat("PopSubpatternTask Alternative {0} {1}\n", AlternativeOrIteratedName, Parallel ? "Parallel" : ""); } else // Type==PushAndPopSubpatternTaskTypes.Iterated { builder.AppendFrontFormat("PopSubpatternTask Iterated {0} {1}\n", AlternativeOrIteratedName, Parallel ? "Parallel" : ""); } }
public override void Emit(SourceBuilder sourceCode) { if (sourceCode.CommentSourceCode) { if (Type == PushAndPopSubpatternTaskTypes.Subpattern) { sourceCode.AppendFrontFormat("// Pop subpattern matching task for {0}\n", SubpatternElementName); } else if (Type == PushAndPopSubpatternTaskTypes.Alternative) { sourceCode.AppendFrontFormat("// Pop alternative matching task for {0}\n", PathPrefix + AlternativeOrIteratedName); } else // if(Type==PushAndPopSubpatternTaskTypes.Iterated) { sourceCode.AppendFrontFormat("// Pop iterated matching task for {0}\n", PathPrefix + AlternativeOrIteratedName); } } sourceCode.AppendFrontFormat("{0}openTasks.Pop();\n", NegativeIndependentNamePrefix); string variableContainingTask; string typeOfVariableContainingTask; if (Type == PushAndPopSubpatternTaskTypes.Subpattern) { variableContainingTask = NamesOfEntities.TaskVariable(SubpatternElementName, NegativeIndependentNamePrefix); typeOfVariableContainingTask = NamesOfEntities.TypeOfTaskVariable(SubpatternName, false, false); } else if (Type == PushAndPopSubpatternTaskTypes.Alternative) { variableContainingTask = NamesOfEntities.TaskVariable(AlternativeOrIteratedName, NegativeIndependentNamePrefix); typeOfVariableContainingTask = NamesOfEntities.TypeOfTaskVariable(PathPrefix + AlternativeOrIteratedName, true, false); } else // if(Type==PushAndPopSubpatternTaskTypes.Iterated) { variableContainingTask = NamesOfEntities.TaskVariable(AlternativeOrIteratedName, NegativeIndependentNamePrefix); typeOfVariableContainingTask = NamesOfEntities.TypeOfTaskVariable(PathPrefix + AlternativeOrIteratedName, false, true); } string parallelizationThreadId = Parallel ? ", threadId" : ""; sourceCode.AppendFrontFormat("{0}.releaseTask({1}{2});\n", typeOfVariableContainingTask, variableContainingTask, parallelizationThreadId); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFrontFormat("if({0}.Count>0) {{\n", NestedMatchObjectName); sourceCode.Indent(); NestedOperationsList.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
private static void GenerateInternalObjectTypeAttributeInitializer(SequenceCheckingEnvironment env, IGraphModel model, SequenceExpressionNew attributeInitializer, SourceBuilder source) { if (attributeInitializer.AttributeInitializationList == null) { return; // plain constructor without attribute initialization list } string internalObjectType = "GRGEN_MODEL." + attributeInitializer.ConstructedType; source.Append("\n"); source.AppendFront("public static "); source.Append(internalObjectType); source.Append(" fillFromSequence_" + attributeInitializer.Id + "("); BaseObjectType objectType = env.Model.ObjectModel.GetType(attributeInitializer.ConstructedType); if (objectType != null) { source.Append("long uniqueId"); } for (int i = 0; i < attributeInitializer.AttributeInitializationList.Count; ++i) { KeyValuePair <string, SequenceExpression> attributeInitialization = attributeInitializer.AttributeInitializationList[i]; if (i > 0 || objectType != null) { source.Append(", "); } string valueType = TypesHelper.XgrsTypeToCSharpType(env.TypeOfMemberOrAttribute(attributeInitializer.ConstructedType, attributeInitialization.Key), model); source.AppendFormat("{0} {1}", valueType, "param" + i); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} obj = new {0}({1});\n", internalObjectType, objectType != null ? "uniqueId" : ""); for (int i = 0; i < attributeInitializer.AttributeInitializationList.Count; ++i) { KeyValuePair <string, SequenceExpression> attributeInitialization = attributeInitializer.AttributeInitializationList[i]; source.AppendFrontFormat("obj.{0} = {1};\n", attributeInitialization.Key, "param" + i); } source.AppendFront("return obj;\n"); source.Unindent(); source.AppendFront("}\n"); }
public void EmitRewriting(SourceBuilder source, SequenceGenerator seqGen, String matchListName, String enumeratorName, bool fireDebugEvents) { source.AppendFrontFormat("case \"{0}\":\n", plainRuleName); source.AppendFront("{\n"); source.Indent(); source.AppendFront(matchType + " " + matchName + " = (" + matchType + ")" + enumeratorName + ".Current;\n"); String returnParameterDeclarations; String returnArguments; String returnAssignments; String returnParameterDeclarationsAllCall; String intermediateReturnAssignmentsAllCall; String returnAssignmentsAllCall; seqHelper.BuildReturnParameters(seqRule, ReturnVars, out returnParameterDeclarations, out returnArguments, out returnAssignments, out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall); // start a transaction if (fireDebugEvents) { source.AppendFront("procEnv.Matched(" + matchesName + ", " + matchName + ", " + specialStr + ");\n"); } if (fireDebugEvents) { source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n"); } if (returnParameterDeclarations.Length != 0) { source.AppendFront(returnParameterDeclarations + "\n"); } source.AppendFront(ruleName + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if (returnAssignments.Length != 0) { source.AppendFront(returnAssignments + "\n"); } source.AppendFront("++procEnv.PerformanceInfo.RewritesPerformed;\n"); if (fireDebugEvents) { source.AppendFront("procEnv.Finished(" + matchesName + ", " + specialStr + ");\n"); } // rule applied, now execute the sequence seqGen.EmitSequence(seqSeq, source); source.AppendFront(COMP_HELPER.SetResultVar(seqMulti, COMP_HELPER.GetResultVar(seqSeq))); source.AppendFront("break;\n"); source.Unindent(); source.AppendFront("}\n"); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFrontFormat("foreach({0} {1} in {2}) {{\n", IteratedMatchTypeName, HelperMatchName, NestedMatchObjectName); sourceCode.Indent(); NestedOperationsList.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
public static void GenerateContainerConstructor(IGraphModel model, SequenceExpressionContainerConstructor containerConstructor, SourceBuilder source) { string containerType = TypesHelper.XgrsTypeToCSharpType(GetContainerType(containerConstructor), model); string valueType = TypesHelper.XgrsTypeToCSharpType(containerConstructor.ValueType, model); string keyType = null; if (containerConstructor is SequenceExpressionMapConstructor) { keyType = TypesHelper.XgrsTypeToCSharpType(((SequenceExpressionMapConstructor)containerConstructor).KeyType, model); } source.Append("\n"); source.AppendFront("public static "); source.Append(containerType); source.Append(" fillFromSequence_" + containerConstructor.Id); source.Append("("); for (int i = 0; i < containerConstructor.ContainerItems.Length; ++i) { if (i > 0) { source.Append(", "); } if (keyType != null) { source.AppendFormat("{0} paramkey{1}, ", keyType, i); } source.AppendFormat("{0} param{1}", valueType, i); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} container = new {0}();\n", containerType); for (int i = 0; i < containerConstructor.ContainerItems.Length; ++i) { source.AppendFrontFormat(GetAddToContainer(containerConstructor, "param" + i, keyType != null ? "paramkey" + i : null)); } source.AppendFront("return container;\n"); source.Unindent(); source.AppendFront("}\n"); }
public override void Emit(SourceBuilder sourceCode) { if (sourceCode.CommentSourceCode) { sourceCode.AppendFrontFormat("// Match subpatterns {0}\n", NegativeIndependentNamePrefix != "" ? "of " + NegativeIndependentNamePrefix : ""); } if (Parallelized) { sourceCode.AppendFrontFormat("{0}openTasks.Peek().myMatch_parallelized({0}matchesList, {1}, isoSpace, threadId);\n", NegativeIndependentNamePrefix, NegativeIndependentNamePrefix == "" ? "maxMatches - foundPartialMatches.Count" : "1"); } else { sourceCode.AppendFrontFormat("{0}openTasks.Peek().myMatch({0}matchesList, {1}, isoSpace);\n", NegativeIndependentNamePrefix, NegativeIndependentNamePrefix == "" ? "maxMatches - foundPartialMatches.Count" : "1"); } }
public override void Emit(SourceBuilder sourceCode) { if (ConnectednessType == CheckCandidateForConnectednessType.Source) { // emit check decision for is candidate connected to already found partial match, i.e. edge source equals node sourceCode.AppendFrontFormat("if({0}.lgspSource != {1}) ", NamesOfEntities.CandidateVariable(PatternEdgeName), NamesOfEntities.CandidateVariable(PatternNodeName)); } else if (ConnectednessType == CheckCandidateForConnectednessType.Target) { // emit check decision for is candidate connected to already found partial match, i.e. edge target equals node sourceCode.AppendFrontFormat("if({0}.lgspTarget != {1}) ", NamesOfEntities.CandidateVariable(PatternEdgeName), NamesOfEntities.CandidateVariable(PatternNodeName)); } else if (ConnectednessType == CheckCandidateForConnectednessType.SourceOrTarget) { // we've to check both node positions of the edge, we do so by checking source or target dependent on the direction run sourceCode.AppendFrontFormat("if( ({0}==0 ? {1}.lgspSource : {1}.lgspTarget) != {2}) ", NamesOfEntities.DirectionRunCounterVariable(PatternEdgeName), NamesOfEntities.CandidateVariable(PatternEdgeName), NamesOfEntities.CandidateVariable(PatternNodeName)); } else //ConnectednessType == CheckCandidateForConnectednessType.TheOther { // we've to check the node position of the edge the first node is not assigned to sourceCode.AppendFrontFormat("if( ({0}=={1}.lgspSource ? {1}.lgspTarget : {1}.lgspSource) != {2}) ", NamesOfEntities.CandidateVariable(TheOtherPatternNodeName), NamesOfEntities.CandidateVariable(PatternEdgeName), NamesOfEntities.CandidateVariable(PatternNodeName)); } // emit check failed code sourceCode.Append("{\n"); sourceCode.Indent(); CheckFailedOperations.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFrontFormat("YieldingBlock {0}\n", Name); // then nested content if (NestedOperationsList != null) { builder.Indent(); NestedOperationsList.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFrontFormat("BubbleUpYieldIterated on {0}\n", NestedMatchObjectName); // then nested content if (NestedOperationsList != null) { builder.Indent(); NestedOperationsList.Dump(builder); builder.Unindent(); } }
/// <summary> /// Dumps search program /// </summary> public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFrontFormat("Search program {0} of alternative case\n", Parallel ? Name + "_parallelized" : Name); // then nested content if (OperationsList != null) { builder.Indent(); OperationsList.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFrontFormat("BubbleUpYieldAlternativeCase on {0}.{1} case match type {2} {3}\n", MatchObjectName, NestedMatchObjectName, AlternativeCaseMatchTypeName, First ? "first" : ""); // then nested content if (NestedOperationsList != null) { builder.Indent(); NestedOperationsList.Dump(builder); builder.Unindent(); } }
public override void Emit(SourceBuilder sourceCode) { // emit initialization with element mapped from unique index string tempVariableForUniqueResult = NamesOfEntities.MapByUniqueTemporary(PatternElementName); sourceCode.AppendFrontFormat("if({0}==null || !({0} is {1}))", tempVariableForUniqueResult, IsNode ? "GRGEN_LIBGR.INode" : "GRGEN_LIBGR.IEdge"); // emit check failed code sourceCode.Append("{\n"); sourceCode.Indent(); CheckFailedOperations.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); // assign the value to the candidate variable, cast it to the variable type string typeOfVariableContainingCandidate = "GRGEN_LGSP." + (IsNode ? "LGSPNode" : "LGSPEdge"); string variableContainingCandidate = NamesOfEntities.CandidateVariable(PatternElementName); sourceCode.AppendFrontFormat("{0} = ({1}){2};\n", variableContainingCandidate, typeOfVariableContainingCandidate, tempVariableForUniqueResult); }
public override void Emit(SourceBuilder sourceCode) { if (Type == ContinueOperationType.ByReturn) { if (InParallelizedBody) { sourceCode.AppendFrontFormat("return;\n"); } else { if (ReturnMatches) { #if ENSURE_FLAGS_IN_GRAPH_ARE_EMPTY_AT_LEAVING_TOP_LEVEL_MATCHING_ACTION sourceCode.AppendFront("graph.CheckEmptyFlags();\n"); #endif sourceCode.AppendFront("return matches;\n"); } else { sourceCode.AppendFront("return;\n"); } } } else if (Type == ContinueOperationType.ByContinue) { if (ContinueAtParallelizedLoop) //re-aquire parallel matching enumeration lock before entering loop header //sourceCode.AppendFront("Monitor.Enter(this);\n"); { sourceCode.AppendFront("while(Interlocked.CompareExchange(ref iterationLock, 1, 0) != 0) Thread.SpinWait(10);//lock parallel matching enumeration with iteration lock\n"); } sourceCode.AppendFront("continue;\n"); } else //Type == ContinueOperationType.ByGoto { sourceCode.AppendFrontFormat("goto {0};\n", LabelName); } }
public void EmitRewritingRuleAllCallRandom(SourceBuilder source) { // as long as a further rewrite has to be selected: randomly choose next match, rewrite it and remove it from available matches; fire the next match event after the first SequenceRuleAllCall seqRuleAll = (SequenceRuleAllCall)ruleCallGen.seqRule; if (returnParameterDeclarations.Length != 0) { source.AppendFront(returnParameterDeclarationsAllCall + "\n"); } String matchesToChoose = "numchooserandomvar_" + seqRuleAll.Id; // variable storing number of matches to choose randomly source.AppendFrontFormat("int {0} = (int){1};\n", matchesToChoose, seqRuleAll.MaxVarChooseRandom != null ? ruleCallGen.seqHelper.GetVar(seqRuleAll.MaxVarChooseRandom) : (seqRuleAll.MinSpecified ? "2147483647" : "1")); source.AppendFrontFormat("if({0}.Count < {1}) {1} = {0}.Count;\n", matchesName, matchesToChoose); source.AppendFrontFormat("for(int i = 0; i < {0}; ++i)\n", matchesToChoose); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(i != 0) procEnv.RewritingNextMatch();\n"); source.AppendFront(matchType + " " + matchName + " = " + matchesName + ".RemoveMatchExact(GRGEN_LIBGR.Sequence.randomGenerator.Next(" + matchesName + ".Count));\n"); if (returnParameterDeclarations.Length != 0) { source.AppendFront(returnParameterDeclarations + "\n"); } source.AppendFront(ruleCallGen.ruleName + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if (returnAssignments.Length != 0) { source.AppendFront(intermediateReturnAssignmentsAllCall + "\n"); } source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed++;\n"); source.Unindent(); source.AppendFront("}\n"); if (returnAssignments.Length != 0) { source.AppendFront(returnAssignmentsAllCall + "\n"); } }
public override void Emit(SourceBuilder sourceCode) { // emit check decision string variableContainingCandidate = NamesOfEntities.CandidateVariable(PatternElementName); string variableContainingOtherElement = NamesOfEntities.CandidateVariable(OtherPatternElementName); sourceCode.AppendFrontFormat("if({0}!={1}) ", variableContainingCandidate, variableContainingOtherElement); // emit check failed code sourceCode.Append("{\n"); sourceCode.Indent(); CheckFailedOperations.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
/// <summary> // generate implementation of the exact action interface, // delegate calls of the inexact action interface IAction to the exact action interface /// </summary> void GenerateActionImplementation(SourceBuilder sb, LGSPRulePattern matchingPattern) { StringBuilder sbInParameters = new StringBuilder(); StringBuilder sbInArguments = new StringBuilder(); StringBuilder sbInArgumentsFromArray = new StringBuilder(); for(int i = 0; i < matchingPattern.Inputs.Length; ++i) { sbInParameters.Append(", "); sbInParameters.Append(TypesHelper.TypeName(matchingPattern.Inputs[i])); sbInParameters.Append(" "); sbInParameters.Append(matchingPattern.InputNames[i]); sbInArguments.Append(", "); sbInArguments.Append(matchingPattern.InputNames[i]); sbInArgumentsFromArray.Append(", ("); sbInArgumentsFromArray.Append(TypesHelper.TypeName(matchingPattern.Inputs[i])); sbInArgumentsFromArray.Append(") parameters["); sbInArgumentsFromArray.Append(i); sbInArgumentsFromArray.Append("]"); } String inParameters = sbInParameters.ToString(); String inArguments = sbInArguments.ToString(); String inArgumentsFromArray = sbInArgumentsFromArray.ToString(); StringBuilder sbOutParameters = new StringBuilder(); StringBuilder sbRefParameters = new StringBuilder(); StringBuilder sbOutLocals = new StringBuilder(); StringBuilder sbRefLocals = new StringBuilder(); StringBuilder sbOutArguments = new StringBuilder(); StringBuilder sbRefArguments = new StringBuilder(); StringBuilder sbOutIntermediateLocalsAll = new StringBuilder(); StringBuilder sbOutParametersAll = new StringBuilder(); StringBuilder sbOutArgumentsAll = new StringBuilder(); StringBuilder sbIntermediateLocalArgumentsAll = new StringBuilder(); StringBuilder sbOutClassArgumentsAll = new StringBuilder(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sbOutParameters.Append(", out "); sbOutParameters.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbOutParameters.Append(" output_"); sbOutParameters.Append(i); sbRefParameters.Append(", ref "); sbRefParameters.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbRefParameters.Append(" output_"); sbRefParameters.Append(i); sbOutLocals.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbOutLocals.Append(" output_"); sbOutLocals.Append(i); sbOutLocals.Append("; "); sbRefLocals.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbRefLocals.Append(" output_"); sbRefLocals.Append(i); sbRefLocals.Append(" = "); sbRefLocals.Append(TypesHelper.DefaultValueString(matchingPattern.Outputs[i].PackagePrefixedName, model)); sbRefLocals.Append("; "); sbOutArguments.Append(", out output_"); sbOutArguments.Append(i); sbRefArguments.Append(", ref output_"); sbRefArguments.Append(i); sbOutIntermediateLocalsAll.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbOutIntermediateLocalsAll.Append(" output_local_"); sbOutIntermediateLocalsAll.Append(i); sbOutIntermediateLocalsAll.Append("; "); sbOutParametersAll.Append(", List<"); sbOutParametersAll.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbOutParametersAll.Append("> output_"); sbOutParametersAll.Append(i); sbOutArgumentsAll.Append(", output_"); sbOutArgumentsAll.Append(i); sbIntermediateLocalArgumentsAll.Append(", out output_local_"); sbIntermediateLocalArgumentsAll.Append(i); sbOutClassArgumentsAll.Append(", output_list_"); sbOutClassArgumentsAll.Append(i); } String outParameters = sbOutParameters.ToString(); String refParameters = sbRefParameters.ToString(); String outLocals = sbOutLocals.ToString(); String refLocals = sbRefLocals.ToString(); String outArguments = sbOutArguments.ToString(); String refArguments = sbRefArguments.ToString(); String outIntermediateLocalsAll = sbOutIntermediateLocalsAll.ToString(); String outParametersAll = sbOutParametersAll.ToString(); String outArgumentsAll = sbOutArgumentsAll.ToString(); String intermediateLocalArgumentsAll = sbIntermediateLocalArgumentsAll.ToString(); String outClassArgumentsAll = sbOutClassArgumentsAll.ToString(); String matchingPatternClassName = matchingPattern.GetType().Name; String patternName = matchingPattern.name; String matchType = matchingPatternClassName + "." + NamesOfEntities.MatchInterfaceName(patternName); String matchesType = "GRGEN_LIBGR.IMatchesExact<" + matchType + ">"; // implementation of exact action interface sb.AppendFront("/// <summary> Type of the matcher method (with parameters processing environment containing host graph, maximum number of matches to search for (zero=unlimited), and rule parameters; returning found matches). </summary>\n"); sb.AppendFrontFormat("public delegate {0} MatchInvoker(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv, int maxMatches{1});\n", matchesType, inParameters); sb.AppendFront("/// <summary> A delegate pointing to the current matcher program for this rule. </summary>\n"); sb.AppendFront("public MatchInvoker DynamicMatch;\n"); sb.AppendFront("/// <summary> The RulePattern object from which this LGSPAction object has been created. </summary>\n"); sb.AppendFront("public GRGEN_LIBGR.IRulePattern RulePattern { get { return _rulePattern; } }\n"); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFront("List<"); sb.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sb.Append("> output_list_"); sb.Append(i.ToString()); sb.Append(" = new List<"); sb.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sb.Append(">();\n"); } sb.AppendFrontFormat("public {0} Match(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int maxMatches{1})\n", matchesType, inParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, maxMatches{0});\n", inArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public void Modify(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, {0} match{1})\n", matchType, outParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, match{0});\n", outArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public void ModifyAll(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, {0} matches{1})\n", matchesType, outParametersAll); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("foreach({0} match in matches)\n", matchType); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0}\n", outIntermediateLocalsAll); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, match{0});\n", intermediateLocalArgumentsAll); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("output_{0}.Add(output_local_{0});\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public bool Apply(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0}{1})\n", inParameters, refParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{1});\n", matchesType, inArguments); sb.AppendFront("if(matches.Count <= 0) return false;\n"); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, matches.First{0});\n", outArguments); sb.AppendFront("return true;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public int ApplyAll(int maxMatches, GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0}{1})\n", inParameters, outParametersAll); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, maxMatches{1});\n", matchesType, inArguments); sb.AppendFront("if(matches.Count <= 0) return 0;\n"); sb.AppendFrontFormat("foreach({0} match in matches)\n", matchType); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0}\n", outIntermediateLocalsAll); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, match{0});\n", intermediateLocalArgumentsAll); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("output_{0}.Add(output_local_{0});\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return matches.Count;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public bool ApplyStar(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0})\n", inParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches;\n", matchesType); sb.AppendFrontFormat("{0}\n", outLocals); sb.AppendFront("while(true)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{0});\n", inArguments); sb.AppendFront("if(matches.Count <= 0) return true;\n"); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, matches.First{0});\n", outArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public bool ApplyPlus(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0})\n", inParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{1});\n", matchesType, inArguments); sb.AppendFront("if(matches.Count <= 0) return false;\n"); sb.AppendFrontFormat("{0}\n", outLocals); sb.AppendFront("do\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, matches.First{0});\n", outArguments); sb.AppendFrontFormat("matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{0});\n", inArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("while(matches.Count > 0) ;\n"); sb.AppendFront("return true;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public bool ApplyMinMax(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int min, int max{0})\n", inParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches;\n", matchesType); sb.AppendFrontFormat("{0}\n", outLocals); sb.AppendFront("for(int i = 0; i < max; i++)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{0});\n", inArguments); sb.AppendFront("if(matches.Count <= 0) return i >= min;\n"); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, matches.First{0});\n", outArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return true;\n"); sb.Unindent(); sb.AppendFront("}\n"); // implementation of inexact action interface by delegation to exact action interface sb.AppendFront("// implementation of inexact action interface by delegation to exact action interface\n"); sb.AppendFront("public GRGEN_LIBGR.IMatches Match(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int maxMatches, object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return Match(actionEnv, maxMatches{0});\n", inArgumentsFromArray); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("public object[] Modify(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, GRGEN_LIBGR.IMatch match)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0}\n", outLocals); sb.AppendFrontFormat("Modify(actionEnv, ({0})match{1});\n", matchType, outArguments); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArray[{0}] = output_{0};\n", i); } sb.AppendFront("return ReturnArray;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("public List<object[]> ModifyAll(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, GRGEN_LIBGR.IMatches matches)\n"); sb.AppendFront("{\n"); sb.Indent(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFront("output_list_"); sb.Append(i.ToString()); sb.Append(".Clear();\n"); } sb.AppendFrontFormat("ModifyAll(actionEnv, ({0})matches{1});\n", matchesType, outClassArgumentsAll); sb.AppendFront("while(AvailableReturnArrays.Count < matches.Count) AvailableReturnArrays.Add(new object[" + matchingPattern.Outputs.Length + "]);\n"); sb.AppendFront("ReturnArrayListForAll.Clear();\n"); sb.AppendFront("for(int i=0; i<matches.Count; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("ReturnArrayListForAll.Add(AvailableReturnArrays[i]);\n"); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArrayListForAll[i][{0}] = output_list_{0}[i];\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return ReturnArrayListForAll;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("object[] GRGEN_LIBGR.IAction.Apply(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) { sb.AppendFrontFormat("{0}\n", refLocals); sb.AppendFrontFormat("if(Apply(actionEnv{0})) ", refArguments); sb.Append("{\n"); sb.Indent(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArray[{0}] = output_{0};\n", i); } sb.AppendFront("return ReturnArray;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("else return null;\n"); } else sb.AppendFront("throw new Exception();\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("object[] GRGEN_LIBGR.IAction.Apply(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0}\n", refLocals); sb.AppendFrontFormat("if(Apply(actionEnv{0}{1})) ", inArgumentsFromArray, refArguments); sb.Append("{\n"); sb.Indent(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArray[{0}] = output_{0};\n", i); } sb.AppendFront("return ReturnArray;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("else return null;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("public List<object[]> Reserve(int numReturns)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("while(AvailableReturnArrays.Count < numReturns) AvailableReturnArrays.Add(new object[" + matchingPattern.Outputs.Length + "]);\n"); sb.AppendFront("ReturnArrayListForAll.Clear();\n"); sb.AppendFront("for(int i=0; i<numReturns; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("ReturnArrayListForAll.Add(AvailableReturnArrays[i]);\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return ReturnArrayListForAll;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("List<object[]> GRGEN_LIBGR.IAction.ApplyAll(int maxMatches, GRGEN_LIBGR.IActionExecutionEnvironment actionEnv)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) { for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFront("output_list_"); sb.Append(i.ToString()); sb.Append(".Clear();\n"); } sb.AppendFrontFormat("int matchesCount = ApplyAll(maxMatches, actionEnv{0});\n", outClassArgumentsAll); sb.AppendFront("while(AvailableReturnArrays.Count < matchesCount) AvailableReturnArrays.Add(new object[" + matchingPattern.Outputs.Length + "]);\n"); sb.AppendFront("ReturnArrayListForAll.Clear();\n"); sb.AppendFront("for(int i=0; i<matchesCount; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("ReturnArrayListForAll.Add(AvailableReturnArrays[i]);\n"); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArrayListForAll[i][{0}] = output_list_{0}[i];\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return ReturnArrayListForAll;\n"); } else sb.AppendFront("throw new Exception();\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("List<object[]> GRGEN_LIBGR.IAction.ApplyAll(int maxMatches, GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFront("output_list_"); sb.Append(i.ToString()); sb.Append(".Clear();\n"); } sb.AppendFrontFormat("int matchesCount = ApplyAll(maxMatches, actionEnv{0}{1});\n", inArgumentsFromArray, outClassArgumentsAll); sb.AppendFront("while(AvailableReturnArrays.Count < matchesCount) AvailableReturnArrays.Add(new object[" + matchingPattern.Outputs.Length + "]);\n"); sb.AppendFront("ReturnArrayListForAll.Clear();\n"); sb.AppendFront("for(int i=0; i<matchesCount; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("ReturnArrayListForAll.Add(AvailableReturnArrays[i]);\n"); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArrayListForAll[i][{0}] = output_list_{0}[i];\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return ReturnArrayListForAll;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyStar(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) sb.AppendFront("return ApplyStar(actionEnv);\n"); else sb.AppendFront("throw new Exception(); return false;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyStar(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return ApplyStar(actionEnv{0});\n", inArgumentsFromArray); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyPlus(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) sb.AppendFront("return ApplyPlus(actionEnv);\n"); else sb.AppendFront("throw new Exception(); return false;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyPlus(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return ApplyPlus(actionEnv{0});\n", inArgumentsFromArray); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyMinMax(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int min, int max)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) sb.AppendFront("return ApplyMinMax(actionEnv, min, max);\n"); else sb.AppendFront("throw new Exception(); return false;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyMinMax(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int min, int max, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return ApplyMinMax(actionEnv, min, max{0});\n", inArgumentsFromArray); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("void GRGEN_LIBGR.IAction.Filter(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, GRGEN_LIBGR.IMatches matches, GRGEN_LIBGR.FilterCall filter)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("if(filter.IsAutoSupplied) {\n"); sb.Indent(); sb.AppendFront("switch(filter.Name) {\n"); sb.Indent(); sb.AppendFront("case \"keepFirst\": matches.FilterKeepFirst((int)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"keepLast\": matches.FilterKeepLast((int)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"keepFirstFraction\": matches.FilterKeepFirstFraction((double)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"keepLastFraction\": matches.FilterKeepLastFraction((double)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"removeFirst\": matches.FilterRemoveFirst((int)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"removeLast\": matches.FilterRemoveLast((int)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"removeFirstFraction\": matches.FilterRemoveFirstFraction((double)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"removeLastFraction\": matches.FilterRemoveLastFraction((double)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("default: throw new Exception(\"Unknown auto supplied filter name!\");\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("switch(filter.FullName) {\n"); sb.Indent(); foreach(IFilter filter in matchingPattern.Filters) { if(filter is IFilterAutoGenerated) { if(((IFilterAutoGenerated)filter).Entity != null) { sb.AppendFrontFormat("case \"{1}<{2}>\": GRGEN_ACTIONS.{4}MatchFilters.Filter_{0}_{1}_{2}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({3})matches); break;\n", patternName, filter.Name, ((IFilterAutoGenerated)filter).Entity, matchesType, TypesHelper.GetPackagePrefixDot(filter.Package)); if(filter.Package != null) sb.AppendFrontFormat("case \"{5}{1}<{2}>\": GRGEN_ACTIONS.{4}MatchFilters.Filter_{0}_{1}_{2}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({3})matches); break;\n", patternName, filter.Name, ((IFilterAutoGenerated)filter).Entity, matchesType, filter.Package + ".", filter.Package + "::"); } else // auto { sb.AppendFrontFormat("case \"{1}\": GRGEN_ACTIONS.{3}MatchFilters.Filter_{0}_{1}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({2})matches); break;\n", patternName, filter.Name, matchesType, TypesHelper.GetPackagePrefixDot(filter.Package)); if(filter.Package != null) sb.AppendFrontFormat("case \"{4}{1}\": GRGEN_ACTIONS.{3}MatchFilters.Filter_{0}_{1}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({2})matches); break;\n", patternName, filter.Name, matchesType, filter.Package + ".", filter.Package + "::"); } } else { IFilterFunction filterFunction = (IFilterFunction)filter; sb.AppendFrontFormat("case \"{0}\": GRGEN_ACTIONS.{1}MatchFilters.Filter_{2}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({3})matches", filterFunction.Name, TypesHelper.GetPackagePrefixDot(filterFunction.Package), filterFunction.Name, matchesType); for(int i=0; i<filterFunction.Inputs.Length; ++i) { sb.AppendFormat(", ({0})(filter.ArgumentExpressions[{1}]!=null ? filter.ArgumentExpressions[{1}].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[{1}])", TypesHelper.TypeName(filterFunction.Inputs[i]), i); } sb.Append("); break;\n"); if(filter.Package != null) { sb.AppendFrontFormat("case \"{4}{0}\": GRGEN_ACTIONS.{1}MatchFilters.Filter_{2}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({3})matches", filterFunction.Name, TypesHelper.GetPackagePrefixDot(filterFunction.Package), filterFunction.Name, matchesType, filter.Package + "::"); for(int i = 0; i < filterFunction.Inputs.Length; ++i) { sb.AppendFormat(", ({0})(filter.ArgumentExpressions[{1}]!=null ? filter.ArgumentExpressions[{1}].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[{1}])", TypesHelper.TypeName(filterFunction.Inputs[i]), i); } sb.Append("); break;\n"); } } } sb.AppendFront("default: throw new Exception(\"Unknown filter name!\");\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.Unindent(); sb.AppendFront("}\n"); }
void EmitSequenceComputation(SequenceComputation seqComp, SourceBuilder source) { // take care that the operations returning a value are emitted similarily to expressions, // whereas the operations returning no value are emitted as statements switch(seqComp.SequenceComputationType) { case SequenceComputationType.Then: { SequenceComputationThen seqThen = (SequenceComputationThen)seqComp; EmitSequenceComputation(seqThen.left, source); EmitSequenceComputation(seqThen.right, source); source.AppendFront(SetResultVar(seqThen, GetResultVar(seqThen.right))); break; } case SequenceComputationType.Assignment: { SequenceComputationAssignment seqAssign = (SequenceComputationAssignment)seqComp; if(seqAssign.SourceValueProvider is SequenceComputationAssignment) { EmitSequenceComputation(seqAssign.SourceValueProvider, source); EmitAssignment(seqAssign.Target, GetResultVar(seqAssign.SourceValueProvider), source); source.AppendFront(SetResultVar(seqAssign, GetResultVar(seqAssign.Target))); } else { string comp = GetSequenceExpression((SequenceExpression)seqAssign.SourceValueProvider, source); EmitAssignment(seqAssign.Target, comp, source); source.AppendFront(SetResultVar(seqAssign, GetResultVar(seqAssign.Target))); } break; } case SequenceComputationType.VariableDeclaration: { SequenceComputationVariableDeclaration seqVarDecl = (SequenceComputationVariableDeclaration)seqComp; source.AppendFront(SetVar(seqVarDecl.Target, TypesHelper.DefaultValueString(seqVarDecl.Target.Type, model))); source.AppendFront(SetResultVar(seqVarDecl, GetVar(seqVarDecl.Target))); break; } case SequenceComputationType.ContainerAdd: { SequenceComputationContainerAdd seqAdd = (SequenceComputationContainerAdd)seqComp; string container = GetContainerValue(seqAdd); if(seqAdd.ContainerType(env) == "") { if(seqAdd.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqAdd.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqAdd.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqAdd.Id + " = elem_" + seqAdd.Id + ".Type.GetAttributeType(\"" + seqAdd.Attribute.AttributeName + "\");\n"); } string containerVar = "tmp_eval_once_" + seqAdd.Id; source.AppendFront("object " + containerVar + " = " + container + ";\n"); string sourceValue = "srcval_" + seqAdd.Id; source.AppendFront("object " + sourceValue + " = " + GetSequenceExpression(seqAdd.Expr, source) + ";\n"); string destinationValue = seqAdd.ExprDst == null ? null : "dstval_" + seqAdd.Id; source.AppendFront("if(" + containerVar + " is IList) {\n"); source.Indent(); if(destinationValue != null && !TypesHelper.IsSameOrSubtype(seqAdd.ExprDst.Type(env), "int", model)) source.AppendFront("throw new Exception(\"Can't add non-int key to array\");\n"); else { string array = "((System.Collections.IList)" + containerVar + ")"; if(destinationValue != null) source.AppendFront("int " + destinationValue + " = (int)" + GetSequenceExpression(seqAdd.ExprDst, source) + ";\n"); if(seqAdd.Attribute != null) { if(destinationValue != null) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); } else { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); } } if(destinationValue == null) source.AppendFront(array + ".Add(" + sourceValue + ");\n"); else source.AppendFront(array + ".Insert(" + destinationValue + ", " + sourceValue + ");\n"); if(seqAdd.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); } } } source.Unindent(); source.AppendFront("} else if(" + containerVar + " is GRGEN_LIBGR.IDeque) {\n"); source.Indent(); if(destinationValue != null && !TypesHelper.IsSameOrSubtype(seqAdd.ExprDst.Type(env), "int", model)) source.AppendFront("throw new Exception(\"Can't add non-int key to deque\");\n"); else { string deque = "((GRGEN_LIBGR.IDeque)" + containerVar + ")"; if(destinationValue != null) source.AppendFront("int " + destinationValue + " = (int)" + GetSequenceExpression(seqAdd.ExprDst, source) + ";\n"); if(seqAdd.Attribute != null) { if(destinationValue != null) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); } else { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); } } if(destinationValue == null) source.AppendFront(deque + ".Enqueue(" + sourceValue + ");\n"); else source.AppendFront(deque + ".EnqueueAt(" + destinationValue + ", " + sourceValue + ");\n"); if(seqAdd.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); } } } source.Unindent(); source.AppendFront("} else {\n"); source.Indent(); if(destinationValue != null) source.AppendFront("object " + destinationValue + " = " + GetSequenceExpression(seqAdd.ExprDst, source) + ";\n"); string dictionary = "((System.Collections.IDictionary)" + containerVar + ")"; if(seqAdd.Attribute != null) { if(seqAdd.ExprDst != null) // must be map { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + destinationValue + ", " + sourceValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + destinationValue + ", " + sourceValue + ");\n"); } else { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); } } if(destinationValue == null) source.AppendFront(dictionary + "[" + sourceValue + "] = null;\n"); else source.AppendFront(dictionary + "[" + sourceValue + "] = " + destinationValue + ";\n"); if(seqAdd.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); } } source.Unindent(); source.AppendFront("}\n"); source.AppendFront(SetResultVar(seqAdd, containerVar)); } else if(seqAdd.ContainerType(env).StartsWith("array")) { string array = container; string arrayValueType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(seqAdd.ContainerType(env)), model); string sourceValue = "srcval_" + seqAdd.Id; source.AppendFront(arrayValueType + " " + sourceValue + " = (" + arrayValueType + ")" + GetSequenceExpression(seqAdd.Expr, source) + ";\n"); string destinationValue = seqAdd.ExprDst == null ? null : "dstval_" + seqAdd.Id; if(destinationValue != null) source.AppendFront("int " + destinationValue + " = (int)" + GetSequenceExpression(seqAdd.ExprDst, source) + ";\n"); if(seqAdd.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqAdd.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqAdd.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqAdd.Id + " = elem_" + seqAdd.Id + ".Type.GetAttributeType(\"" + seqAdd.Attribute.AttributeName + "\");\n"); if(destinationValue != null) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); } else { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); } } if(destinationValue == null) source.AppendFront(array + ".Add(" + sourceValue + ");\n"); else source.AppendFront(array + ".Insert(" + destinationValue + ", " + sourceValue + ");\n"); if(seqAdd.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); } } source.AppendFront(SetResultVar(seqAdd, container)); } else if(seqAdd.ContainerType(env).StartsWith("deque")) { string deque = container; string dequeValueType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(seqAdd.ContainerType(env)), model); string sourceValue = "srcval_" + seqAdd.Id; source.AppendFront(dequeValueType + " " + sourceValue + " = (" + dequeValueType + ")" + GetSequenceExpression(seqAdd.Expr, source) + ";\n"); string destinationValue = seqAdd.ExprDst == null ? null : "dstval_" + seqAdd.Id; if(destinationValue != null) source.AppendFront("int " + destinationValue + " = (int)" + GetSequenceExpression(seqAdd.ExprDst, source) + ";\n"); if(seqAdd.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqAdd.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqAdd.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqAdd.Id + " = elem_" + seqAdd.Id + ".Type.GetAttributeType(\"" + seqAdd.Attribute.AttributeName + "\");\n"); if(destinationValue != null) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", " + destinationValue + ");\n"); } else { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); } } if(destinationValue == null) source.AppendFront(deque + ".Enqueue(" + sourceValue + ");\n"); else source.AppendFront(deque + ".EnqueueAt(" + destinationValue + ", " + sourceValue + ");\n"); if(seqAdd.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); } } source.AppendFront(SetResultVar(seqAdd, container)); } else { string dictionary = container; string dictSrcType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(seqAdd.ContainerType(env)), model); string sourceValue = " srcval_" + seqAdd.Id; source.AppendFront(dictSrcType + " " + sourceValue + " = (" + dictSrcType + ")" + GetSequenceExpression(seqAdd.Expr, source) + ";\n"); string dictDstType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractDst(seqAdd.ContainerType(env)), model); string destinationValue = seqAdd.ExprDst == null ? null : "dstval_" + seqAdd.Id; if(destinationValue != null) source.AppendFront(dictDstType + " " + destinationValue + " = (" + dictDstType + ")" + GetSequenceExpression(seqAdd.ExprDst, source) + ";\n"); if(seqAdd.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqAdd.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqAdd.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqAdd.Id + " = elem_" + seqAdd.Id + ".Type.GetAttributeType(\"" + seqAdd.Attribute.AttributeName + "\");\n"); if(destinationValue != null) // must be map { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + destinationValue + ", " + sourceValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + destinationValue + ", " + sourceValue + ");\n"); } else { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ", GRGEN_LIBGR.AttributeChangeType.PutElement, " + sourceValue + ", null);\n"); } } if(destinationValue == null) source.AppendFront(dictionary + "[" + sourceValue + "] = null;\n"); else source.AppendFront(dictionary + "[" + sourceValue + "] = " + destinationValue + ";\n"); if(seqAdd.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqAdd.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqAdd.Id + ", attrType_" + seqAdd.Id + ");\n"); } } source.AppendFront(SetResultVar(seqAdd, container)); } break; } case SequenceComputationType.ContainerRem: { SequenceComputationContainerRem seqDel = (SequenceComputationContainerRem)seqComp; string container = GetContainerValue(seqDel); if(seqDel.ContainerType(env) == "") { if(seqDel.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqDel.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqDel.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqDel.Id + " = elem_" + seqDel.Id + ".Type.GetAttributeType(\"" + seqDel.Attribute.AttributeName + "\");\n"); } string containerVar = "tmp_eval_once_" + seqDel.Id; source.AppendFront("object " + containerVar + " = " + container + ";\n"); string sourceValue = seqDel.Expr == null ? null : "srcval_" + seqDel.Id; source.AppendFront("if(" + containerVar + " is IList) {\n"); source.Indent(); if(sourceValue != null && !TypesHelper.IsSameOrSubtype(seqDel.Expr.Type(env), "int", model)) source.AppendFront("throw new Exception(\"Can't remove non-int index from array\");\n"); else { string array = "((System.Collections.IList)" + containerVar + ")"; if(sourceValue != null) source.AppendFront("int " + sourceValue + " = (int)" + GetSequenceExpression(seqDel.Expr, source) + ";\n"); if(seqDel.Attribute != null) { if(sourceValue != null) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); } else { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, null);\n"); } } if(sourceValue == null) source.AppendFront(array + ".RemoveAt(" + array + ".Count - 1);\n"); else source.AppendFront(array + ".RemoveAt(" + sourceValue + ");\n"); if(seqDel.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); } } } source.Unindent(); source.AppendFront("} else if(" + containerVar + " is GRGEN_LIBGR.IDeque) {\n"); source.Indent(); if(sourceValue != null && !TypesHelper.IsSameOrSubtype(seqDel.Expr.Type(env), "int", model)) source.AppendFront("throw new Exception(\"Can't remove non-int index from deque\");\n"); else { string deque = "((GRGEN_LIBGR.IDeque)" + containerVar + ")"; if(sourceValue != null) source.AppendFront("int " + sourceValue + " = (int)" + GetSequenceExpression(seqDel.Expr, source) + ";\n"); if(seqDel.Attribute != null) { if(sourceValue != null) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); } else { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, null);\n"); } } if(sourceValue == null) source.AppendFront(deque + ".Dequeue();\n"); else source.AppendFront(deque + ".DequeueAt(" + sourceValue + ");\n"); if(seqDel.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); } } } source.Unindent(); source.AppendFront("} else {\n"); source.Indent(); string dictionary = "((System.Collections.IDictionary)" + containerVar + ")"; if(sourceValue != null) source.AppendFront("object " + sourceValue + " = " + GetSequenceExpression(seqDel.Expr, source) + ";\n"); if(seqDel.Attribute != null) { source.AppendFront("if(GRGEN_LIBGR.TypesHelper.ExtractDst(GRGEN_LIBGR.TypesHelper.AttributeTypeToXgrsType(attrType_" + seqDel.Id + ")) == \"SetValueType\")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, " + sourceValue + ", null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, " + sourceValue + ", null);\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); source.Unindent(); source.AppendFront("}\n"); } if(sourceValue == null) source.AppendFront("throw new Exception(\""+seqDel.Container.PureName+".rem() only possible on array or deque!\");\n"); else source.AppendFront(dictionary + ".Remove(" + sourceValue + ");\n"); if(seqDel.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); } } source.Unindent(); source.AppendFront("}\n"); source.AppendFront(SetResultVar(seqDel, containerVar)); } else if(seqDel.ContainerType(env).StartsWith("array")) { string array = container; string sourceValue = seqDel.Expr == null ? null : "srcval_" + seqDel.Id; if(sourceValue != null) source.AppendFront("int " + sourceValue + " = (int)" + GetSequenceExpression(seqDel.Expr, source) + ";\n"); if(seqDel.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqDel.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqDel.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqDel.Id + " = elem_" + seqDel.Id + ".Type.GetAttributeType(\"" + seqDel.Attribute.AttributeName + "\");\n"); if(sourceValue != null) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); } else { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, null);\n"); } } if(sourceValue == null) source.AppendFront(array + ".RemoveAt(" + array + ".Count - 1);\n"); else source.AppendFront(array + ".RemoveAt(" + sourceValue + ");\n"); if(seqDel.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); } } source.AppendFront(SetResultVar(seqDel, container)); } else if(seqDel.ContainerType(env).StartsWith("deque")) { string deque = container; string sourceValue = seqDel.Expr == null ? null : "srcval_" + seqDel.Id; if(sourceValue != null) source.AppendFront("int " + sourceValue + " = (int)" + GetSequenceExpression(seqDel.Expr, source) + ";\n"); if(seqDel.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqDel.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqDel.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqDel.Id + " = elem_" + seqDel.Id + ".Type.GetAttributeType(\"" + seqDel.Attribute.AttributeName + "\");\n"); if(sourceValue != null) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); } else { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, null);\n"); } } if(sourceValue == null) source.AppendFront(deque + ".Dequeue();\n"); else source.AppendFront(deque + ".DequeueAt(" + sourceValue + ");\n"); if(seqDel.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); } } source.AppendFront(SetResultVar(seqDel, container)); } else { string dictionary = container; string dictSrcType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(seqDel.ContainerType(env)), model); string sourceValue = "srcval_" + seqDel.Id; source.AppendFront(dictSrcType + " " + sourceValue + " = (" + dictSrcType + ")" + GetSequenceExpression(seqDel.Expr, source) + ";\n"); if(seqDel.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqDel.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqDel.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqDel.Id + " = elem_" + seqDel.Id + ".Type.GetAttributeType(\"" + seqDel.Attribute.AttributeName + "\");\n"); if(TypesHelper.ExtractDst(seqDel.ContainerType(env)) == "SetValueType") { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, " + sourceValue + ", null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, " + sourceValue + ", null);\n"); } else { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, " + sourceValue + ");\n"); } } source.AppendFront(dictionary + ".Remove(" + sourceValue + ");\n"); if(seqDel.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqDel.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqDel.Id + ", attrType_" + seqDel.Id + ");\n"); } } source.AppendFront(SetResultVar(seqDel, container)); } break; } case SequenceComputationType.ContainerClear: { SequenceComputationContainerClear seqClear = (SequenceComputationContainerClear)seqComp; string container = GetContainerValue(seqClear); if(seqClear.ContainerType(env) == "") { if(seqClear.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqClear.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqClear.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqClear.Id + " = elem_" + seqClear.Id + ".Type.GetAttributeType(\"" + seqClear.Attribute.AttributeName + "\");\n"); } string containerVar = "tmp_eval_once_" + seqClear.Id; source.AppendFront("object " + containerVar + " = " + container + ";\n"); source.AppendFront("if(" + containerVar + " is IList) {\n"); source.Indent(); string array = "((System.Collections.IList)" + containerVar + ")"; if(seqClear.Attribute != null) { source.AppendFront("for(int i_" + seqClear.Id + " = " + array + ".Count; i_" + seqClear.Id + " >= 0; --i_" + seqClear.Id + ")\n"); source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, i_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, i_" + seqClear.Id + ");\n"); } source.AppendFront(array + ".Clear();\n"); if(seqClear.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); } } source.Unindent(); source.AppendFront("} else if(" + containerVar + " is GRGEN_LIBGR.IDeque) {\n"); source.Indent(); string deque = "((GRGEN_LIBGR.IDeque)" + containerVar + ")"; if(seqClear.Attribute != null) { source.AppendFront("for(int i_" + seqClear.Id + " = " + deque + ".Count; i_" + seqClear.Id + " >= 0; --i_" + seqClear.Id + ")\n"); source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, i_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, i_" + seqClear.Id + ");\n"); } source.AppendFront(deque + ".Clear();\n"); if(seqClear.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); } } source.Unindent(); source.AppendFront("} else {\n"); source.Indent(); string dictionary = "((System.Collections.IDictionary)" + containerVar + ")"; if(seqClear.Attribute != null) { source.AppendFront("if(GRGEN_LIBGR.TypesHelper.ExtractDst(GRGEN_LIBGR.TypesHelper.AttributeTypeToXgrsType(attrType_" + seqClear.Id + ")) == \"SetValueType\")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("foreach(DictionaryEntry kvp_" + seqClear.Id + " in " + dictionary + ")\n"); source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, kvp_" + seqClear.Id + ", null);\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, kvp_" + seqClear.Id + ", null);\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("foreach(DictionaryEntry kvp_" + seqClear.Id + " in " + dictionary + ")\n"); source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, kvp_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, kvp_" + seqClear.Id + ");\n"); source.Unindent(); source.AppendFront("}\n"); } source.AppendFront(dictionary + ".Clear();\n"); if(seqClear.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); } } source.Unindent(); source.AppendFront("}\n"); source.AppendFront(SetResultVar(seqClear, containerVar)); } else if(seqClear.ContainerType(env).StartsWith("array")) { string array = container; if(seqClear.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqClear.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqClear.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqClear.Id + " = elem_" + seqClear.Id + ".Type.GetAttributeType(\"" + seqClear.Attribute.AttributeName + "\");\n"); source.AppendFront("for(int i_" + seqClear.Id + " = " + array + ".Count; i_" + seqClear.Id + " >= 0; --i_" + seqClear.Id + ")\n"); source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, i_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, i_" + seqClear.Id + ");\n"); } source.AppendFront(array + ".Clear();\n"); if(seqClear.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); } } source.AppendFront(SetResultVar(seqClear, container)); } else if(seqClear.ContainerType(env).StartsWith("deque")) { string deque = container; if(seqClear.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqClear.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqClear.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqClear.Id + " = elem_" + seqClear.Id + ".Type.GetAttributeType(\"" + seqClear.Attribute.AttributeName + "\");\n"); source.AppendFront("for(int i_" + seqClear.Id + " = " + deque + ".Count; i_" + seqClear.Id + " >= 0; --i_" + seqClear.Id + ")\n"); source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, i_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, i_" + seqClear.Id + ");\n"); } source.AppendFront(deque + ".Clear();\n"); if(seqClear.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("\tif(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\t\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); } } source.AppendFront(SetResultVar(seqClear, container)); } else { string dictionary = container; if(seqClear.Attribute != null) { source.AppendFront("GRGEN_LIBGR.IGraphElement elem_" + seqClear.Id + " = (GRGEN_LIBGR.IGraphElement)" + GetVar(seqClear.Attribute.SourceVar) + ";\n"); source.AppendFront("GRGEN_LIBGR.AttributeType attrType_" + seqClear.Id + " = elem_" + seqClear.Id + ".Type.GetAttributeType(\"" + seqClear.Attribute.AttributeName + "\");\n"); if(TypesHelper.ExtractDst(seqClear.ContainerType(env)) == "SetValueType") { source.AppendFront("foreach(DictionaryEntry kvp_" + seqClear.Id + " in " + dictionary + ")\n"); source.AppendFront("if(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, kvp_" + seqClear.Id + ", null);\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, kvp_" + seqClear.Id + ", null);\n"); } else { source.AppendFront("foreach(DictionaryEntry kvp_" + seqClear.Id + " in " + dictionary + ")\n"); source.AppendFront("if(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangingNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, kvp_" + seqClear.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangingEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ", GRGEN_LIBGR.AttributeChangeType.RemoveElement, null, kvp_" + seqClear.Id + ");\n"); } } source.AppendFront(dictionary + ".Clear();\n"); if(seqClear.Attribute != null) { if(gen.FireDebugEvents) { source.AppendFront("if(elem_" + seqClear.Id + " is GRGEN_LIBGR.INode)\n"); source.AppendFront("\tgraph.ChangedNodeAttribute((GRGEN_LIBGR.INode)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tgraph.ChangedEdgeAttribute((GRGEN_LIBGR.IEdge)elem_" + seqClear.Id + ", attrType_" + seqClear.Id + ");\n"); } } source.AppendFront(SetResultVar(seqClear, container)); } break; } case SequenceComputationType.VAlloc: source.Append("graph.AllocateVisitedFlag()"); break; case SequenceComputationType.VFree: case SequenceComputationType.VFreeNonReset: { SequenceComputationVFree seqVFree = (SequenceComputationVFree)seqComp; if(seqVFree.Reset) source.AppendFront("graph.FreeVisitedFlag((int)" + GetSequenceExpression(seqVFree.VisitedFlagExpression, source) + ");\n"); else source.AppendFront("graph.FreeVisitedFlagNonReset((int)" + GetSequenceExpression(seqVFree.VisitedFlagExpression, source) + ");\n"); source.AppendFront(SetResultVar(seqVFree, "null")); break; } case SequenceComputationType.VReset: { SequenceComputationVReset seqVReset = (SequenceComputationVReset)seqComp; source.AppendFront("graph.ResetVisitedFlag((int)" + GetSequenceExpression(seqVReset.VisitedFlagExpression, source) + ");\n"); source.AppendFront(SetResultVar(seqVReset, "null")); break; } case SequenceComputationType.DebugAdd: { SequenceComputationDebugAdd seqDebug = (SequenceComputationDebugAdd)seqComp; source.AppendFront("procEnv.DebugEntering("); for(int i = 0; i < seqDebug.ArgExprs.Count; ++i) { if(i == 0) source.Append("(string)"); else source.Append(", "); source.Append(GetSequenceExpression(seqDebug.ArgExprs[i], source)); } source.Append(");\n"); source.AppendFront(SetResultVar(seqDebug, "null")); break; } case SequenceComputationType.DebugRem: { SequenceComputationDebugRem seqDebug = (SequenceComputationDebugRem)seqComp; source.AppendFront("procEnv.DebugExiting("); for(int i = 0; i < seqDebug.ArgExprs.Count; ++i) { if(i == 0) source.Append("(string)"); else source.Append(", "); source.Append(GetSequenceExpression(seqDebug.ArgExprs[i], source)); } source.Append(");\n"); source.AppendFront(SetResultVar(seqDebug, "null")); break; } case SequenceComputationType.DebugEmit: { SequenceComputationDebugEmit seqDebug = (SequenceComputationDebugEmit)seqComp; source.AppendFront("procEnv.DebugEmitting("); for(int i = 0; i < seqDebug.ArgExprs.Count; ++i) { if(i == 0) source.Append("(string)"); else source.Append(", "); source.Append(GetSequenceExpression(seqDebug.ArgExprs[i], source)); } source.Append(");\n"); source.AppendFront(SetResultVar(seqDebug, "null")); break; } case SequenceComputationType.DebugHalt: { SequenceComputationDebugHalt seqDebug = (SequenceComputationDebugHalt)seqComp; source.AppendFront("procEnv.DebugHalting("); for(int i = 0; i < seqDebug.ArgExprs.Count; ++i) { if(i == 0) source.Append("(string)"); else source.Append(", "); source.Append(GetSequenceExpression(seqDebug.ArgExprs[i], source)); } source.Append(");\n"); source.AppendFront(SetResultVar(seqDebug, "null")); break; } case SequenceComputationType.DebugHighlight: { SequenceComputationDebugHighlight seqDebug = (SequenceComputationDebugHighlight)seqComp; source.AppendFront("List<object> values = new List<object>();\n"); source.AppendFront("List<string> annotations = new List<string>();\n"); for(int i = 1; i < seqDebug.ArgExprs.Count; ++i) { if(i % 2 == 1) source.AppendFront("values.Add(" + GetSequenceExpression(seqDebug.ArgExprs[i], source) + ");\n"); else source.AppendFront("annotations.Add((string)" + GetSequenceExpression(seqDebug.ArgExprs[i], source) + ");\n"); } source.AppendFront("procEnv.DebugHighlighting(" + GetSequenceExpression(seqDebug.ArgExprs[0], source) + ", values, annotations);\n"); source.AppendFront(SetResultVar(seqDebug, "null")); break; } case SequenceComputationType.Emit: { SequenceComputationEmit seqEmit = (SequenceComputationEmit)seqComp; bool declarationEmitted = false; for(int i = 0; i < seqEmit.Expressions.Count; ++i) { if(!(seqEmit.Expressions[i] is SequenceExpressionConstant)) { string emitVal = "emitval_" + seqEmit.Id; if(!declarationEmitted) { source.AppendFront("object " + emitVal + ";\n"); declarationEmitted = true; } source.AppendFront(emitVal + " = " + GetSequenceExpression(seqEmit.Expressions[i], source) + ";\n"); if(seqEmit.Expressions[i].Type(env) == "" || seqEmit.Expressions[i].Type(env).StartsWith("set<") || seqEmit.Expressions[i].Type(env).StartsWith("map<") || seqEmit.Expressions[i].Type(env).StartsWith("array<") || seqEmit.Expressions[i].Type(env).StartsWith("deque<")) { source.AppendFront("if(" + emitVal + " is IDictionary)\n"); source.AppendFront("\tprocEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString((IDictionary)" + emitVal + ", graph));\n"); source.AppendFront("else if(" + emitVal + " is IList)\n"); source.AppendFront("\tprocEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString((IList)" + emitVal + ", graph));\n"); source.AppendFront("else if(" + emitVal + " is GRGEN_LIBGR.IDeque)\n"); source.AppendFront("\tprocEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString((GRGEN_LIBGR.IDeque)" + emitVal + ", graph));\n"); source.AppendFront("else\n\t"); } source.AppendFront("procEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString(" + emitVal + ", graph));\n"); } else { SequenceExpressionConstant constant = (SequenceExpressionConstant)seqEmit.Expressions[i]; if(constant.Constant is string) { String text = (string)constant.Constant; text = text.Replace("\n", "\\n"); text = text.Replace("\r", "\\r"); text = text.Replace("\t", "\\t"); source.AppendFront("procEnv.EmitWriter.Write(\"" + text + "\");\n"); } else source.AppendFront("procEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString(" + GetSequenceExpression(seqEmit.Expressions[i], source) + ", graph));\n"); } } source.AppendFront(SetResultVar(seqEmit, "null")); break; } case SequenceComputationType.Record: { SequenceComputationRecord seqRec = (SequenceComputationRecord)seqComp; if(!(seqRec.Expression is SequenceExpressionConstant)) { string recVal = "recval_" + seqRec.Id; source.AppendFront("object " + recVal + " = " + GetSequenceExpression(seqRec.Expression, source) + ";\n"); if(seqRec.Expression.Type(env) == "" || seqRec.Expression.Type(env).StartsWith("set<") || seqRec.Expression.Type(env).StartsWith("map<") || seqRec.Expression.Type(env).StartsWith("array<") || seqRec.Expression.Type(env).StartsWith("deque<")) { source.AppendFront("if(" + recVal + " is IDictionary)\n"); source.AppendFront("\tprocEnv.Recorder.Write(GRGEN_LIBGR.EmitHelper.ToString((IDictionary)" + recVal + ", graph));\n"); source.AppendFront("else if(" + recVal + " is IList)\n"); source.AppendFront("\tprocEnv.Recorder.Write(GRGEN_LIBGR.EmitHelper.ToString((IList)" + recVal + ", graph));\n"); source.AppendFront("else if(" + recVal + " is GRGEN_LIBGR.IDeque)\n"); source.AppendFront("\tprocEnv.Recorder.Write(GRGEN_LIBGR.EmitHelper.ToString((GRGEN_LIBGR.IDeque)" + recVal + ", graph));\n"); source.AppendFront("else\n\t"); } source.AppendFront("procEnv.Recorder.Write(GRGEN_LIBGR.EmitHelper.ToString(" + recVal + ", graph));\n"); } else { SequenceExpressionConstant constant = (SequenceExpressionConstant)seqRec.Expression; if(constant.Constant is string) { String text = (string)constant.Constant; text = text.Replace("\n", "\\n"); text = text.Replace("\r", "\\r"); text = text.Replace("\t", "\\t"); source.AppendFront("procEnv.Recorder.Write(\"" + text + "\");\n"); } else source.AppendFront("procEnv.Recorder.Write(GRGEN_LIBGR.EmitHelper.ToString(" + GetSequenceExpression(seqRec.Expression, source) + ", graph));\n"); } source.AppendFront(SetResultVar(seqRec, "null")); break; } case SequenceComputationType.Export: { SequenceComputationExport seqExp = (SequenceComputationExport)seqComp; string expFileName = "expfilename_" + seqExp.Id; source.AppendFront("object " + expFileName + " = " + GetSequenceExpression(seqExp.Name, source) + ";\n"); string expArguments = "exparguments_" + seqExp.Id; source.AppendFront("List<string> " + expArguments + " = new List<string>();\n"); source.AppendFront(expArguments + ".Add(" + expFileName + ".ToString());\n"); string expGraph = "expgraph_" + seqExp.Id; if(seqExp.Graph != null) source.AppendFront("GRGEN_LIBGR.IGraph " + expGraph + " = (GRGEN_LIBGR.IGraph)" + GetSequenceExpression(seqExp.Graph, source) + ";\n"); else source.AppendFront("GRGEN_LIBGR.IGraph " + expGraph + " = graph;\n"); source.AppendFront(expArguments + ".Add(" + expFileName + ".ToString());\n"); source.AppendFront("if(" + expGraph + " is GRGEN_LIBGR.INamedGraph)\n"); source.AppendFront("\tGRGEN_LIBGR.Porter.Export((GRGEN_LIBGR.INamedGraph)" + expGraph + ", " + expArguments + ");\n"); source.AppendFront("else\n"); source.AppendFront("\tGRGEN_LIBGR.Porter.Export(" + expGraph + ", " + expArguments + ");\n"); source.AppendFront(SetResultVar(seqExp, "null")); break; } case SequenceComputationType.DeleteFile: { SequenceComputationDeleteFile seqDelFile = (SequenceComputationDeleteFile)seqComp; string delFileName = "delfilename_" + seqDelFile.Id; source.AppendFront("object " + delFileName + " = " + GetSequenceExpression(seqDelFile.Name, source) + ";\n"); source.AppendFront("\tSystem.IO.File.Delete((string)" + delFileName + ");\n"); source.AppendFront(SetResultVar(seqDelFile, "null")); break; } case SequenceComputationType.GraphAdd: { SequenceComputationGraphAdd seqAdd = (SequenceComputationGraphAdd)seqComp; if(seqAdd.ExprSrc == null) { string typeExpr = GetSequenceExpression(seqAdd.Expr, source); source.Append("GRGEN_LIBGR.GraphHelper.AddNodeOfType(" + typeExpr + ", graph)"); } else { string typeExpr = GetSequenceExpression(seqAdd.Expr, source); string srcExpr = GetSequenceExpression(seqAdd.ExprSrc, source); string tgtExpr = GetSequenceExpression(seqAdd.ExprDst, source); source.Append("GRGEN_LIBGR.GraphHelper.AddEdgeOfType(" + typeExpr + ", (GRGEN_LIBGR.INode)" + srcExpr + ", (GRGEN_LIBGR.INode)" + tgtExpr + ", graph)"); } break; } case SequenceComputationType.GraphRem: { SequenceComputationGraphRem seqRem = (SequenceComputationGraphRem)seqComp; string remVal = "remval_" + seqRem.Id; string seqRemExpr = GetSequenceExpression(seqRem.Expr, source); if(seqRem.Expr.Type(env) == "") { source.AppendFront("GRGEN_LIBGR.IGraphElement " + remVal + " = (GRGEN_LIBGR.IGraphElement)" + seqRemExpr + ";\n"); source.AppendFront("if(" + remVal + " is GRGEN_LIBGR.IEdge)\n"); source.AppendFront("\tgraph.Remove((GRGEN_LIBGR.IEdge)" + remVal + ");\n"); source.AppendFront("else\n"); source.AppendFront("\t{graph.RemoveEdges((GRGEN_LIBGR.INode)" + remVal + "); graph.Remove((GRGEN_LIBGR.INode)" + remVal + ");}\n"); } else { if(TypesHelper.IsSameOrSubtype(seqRem.Expr.Type(env), "Node", model)) { source.AppendFront("GRGEN_LIBGR.INode " + remVal + " = (GRGEN_LIBGR.INode)" + seqRemExpr + ";\n"); source.AppendFront("graph.RemoveEdges(" + remVal + "); graph.Remove(" + remVal + ");\n"); } else if(TypesHelper.IsSameOrSubtype(seqRem.Expr.Type(env), "Edge", model)) { source.AppendFront("GRGEN_LIBGR.IEdge " + remVal + " = (GRGEN_LIBGR.IEdge)" + seqRemExpr + ";\n"); source.AppendFront("\tgraph.Remove(" + remVal + ");\n"); } else source.AppendFront("throw new Exception(\"rem() on non-node/edge\");\n"); } source.AppendFront(SetResultVar(seqRem, "null")); break; } case SequenceComputationType.GraphClear: { SequenceComputationGraphClear seqClr = (SequenceComputationGraphClear)seqComp; source.AppendFront("graph.Clear();\n"); source.AppendFront(SetResultVar(seqClr, "null")); break; } case SequenceComputationType.GraphRetype: { SequenceComputationGraphRetype seqRetype = (SequenceComputationGraphRetype)seqComp; string typeExpr = GetSequenceExpression(seqRetype.TypeExpr, source); string elemExpr = GetSequenceExpression(seqRetype.ElemExpr, source); source.Append("GRGEN_LIBGR.GraphHelper.RetypeGraphElement((GRGEN_LIBGR.IGraphElement)" + elemExpr + ", " + typeExpr + ", graph)"); break; } case SequenceComputationType.GraphAddCopy: { SequenceComputationGraphAddCopy seqAddCopy = (SequenceComputationGraphAddCopy)seqComp; if(seqAddCopy.ExprSrc == null) { string nodeExpr = GetSequenceExpression(seqAddCopy.Expr, source); source.Append("GRGEN_LIBGR.GraphHelper.AddCopyOfNode(" + nodeExpr + ", graph)"); } else { string edgeExpr = GetSequenceExpression(seqAddCopy.Expr, source); string srcExpr = GetSequenceExpression(seqAddCopy.ExprSrc, source); string tgtExpr = GetSequenceExpression(seqAddCopy.ExprDst, source); source.Append("GRGEN_LIBGR.GraphHelper.AddCopyOfEdge(" + edgeExpr + ", (GRGEN_LIBGR.INode)" + srcExpr + ", (GRGEN_LIBGR.INode)" + tgtExpr + ", graph)"); } break; } case SequenceComputationType.GraphMerge: { SequenceComputationGraphMerge seqMrg = (SequenceComputationGraphMerge)seqComp; string tgtNodeExpr = GetSequenceExpression(seqMrg.TargetNodeExpr, source); string srcNodeExpr = GetSequenceExpression(seqMrg.SourceNodeExpr, source); source.AppendFrontFormat("graph.Merge((GRGEN_LIBGR.INode){0}, (GRGEN_LIBGR.INode){1}, \"merge\");\n", tgtNodeExpr, srcNodeExpr); source.AppendFront(SetResultVar(seqMrg, "null")); break; } case SequenceComputationType.GraphRedirectSource: { SequenceComputationGraphRedirectSource seqRedir = (SequenceComputationGraphRedirectSource)seqComp; string edgeExpr = GetSequenceExpression(seqRedir.EdgeExpr, source); string srcNodeExpr = GetSequenceExpression(seqRedir.SourceNodeExpr, source); source.AppendFrontFormat("graph.RedirectSource((GRGEN_LIBGR.IEdge){0}, (GRGEN_LIBGR.INode){1}, \"old source\");\n", edgeExpr, srcNodeExpr); source.AppendFront(SetResultVar(seqRedir, "null")); break; } case SequenceComputationType.GraphRedirectTarget: { SequenceComputationGraphRedirectTarget seqRedir = (SequenceComputationGraphRedirectTarget)seqComp; string edgeExpr = GetSequenceExpression(seqRedir.EdgeExpr, source); string tgtNodeExpr = GetSequenceExpression(seqRedir.TargetNodeExpr, source); source.AppendFrontFormat("graph.RedirectTarget((GRGEN_LIBGR.IEdge){0}, (GRGEN_LIBGR.INode){1}, \"old target\");\n", edgeExpr, tgtNodeExpr); source.AppendFront(SetResultVar(seqRedir, "null")); break; } case SequenceComputationType.GraphRedirectSourceAndTarget: { SequenceComputationGraphRedirectSourceAndTarget seqRedir = (SequenceComputationGraphRedirectSourceAndTarget)seqComp; string edgeExpr = GetSequenceExpression(seqRedir.EdgeExpr, source); string srcNodeExpr = GetSequenceExpression(seqRedir.SourceNodeExpr, source); string tgtNodeExpr = GetSequenceExpression(seqRedir.TargetNodeExpr, source); source.AppendFrontFormat("graph.RedirectSourceAndTarget((GRGEN_LIBGR.IEdge){0}, (GRGEN_LIBGR.INode){1}, (GRGEN_LIBGR.INode){2}, \"old source\", \"old target\");\n", edgeExpr, srcNodeExpr, tgtNodeExpr); source.AppendFront(SetResultVar(seqRedir, "null")); break; } case SequenceComputationType.Insert: { SequenceComputationInsert seqIns = (SequenceComputationInsert)seqComp; string graphExpr = GetSequenceExpression(seqIns.Graph, source); source.AppendFrontFormat("GRGEN_LIBGR.GraphHelper.Insert((GRGEN_LIBGR.IGraph){0}, graph);\n", graphExpr); source.AppendFront(SetResultVar(seqIns, "null")); break; } case SequenceComputationType.InsertCopy: { SequenceComputationInsertCopy seqInsCopy = (SequenceComputationInsertCopy)seqComp; string graphExpr = GetSequenceExpression(seqInsCopy.Graph, source); string rootNodeExpr = GetSequenceExpression(seqInsCopy.RootNode, source); source.AppendFormat("GRGEN_LIBGR.GraphHelper.InsertCopy((GRGEN_LIBGR.IGraph){0}, (GRGEN_LIBGR.INode){1}, graph)", graphExpr, rootNodeExpr); break; } case SequenceComputationType.InsertInduced: { SequenceComputationInsertInduced seqInsInd = (SequenceComputationInsertInduced)seqComp; source.Append("GRGEN_LIBGR.GraphHelper.InsertInduced((IDictionary<GRGEN_LIBGR.INode, GRGEN_LIBGR.SetValueType>)" + GetSequenceExpression(seqInsInd.NodeSet, source) + ", (GRGEN_LIBGR.INode)" + GetSequenceExpression(seqInsInd.RootNode, source) + ", graph)"); break; } case SequenceComputationType.InsertDefined: { SequenceComputationInsertDefined seqInsDef = (SequenceComputationInsertDefined)seqComp; source.Append("GRGEN_LIBGR.GraphHelper.InsertDefined((IDictionary<GRGEN_LIBGR.IEdge, GRGEN_LIBGR.SetValueType>)" + GetSequenceExpression(seqInsDef.EdgeSet, source) + ", (GRGEN_LIBGR.IEdge)" + GetSequenceExpression(seqInsDef.RootEdge, source) + ", graph)"); break; } case SequenceComputationType.Expression: { SequenceExpression seqExpr = (SequenceExpression)seqComp; source.AppendFront(SetResultVar(seqExpr, GetSequenceExpression(seqExpr, source))); break; } case SequenceComputationType.BuiltinProcedureCall: { SequenceComputationBuiltinProcedureCall seqCall = (SequenceComputationBuiltinProcedureCall)seqComp; SourceBuilder sb = new SourceBuilder(); EmitSequenceComputation(seqCall.BuiltinProcedure, sb); if(seqCall.ReturnVars.Count > 0) { source.AppendFront(SetVar(seqCall.ReturnVars[0], sb.ToString())); source.AppendFront(SetResultVar(seqCall, GetVar(seqCall.ReturnVars[0]))); } else { source.AppendFront(sb.ToString() + ";\n"); source.AppendFront(SetResultVar(seqCall, "null")); } break; } case SequenceComputationType.ProcedureCall: { SequenceComputationProcedureCall seqCall = (SequenceComputationProcedureCall)seqComp; String returnParameterDeclarations; String returnArguments; String returnAssignments; BuildReturnParameters(seqCall.ParamBindings, out returnParameterDeclarations, out returnArguments, out returnAssignments); if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarations + "\n"); if(seqCall.IsExternalProcedureCalled) source.AppendFront("GRGEN_EXPR.ExternalProcedures."); else source.AppendFrontFormat("GRGEN_ACTIONS.{0}Procedures.", TypesHelper.GetPackagePrefixDot(seqCall.ParamBindings.Package)); source.Append(seqCall.ParamBindings.Name); source.Append("(procEnv, graph"); source.Append(BuildParameters(seqCall.ParamBindings)); source.Append(returnArguments); source.Append(");\n"); if(returnAssignments.Length != 0) source.AppendFront(returnAssignments + "\n"); source.AppendFront(SetResultVar(seqCall, "null")); break; } case SequenceComputationType.ProcedureMethodCall: { SequenceComputationProcedureMethodCall seqCall = (SequenceComputationProcedureMethodCall)seqComp; String type = seqCall.TargetExpr != null ? seqCall.TargetExpr.Type(env) : seqCall.TargetVar.Type; if(type == "") { string tmpVarName = "tmpvar_" + tmpVarCtr.ToString(); ++tmpVarCtr; source.AppendFront("object[] " + tmpVarName + " = "); source.Append("((GRGEN_LIBGR.IGraphElement)"); if(seqCall.TargetExpr != null) source.Append(GetSequenceExpression(seqCall.TargetExpr, source)); else source.Append(GetVar(seqCall.TargetVar)); source.Append(").ApplyProcedureMethod(procEnv, graph, "); source.Append("\"" + seqCall.ParamBindings.Name + "\""); source.Append(BuildParametersInObject(seqCall.ParamBindings)); source.Append(");\n"); for(int i = 0; i < seqCall.ParamBindings.ReturnVars.Length; i++) source.Append(SetVar(seqCall.ParamBindings.ReturnVars[i], tmpVarName)); } else { String returnParameterDeclarations; String returnArguments; String returnAssignments; BuildReturnParameters(seqCall.ParamBindings, TypesHelper.GetNodeOrEdgeType(type, model), out returnParameterDeclarations, out returnArguments, out returnAssignments); if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarations + "\n"); source.AppendFront("(("); source.Append(TypesHelper.XgrsTypeToCSharpType(type, model)); source.Append(")"); if(seqCall.TargetExpr != null) source.Append(GetSequenceExpression(seqCall.TargetExpr, source)); else source.Append(GetVar(seqCall.TargetVar)); source.Append(")."); source.Append(seqCall.ParamBindings.Name); source.Append("(procEnv, graph"); source.Append(BuildParameters(seqCall.ParamBindings, TypesHelper.GetNodeOrEdgeType(type, model).GetProcedureMethod(seqCall.ParamBindings.Name))); source.Append(returnArguments); source.Append(");\n"); } source.AppendFront(SetResultVar(seqCall, "null")); break; } default: throw new Exception("Unknown sequence computation type: " + seqComp.SequenceComputationType); } }
/// <summary> // generate the exact action interface /// </summary> void GenerateActionInterface(SourceBuilder sb, LGSPRulePattern matchingPattern) { String actionInterfaceName = "IAction_"+matchingPattern.name; String outParameters = ""; String refParameters = ""; String allParameters = ""; for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { outParameters += ", out " + TypesHelper.TypeName(matchingPattern.Outputs[i]) + " output_"+i; refParameters += ", ref " + TypesHelper.TypeName(matchingPattern.Outputs[i]) + " output_"+i; allParameters += ", List<" + TypesHelper.TypeName(matchingPattern.Outputs[i]) + "> output_"+i; } String inParameters = ""; for(int i=0; i<matchingPattern.Inputs.Length; ++i) { inParameters += ", " + TypesHelper.TypeName(matchingPattern.Inputs[i]) + " " + matchingPattern.InputNames[i]; } String matchingPatternClassName = matchingPattern.GetType().Name; String patternName = matchingPattern.name; String matchType = matchingPatternClassName + "." + NamesOfEntities.MatchInterfaceName(patternName); String matchesType = "GRGEN_LIBGR.IMatchesExact<" + matchType + ">" ; if(matchingPattern.PatternGraph.Package != null) { sb.AppendFrontFormat("namespace {0}\n", matchingPattern.PatternGraph.Package); sb.AppendFront("{\n"); sb.Indent(); } sb.AppendFront("/// <summary>\n"); sb.AppendFront("/// An object representing an executable rule - same as IAction, but with exact types and distinct parameters.\n"); sb.AppendFront("/// </summary>\n"); sb.AppendFrontFormat("public interface {0}\n", actionInterfaceName); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("/// <summary> same as IAction.Match, but with exact types and distinct parameters. </summary>\n"); sb.AppendFrontFormat("{0} Match(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int maxMatches{1});\n", matchesType, inParameters); sb.AppendFront("/// <summary> same as IAction.Modify, but with exact types and distinct parameters. </summary>\n"); sb.AppendFrontFormat("void Modify(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, {0} match{1});\n", matchType, outParameters); sb.AppendFront("/// <summary> same as IAction.ModifyAll, but with exact types and distinct parameters. </summary>\n"); sb.AppendFrontFormat("void ModifyAll(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, {0} matches{1});\n", matchesType, allParameters); sb.AppendFront("/// <summary> same as IAction.Apply, but with exact types and distinct parameters; returns true if applied </summary>\n"); sb.AppendFrontFormat("bool Apply(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0}{1});\n", inParameters, refParameters); sb.AppendFront("/// <summary> same as IAction.ApplyAll, but with exact types and distinct parameters; returns the number of matches found/applied. </summary>\n"); sb.AppendFrontFormat("int ApplyAll(int maxMatches, GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0}{1});\n", inParameters, allParameters); sb.AppendFront("/// <summary> same as IAction.ApplyStar, but with exact types and distinct parameters. </summary>\n"); sb.AppendFrontFormat("bool ApplyStar(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0});\n", inParameters); sb.AppendFront("/// <summary> same as IAction.ApplyPlus, but with exact types and distinct parameters. </summary>\n"); sb.AppendFrontFormat("bool ApplyPlus(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0});\n", inParameters); sb.AppendFront("/// <summary> same as IAction.ApplyMinMax, but with exact types and distinct parameters. </summary>\n"); sb.AppendFrontFormat("bool ApplyMinMax(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int min, int max{0});\n", inParameters); sb.Unindent(); sb.AppendFront("}\n"); if(matchingPattern.PatternGraph.Package != null) { sb.Unindent(); sb.AppendFront("}\n"); } sb.AppendFront("\n"); }
private static void GenerateAutomorphyFilter(SourceBuilder source, LGSPRulePattern rulePattern) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchClassName = rulePatternClassName + "." + NamesOfEntities.MatchClassName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = "auto"; source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(matches.Count < 2)\n"); source.AppendFront("\treturn;\n"); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); source.AppendFrontFormat("if(matches.Count < 5 || {0}.Instance.patternGraph.nodes.Length + {0}.Instance.patternGraph.edges.Length < 1)\n", rulePatternClassName); source.AppendFront("{\n"); source.Indent(); source.AppendFront("for(int i = 0; i < matchesArray.Count; ++i)\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(matchesArray[i] == null)\n"); source.AppendFront("\tcontinue;\n"); source.AppendFront("for(int j = i + 1; j < matchesArray.Count; ++j)\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(matchesArray[j] == null)\n"); source.AppendFront("\tcontinue;\n"); source.AppendFront("if(GRGEN_LIBGR.SymmetryChecker.AreSymmetric(matchesArray[i], matchesArray[j], procEnv.graph))\n"); source.AppendFront("\tmatchesArray[j] = null;\n"); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("Dictionary<int, {0}> foundMatchesOfSameMainPatternHash = new Dictionary<int, {0}>();\n", matchClassName); source.AppendFront("for(int i = 0; i < matchesArray.Count; ++i)\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} match = ({0})matchesArray[i];\n", matchClassName); source.AppendFront("int duplicateMatchHash = 0;\n"); source.AppendFront("for(int j = 0; j < match.NumberOfNodes; ++j) duplicateMatchHash ^= match.getNodeAt(j).GetHashCode();\n"); source.AppendFront("for(int j = 0; j < match.NumberOfEdges; ++j) duplicateMatchHash ^= match.getEdgeAt(j).GetHashCode();\n"); source.AppendFront("bool contained = foundMatchesOfSameMainPatternHash.ContainsKey(duplicateMatchHash);\n"); source.AppendFront("if(contained)\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} duplicateMatchCandidate = foundMatchesOfSameMainPatternHash[duplicateMatchHash];\n", matchClassName); source.AppendFront("do\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(GRGEN_LIBGR.SymmetryChecker.AreSymmetric(match, duplicateMatchCandidate, procEnv.graph))\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("matchesArray[i] = null;\n"); source.AppendFrontFormat("goto label_auto_{0};\n", rulePatternClassName.Replace('.', '_')); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("while((duplicateMatchCandidate = duplicateMatchCandidate.nextWithSameHash) != null);\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("if(!contained)\n"); source.AppendFront("\tfoundMatchesOfSameMainPatternHash[duplicateMatchHash] = match;\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} duplicateMatchCandidate = foundMatchesOfSameMainPatternHash[duplicateMatchHash];\n", matchClassName); source.AppendFront("while(duplicateMatchCandidate.nextWithSameHash != null) duplicateMatchCandidate = duplicateMatchCandidate.nextWithSameHash;\n"); source.AppendFront("duplicateMatchCandidate.nextWithSameHash = match;\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFormat("label_auto_{0}: ;\n", rulePatternClassName.Replace('.', '_')); source.Unindent(); source.AppendFront("}\n"); source.AppendFrontFormat("foreach({0} toClean in foundMatchesOfSameMainPatternHash.Values) toClean.CleanNextWithSameHash();\n", matchClassName); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); }
void GenerateKeepSameFilter(SourceBuilder source, LGSPRulePattern rulePattern, String filterVariable, bool sameAsFirst) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = sameAsFirst ? "keepSameAsFirst_" + filterVariable : "keepSameAsLast_" + filterVariable; source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); if(sameAsFirst) { source.AppendFront("int pos = 0 + 1;\n"); source.AppendFrontFormat("while(pos < matchesArray.Count && matchesArray[pos].{0} == matchesArray[0].{0})\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.AppendFront("{\n"); source.AppendFront("\t++pos;\n"); source.AppendFront("}\n"); source.AppendFront("for(; pos < matchesArray.Count; ++pos)\n"); source.AppendFront("{\n"); source.AppendFront("\tmatchesArray[pos] = null;\n"); source.AppendFront("}\n"); } else { source.AppendFront("int pos = matchesArray.Count-1 - 1;\n"); source.AppendFrontFormat("while(pos >= 0 && matchesArray[pos].{0} == matchesArray[matchesArray.Count-1].{0})\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.AppendFront("{\n"); source.AppendFront("\t--pos;\n"); source.AppendFront("}\n"); source.AppendFront("for(; pos >= 0; --pos)\n"); source.AppendFront("{\n"); source.AppendFront("\tmatchesArray[pos] = null;\n"); source.AppendFront("}\n"); } source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); }
/// <summary> /// Generates matcher class head source code for the subpattern of the rulePattern into given source builder /// isInitialStatic tells whether the initial static version or a dynamic version after analyze is to be generated. /// </summary> public void GenerateMatcherClassHeadSubpattern(SourceBuilder sb, LGSPMatchingPattern matchingPattern, bool isInitialStatic) { Debug.Assert(!(matchingPattern is LGSPRulePattern)); PatternGraph patternGraph = (PatternGraph)matchingPattern.PatternGraph; String namePrefix = (isInitialStatic ? "" : "Dyn") + "PatternAction_"; String className = namePrefix + matchingPattern.name; String matchingPatternClassName = matchingPattern.GetType().Name; if(patternGraph.Package != null) { sb.AppendFrontFormat("namespace {0}\n", patternGraph.Package); sb.AppendFront("{\n"); sb.Indent(); } sb.AppendFront("public class " + className + " : GRGEN_LGSP.LGSPSubpatternAction\n"); sb.AppendFront("{\n"); sb.Indent(); // class level sb.AppendFront("private " + className + "(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv_, Stack<GRGEN_LGSP.LGSPSubpatternAction> openTasks_) {\n"); sb.Indent(); // method body level sb.AppendFront("actionEnv = actionEnv_; openTasks = openTasks_;\n"); sb.AppendFront("patternGraph = " + matchingPatternClassName + ".Instance.patternGraph;\n"); sb.Unindent(); // class level sb.AppendFront("}\n\n"); GenerateTasksMemoryPool(sb, className, false, false, matchingPattern.patternGraph.branchingFactor); for (int i = 0; i < patternGraph.nodesPlusInlined.Length; ++i) { PatternNode node = patternGraph.nodesPlusInlined[i]; if (node.PointOfDefinition == null) { sb.AppendFront("public GRGEN_LGSP.LGSPNode " + node.name + ";\n"); } } for (int i = 0; i < patternGraph.edgesPlusInlined.Length; ++i) { PatternEdge edge = patternGraph.edgesPlusInlined[i]; if (edge.PointOfDefinition == null) { sb.AppendFront("public GRGEN_LGSP.LGSPEdge " + edge.name + ";\n"); } } for (int i = 0; i < patternGraph.variablesPlusInlined.Length; ++i) { PatternVariable variable = patternGraph.variablesPlusInlined[i]; sb.AppendFront("public " +TypesHelper.TypeName(variable.type) + " " + variable.name + ";\n"); } GenerateIndependentsMatchObjects(sb, matchingPattern, patternGraph); sb.AppendFront("\n"); }
/// <summary> /// Generates matcher class head source code for the given iterated pattern into given source builder /// isInitialStatic tells whether the initial static version or a dynamic version after analyze is to be generated. /// </summary> public void GenerateMatcherClassHeadIterated(SourceBuilder sb, LGSPMatchingPattern matchingPattern, PatternGraph iter, bool isInitialStatic) { PatternGraph patternGraph = (PatternGraph)matchingPattern.PatternGraph; String namePrefix = (isInitialStatic ? "" : "Dyn") + "IteratedAction_"; String className = namePrefix + iter.pathPrefix + iter.name; String matchingPatternClassName = matchingPattern.GetType().Name; if(patternGraph.Package != null) { sb.AppendFrontFormat("namespace {0}\n", patternGraph.Package); sb.AppendFront("{\n"); sb.Indent(); } sb.AppendFront("public class " + className + " : GRGEN_LGSP.LGSPSubpatternAction\n"); sb.AppendFront("{\n"); sb.Indent(); // class level sb.AppendFront("private " + className + "(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv_, Stack<GRGEN_LGSP.LGSPSubpatternAction> openTasks_) {\n"); sb.Indent(); // method body level sb.AppendFront("actionEnv = actionEnv_; openTasks = openTasks_;\n"); sb.AppendFront("patternGraph = " + matchingPatternClassName + ".Instance.patternGraph;\n"); int index = -1; for (int i=0; i<iter.embeddingGraph.iteratedsPlusInlined.Length; ++i) { if (iter.embeddingGraph.iteratedsPlusInlined[i].iteratedPattern == iter) index = i; } sb.AppendFrontFormat("minMatchesIter = {0};\n", iter.embeddingGraph.iteratedsPlusInlined[index].minMatches); sb.AppendFrontFormat("maxMatchesIter = {0};\n", iter.embeddingGraph.iteratedsPlusInlined[index].maxMatches); sb.AppendFront("numMatchesIter = 0;\n"); if(iter.isIterationBreaking) sb.AppendFront("breakIteration = false;\n"); sb.Unindent(); // class level sb.AppendFront("}\n\n"); sb.AppendFront("int minMatchesIter;\n"); sb.AppendFront("int maxMatchesIter;\n"); sb.AppendFront("int numMatchesIter;\n"); if(iter.isIterationBreaking) sb.AppendFront("bool breakIteration;\n"); sb.Append("\n"); GenerateTasksMemoryPool(sb, className, false, iter.isIterationBreaking, matchingPattern.patternGraph.branchingFactor); Dictionary<string, bool> neededNodes = new Dictionary<string, bool>(); Dictionary<string, bool> neededEdges = new Dictionary<string, bool>(); Dictionary<string, GrGenType> neededVariables = new Dictionary<string, GrGenType>(); foreach (KeyValuePair<string, bool> neededNode in iter.neededNodes) neededNodes[neededNode.Key] = neededNode.Value; foreach (KeyValuePair<string, bool> neededEdge in iter.neededEdges) neededEdges[neededEdge.Key] = neededEdge.Value; foreach (KeyValuePair<string, GrGenType> neededVariable in iter.neededVariables) neededVariables[neededVariable.Key] = neededVariable.Value; foreach (KeyValuePair<string, bool> node in neededNodes) { sb.AppendFront("public GRGEN_LGSP.LGSPNode " + node.Key + ";\n"); } foreach (KeyValuePair<string, bool> edge in neededEdges) { sb.AppendFront("public GRGEN_LGSP.LGSPEdge " + edge.Key + ";\n"); } foreach (KeyValuePair<string, GrGenType> variable in neededVariables) { sb.AppendFront("public " + TypesHelper.TypeName(variable.Value) + " " + variable.Key + ";\n"); } GenerateIndependentsMatchObjects(sb, matchingPattern, iter); sb.AppendFront("\n"); }
void GenerateContainerConstructor(SequenceExpressionContainerConstructor cc, SourceBuilder source) { string containerType = TypesHelper.XgrsTypeToCSharpType(GetContainerType(cc), model); string valueType = TypesHelper.XgrsTypeToCSharpType(cc.ValueType, model); string keyType = null; if(cc is SequenceExpressionMapConstructor) keyType = TypesHelper.XgrsTypeToCSharpType(((SequenceExpressionMapConstructor)cc).KeyType, model); source.Append("\n"); source.AppendFront("public static "); source.Append(containerType); source.Append(" fillFromSequence_" + cc.Id); source.Append("("); for(int i = 0; i < cc.ContainerItems.Length; ++i) { if(i > 0) source.Append(", "); if(keyType != null) source.AppendFormat("{0} paramkey{1}, ", keyType, i); source.AppendFormat("{0} param{1}", valueType, i); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} container = new {0}();\n", containerType); for(int i = 0; i < cc.ContainerItems.Length; ++i) { if(cc is SequenceExpressionSetConstructor) source.AppendFrontFormat("container.Add(param{0}, null);\n", i); else if(cc is SequenceExpressionMapConstructor) source.AppendFrontFormat("container.Add(paramkey{0}, param{0});\n", i); else if(cc is SequenceExpressionArrayConstructor) source.AppendFrontFormat("container.Add(param{0});\n", i); else //if(cc is SequenceExpressionDequeConstructor) source.AppendFrontFormat("container.Enqueue(param{0});\n", i); } source.AppendFront("return container;\n"); source.Unindent(); source.AppendFront("}\n"); }
void EmitSequence(Sequence seq, SourceBuilder source) { switch(seq.SequenceType) { case SequenceType.RuleCall: case SequenceType.RuleAllCall: case SequenceType.RuleCountAllCall: EmitRuleOrRuleAllCall((SequenceRuleCall)seq, source); break; case SequenceType.SequenceCall: EmitSequenceCall((SequenceSequenceCall)seq, source); break; case SequenceType.Not: { SequenceNot seqNot = (SequenceNot) seq; EmitSequence(seqNot.Seq, source); source.AppendFront(SetResultVar(seqNot, "!"+GetResultVar(seqNot.Seq))); break; } case SequenceType.LazyOr: case SequenceType.LazyAnd: case SequenceType.IfThen: { SequenceBinary seqBin = (SequenceBinary) seq; if(seqBin.Random) { Debug.Assert(seq.SequenceType != SequenceType.IfThen); source.AppendFront("if(GRGEN_LIBGR.Sequence.randomGenerator.Next(2) == 1)\n"); source.AppendFront("{\n"); source.Indent(); EmitLazyOp(seqBin, source, true); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); EmitLazyOp(seqBin, source, false); source.Unindent(); source.AppendFront("}\n"); } else { EmitLazyOp(seqBin, source, false); } break; } case SequenceType.ThenLeft: case SequenceType.ThenRight: case SequenceType.StrictAnd: case SequenceType.StrictOr: case SequenceType.Xor: { SequenceBinary seqBin = (SequenceBinary) seq; if(seqBin.Random) { source.AppendFront("if(GRGEN_LIBGR.Sequence.randomGenerator.Next(2) == 1)\n"); source.AppendFront("{\n"); source.Indent(); EmitSequence(seqBin.Right, source); EmitSequence(seqBin.Left, source); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); EmitSequence(seqBin.Left, source); EmitSequence(seqBin.Right, source); source.Unindent(); source.AppendFront("}\n"); } else { EmitSequence(seqBin.Left, source); EmitSequence(seqBin.Right, source); } if(seq.SequenceType==SequenceType.ThenLeft) { source.AppendFront(SetResultVar(seq, GetResultVar(seqBin.Left))); break; } else if(seq.SequenceType==SequenceType.ThenRight) { source.AppendFront(SetResultVar(seq, GetResultVar(seqBin.Right))); break; } String op; switch(seq.SequenceType) { case SequenceType.StrictAnd: op = "&"; break; case SequenceType.StrictOr: op = "|"; break; case SequenceType.Xor: op = "^"; break; default: throw new Exception("Internal error in EmitSequence: Should not have reached this!"); } source.AppendFront(SetResultVar(seq, GetResultVar(seqBin.Left) + " "+op+" " + GetResultVar(seqBin.Right))); break; } case SequenceType.IfThenElse: { SequenceIfThenElse seqIf = (SequenceIfThenElse)seq; EmitSequence(seqIf.Condition, source); source.AppendFront("if(" + GetResultVar(seqIf.Condition) + ")"); source.AppendFront("{\n"); source.Indent(); EmitSequence(seqIf.TrueCase, source); source.AppendFront(SetResultVar(seqIf, GetResultVar(seqIf.TrueCase))); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); EmitSequence(seqIf.FalseCase, source); source.AppendFront(SetResultVar(seqIf, GetResultVar(seqIf.FalseCase))); source.Unindent(); source.AppendFront("}\n"); break; } case SequenceType.ForContainer: { SequenceForContainer seqFor = (SequenceForContainer)seq; source.AppendFront(SetResultVar(seqFor, "true")); if(seqFor.Container.Type == "") { // type not statically known? -> might be Dictionary or List or Deque dynamically, must decide at runtime source.AppendFront("if(" + GetVar(seqFor.Container) + " is IList) {\n"); source.Indent(); source.AppendFront("IList entry_" + seqFor.Id + " = (IList) " + GetVar(seqFor.Container) + ";\n"); source.AppendFrontFormat("for(int index_{0}=0; index_{0} < entry_{0}.Count; ++index_{0})\n", seqFor.Id); source.AppendFront("{\n"); source.Indent(); if(seqFor.VarDst != null) { source.AppendFront(SetVar(seqFor.Var, "index_" + seqFor.Id)); source.AppendFront(SetVar(seqFor.VarDst, "entry_" + seqFor.Id + "[index_" + seqFor.Id + "]")); } else { source.AppendFront(SetVar(seqFor.Var, "entry_" + seqFor.Id + "[index_" + seqFor.Id + "]")); } EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("} else if(" + GetVar(seqFor.Container) + " is GRGEN_LIBGR.IDeque) {\n"); source.Indent(); source.AppendFront("GRGEN_LIBGR.IDeque entry_" + seqFor.Id + " = (GRGEN_LIBGR.IDeque) " + GetVar(seqFor.Container) + ";\n"); source.AppendFrontFormat("for(int index_{0}=0; index_{0} < entry_{0}.Count; ++index_{0})\n", seqFor.Id); source.AppendFront("{\n"); source.Indent(); if(seqFor.VarDst != null) { source.AppendFront(SetVar(seqFor.Var, "index_" + seqFor.Id)); source.AppendFront(SetVar(seqFor.VarDst, "entry_" + seqFor.Id + "[index_" + seqFor.Id + "]")); } else { source.AppendFront(SetVar(seqFor.Var, "entry_" + seqFor.Id + "[index_" + seqFor.Id + "]")); } EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("} else {\n"); source.Indent(); source.AppendFront("foreach(DictionaryEntry entry_" + seqFor.Id + " in (IDictionary)" + GetVar(seqFor.Container) + ")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront(SetVar(seqFor.Var, "entry_" + seqFor.Id + ".Key")); if(seqFor.VarDst != null) { source.AppendFront(SetVar(seqFor.VarDst, "entry_" + seqFor.Id + ".Value")); } EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); } else if(seqFor.Container.Type.StartsWith("array")) { String arrayValueType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(seqFor.Container.Type), model); source.AppendFrontFormat("List<{0}> entry_{1} = (List<{0}>) " + GetVar(seqFor.Container) + ";\n", arrayValueType, seqFor.Id); source.AppendFrontFormat("for(int index_{0}=0; index_{0}<entry_{0}.Count; ++index_{0})\n", seqFor.Id); source.AppendFront("{\n"); source.Indent(); if(seqFor.VarDst != null) { source.AppendFront(SetVar(seqFor.Var, "index_" + seqFor.Id)); source.AppendFront(SetVar(seqFor.VarDst, "entry_" + seqFor.Id + "[index_" + seqFor.Id + "]")); } else { source.AppendFront(SetVar(seqFor.Var, "entry_" + seqFor.Id + "[index_" + seqFor.Id + "]")); } EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); } else if(seqFor.Container.Type.StartsWith("deque")) { String dequeValueType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(seqFor.Container.Type), model); source.AppendFrontFormat("GRGEN_LIBGR.Deque<{0}> entry_{1} = (GRGEN_LIBGR.Deque<{0}>) " + GetVar(seqFor.Container) + ";\n", dequeValueType, seqFor.Id); source.AppendFrontFormat("for(int index_{0}=0; index_{0}<entry_{0}.Count; ++index_{0})\n", seqFor.Id); source.AppendFront("{\n"); source.Indent(); if(seqFor.VarDst != null) { source.AppendFront(SetVar(seqFor.Var, "index_" + seqFor.Id)); source.AppendFront(SetVar(seqFor.VarDst, "entry_" + seqFor.Id + "[index_" + seqFor.Id + "]")); } else { source.AppendFront(SetVar(seqFor.Var, "entry_" + seqFor.Id + "[index_" + seqFor.Id + "]")); } EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); } else { String srcType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(seqFor.Container.Type), model); String dstType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractDst(seqFor.Container.Type), model); source.AppendFront("foreach(KeyValuePair<" + srcType + "," + dstType + "> entry_" + seqFor.Id + " in " + GetVar(seqFor.Container) + ")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront(SetVar(seqFor.Var, "entry_" + seqFor.Id + ".Key")); if(seqFor.VarDst != null) source.AppendFront(SetVar(seqFor.VarDst, "entry_" + seqFor.Id + ".Value")); EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); } break; } case SequenceType.ForIntegerRange: { SequenceForIntegerRange seqFor = (SequenceForIntegerRange)seq; source.AppendFront(SetResultVar(seqFor, "true")); String ascendingVar = "ascending_" + seqFor.Id; String entryVar = "entry_" + seqFor.Id; String limitVar = "limit_" + seqFor.Id; source.AppendFrontFormat("int {0} = (int)({1});\n", entryVar, GetSequenceExpression(seqFor.Left, source)); source.AppendFrontFormat("int {0} = (int)({1});\n", limitVar, GetSequenceExpression(seqFor.Right, source)); source.AppendFront("bool " + ascendingVar + " = " + entryVar + " <= " + limitVar + ";\n"); source.AppendFront("while(" + ascendingVar + " ? " + entryVar + " <= " + limitVar + " : " + entryVar + " >= " + limitVar + ")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront(SetVar(seqFor.Var, entryVar)); EmitSequence(seqFor.Seq, source); source.AppendFront("if(" + ascendingVar + ") ++" + entryVar + "; else --" + entryVar + ";\n"); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); break; } case SequenceType.ForIndexAccessEquality: { SequenceForIndexAccessEquality seqFor = (SequenceForIndexAccessEquality)seq; source.AppendFront(SetResultVar(seqFor, "true")); String indexVar = "index_" + seqFor.Id; source.AppendFrontFormat("GRGEN_LIBGR.IAttributeIndex {0} = (GRGEN_LIBGR.IAttributeIndex)procEnv.Graph.Indices.GetIndex(\"{1}\");\n", indexVar, seqFor.IndexName); String entryVar = "entry_" + seqFor.Id; source.AppendFrontFormat("foreach(GRGEN_LIBGR.IGraphElement {0} in {1}.LookupElements", entryVar, indexVar); source.Append("("); source.Append(GetSequenceExpression(seqFor.Expr, source)); source.Append("))\n"); source.AppendFront("{\n"); source.Indent(); if(gen.EmitProfiling) source.AppendFront("++procEnv.PerformanceInfo.SearchSteps;\n"); source.AppendFront(SetVar(seqFor.Var, entryVar)); EmitSequence(seqFor.Seq, source); source.Unindent(); source.AppendFront("}\n"); break; } case SequenceType.ForIndexAccessOrdering: { SequenceForIndexAccessOrdering seqFor = (SequenceForIndexAccessOrdering)seq; source.AppendFront(SetResultVar(seqFor, "true")); String indexVar = "index_" + seqFor.Id; source.AppendFrontFormat("GRGEN_LIBGR.IAttributeIndex {0} = (GRGEN_LIBGR.IAttributeIndex)procEnv.Graph.Indices.GetIndex(\"{1}\");\n", indexVar, seqFor.IndexName); String entryVar = "entry_" + seqFor.Id; source.AppendFrontFormat("foreach(GRGEN_LIBGR.IGraphElement {0} in {1}.LookupElements", entryVar, indexVar); if(seqFor.Ascending) source.Append("Ascending"); else source.Append("Descending"); if(seqFor.From() != null && seqFor.To() != null) { source.Append("From"); if(seqFor.IncludingFrom()) source.Append("Inclusive"); else source.Append("Exclusive"); source.Append("To"); if(seqFor.IncludingTo()) source.Append("Inclusive"); else source.Append("Exclusive"); source.Append("("); source.Append(GetSequenceExpression(seqFor.From(), source)); source.Append(", "); source.Append(GetSequenceExpression(seqFor.To(), source)); } else if(seqFor.From() != null) { source.Append("From"); if(seqFor.IncludingFrom()) source.Append("Inclusive"); else source.Append("Exclusive"); source.Append("("); source.Append(GetSequenceExpression(seqFor.From(), source)); } else if(seqFor.To() != null) { source.Append("To"); if(seqFor.IncludingTo()) source.Append("Inclusive"); else source.Append("Exclusive"); source.Append("("); source.Append(GetSequenceExpression(seqFor.To(), source)); } else { source.Append("("); } source.Append("))\n"); source.AppendFront("{\n"); source.Indent(); if(gen.EmitProfiling) source.AppendFront("++procEnv.PerformanceInfo.SearchSteps;\n"); source.AppendFront(SetVar(seqFor.Var, entryVar)); EmitSequence(seqFor.Seq, source); source.Unindent(); source.AppendFront("}\n"); break; } case SequenceType.ForAdjacentNodes: case SequenceType.ForAdjacentNodesViaIncoming: case SequenceType.ForAdjacentNodesViaOutgoing: case SequenceType.ForIncidentEdges: case SequenceType.ForIncomingEdges: case SequenceType.ForOutgoingEdges: case SequenceType.ForReachableNodes: case SequenceType.ForReachableNodesViaIncoming: case SequenceType.ForReachableNodesViaOutgoing: case SequenceType.ForReachableEdges: case SequenceType.ForReachableEdgesViaIncoming: case SequenceType.ForReachableEdgesViaOutgoing: { SequenceForFunction seqFor = (SequenceForFunction)seq; source.AppendFront(SetResultVar(seqFor, "true")); string sourceNodeExpr = GetSequenceExpression(seqFor.ArgExprs[0], source); source.AppendFrontFormat("GRGEN_LIBGR.INode node_{0} = (GRGEN_LIBGR.INode)({1});\n", seqFor.Id, sourceNodeExpr); SequenceExpression IncidentEdgeType = seqFor.ArgExprs.Count >= 2 ? seqFor.ArgExprs[1] : null; string incidentEdgeTypeExpr = ExtractEdgeType(source, IncidentEdgeType); SequenceExpression AdjacentNodeType = seqFor.ArgExprs.Count >= 3 ? seqFor.ArgExprs[2] : null; string adjacentNodeTypeExpr = ExtractNodeType(source, AdjacentNodeType); string iterationVariable; // valid for incident/adjacent and reachable string edgeMethod = null; // only valid for incident/adajcent string theOther = null; // only valid for incident/adjacent string reachableMethod = null; // only valid for reachable switch(seqFor.SequenceType) { case SequenceType.ForAdjacentNodes: edgeMethod = "Incident"; theOther = "edge_" + seqFor.Id + ".Opposite(node_" + seqFor.Id + ")"; iterationVariable = theOther; break; case SequenceType.ForAdjacentNodesViaIncoming: edgeMethod = "Incoming"; theOther = "edge_" + seqFor.Id + ".Source"; iterationVariable = theOther; break; case SequenceType.ForAdjacentNodesViaOutgoing: edgeMethod = "Outgoing"; theOther = "edge_" + seqFor.Id + ".Target"; iterationVariable = theOther; break; case SequenceType.ForIncidentEdges: edgeMethod = "Incident"; theOther = "edge_" + seqFor.Id + ".Opposite(node_" + seqFor.Id + ")"; iterationVariable = "edge_" + seqFor.Id; break; case SequenceType.ForIncomingEdges: edgeMethod = "Incoming"; theOther = "edge_" + seqFor.Id + ".Source"; iterationVariable = "edge_" + seqFor.Id; break; case SequenceType.ForOutgoingEdges: edgeMethod = "Outgoing"; theOther = "edge_" + seqFor.Id + ".Target"; iterationVariable = "edge_" + seqFor.Id; break; case SequenceType.ForReachableNodes: reachableMethod = ""; iterationVariable = "iter_" + seqFor.Id; ; break; case SequenceType.ForReachableNodesViaIncoming: reachableMethod = "Incoming"; iterationVariable = "iter_" + seqFor.Id; ; break; case SequenceType.ForReachableNodesViaOutgoing: reachableMethod = "Outgoing"; iterationVariable = "iter_" + seqFor.Id; ; break; case SequenceType.ForReachableEdges: reachableMethod = "Edges"; iterationVariable = "edge_" + seqFor.Id; break; case SequenceType.ForReachableEdgesViaIncoming: reachableMethod = "EdgesIncoming"; iterationVariable = "edge_" + seqFor.Id; break; case SequenceType.ForReachableEdgesViaOutgoing: reachableMethod = "EdgesOutgoing"; iterationVariable = "edge_" + seqFor.Id; break; default: edgeMethod = theOther = iterationVariable = "INTERNAL ERROR"; break; } string profilingArgument = gen.EmitProfiling ? ", procEnv" : ""; if(seqFor.SequenceType == SequenceType.ForReachableNodes || seqFor.SequenceType == SequenceType.ForReachableNodesViaIncoming || seqFor.SequenceType == SequenceType.ForReachableNodesViaOutgoing) { source.AppendFrontFormat("foreach(GRGEN_LIBGR.INode iter_{0} in GraphHelper.Reachable{1}(node_{0}, ({2}), ({3}), graph" + profilingArgument + "))\n", seqFor.Id, reachableMethod, incidentEdgeTypeExpr, adjacentNodeTypeExpr); } else if(seqFor.SequenceType == SequenceType.ForReachableEdges || seqFor.SequenceType == SequenceType.ForReachableEdgesViaIncoming || seqFor.SequenceType == SequenceType.ForReachableEdgesViaOutgoing) { source.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in GraphHelper.Reachable{1}(node_{0}, ({2}), ({3}), graph" + profilingArgument + "))\n", seqFor.Id, reachableMethod, incidentEdgeTypeExpr, adjacentNodeTypeExpr); } else { if(gen.EmitProfiling) source.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.{1})\n", seqFor.Id, edgeMethod); else source.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.GetCompatible{1}({2}))\n", seqFor.Id, edgeMethod, incidentEdgeTypeExpr); } source.AppendFront("{\n"); source.Indent(); if(seqFor.SequenceType != SequenceType.ForReachableNodes && seqFor.SequenceType != SequenceType.ForReachableNodesViaIncoming && seqFor.SequenceType != SequenceType.ForReachableNodesViaOutgoing && seqFor.SequenceType != SequenceType.ForReachableEdges && seqFor.SequenceType != SequenceType.ForReachableEdgesViaIncoming || seqFor.SequenceType != SequenceType.ForReachableEdgesViaOutgoing) { if(gen.EmitProfiling) { source.AppendFront("++procEnv.PerformanceInfo.SearchSteps;\n"); source.AppendFrontFormat("if(!edge_{0}.InstanceOf(", seqFor.Id); source.Append(incidentEdgeTypeExpr); source.Append("))\n"); source.AppendFront("\tcontinue;\n"); } // incident/adjacent needs a check for adjacent node, cause only incident edge can be type constrained in the loop // reachable already allows to iterate exactly the edges of interest source.AppendFrontFormat("if(!{0}.InstanceOf({1}))\n", theOther, adjacentNodeTypeExpr); source.AppendFront("\tcontinue;\n"); } source.AppendFront(SetVar(seqFor.Var, iterationVariable)); EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); break; } case SequenceType.ForBoundedReachableNodes: case SequenceType.ForBoundedReachableNodesViaIncoming: case SequenceType.ForBoundedReachableNodesViaOutgoing: case SequenceType.ForBoundedReachableEdges: case SequenceType.ForBoundedReachableEdgesViaIncoming: case SequenceType.ForBoundedReachableEdgesViaOutgoing: { SequenceForFunction seqFor = (SequenceForFunction)seq; source.AppendFront(SetResultVar(seqFor, "true")); string sourceNodeExpr = GetSequenceExpression(seqFor.ArgExprs[0], source); source.AppendFrontFormat("GRGEN_LIBGR.INode node_{0} = (GRGEN_LIBGR.INode)({1});\n", seqFor.Id, sourceNodeExpr); string depthExpr = GetSequenceExpression(seqFor.ArgExprs[1], source); source.AppendFrontFormat("int depth_{0} = (int)({1});\n", seqFor.Id, depthExpr); SequenceExpression IncidentEdgeType = seqFor.ArgExprs.Count >= 3 ? seqFor.ArgExprs[2] : null; string incidentEdgeTypeExpr = ExtractEdgeType(source, IncidentEdgeType); SequenceExpression AdjacentNodeType = seqFor.ArgExprs.Count >= 4 ? seqFor.ArgExprs[3] : null; string adjacentNodeTypeExpr = ExtractNodeType(source, AdjacentNodeType); string iterationVariable; // valid for incident/adjacent and reachable string edgeMethod = null; // only valid for incident/adajcent string theOther = null; // only valid for incident/adjacent string reachableMethod = null; // only valid for reachable switch(seqFor.SequenceType) { case SequenceType.ForBoundedReachableNodes: reachableMethod = ""; iterationVariable = "iter_" + seqFor.Id; ; break; case SequenceType.ForBoundedReachableNodesViaIncoming: reachableMethod = "Incoming"; iterationVariable = "iter_" + seqFor.Id; ; break; case SequenceType.ForBoundedReachableNodesViaOutgoing: reachableMethod = "Outgoing"; iterationVariable = "iter_" + seqFor.Id; ; break; case SequenceType.ForBoundedReachableEdges: reachableMethod = "Edges"; iterationVariable = "edge_" + seqFor.Id; break; case SequenceType.ForBoundedReachableEdgesViaIncoming: reachableMethod = "EdgesIncoming"; iterationVariable = "edge_" + seqFor.Id; break; case SequenceType.ForBoundedReachableEdgesViaOutgoing: reachableMethod = "EdgesOutgoing"; iterationVariable = "edge_" + seqFor.Id; break; default: edgeMethod = theOther = iterationVariable = "INTERNAL ERROR"; break; } string profilingArgument = gen.EmitProfiling ? ", procEnv" : ""; if(seqFor.SequenceType == SequenceType.ForBoundedReachableNodes || seqFor.SequenceType == SequenceType.ForBoundedReachableNodesViaIncoming || seqFor.SequenceType == SequenceType.ForBoundedReachableNodesViaOutgoing) { source.AppendFrontFormat("foreach(GRGEN_LIBGR.INode iter_{0} in GRGEN_LIBGR.GraphHelper.BoundedReachable{1}(node_{0}, depth_{0}, ({2}), ({3}), graph" + profilingArgument + "))\n", seqFor.Id, reachableMethod, incidentEdgeTypeExpr, adjacentNodeTypeExpr); } else if(seqFor.SequenceType == SequenceType.ForBoundedReachableEdges || seqFor.SequenceType == SequenceType.ForBoundedReachableEdgesViaIncoming || seqFor.SequenceType == SequenceType.ForBoundedReachableEdgesViaOutgoing) { source.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in GRGEN_LIBGR.GraphHelper.BoundedReachable{1}(node_{0}, depth_{0}, ({2}), ({3}), graph" + profilingArgument + "))\n", seqFor.Id, reachableMethod, incidentEdgeTypeExpr, adjacentNodeTypeExpr); } source.AppendFront("{\n"); source.Indent(); source.AppendFront(SetVar(seqFor.Var, iterationVariable)); EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); break; } case SequenceType.ForNodes: case SequenceType.ForEdges: { SequenceForFunction seqFor = (SequenceForFunction)seq; source.AppendFront(SetResultVar(seqFor, "true")); if(seqFor.SequenceType == SequenceType.ForNodes) { SequenceExpression AdjacentNodeType = seqFor.ArgExprs.Count >= 1 ? seqFor.ArgExprs[0] : null; string adjacentNodeTypeExpr = ExtractNodeType(source, AdjacentNodeType); source.AppendFrontFormat("foreach(GRGEN_LIBGR.INode elem_{0} in graph.GetCompatibleNodes({1}))\n", seqFor.Id, adjacentNodeTypeExpr); } else { SequenceExpression IncidentEdgeType = seqFor.ArgExprs.Count >= 1 ? seqFor.ArgExprs[0] : null; string incidentEdgeTypeExpr = ExtractEdgeType(source, IncidentEdgeType); source.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge elem_{0} in graph.GetCompatibleEdges({1}))\n", seqFor.Id, incidentEdgeTypeExpr); } source.AppendFront("{\n"); source.Indent(); if(gen.EmitProfiling) source.AppendFront("++procEnv.PerformanceInfo.SearchSteps;\n"); source.AppendFront(SetVar(seqFor.Var, "elem_" + seqFor.Id)); EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); break; } case SequenceType.ForMatch: { SequenceForMatch seqFor = (SequenceForMatch)seq; source.AppendFront(SetResultVar(seqFor, "true")); RuleInvocationParameterBindings paramBindings = seqFor.Rule.ParamBindings; String specialStr = seqFor.Rule.Special ? "true" : "false"; String parameters = BuildParameters(paramBindings); String matchingPatternClassName = TypesHelper.GetPackagePrefixDot(paramBindings.Package) + "Rule_" + paramBindings.Name; String patternName = paramBindings.Name; String matchType = matchingPatternClassName + "." + NamesOfEntities.MatchInterfaceName(patternName); String matchName = "match_" + seqFor.Id; String matchesType = "GRGEN_LIBGR.IMatchesExact<" + matchType + ">"; String matchesName = "matches_" + seqFor.Id; source.AppendFront(matchesType + " " + matchesName + " = rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Match(procEnv, procEnv.MaxMatches" + parameters + ");\n"); for(int i=0; i<seqFor.Rule.Filters.Count; ++i) { EmitFilterCall(source, seqFor.Rule.Filters[i], patternName, matchesName); } source.AppendFront("if(" + matchesName + ".Count!=0) {\n"); source.Indent(); source.AppendFront(matchesName + " = (" + matchesType + ")" + matchesName + ".Clone();\n"); source.AppendFront("procEnv.PerformanceInfo.MatchesFound += " + matchesName + ".Count;\n"); if(gen.FireDebugEvents) source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n"); String returnParameterDeclarations; String returnArguments; String returnAssignments; String returnParameterDeclarationsAllCall; String intermediateReturnAssignmentsAllCall; String returnAssignmentsAllCall; BuildReturnParameters(paramBindings, out returnParameterDeclarations, out returnArguments, out returnAssignments, out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall); // apply the sequence for every match found String enumeratorName = "enum_" + seqFor.Id; source.AppendFront("IEnumerator<" + matchType + "> " + enumeratorName + " = " + matchesName + ".GetEnumeratorExact();\n"); source.AppendFront("while(" + enumeratorName + ".MoveNext())\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront(matchType + " " + matchName + " = " + enumeratorName + ".Current;\n"); source.AppendFront(SetVar(seqFor.Var, matchName)); EmitSequence(seqFor.Seq, source); source.AppendFront(SetResultVar(seqFor, GetResultVar(seqFor) + " & " + GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); break; } case SequenceType.IterationMin: { SequenceIterationMin seqMin = (SequenceIterationMin)seq; source.AppendFront("long i_" + seqMin.Id + " = 0;\n"); source.AppendFront("while(true)\n"); source.AppendFront("{\n"); source.Indent(); EmitSequence(seqMin.Seq, source); source.AppendFront("if(!" + GetResultVar(seqMin.Seq) + ") break;\n"); source.AppendFront("i_" + seqMin.Id + "++;\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront(SetResultVar(seqMin, "i_" + seqMin.Id + " >= " + seqMin.Min)); break; } case SequenceType.IterationMinMax: { SequenceIterationMinMax seqMinMax = (SequenceIterationMinMax)seq; source.AppendFront("long i_" + seqMinMax.Id + " = 0;\n"); source.AppendFront("for(; i_" + seqMinMax.Id + " < " + seqMinMax.Max + "; i_" + seqMinMax.Id + "++)\n"); source.AppendFront("{\n"); source.Indent(); EmitSequence(seqMinMax.Seq, source); source.AppendFront("if(!" + GetResultVar(seqMinMax.Seq) + ") break;\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront(SetResultVar(seqMinMax, "i_" + seqMinMax.Id + " >= " + seqMinMax.Min)); break; } case SequenceType.DeclareVariable: { SequenceDeclareVariable seqDeclVar = (SequenceDeclareVariable)seq; source.AppendFront(SetVar(seqDeclVar.DestVar, TypesHelper.DefaultValueString(seqDeclVar.DestVar.Type, env.Model))); source.AppendFront(SetResultVar(seqDeclVar, "true")); break; } case SequenceType.AssignConstToVar: { SequenceAssignConstToVar seqToVar = (SequenceAssignConstToVar) seq; source.AppendFront(SetVar(seqToVar.DestVar, GetConstant(seqToVar.Constant))); source.AppendFront(SetResultVar(seqToVar, "true")); break; } case SequenceType.AssignContainerConstructorToVar: { SequenceAssignContainerConstructorToVar seqToVar = (SequenceAssignContainerConstructorToVar)seq; source.AppendFront(SetVar(seqToVar.DestVar, GetSequenceExpression(seqToVar.Constructor, source))); source.AppendFront(SetResultVar(seqToVar, "true")); break; } case SequenceType.AssignVarToVar: { SequenceAssignVarToVar seqToVar = (SequenceAssignVarToVar)seq; source.AppendFront(SetVar(seqToVar.DestVar, GetVar(seqToVar.Variable))); source.AppendFront(SetResultVar(seqToVar, "true")); break; } case SequenceType.AssignSequenceResultToVar: { SequenceAssignSequenceResultToVar seqToVar = (SequenceAssignSequenceResultToVar)seq; EmitSequence(seqToVar.Seq, source); source.AppendFront(SetVar(seqToVar.DestVar, GetResultVar(seqToVar.Seq))); source.AppendFront(SetResultVar(seqToVar, "true")); break; } case SequenceType.OrAssignSequenceResultToVar: { SequenceOrAssignSequenceResultToVar seqToVar = (SequenceOrAssignSequenceResultToVar)seq; EmitSequence(seqToVar.Seq, source); source.AppendFront(SetVar(seqToVar.DestVar, GetResultVar(seqToVar.Seq) + "|| (bool)" + GetVar(seqToVar.DestVar))); source.AppendFront(SetResultVar(seqToVar, "true")); break; } case SequenceType.AndAssignSequenceResultToVar: { SequenceAndAssignSequenceResultToVar seqToVar = (SequenceAndAssignSequenceResultToVar)seq; EmitSequence(seqToVar.Seq, source); source.AppendFront(SetVar(seqToVar.DestVar, GetResultVar(seqToVar.Seq) + "&& (bool)" + GetVar(seqToVar.DestVar))); source.AppendFront(SetResultVar(seqToVar, "true")); break; } case SequenceType.AssignUserInputToVar: { throw new Exception("Internal Error: the AssignUserInputToVar is interpreted only (no Debugger available at lgsp level)"); } case SequenceType.AssignRandomIntToVar: { SequenceAssignRandomIntToVar seqRandomToVar = (SequenceAssignRandomIntToVar)seq; source.AppendFront(SetVar(seqRandomToVar.DestVar, "GRGEN_LIBGR.Sequence.randomGenerator.Next(" + seqRandomToVar.Number + ")")); source.AppendFront(SetResultVar(seqRandomToVar, "true")); break; } case SequenceType.AssignRandomDoubleToVar: { SequenceAssignRandomDoubleToVar seqRandomToVar = (SequenceAssignRandomDoubleToVar)seq; source.AppendFront(SetVar(seqRandomToVar.DestVar, "GRGEN_LIBGR.Sequence.randomGenerator.NextDouble()")); source.AppendFront(SetResultVar(seqRandomToVar, "true")); break; } case SequenceType.LazyOrAll: { SequenceLazyOrAll seqAll = (SequenceLazyOrAll)seq; EmitSequenceAll(seqAll, true, true, source); break; } case SequenceType.LazyAndAll: { SequenceLazyAndAll seqAll = (SequenceLazyAndAll)seq; EmitSequenceAll(seqAll, false, true, source); break; } case SequenceType.StrictOrAll: { SequenceStrictOrAll seqAll = (SequenceStrictOrAll)seq; EmitSequenceAll(seqAll, true, false, source); break; } case SequenceType.StrictAndAll: { SequenceStrictAndAll seqAll = (SequenceStrictAndAll)seq; EmitSequenceAll(seqAll, false, false, source); break; } case SequenceType.WeightedOne: { SequenceWeightedOne seqWeighted = (SequenceWeightedOne)seq; EmitSequenceWeighted(seqWeighted, source); break; } case SequenceType.SomeFromSet: { SequenceSomeFromSet seqSome = (SequenceSomeFromSet)seq; EmitSequenceSome(seqSome, source); break; } case SequenceType.Transaction: { SequenceTransaction seqTrans = (SequenceTransaction) seq; source.AppendFront("int transID_" + seqTrans.Id + " = procEnv.TransactionManager.Start();\n"); EmitSequence(seqTrans.Seq, source); source.AppendFront("if("+ GetResultVar(seqTrans.Seq) + ") procEnv.TransactionManager.Commit(transID_" + seqTrans.Id + ");\n"); source.AppendFront("else procEnv.TransactionManager.Rollback(transID_" + seqTrans.Id + ");\n"); source.AppendFront(SetResultVar(seqTrans, GetResultVar(seqTrans.Seq))); break; } case SequenceType.Backtrack: { SequenceBacktrack seqBack = (SequenceBacktrack)seq; EmitSequenceBacktrack(seqBack, source); break; } case SequenceType.Pause: { SequencePause seqPause = (SequencePause)seq; source.AppendFront("procEnv.TransactionManager.Pause();\n"); EmitSequence(seqPause.Seq, source); source.AppendFront("procEnv.TransactionManager.Resume();\n"); source.AppendFront(SetResultVar(seqPause, GetResultVar(seqPause.Seq))); break; } case SequenceType.ExecuteInSubgraph: { SequenceExecuteInSubgraph seqExecInSub = (SequenceExecuteInSubgraph)seq; string subgraph; if(seqExecInSub.AttributeName == null) subgraph = GetVar(seqExecInSub.SubgraphVar); else { string element = "((GRGEN_LIBGR.IGraphElement)" + GetVar(seqExecInSub.SubgraphVar) + ")"; subgraph = element + ".GetAttribute(\"" + seqExecInSub.AttributeName + "\")"; } source.AppendFront("procEnv.SwitchToSubgraph((GRGEN_LIBGR.IGraph)" + subgraph + ");\n"); source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n"); EmitSequence(seqExecInSub.Seq, source); source.AppendFront("procEnv.ReturnFromSubgraph();\n"); source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n"); source.AppendFront(SetResultVar(seqExecInSub, GetResultVar(seqExecInSub.Seq))); break; } case SequenceType.BooleanComputation: { SequenceBooleanComputation seqComp = (SequenceBooleanComputation)seq; EmitSequenceComputation(seqComp.Computation, source); if(seqComp.Computation.ReturnsValue) source.AppendFront(SetResultVar(seqComp, "!GRGEN_LIBGR.TypesHelper.IsDefaultValue(" + GetResultVar(seqComp.Computation) + ")")); else source.AppendFront(SetResultVar(seqComp, "true")); break; } default: throw new Exception("Unknown sequence type: " + seq.SequenceType); } }
private void GenerateInternalDefinedSequenceApplicationMethodStub(SourceBuilder source, DefinedSequenceInfo sequence, String externalActionsExtensionFilename) { source.AppendFrontFormat("// You must implement the following function in the same partial class in ./{0}\n", externalActionsExtensionFilename); source.AppendFront("//public static bool ApplyXGRS_" + sequence.Name + "(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv"); for(int i = 0; i < sequence.Parameters.Length; ++i) { source.Append(", " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i]), model) + " var_"); source.Append(sequence.Parameters[i]); } for(int i = 0; i < sequence.OutParameters.Length; ++i) { source.Append(", ref " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model) + " var_"); source.Append(sequence.OutParameters[i]); } source.Append(")\n"); }
void GenerateKeepOneForEachFilter(SourceBuilder source, LGSPRulePattern rulePattern, String filterVariable) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = "keepOneForEach_" + filterVariable; source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); source.AppendFront("int cmpPos = 0;\n"); source.AppendFront("int pos = 0 + 1;\n"); source.AppendFront("for(; pos < matchesArray.Count; ++pos)\n"); source.AppendFront("{\n"); source.AppendFrontFormat("\tif(matchesArray[pos].{0} == matchesArray[cmpPos].{0})\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.AppendFront("\t\tmatchesArray[pos] = null;\n"); source.AppendFront("\telse\n"); source.AppendFront("\t\tcmpPos = pos;\n"); source.AppendFront("}\n"); source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); }
void EmitRuleOrRuleAllCall(SequenceRuleCall seqRule, SourceBuilder source) { RuleInvocationParameterBindings paramBindings = seqRule.ParamBindings; String specialStr = seqRule.Special ? "true" : "false"; String parameterDeclarations = null; String parameters = null; if(paramBindings.Subgraph != null) parameters = BuildParametersInDeclarations(paramBindings, out parameterDeclarations); else parameters = BuildParameters(paramBindings); String matchingPatternClassName = TypesHelper.GetPackagePrefixDot(paramBindings.Package) + "Rule_" + paramBindings.Name; String patternName = paramBindings.Name; String matchType = matchingPatternClassName + "." + NamesOfEntities.MatchInterfaceName(patternName); String matchName = "match_" + seqRule.Id; String matchesType = "GRGEN_LIBGR.IMatchesExact<" + matchType + ">"; String matchesName = "matches_" + seqRule.Id; if(paramBindings.Subgraph != null) { source.AppendFront(parameterDeclarations + "\n"); source.AppendFront("procEnv.SwitchToSubgraph((GRGEN_LIBGR.IGraph)" + GetVar(paramBindings.Subgraph) + ");\n"); source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n"); } source.AppendFront(matchesType + " " + matchesName + " = rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Match(procEnv, " + (seqRule.SequenceType == SequenceType.RuleCall ? "1" : "procEnv.MaxMatches") + parameters + ");\n"); for(int i = 0; i < seqRule.Filters.Count; ++i) { EmitFilterCall(source, seqRule.Filters[i], patternName, matchesName); } if(gen.FireDebugEvents) source.AppendFront("procEnv.Matched(" + matchesName + ", null, " + specialStr + ");\n"); if(seqRule is SequenceRuleCountAllCall) { SequenceRuleCountAllCall seqRuleCountAll = (SequenceRuleCountAllCall)seqRule; source.AppendFront(SetVar(seqRuleCountAll.CountResult, matchesName + ".Count")); } if(seqRule is SequenceRuleAllCall && ((SequenceRuleAllCall)seqRule).ChooseRandom && ((SequenceRuleAllCall)seqRule).MinSpecified) { SequenceRuleAllCall seqRuleAll = (SequenceRuleAllCall)seqRule; source.AppendFrontFormat("int minmatchesvar_{0} = (int){1};\n", seqRuleAll.Id, GetVar(seqRuleAll.MinVarChooseRandom)); source.AppendFrontFormat("if({0}.Count < minmatchesvar_{1}) {{\n", matchesName, seqRuleAll.Id); } else { source.AppendFront("if(" + matchesName + ".Count==0) {\n"); } source.Indent(); source.AppendFront(SetResultVar(seqRule, "false")); source.Unindent(); source.AppendFront("} else {\n"); source.Indent(); source.AppendFront(SetResultVar(seqRule, "true")); source.AppendFront("procEnv.PerformanceInfo.MatchesFound += " + matchesName + ".Count;\n"); if(gen.FireDebugEvents) source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n"); String returnParameterDeclarations; String returnArguments; String returnAssignments; String returnParameterDeclarationsAllCall; String intermediateReturnAssignmentsAllCall; String returnAssignmentsAllCall; BuildReturnParameters(paramBindings, out returnParameterDeclarations, out returnArguments, out returnAssignments, out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall); if(seqRule.SequenceType == SequenceType.RuleCall) { source.AppendFront(matchType + " " + matchName + " = " + matchesName + ".FirstExact;\n"); if(returnParameterDeclarations.Length!=0) source.AppendFront(returnParameterDeclarations + "\n"); source.AppendFront("rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if(returnAssignments.Length != 0) source.AppendFront(returnAssignments + "\n"); source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed++;\n"); } else if(seqRule.SequenceType == SequenceType.RuleCountAllCall || !((SequenceRuleAllCall)seqRule).ChooseRandom) // seq.SequenceType == SequenceType.RuleAll { // iterate through matches, use Modify on each, fire the next match event after the first if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarationsAllCall + "\n"); String enumeratorName = "enum_" + seqRule.Id; source.AppendFront("IEnumerator<" + matchType + "> " + enumeratorName + " = " + matchesName + ".GetEnumeratorExact();\n"); source.AppendFront("while(" + enumeratorName + ".MoveNext())\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront(matchType + " " + matchName + " = " + enumeratorName + ".Current;\n"); source.AppendFront("if(" + matchName + "!=" + matchesName + ".FirstExact) procEnv.RewritingNextMatch();\n"); if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarations + "\n"); source.AppendFront("rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if(returnAssignments.Length != 0) source.AppendFront(intermediateReturnAssignmentsAllCall + "\n"); source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed++;\n"); source.Unindent(); source.AppendFront("}\n"); if(returnAssignments.Length != 0) source.AppendFront(returnAssignmentsAllCall + "\n"); } else // seq.SequenceType == SequenceType.RuleAll && ((SequenceRuleAll)seqRule).ChooseRandom { // as long as a further rewrite has to be selected: randomly choose next match, rewrite it and remove it from available matches; fire the next match event after the first SequenceRuleAllCall seqRuleAll = (SequenceRuleAllCall)seqRule; if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarationsAllCall + "\n"); source.AppendFrontFormat("int numchooserandomvar_{0} = (int){1};\n", seqRuleAll.Id, seqRuleAll.MaxVarChooseRandom != null ? GetVar(seqRuleAll.MaxVarChooseRandom) : (seqRuleAll.MinSpecified ? "2147483647" : "1")); source.AppendFrontFormat("if({0}.Count < numchooserandomvar_{1}) numchooserandomvar_{1} = {0}.Count;\n", matchesName, seqRule.Id); source.AppendFrontFormat("for(int i = 0; i < numchooserandomvar_{0}; ++i)\n", seqRule.Id); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(i != 0) procEnv.RewritingNextMatch();\n"); source.AppendFront(matchType + " " + matchName + " = " + matchesName + ".RemoveMatchExact(GRGEN_LIBGR.Sequence.randomGenerator.Next(" + matchesName + ".Count));\n"); if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarations + "\n"); source.AppendFront("rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if(returnAssignments.Length != 0) source.AppendFront(intermediateReturnAssignmentsAllCall + "\n"); source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed++;\n"); source.Unindent(); source.AppendFront("}\n"); if(returnAssignments.Length != 0) source.AppendFront(returnAssignmentsAllCall + "\n"); } if(gen.FireDebugEvents) source.AppendFront("procEnv.Finished(" + matchesName + ", " + specialStr + ");\n"); source.Unindent(); source.AppendFront("}\n"); if(paramBindings.Subgraph != null) { source.AppendFront("procEnv.ReturnFromSubgraph();\n"); source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n"); } }
private static void GenerateOrderByFilter(SourceBuilder source, LGSPRulePattern rulePattern, String filterVariable, bool ascending) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = ascending ? "orderAscendingBy_" + filterVariable : "orderDescendingBy_" + filterVariable; source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); source.AppendFrontFormat("matchesArray.Sort(new Comparer_{0}_{1}());\n", rulePattern.name, filterName); source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFrontFormat("class Comparer_{0}_{1} : Comparer<{2}>\n", rulePattern.name, filterName, matchInterfaceName); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("public override int Compare({0} left, {0} right)\n", matchInterfaceName); source.AppendFront("{\n"); source.Indent(); if(ascending) source.AppendFrontFormat("return left.{0}.CompareTo(right.{0});\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); else source.AppendFrontFormat("return -left.{0}.CompareTo(right.{0});\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); }
public void GenerateFilters(SourceBuilder source, LGSPRulePattern rulePattern) { foreach(IFilter f in rulePattern.Filters) { if(f is IFilterAutoGenerated) { IFilterAutoGenerated filter = (IFilterAutoGenerated)f; if(filter.Package != null) { source.AppendFrontFormat("namespace {0}\n", filter.Package); source.AppendFront("{\n"); source.Indent(); } source.AppendFront("public partial class MatchFilters\n"); source.AppendFront("{\n"); source.Indent(); if(filter.Name == "auto") GenerateAutomorphyFilter(source, rulePattern); else { if(filter.Name == "orderAscendingBy") GenerateOrderByFilter(source, rulePattern, filter.Entity, true); if(filter.Name == "orderDescendingBy") GenerateOrderByFilter(source, rulePattern, filter.Entity, false); if(filter.Name == "groupBy") GenerateGroupByFilter(source, rulePattern, filter.Entity); if(filter.Name == "keepSameAsFirst") GenerateKeepSameFilter(source, rulePattern, filter.Entity, true); if(filter.Name == "keepSameAsLast") GenerateKeepSameFilter(source, rulePattern, filter.Entity, false); if(filter.Name == "keepOneForEach") GenerateKeepOneForEachFilter(source, rulePattern, filter.Entity); } source.Unindent(); source.AppendFront("}\n"); if(filter.Package != null) { source.Unindent(); source.AppendFront("}\n"); } } } }
/// <summary> /// Generates matcher class head source code for the pattern of the rulePattern into given source builder /// isInitialStatic tells whether the initial static version or a dynamic version after analyze is to be generated. /// </summary> void GenerateMatcherClassHeadAction(SourceBuilder sb, LGSPRulePattern rulePattern, bool isInitialStatic, SearchProgram searchProgram) { PatternGraph patternGraph = (PatternGraph)rulePattern.PatternGraph; String namePrefix = (isInitialStatic ? "" : "Dyn") + "Action_"; String className = namePrefix + rulePattern.name; String rulePatternClassName = rulePattern.GetType().Name; String matchClassName = rulePatternClassName + "." + "Match_" + rulePattern.name; String matchInterfaceName = rulePatternClassName + "." + "IMatch_" + rulePattern.name; String actionInterfaceName = "IAction_" + rulePattern.name; if(patternGraph.Package != null) { sb.AppendFrontFormat("namespace {0}\n", patternGraph.Package); sb.AppendFront("{\n"); sb.Indent(); } sb.AppendFront("public class " + className + " : GRGEN_LGSP.LGSPAction, " + "GRGEN_LIBGR.IAction, " + actionInterfaceName + "\n"); sb.AppendFront("{\n"); sb.Indent(); // class level sb.AppendFront("public " + className + "() {\n"); sb.Indent(); // method body level sb.AppendFront("_rulePattern = " + rulePatternClassName + ".Instance;\n"); sb.AppendFront("patternGraph = _rulePattern.patternGraph;\n"); if(rulePattern.patternGraph.branchingFactor < 2) { sb.AppendFront("DynamicMatch = myMatch;\n"); if(!isInitialStatic) sb.AppendFrontFormat("GRGEN_ACTIONS.Action_{0}.Instance.DynamicMatch = myMatch;\n", rulePattern.name); } else { sb.AppendFront("if(Environment.ProcessorCount == 1)\n"); sb.AppendFront("{\n"); sb.AppendFront("\tDynamicMatch = myMatch;\n"); if(!isInitialStatic) sb.AppendFrontFormat("\tGRGEN_ACTIONS.Action_{0}.Instance.DynamicMatch = myMatch;\n", rulePattern.name); sb.AppendFront("}\n"); sb.AppendFront("else\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("DynamicMatch = myMatch_parallelized;\n"); if(!isInitialStatic) sb.AppendFrontFormat("GRGEN_ACTIONS.Action_{0}.Instance.DynamicMatch = myMatch_parallelized;\n", rulePattern.name); sb.AppendFrontFormat("numWorkerThreads = GRGEN_LGSP.WorkerPool.EnsurePoolSize({0});\n", rulePattern.patternGraph.branchingFactor); sb.AppendFrontFormat("parallelTaskMatches = new GRGEN_LGSP.LGSPMatchesList<{0}, {1}>[numWorkerThreads];\n", matchClassName, matchInterfaceName); sb.AppendFront("moveHeadAfterNodes = new List<GRGEN_LGSP.LGSPNode>[numWorkerThreads];\n"); sb.AppendFront("moveHeadAfterEdges = new List<GRGEN_LGSP.LGSPEdge>[numWorkerThreads];\n"); sb.AppendFront("moveOutHeadAfter = new List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>[numWorkerThreads];\n"); sb.AppendFront("moveInHeadAfter = new List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>[numWorkerThreads];\n"); sb.AppendFront("for(int i=0; i<numWorkerThreads; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("moveHeadAfterNodes[i] = new List<GRGEN_LGSP.LGSPNode>();\n"); sb.AppendFront("moveHeadAfterEdges[i] = new List<GRGEN_LGSP.LGSPEdge>();\n"); sb.AppendFront("moveOutHeadAfter[i] = new List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>();\n"); sb.AppendFront("moveInHeadAfter[i] = new List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>();\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("for(int i=0; i<parallelTaskMatches.Length; ++i)\n"); sb.AppendFrontFormat("\tparallelTaskMatches[i] = new GRGEN_LGSP.LGSPMatchesList<{0}, {1}>(this);\n", matchClassName, matchInterfaceName); sb.Unindent(); sb.AppendFront("}\n"); } sb.AppendFrontFormat("ReturnArray = new object[{0}];\n", rulePattern.Outputs.Length); sb.AppendFront("matches = new GRGEN_LGSP.LGSPMatchesList<" + matchClassName +", " + matchInterfaceName + ">(this);\n"); sb.Unindent(); // class level sb.AppendFront("}\n\n"); sb.AppendFront("public " + rulePatternClassName + " _rulePattern;\n"); sb.AppendFront("public override GRGEN_LGSP.LGSPRulePattern rulePattern { get { return _rulePattern; } }\n"); sb.AppendFront("public override string Name { get { return \"" + rulePattern.name + "\"; } }\n"); sb.AppendFront("private GRGEN_LGSP.LGSPMatchesList<" + matchClassName + ", " + matchInterfaceName + "> matches;\n\n"); if (isInitialStatic) { sb.AppendFront("public static " + className + " Instance { get { return instance; } set { instance = value; } }\n"); sb.AppendFront("private static " + className + " instance = new " + className + "();\n"); } GenerateIndependentsMatchObjects(sb, rulePattern, patternGraph); sb.AppendFront("\n"); GenerateParallelizationSetupAsNeeded(sb, rulePattern, searchProgram); }
public override void Emit(SourceBuilder sourceCode) { String id = fetchId().ToString(); if(ContainerType.StartsWith("List")) { sourceCode.AppendFrontFormat("{0} entry_{1} = ({0}) " + NamesOfEntities.Variable(Container) + ";\n", ContainerType, id); sourceCode.AppendFrontFormat("for(int index_{0}=0; index_{0}<entry_{0}.Count; ++index_{0})\n", id); sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Index != null) { sourceCode.AppendFront(IndexType + " " + NamesOfEntities.Variable(Index) + " = index_" + id + ";\n"); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + "[index_" + id + "];\n"); } else { sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + "[index_" + id + "];\n"); } } else if(ContainerType.StartsWith("GRGEN_LIBGR.Deque")) { sourceCode.AppendFrontFormat("{0} entry_{1} = ({0}) " + NamesOfEntities.Variable(Container) + ";\n", ContainerType, id); sourceCode.AppendFrontFormat("for(int index_{0}=0; index_{0}<entry_{0}.Count; ++index_{0})\n", id); sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Index != null) { sourceCode.AppendFront(IndexType + " " + NamesOfEntities.Variable(Index) + " = index_" + id + ";\n"); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + "[index_" + id + "];\n"); } else { sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + "[index_" + id + "];\n"); } } else if(ContainerType.StartsWith("Dictionary") && ContainerType.Contains("SetValueType")) { sourceCode.AppendFrontFormat("foreach(KeyValuePair<{0},GRGEN_LIBGR.SetValueType> entry_{1} in {2})\n", VariableType, id, NamesOfEntities.Variable(Container)); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + ".Key;\n"); } else { sourceCode.AppendFrontFormat("foreach(KeyValuePair<{0},{1}> entry_{2} in {3})\n", IndexType, VariableType, id, NamesOfEntities.Variable(Container)); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFront(IndexType + " " + NamesOfEntities.Variable(Index) + " = entry_" + id + ".Key;\n"); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + ".Value;\n"); } foreach(Yielding statement in Statements) statement.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
void GenerateParallelizationSetupAsNeeded(SourceBuilder sb, LGSPRulePattern rulePattern, SearchProgram searchProgram) { if(rulePattern.patternGraph.branchingFactor < 2) return; foreach(SearchOperation so in rulePattern.patternGraph.parallelizedSchedule[0].Operations) { switch(so.Type) { case SearchOperationType.WriteParallelPreset: if(so.Element is SearchPlanNodeNode) sb.AppendFrontFormat("GRGEN_LGSP.LGSPNode {0};\n", NamesOfEntities.IterationParallelizationParallelPresetCandidate(((SearchPlanNodeNode)so.Element).PatternElement.Name)); else //SearchPlanEdgeNode sb.AppendFrontFormat("GRGEN_LGSP.LGSPEdge {0};\n", NamesOfEntities.IterationParallelizationParallelPresetCandidate(((SearchPlanEdgeNode)so.Element).PatternElement.Name)); break; case SearchOperationType.WriteParallelPresetVar: sb.AppendFrontFormat("{0} {1};\n", TypesHelper.TypeName(((PatternVariable)so.Element).Type), NamesOfEntities.IterationParallelizationParallelPresetCandidate(((PatternVariable)so.Element).Name)); break; case SearchOperationType.SetupParallelLookup: if(so.Element is SearchPlanNodeNode) { sb.AppendFrontFormat("GRGEN_LGSP.LGSPNode {0};\n", NamesOfEntities.IterationParallelizationListHead(((SearchPlanNodeNode)so.Element).PatternElement.Name)); sb.AppendFrontFormat("GRGEN_LGSP.LGSPNode {0};\n", NamesOfEntities.IterationParallelizationNextCandidate(((SearchPlanNodeNode)so.Element).PatternElement.Name)); } else { sb.AppendFrontFormat("GRGEN_LGSP.LGSPEdge {0};\n", NamesOfEntities.IterationParallelizationListHead(((SearchPlanEdgeNode)so.Element).PatternElement.Name)); sb.AppendFrontFormat("GRGEN_LGSP.LGSPEdge {0};\n", NamesOfEntities.IterationParallelizationNextCandidate(((SearchPlanEdgeNode)so.Element).PatternElement.Name)); } break; case SearchOperationType.SetupParallelPickFromStorage: if(TypesHelper.DotNetTypeToXgrsType(so.Storage.Variable.type).StartsWith("set") || TypesHelper.DotNetTypeToXgrsType(so.Storage.Variable.type).StartsWith("map")) { sb.AppendFrontFormat("IEnumerator<KeyValuePair<{0},{1}>> {2};\n", TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(TypesHelper.DotNetTypeToXgrsType(so.Storage.Variable.Type)), model), TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractDst(TypesHelper.DotNetTypeToXgrsType(so.Storage.Variable.Type)), model), NamesOfEntities.IterationParallelizationIterator(((SearchPlanNode)so.Element).PatternElement.Name)); } else { sb.AppendFrontFormat("IEnumerator<{0}> {1};\n", TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(TypesHelper.DotNetTypeToXgrsType(so.Storage.Variable.Type)), model), NamesOfEntities.IterationParallelizationIterator(((SearchPlanNode)so.Element).PatternElement.Name)); } break; case SearchOperationType.SetupParallelPickFromStorageDependent: if(TypesHelper.AttributeTypeToXgrsType(so.Storage.Attribute.Attribute).StartsWith("set") || TypesHelper.AttributeTypeToXgrsType(so.Storage.Attribute.Attribute).StartsWith("map")) { sb.AppendFrontFormat("IEnumerator<KeyValuePair<{0},{1}>> {2};\n", TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(TypesHelper.AttributeTypeToXgrsType(so.Storage.Attribute.Attribute)), model), TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractDst(TypesHelper.AttributeTypeToXgrsType(so.Storage.Attribute.Attribute)), model), NamesOfEntities.IterationParallelizationIterator(((SearchPlanNode)so.Element).PatternElement.Name)); } else { sb.AppendFrontFormat("IEnumerator<{0}> {1};\n", TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(TypesHelper.AttributeTypeToXgrsType(so.Storage.Attribute.Attribute)), model), NamesOfEntities.IterationParallelizationIterator(((SearchPlanNode)so.Element).PatternElement.Name)); } break; case SearchOperationType.SetupParallelPickFromIndex: sb.AppendFrontFormat("IEnumerator<{0}> {1};\n", TypesHelper.TypeName(so.IndexAccess.Index is AttributeIndexDescription ? ((AttributeIndexDescription)so.IndexAccess.Index).GraphElementType : ((IncidenceCountIndexDescription)so.IndexAccess.Index).StartNodeType), NamesOfEntities.IterationParallelizationIterator(((SearchPlanNode)so.Element).PatternElement.Name)); break; case SearchOperationType.SetupParallelPickFromIndexDependent: sb.AppendFrontFormat("IEnumerator<{0}> {1};\n", TypesHelper.TypeName(so.IndexAccess.Index is AttributeIndexDescription ? ((AttributeIndexDescription)so.IndexAccess.Index).GraphElementType : ((IncidenceCountIndexDescription)so.IndexAccess.Index).StartNodeType), NamesOfEntities.IterationParallelizationIterator(((SearchPlanNode)so.Element).PatternElement.Name)); break; case SearchOperationType.SetupParallelIncoming: case SearchOperationType.SetupParallelOutgoing: sb.AppendFrontFormat("GRGEN_LGSP.LGSPEdge {0};\n", NamesOfEntities.IterationParallelizationListHead(((SearchPlanEdgeNode)so.Element).PatternElement.Name)); sb.AppendFrontFormat("GRGEN_LGSP.LGSPEdge {0};\n", NamesOfEntities.IterationParallelizationNextCandidate(((SearchPlanEdgeNode)so.Element).PatternElement.Name)); break; case SearchOperationType.SetupParallelIncident: sb.AppendFrontFormat("GRGEN_LGSP.LGSPEdge {0};\n", NamesOfEntities.IterationParallelizationListHead(((SearchPlanEdgeNode)so.Element).PatternElement.Name)); sb.AppendFrontFormat("GRGEN_LGSP.LGSPEdge {0};\n", NamesOfEntities.IterationParallelizationNextCandidate(((SearchPlanEdgeNode)so.Element).PatternElement.Name)); sb.AppendFrontFormat("int {0};\n", NamesOfEntities.IterationParallelizationDirectionRunCounterVariable(((SearchPlanEdgeNode)so.Element).PatternElement.Name)); break; } } sb.AppendFront("\n"); String rulePatternClassName = rulePattern.GetType().Name; String matchClassName = rulePatternClassName + "." + "Match_" + rulePattern.name; String matchInterfaceName = rulePatternClassName + "." + "IMatch_" + rulePattern.name; sb.AppendFront("private static GRGEN_LGSP.LGSPMatchesList<" + matchClassName + ", " + matchInterfaceName + ">[] parallelTaskMatches;\n"); sb.AppendFront("private static int numWorkerThreads;\n"); sb.AppendFront("private static int iterationNumber;\n"); sb.AppendFront("private static int iterationLock;\n"); sb.AppendFront("[ThreadStatic] private static int currentIterationNumber;\n"); sb.AppendFront("[ThreadStatic] private static int threadId;\n"); sb.AppendFront("private static GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnvParallel;\n"); sb.AppendFront("private static int maxMatchesParallel;\n"); sb.AppendFront("private static bool maxMatchesFound = false;\n"); sb.AppendFront("private static List<GRGEN_LGSP.LGSPNode>[] moveHeadAfterNodes;\n"); sb.AppendFront("private static List<GRGEN_LGSP.LGSPEdge>[] moveHeadAfterEdges;\n"); sb.AppendFront("private static List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>[] moveOutHeadAfter;\n"); sb.AppendFront("private static List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>[] moveInHeadAfter;\n"); sb.AppendFront("\n"); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFrontFormat("foreach({0} {1} in (({2})graph.indices).{3}.Lookup(", VariableType, NamesOfEntities.Variable(Variable), IndexSetType, Index.Name); Expr.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); } foreach(Yielding statement in Statements) statement.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
/// <summary> /// Generates matcher class head source code for the given alternative into given source builder /// isInitialStatic tells whether the initial static version or a dynamic version after analyze is to be generated. /// </summary> public void GenerateMatcherClassHeadAlternative(SourceBuilder sb, LGSPMatchingPattern matchingPattern, Alternative alternative, bool isInitialStatic) { PatternGraph patternGraph = (PatternGraph)matchingPattern.PatternGraph; String namePrefix = (isInitialStatic ? "" : "Dyn") + "AlternativeAction_"; String className = namePrefix + alternative.pathPrefix+alternative.name; if(patternGraph.Package != null) { sb.AppendFrontFormat("namespace {0}\n", patternGraph.Package); sb.AppendFront("{\n"); sb.Indent(); } sb.AppendFront("public class " + className + " : GRGEN_LGSP.LGSPSubpatternAction\n"); sb.AppendFront("{\n"); sb.Indent(); // class level sb.AppendFront("private " + className + "(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv_, " + "Stack<GRGEN_LGSP.LGSPSubpatternAction> openTasks_, GRGEN_LGSP.PatternGraph[] patternGraphs_) {\n"); sb.Indent(); // method body level sb.AppendFront("actionEnv = actionEnv_; openTasks = openTasks_;\n"); // pfadausdruck gebraucht, da das alternative-objekt im pattern graph steckt sb.AppendFront("patternGraphs = patternGraphs_;\n"); sb.Unindent(); // class level sb.AppendFront("}\n\n"); GenerateTasksMemoryPool(sb, className, true, false, matchingPattern.patternGraph.branchingFactor); Dictionary<string, bool> neededNodes = new Dictionary<string,bool>(); Dictionary<string, bool> neededEdges = new Dictionary<string,bool>(); Dictionary<string, GrGenType> neededVariables = new Dictionary<string, GrGenType>(); foreach (PatternGraph altCase in alternative.alternativeCases) { foreach (KeyValuePair<string, bool> neededNode in altCase.neededNodes) neededNodes[neededNode.Key] = neededNode.Value; foreach (KeyValuePair<string, bool> neededEdge in altCase.neededEdges) neededEdges[neededEdge.Key] = neededEdge.Value; foreach (KeyValuePair<string, GrGenType> neededVariable in altCase.neededVariables) neededVariables[neededVariable.Key] = neededVariable.Value; } foreach (KeyValuePair<string, bool> node in neededNodes) { sb.AppendFront("public GRGEN_LGSP.LGSPNode " + node.Key + ";\n"); } foreach (KeyValuePair<string, bool> edge in neededEdges) { sb.AppendFront("public GRGEN_LGSP.LGSPEdge " + edge.Key + ";\n"); } foreach (KeyValuePair<string, GrGenType> variable in neededVariables) { sb.AppendFront("public " + TypesHelper.TypeName(variable.Value) + " " + variable.Key + ";\n"); } foreach (PatternGraph altCase in alternative.alternativeCases) { GenerateIndependentsMatchObjects(sb, matchingPattern, altCase); } sb.AppendFront("\n"); }
public bool GenerateXGRSCode(string xgrsName, String package, String xgrsStr, String[] paramNames, GrGenType[] paramTypes, String[] defToBeYieldedToNames, GrGenType[] defToBeYieldedToTypes, SourceBuilder source, int lineNr) { Dictionary<String, String> varDecls = new Dictionary<String, String>(); for (int i = 0; i < paramNames.Length; i++) { varDecls.Add(paramNames[i], TypesHelper.DotNetTypeToXgrsType(paramTypes[i])); } for(int i = 0; i < defToBeYieldedToNames.Length; i++) { varDecls.Add(defToBeYieldedToNames[i], TypesHelper.DotNetTypeToXgrsType(defToBeYieldedToTypes[i])); } Sequence seq; try { List<string> warnings = new List<string>(); seq = SequenceParser.ParseSequence(xgrsStr, package, ruleNames, sequenceNames, procedureNames, functionNames, functionOutputTypes, filterFunctionNames, varDecls, model, warnings); foreach(string warning in warnings) { Console.Error.WriteLine("The exec statement \"" + xgrsStr + "\" given on line " + lineNr + " reported back:\n" + warning); } seq.Check(env); seq.SetNeedForProfilingRecursive(gen.EmitProfiling); } catch(ParseException ex) { Console.Error.WriteLine("The exec statement \"" + xgrsStr + "\" given on line " + lineNr + " caused the following error:\n" + ex.Message); return false; } catch(SequenceParserException ex) { Console.Error.WriteLine("The exec statement \"" + xgrsStr + "\" given on line " + lineNr + " caused the following error:\n"); HandleSequenceParserException(ex); return false; } source.Append("\n"); source.AppendFront("public static bool ApplyXGRS_" + xgrsName + "(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv"); for(int i = 0; i < paramNames.Length; i++) { source.Append(", " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(paramTypes[i]), model) + " var_"); source.Append(paramNames[i]); } for(int i = 0; i < defToBeYieldedToTypes.Length; i++) { source.Append(", ref " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(defToBeYieldedToTypes[i]), model) + " var_"); source.Append(defToBeYieldedToNames[i]); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("GRGEN_LGSP.LGSPGraph graph = procEnv.graph;\n"); source.AppendFront("GRGEN_LGSP.LGSPActions actions = procEnv.curActions;\n"); knownRules.Clear(); if(gen.FireDebugEvents) { source.AppendFrontFormat("procEnv.DebugEntering(\"{0}\", \"{1}\");\n", InjectExec(xgrsName), xgrsStr.Replace("\\", "\\\\").Replace("\"", "\\\"")); } EmitNeededVarAndRuleEntities(seq, source); EmitSequence(seq, source); if(gen.FireDebugEvents) { source.AppendFrontFormat("procEnv.DebugExiting(\"{0}\");\n", InjectExec(xgrsName)); } source.AppendFront("return " + GetResultVar(seq) + ";\n"); source.Unindent(); source.AppendFront("}\n"); List<SequenceExpressionContainerConstructor> containerConstructors = new List<SequenceExpressionContainerConstructor>(); Dictionary<SequenceVariable, SetValueType> variables = new Dictionary<SequenceVariable, SetValueType>(); seq.GetLocalVariables(variables, containerConstructors, null); foreach(SequenceExpressionContainerConstructor cc in containerConstructors) { GenerateContainerConstructor(cc, source); } return true; }
/// <summary> /// Generates match objects of independents (one pre-allocated is part of action class) /// </summary> private void GenerateIndependentsMatchObjects(SourceBuilder sb, LGSPMatchingPattern matchingPatternClass, PatternGraph patternGraph) { if (patternGraph.nestedIndependents != null) { foreach (KeyValuePair<PatternGraph, PatternGraph> nestedIndependent in patternGraph.nestedIndependents) { if(nestedIndependent.Key.originalPatternGraph != null) { sb.AppendFrontFormat("private {0} {1} = new {0}();", nestedIndependent.Key.originalSubpatternEmbedding.matchingPatternOfEmbeddedGraph.GetType().Name + "." + NamesOfEntities.MatchClassName(nestedIndependent.Key.originalPatternGraph.pathPrefix + nestedIndependent.Key.originalPatternGraph.name), NamesOfEntities.MatchedIndependentVariable(nestedIndependent.Key.pathPrefix + nestedIndependent.Key.name)); } else { sb.AppendFrontFormat("private {0} {1} = new {0}();", matchingPatternClass.GetType().Name + "." + NamesOfEntities.MatchClassName(nestedIndependent.Key.pathPrefix + nestedIndependent.Key.name), NamesOfEntities.MatchedIndependentVariable(nestedIndependent.Key.pathPrefix + nestedIndependent.Key.name)); } } } foreach (PatternGraph idpt in patternGraph.independentPatternGraphsPlusInlined) { GenerateIndependentsMatchObjects(sb, matchingPatternClass, idpt); } }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFrontFormat("foreach({0} {1} in (({2})graph.indices).{3}.Lookup", VariableType, NamesOfEntities.Variable(Variable), IndexSetType, Index.Name); if(Ascending) sourceCode.Append("Ascending"); else sourceCode.Append("Descending"); if(From != null && To != null) { sourceCode.Append("From"); if(IncludingFrom) sourceCode.Append("Inclusive"); else sourceCode.Append("Exclusive"); sourceCode.Append("To"); if(IncludingTo) sourceCode.Append("Inclusive"); else sourceCode.Append("Exclusive"); sourceCode.Append("("); From.Emit(sourceCode); ; sourceCode.Append(", "); To.Emit(sourceCode); ; } else if(From != null) { sourceCode.Append("From"); if(IncludingFrom) sourceCode.Append("Inclusive"); else sourceCode.Append("Exclusive"); sourceCode.Append("("); From.Emit(sourceCode); ; } else if(To != null) { sourceCode.Append("To"); if(IncludingTo) sourceCode.Append("Inclusive"); else sourceCode.Append("Exclusive"); sourceCode.Append("("); To.Emit(sourceCode); ; } else { sourceCode.Append("("); } sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); } foreach(Yielding statement in Statements) statement.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
private void GenerateInternalDefinedSequenceApplicationMethod(SourceBuilder source, DefinedSequenceInfo sequence, Sequence seq) { source.AppendFront("public static bool ApplyXGRS_" + sequence.Name + "(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv"); for(int i = 0; i < sequence.Parameters.Length; ++i) { source.Append(", " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i]), model) + " var_"); source.Append(sequence.Parameters[i]); } for(int i = 0; i < sequence.OutParameters.Length; ++i) { source.Append(", ref " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model) + " var_"); source.Append(sequence.OutParameters[i]); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("GRGEN_LGSP.LGSPGraph graph = procEnv.graph;\n"); source.AppendFront("GRGEN_LGSP.LGSPActions actions = procEnv.curActions;\n"); knownRules.Clear(); if(gen.FireDebugEvents) { source.AppendFrontFormat("procEnv.DebugEntering(\"{0}\"", sequence.Name); for(int i = 0; i < sequence.Parameters.Length; ++i) { source.Append(", var_"); source.Append(sequence.Parameters[i]); } source.Append(");\n"); } EmitNeededVarAndRuleEntities(seq, source); EmitSequence(seq, source); if(gen.FireDebugEvents) { source.AppendFrontFormat("procEnv.DebugExiting(\"{0}\"", sequence.Name); for(int i = 0; i < sequence.OutParameters.Length; ++i) { source.Append(", var_"); source.Append(sequence.OutParameters[i]); } source.Append(");\n"); } source.AppendFront("return " + GetResultVar(seq) + ";\n"); source.Unindent(); source.AppendFront("}\n"); List<SequenceExpressionContainerConstructor> containerConstructors = new List<SequenceExpressionContainerConstructor>(); Dictionary<SequenceVariable, SetValueType> variables = new Dictionary<SequenceVariable, SetValueType>(); seq.GetLocalVariables(variables, containerConstructors, null); foreach(SequenceExpressionContainerConstructor cc in containerConstructors) { GenerateContainerConstructor(cc, source); } }
void GenerateGroupByFilter(SourceBuilder source, LGSPRulePattern rulePattern, String filterVariable) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = "groupBy_" + filterVariable; if(true) // does the type of the variable to group-by support ordering? then order, is more efficient than equality comparisons { source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); source.AppendFrontFormat("matchesArray.Sort(new Comparer_{0}_{1}());\n", rulePattern.name, filterName); source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFrontFormat("class Comparer_{0}_{1} : Comparer<{2}>\n", rulePattern.name, filterName, matchInterfaceName); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("public override int Compare({0} left, {0} right)\n", matchInterfaceName); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("return left.{0}.CompareTo(right.{0});\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); } else { // ensure that if two elements are equal, they are neighbours or only separated by equal elements // not needed yet, as of now we only support numerical types and string, that support ordering in addition to equality comparison /*List<T> matchesArray; for(int i = 0; i < matchesArray.Count - 1; ++i) { for(int j = i + 1; j < matchesArray.Count; ++j) { if(matchesArray[i] == matchesArray[j]) { T tmp = matchesArray[i + 1]; matchesArray[i + 1] = matchesArray[j]; matchesArray[j] = tmp; break; } } }*/ } }
void EmitFilterCall(SourceBuilder source, FilterCall filterCall, string patternName, string matchesName) { if(filterCall.Name == "keepFirst" || filterCall.Name == "removeFirst" || filterCall.Name == "keepFirstFraction" || filterCall.Name == "removeFirstFraction" || filterCall.Name == "keepLast" || filterCall.Name == "removeLast" || filterCall.Name == "keepLastFraction" || filterCall.Name == "removeLastFraction") { switch(filterCall.Name) { case "keepFirst": source.AppendFrontFormat("{0}.FilterKeepFirst((int)({1}));\n", matchesName, GetSequenceExpression(filterCall.ArgumentExpressions[0], source)); break; case "keepLast": source.AppendFrontFormat("{0}.FilterKeepLast((int)({1}));\n", matchesName, GetSequenceExpression(filterCall.ArgumentExpressions[0], source)); break; case "keepFirstFraction": source.AppendFrontFormat("{0}.FilterKeepFirstFraction((double)({1}));\n", matchesName, GetSequenceExpression(filterCall.ArgumentExpressions[0], source)); break; case "keepLastFraction": source.AppendFrontFormat("{0}.FilterKeepLastFraction((double)({1}));\n", matchesName, GetSequenceExpression(filterCall.ArgumentExpressions[0], source)); break; case "removeFirst": source.AppendFrontFormat("{0}.FilterRemoveFirst((int)({1}));\n", matchesName, GetSequenceExpression(filterCall.ArgumentExpressions[0], source)); break; case "removeLast": source.AppendFrontFormat("{0}.FilterRemoveLast((int)({1}));\n", matchesName, GetSequenceExpression(filterCall.ArgumentExpressions[0], source)); break; case "removeFirstFraction": source.AppendFrontFormat("{0}.FilterRemoveFirstFraction((double)({1}));\n", matchesName, GetSequenceExpression(filterCall.ArgumentExpressions[0], source)); break; case "removeLastFraction": source.AppendFrontFormat("{0}.FilterRemoveLastFraction((double)({1}));\n", matchesName, GetSequenceExpression(filterCall.ArgumentExpressions[0], source)); break; } } else { if(filterCall.IsAutoGenerated && filterCall.Name == "auto") source.AppendFrontFormat("GRGEN_ACTIONS.{0}MatchFilters.Filter_{1}_{2}(procEnv, {3});\n", TypesHelper.GetPackagePrefixDot(filterCall.Package), patternName, filterCall.Name, matchesName); else if(filterCall.IsAutoGenerated) source.AppendFrontFormat("GRGEN_ACTIONS.{0}MatchFilters.Filter_{1}_{2}_{3}(procEnv, {4});\n", TypesHelper.GetPackagePrefixDot(filterCall.Package), patternName, filterCall.Name, filterCall.Entity, matchesName); else { source.AppendFrontFormat("GRGEN_ACTIONS.{0}MatchFilters.Filter_{1}(procEnv, {2}", TypesHelper.GetPackagePrefixDot(filterCall.Package), filterCall.Name, matchesName); for(int i = 0; i < filterCall.ArgumentExpressions.Length; ++i) { source.AppendFormat(", ({0})({1})", TypesHelper.XgrsTypeToCSharpType(filterFunctionsToInputTypes[filterCall.Name][i], model), GetSequenceExpression(filterCall.ArgumentExpressions[i], source)); } source.Append(");\n"); } } }
public bool GenerateDefinedSequence(SourceBuilder source, DefinedSequenceInfo sequence) { Dictionary<String, String> varDecls = new Dictionary<String, String>(); for(int i = 0; i < sequence.Parameters.Length; i++) { varDecls.Add(sequence.Parameters[i], TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i])); } for(int i = 0; i < sequence.OutParameters.Length; i++) { varDecls.Add(sequence.OutParameters[i], TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i])); } Sequence seq; try { List<string> warnings = new List<string>(); seq = SequenceParser.ParseSequence(sequence.XGRS, sequence.Package, ruleNames, sequenceNames, procedureNames, functionNames, functionOutputTypes, filterFunctionNames, varDecls, model, warnings); foreach(string warning in warnings) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" reported back:\n" + warning); } seq.Check(env); seq.SetNeedForProfilingRecursive(gen.EmitProfiling); } catch(ParseException ex) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" caused the following error:\n" + ex.Message); return false; } catch(SequenceParserException ex) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" caused the following error:\n"); HandleSequenceParserException(ex); return false; } // exact sequence definition compiled class source.Append("\n"); if(sequence.Package != null) { source.AppendFrontFormat("namespace {0}\n", sequence.Package); source.AppendFront("{\n"); source.Indent(); } source.AppendFront("public class Sequence_" + sequence.Name + " : GRGEN_LIBGR.SequenceDefinitionCompiled\n"); source.AppendFront("{\n"); source.Indent(); GenerateSequenceDefinedSingleton(source, sequence); source.Append("\n"); GenerateInternalDefinedSequenceApplicationMethod(source, sequence, seq); source.Append("\n"); GenerateExactExternalDefinedSequenceApplicationMethod(source, sequence); source.Append("\n"); GenerateGenericExternalDefinedSequenceApplicationMethod(source, sequence); // end of exact sequence definition compiled class source.Unindent(); source.AppendFront("}\n"); if(sequence.Package != null) { source.Unindent(); source.AppendFront("}\n"); } return true; }
public void GenerateFilterStubs(SourceBuilder source, LGSPRulePattern rulePattern) { String rulePatternClassName = rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; foreach(IFilter filter in rulePattern.Filters) { if(filter is IFilterAutoGenerated) continue; IFilterFunction filterFunction = (IFilterFunction)filter; if(!filterFunction.IsExternal) continue; if(filter.Package != null) { source.AppendFrontFormat("namespace {0}\n", filter.Package); source.AppendFront("{\n"); source.Indent(); } source.AppendFront("public partial class MatchFilters\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("//public static void Filter_{0}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {1} matches", filter.Name, matchesListType); for(int i = 0; i < filterFunction.Inputs.Length; ++i) { source.AppendFormat(", {0} {1}", TypesHelper.TypeName(filterFunction.Inputs[i]), filterFunction.InputNames[i]); } source.Append(")\n"); source.Unindent(); source.AppendFront("}\n"); if(filter.Package != null) { source.Unindent(); source.AppendFront("}\n"); } } }
public override void Emit(SourceBuilder sourceCode) { String id = fetchId().ToString(); if(Function is Adjacent) { Adjacent adjacent = (Adjacent)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); adjacent.Node.Emit(sourceCode); sourceCode.Append(";\n"); if(!Profiling) { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.GetCompatibleIncident(", id); adjacent.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); } else { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.Incident)\n", id); } sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); sourceCode.AppendFrontFormat("if(!edge_{0}.InstanceOf(", id); adjacent.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); } sourceCode.AppendFrontFormat("if(!edge_{0}.Opposite(node_{0}).InstanceOf(", id); adjacent.AdjacentNodeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2}.Opposite(node_{2});\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is AdjacentIncoming) { AdjacentIncoming adjacent = (AdjacentIncoming)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); adjacent.Node.Emit(sourceCode); sourceCode.Append(";\n"); if(!Profiling) { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.GetCompatibleIncoming(", id); adjacent.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); } else { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.Incoming)\n", id); } sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); sourceCode.AppendFrontFormat("if(!edge_{0}.InstanceOf(", id); adjacent.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); } sourceCode.AppendFrontFormat("if(!edge_{0}.Source.InstanceOf(", id); adjacent.AdjacentNodeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2}.Source;\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is AdjacentOutgoing) { AdjacentOutgoing adjacent = (AdjacentOutgoing)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); adjacent.Node.Emit(sourceCode); sourceCode.Append(";\n"); if(!Profiling) { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.GetCompatibleOutgoing(", id); adjacent.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); } else { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.Outgoing)\n", id); } sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); sourceCode.AppendFrontFormat("if(!edge_{0}.InstanceOf(", id); adjacent.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); } sourceCode.AppendFrontFormat("if(!edge_{0}.Target.InstanceOf(", id); adjacent.AdjacentNodeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2}.Target;\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is Incident) { Incident incident = (Incident)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); incident.Node.Emit(sourceCode); sourceCode.Append(";\n"); if(!Profiling) { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.GetCompatibleIncident(", id); incident.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); } else { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.Incident)\n", id); } sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); sourceCode.AppendFrontFormat("if(!edge_{0}.InstanceOf(", id); incident.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); } sourceCode.AppendFrontFormat("if(!edge_{0}.Opposite(node_{0}).InstanceOf(", id); incident.AdjacentNodeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is Incoming) { Incoming incident = (Incoming)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); incident.Node.Emit(sourceCode); sourceCode.Append(";\n"); if(!Profiling) { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.GetCompatibleIncoming(", id); incident.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); } else { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.Incoming)\n", id); } sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); sourceCode.AppendFrontFormat("if(!edge_{0}.InstanceOf(", id); incident.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); } sourceCode.AppendFrontFormat("if(!edge_{0}.Source.InstanceOf(", id); incident.AdjacentNodeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is Outgoing) { Outgoing incident = (Outgoing)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); incident.Node.Emit(sourceCode); sourceCode.Append(";\n"); if(!Profiling) { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.GetCompatibleOutgoing(", id); incident.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); } else { sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in node_{0}.Outgoing)\n", id); } sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); sourceCode.AppendFrontFormat("if(!edge_{0}.InstanceOf(", id); incident.IncidentEdgeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); } sourceCode.AppendFrontFormat("if(!edge_{0}.Target.InstanceOf(", id); incident.AdjacentNodeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("\tcontinue;\n"); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is Reachable) { Reachable reachable = (Reachable)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.INode iter_{0} in GRGEN_LIBGR.GraphHelper.Reachable(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})iter_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is ReachableIncoming) { ReachableIncoming reachable = (ReachableIncoming)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.INode iter_{0} in GRGEN_LIBGR.GraphHelper.ReachableIncoming(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})iter_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is ReachableOutgoing) { ReachableOutgoing reachable = (ReachableOutgoing)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.INode iter_{0} in GRGEN_LIBGR.GraphHelper.ReachableOutgoing(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})iter_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is ReachableEdges) { ReachableEdges reachable = (ReachableEdges)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in GRGEN_LIBGR.GraphHelper.ReachableEdges(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is ReachableEdgesIncoming) { ReachableEdgesIncoming reachable = (ReachableEdgesIncoming)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in GRGEN_LIBGR.GraphHelper.ReachableEdgesIncoming(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is ReachableEdgesOutgoing) { ReachableEdgesOutgoing reachable = (ReachableEdgesOutgoing)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in GRGEN_LIBGR.GraphHelper.ReachableEdgesOutgoing(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is BoundedReachable) { BoundedReachable reachable = (BoundedReachable)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.INode iter_{0} in GRGEN_LIBGR.GraphHelper.BoundedReachable(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})iter_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is BoundedReachableIncoming) { BoundedReachableIncoming reachable = (BoundedReachableIncoming)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.INode iter_{0} in GRGEN_LIBGR.GraphHelper.BoundedReachableIncoming(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})iter_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is BoundedReachableOutgoing) { BoundedReachableOutgoing reachable = (BoundedReachableOutgoing)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.INode iter_{0} in GRGEN_LIBGR.GraphHelper.BoundedReachableOutgoing(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})iter_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is BoundedReachableEdges) { BoundedReachableEdges reachable = (BoundedReachableEdges)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in GRGEN_LIBGR.GraphHelper.BoundedReachableEdges(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is BoundedReachableEdgesIncoming) { BoundedReachableEdgesIncoming reachable = (BoundedReachableEdgesIncoming)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in GRGEN_LIBGR.GraphHelper.BoundedReachableEdgesIncoming(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is BoundedReachableEdgesOutgoing) { BoundedReachableEdgesOutgoing reachable = (BoundedReachableEdgesOutgoing)Function; sourceCode.AppendFront("GRGEN_LIBGR.INode node_" + id + " = "); reachable.Node.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in GRGEN_LIBGR.GraphHelper.BoundedReachableEdgesOutgoing(node_{0}, ", id); reachable.IncidentEdgeType.Emit(sourceCode); sourceCode.Append(", "); reachable.AdjacentNodeType.Emit(sourceCode); sourceCode.Append(", "); sourceCode.Append("graph"); if(Profiling) sourceCode.Append(", actionEnv"); if(Parallel) sourceCode.Append(", threadId"); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFrontFormat("{0} {1} = ({0})edge_{2};\n", VariableType, NamesOfEntities.Variable(Variable), id); } else if(Function is Nodes) { Nodes nodes = (Nodes)Function; sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.INode node_{0} in graph.GetCompatibleNodes(", id); nodes.NodeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); } sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = (" + VariableType + ") node_" + id + ";\n"); } else if(Function is Edges) { Edges edges = (Edges)Function; sourceCode.AppendFrontFormat("foreach(GRGEN_LIBGR.IEdge edge_{0} in graph.GetCompatibleEdges(", id); edges.EdgeType.Emit(sourceCode); sourceCode.Append("))\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Profiling) { if(Parallel) sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];\n"); else sourceCode.AppendFront("++actionEnv.PerformanceInfo.SearchSteps;\n"); } sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = (" + VariableType + ") edge_" + id + ";\n"); } foreach(Yielding statement in Statements) statement.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }