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); } }
/// <summary> /// Emit variable declarations needed (only once for every variable) /// </summary> private void EmitVarIfNew(SequenceVariable var, SourceBuilder source) { if (!var.Visited) { var.Visited = true; source.AppendFront(seqHelper.DeclareVar(var)); } }
public override void Emit(SourceBuilder sourceCode) { if (sourceCode.CommentSourceCode) { sourceCode.AppendFront("// Check whether subpatterns were found \n"); } // emit decision sourceCode.AppendFrontFormat("if({0}matchesList.Count>0) ", NegativeIndependentNamePrefix); // emit check failed code sourceCode.Append("{\n"); sourceCode.Indent(); CheckFailedOperations.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
private void GenerateExactExternalDefinedSequenceApplicationMethod(SourceBuilder source, DefinedSequenceInfo sequence) { source.AppendFront("public static bool Apply_" + sequence.Name + "(GRGEN_LIBGR.IGraphProcessingEnvironment 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(); for (int i = 0; i < sequence.OutParameters.Length; ++i) { string typeName = TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model); source.AppendFront(typeName + " vari_" + sequence.OutParameters[i]); source.Append(" = " + TypesHelper.DefaultValueString(typeName, model) + ";\n"); } source.AppendFront("bool result = ApplyXGRS_" + sequence.Name + "((GRGEN_LGSP.LGSPGraphProcessingEnvironment)procEnv"); for (int i = 0; i < sequence.Parameters.Length; ++i) { source.Append(", var_" + sequence.Parameters[i]); } for (int i = 0; i < sequence.OutParameters.Length; ++i) { source.Append(", ref var_" + sequence.OutParameters[i]); } source.Append(");\n"); if (sequence.OutParameters.Length > 0) { source.AppendFront("if(result) {\n"); source.Indent(); for (int i = 0; i < sequence.OutParameters.Length; ++i) { source.AppendFront("var_" + sequence.OutParameters[i]); source.Append(" = vari_" + sequence.OutParameters[i] + ";\n"); } source.Unindent(); source.AppendFront("}\n"); } source.AppendFront("return result;\n"); 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 void EmitMatching(SourceBuilder source, SequenceGenerator seqGen, String matchListName) { String parameters = seqHelper.BuildParameters(seqRule, ArgumentExpressions, source); source.AppendFront(matchesType + " " + matchesName + " = " + ruleName + ".Match(procEnv, procEnv.MaxMatches" + parameters + ");\n"); source.AppendFront("procEnv.PerformanceInfo.MatchesFound += " + matchesName + ".Count;\n"); for (int i = 0; i < seqRule.Filters.Count; ++i) { seqExprGen.EmitFilterCall(source, (SequenceFilterCallCompiled)seqRule.Filters[i], patternName, matchesName, seqRule.PackagePrefixedName, false); } 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) { if (Type != InitializeFinalizeSubpatternMatchingType.Iteration) { sourceCode.AppendFront("openTasks.Pop();\n"); } if (Type != InitializeFinalizeSubpatternMatchingType.EndOfIteration) { sourceCode.AppendFront("List<Stack<GRGEN_LIBGR.IMatch>> matchesList = foundPartialMatches;\n"); sourceCode.AppendFront("if(matchesList.Count!=0) throw new ApplicationException(); //debug assert\n"); if (Type == InitializeFinalizeSubpatternMatchingType.Iteration) { sourceCode.AppendFront("// if the maximum number of matches of the iterated is reached, we complete iterated matching by building the null match object\n"); sourceCode.AppendFront("if(maxMatchesIter>0 && numMatchesIter>=maxMatchesIter) goto maxMatchesIterReached;\n"); } } }
/// <summary> /// Emits the matcher source code for the search program /// head, search program operations list in depth first walk over search program operations list, tail /// </summary> public override void Emit(SourceBuilder sourceCode) { #if RANDOM_LOOKUP_LIST_START sourceCode.AppendFront("private Random random = new Random(13795661);\n"); #endif if (Parallel) { sourceCode.AppendFront("public override void " + Name + "_parallelized" + "(List<Stack<GRGEN_LIBGR.IMatch>> foundPartialMatches, " + "int maxMatches, int isoSpace, int threadId)\n"); } else { sourceCode.AppendFront("public override void " + Name + "(List<Stack<GRGEN_LIBGR.IMatch>> foundPartialMatches, " + "int maxMatches, int isoSpace)\n"); } sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFront("GRGEN_LGSP.LGSPGraph graph = actionEnv.graph;\n"); if (Parallel) { sourceCode.AppendFront("List<ushort> flagsPerElement = graph.flagsPerThreadPerElement[threadId];\n"); sourceCode.AppendFront("List<ushort> flagsPerElement0 = graph.flagsPerThreadPerElement[0];\n"); sourceCode.AppendFront("List<ushort> flagsPerElementGlobal = graph.flagsPerThreadPerElement[threadId];\n"); } foreach (string graphsOnPath in NamesOfPatternGraphsOnPathToEnclosedPatternpath) { sourceCode.AppendFrontFormat("{0}.{1} {2} = null;\n", RulePatternClassName, NamesOfEntities.MatchClassName(graphsOnPath), NamesOfEntities.PatternpathMatch(graphsOnPath)); } GenerateIndependentsMatchObjects(sourceCode); OperationsList.Emit(sourceCode); sourceCode.AppendFront("return;\n"); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFront("FillPartialMatchForDuplicateChecking with "); foreach (string neededElement in NeededElements) { builder.AppendFormat("{0} ", neededElement); } builder.Append("\n"); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFrontFormat("if({0}.Count>0) {{\n", NestedMatchObjectName); sourceCode.Indent(); NestedOperationsList.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
public void EmitMatching(SourceBuilder source, SequenceGenerator seqGen) { String parameters = seqHelper.BuildParameters(seqRule, ArgumentExpressions, source); source.AppendFront(matchesType + " " + matchesName + " = " + ruleName + ".Match(procEnv, " + (seqRule.SequenceType == SequenceType.RuleCall ? "1" : "procEnv.MaxMatches") + parameters + ");\n"); source.AppendFront("procEnv.PerformanceInfo.MatchesFound += " + matchesName + ".Count;\n"); for (int i = 0; i < seqRule.Filters.Count; ++i) { seqExprGen.EmitFilterCall(source, (SequenceFilterCallCompiled)seqRule.Filters[i], patternName, matchesName, seqRule.PackagePrefixedName, false); } source.AppendFront("if(" + matchesName + ".Count != 0) {\n"); source.Indent(); source.AppendFront(COMP_HELPER.SetResultVar(seqSome, "true")); source.Unindent(); source.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 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 override void Emit(SourceBuilder sourceCode) { if (sourceCode.CommentSourceCode) { sourceCode.AppendFront("// NegativePattern \n"); } // currently needed because of multiple negMapped backup variables with same name // todo: assign names to negatives, mangle that name in, then remove block again // todo: remove (neg)mapped backup variables altogether, then remove block again sourceCode.AppendFront("{\n"); sourceCode.Indent(); NestedOperationsList.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); //if(sourceCode.CommentSourceCode) reinsert when block is removed // sourceCode.AppendFront("// NegativePattern end\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.AppendFront("// Condition \n"); } // open decision sourceCode.AppendFront("if("); // emit condition expression sourceCode.AppendFormat("!({0})", ConditionExpression); // close decision 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) { // first dump check builder.AppendFront("CheckCandidate Failed \n"); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump check builder.AppendFront("CheckPartialMatch ForSubpatternsFound\n"); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
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 override void Dump(SourceBuilder builder) { // first dump check builder.AppendFront("CheckCandidate ForConnectedness "); builder.AppendFormat("{0}=={1}.{2}\n", PatternNodeName, PatternEdgeName, ConnectednessType.ToString()); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump check builder.AppendFront("CheckCandidate MapByUnique "); builder.AppendFormat("on {0} node:{1}\n", PatternElementName, IsNode); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public override void Emit(SourceBuilder sourceCode) { if (OnlyIfMatchWasFound) { sourceCode.AppendFront("if(matchesList.Count>0) {\n"); sourceCode.Indent(); } sourceCode.AppendFront("if(matchesList==foundPartialMatches) {\n"); sourceCode.AppendFront(" matchesList = new List<Stack<GRGEN_LIBGR.IMatch>>();\n"); sourceCode.AppendFront("} else {\n"); sourceCode.AppendFront(" foreach(Stack<GRGEN_LIBGR.IMatch> match in matchesList) {\n"); sourceCode.AppendFront(" foundPartialMatches.Add(match);\n"); sourceCode.AppendFront(" }\n"); sourceCode.AppendFront(" matchesList.Clear();\n"); sourceCode.AppendFront("}\n"); if (OnlyIfMatchWasFound) { sourceCode.Unindent(); sourceCode.AppendFront("}\n"); } }
public override void Dump(SourceBuilder builder) { if (Type == PushAndPopSubpatternTaskTypes.Subpattern) { builder.AppendFront("PushSubpatternTask Subpattern "); } else if (Type == PushAndPopSubpatternTaskTypes.Alternative) { builder.AppendFront("PushSubpatternTask Alternative "); } else // Type==PushAndPopSubpatternTaskTypes.Iterated { builder.AppendFront("PushSubpatternTask Iterated "); } if (Type == PushAndPopSubpatternTaskTypes.Subpattern) { builder.AppendFormat("{0} of {1} ", SubpatternElementName, SubpatternName); } else { builder.AppendFormat("{0}/{1} ", PathPrefix, AlternativeOrIteratedName); } if (Parallel) { builder.Append("Parallel "); } builder.Append("with "); for (int i = 0; i < ConnectionName.Length; ++i) { builder.AppendFormat("{0} <- {1} ", ConnectionName[i], ArgumentExpressions[i]); } builder.Append("\n"); }
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); } }
/// <summary> /// pre-run for emitting the needed entities before emitting the real code /// - emits sequence variable declarations (only once for every variable, declaration only possible at assignment targets) /// </summary> private void EmitNeededVarEntities(SequenceComputation seqComp, SourceBuilder source) { source.AppendFront(COMP_HELPER.DeclareResultVar(seqComp)); switch (seqComp.SequenceComputationType) { case SequenceComputationType.Assignment: { SequenceComputationAssignment assign = (SequenceComputationAssignment)seqComp; EmitNeededVarEntities(assign.Target, source); if (assign.SourceValueProvider is SequenceComputationAssignment) { EmitNeededVarEntities(assign.SourceValueProvider, source); } break; } case SequenceComputationType.ProcedureCall: { SequenceComputationProcedureCall seqProc = (SequenceComputationProcedureCall)seqComp; // no handling for the input arguments seqProc.ArgumentExpressions needed // because there can only be variable uses for (int i = 0; i < seqProc.ReturnVars.Length; ++i) { EmitVarIfNew(seqProc.ReturnVars[i], source); } break; } case SequenceComputationType.BuiltinProcedureCall: { SequenceComputationBuiltinProcedureCall seqProc = (SequenceComputationBuiltinProcedureCall)seqComp; // no handling for the input arguments seqProc.ArgumentExpressions needed // because there can only be variable uses for (int i = 0; i < seqProc.ReturnVars.Count; ++i) { EmitVarIfNew(seqProc.ReturnVars[i], source); } break; } default: foreach (SequenceComputation childSeqComp in seqComp.Children) { EmitNeededVarEntities(childSeqComp, source); } break; } }
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 Dump(SourceBuilder builder) { // first dump check builder.AppendFront("CheckCandidate ForIsomorphyPatternPath "); builder.AppendFormat("on {0} node:{1} last match at previous nesting level in:{2}", PatternElementName, IsNode, LastMatchAtPreviousNestingLevel); builder.Append("\n"); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { builder.AppendFront("AdjustListHeads "); if (Type == AdjustListHeadsTypes.GraphElements) { builder.Append("GraphElements "); builder.AppendFormat("on {0} node:{1} {2}\n", PatternElementName, IsNode, Parallel ? "Parallel " : ""); } else // Type==AdjustListHeadsTypes.IncidentEdges { builder.Append("IncidentEdges "); builder.AppendFormat("on {0} from:{1} incident type:{2} {3}\n", PatternElementName, StartingPointNodeName, IncidentType.ToString(), Parallel ? "Parallel " : ""); } }
public override void Dump(SourceBuilder builder) { builder.AppendFront("RandomizeListHeads "); if (Type == RandomizeListHeadsTypes.GraphElements) { builder.Append("GraphElements "); builder.AppendFormat("on {0} node:{1}\n", PatternElementName, IsNode); } else // Type==RandomizeListHeadsTypes.IncidentEdges { builder.Append("IncidentEdges "); builder.AppendFormat("on {0} from:{1} incoming:{2}\n", PatternElementName, StartingPointNodeName, IsIncoming); } }
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"); }
public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFront("CheckPartialMatch ForDuplicate with "); foreach (string neededElement in NeededElements) { builder.AppendFormat("{0} ", neededElement); } builder.Append("\n"); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
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"); }
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"); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFront("((GRGEN_LGSP.LGSPSubactionAndOutputAdditionEnvironment)actionEnv).DebugHalting("); Message.Emit(sourceCode); foreach(Expression value in Values) { sourceCode.Append(", "); value.Emit(sourceCode); } sourceCode.Append(");\n"); }
public override void Emit(SourceBuilder sourceCode) { String ascendingVar = "ascending_" + fetchId().ToString(); String entryVar = "entry_" + fetchId().ToString(); String limitVar = "limit_" + fetchId().ToString(); sourceCode.AppendFront("int " + entryVar + " = (int)("); Left.Emit(sourceCode); sourceCode.AppendFront(");\n"); sourceCode.AppendFront("int " + limitVar + " = (int)("); Right.Emit(sourceCode); sourceCode.AppendFront(");\n"); sourceCode.AppendFront("bool " + ascendingVar + " = " + entryVar + " <= " + limitVar + ";\n"); sourceCode.AppendFront("while(" + ascendingVar + " ? " + entryVar + " <= " + limitVar + " : " + entryVar + " >= " + limitVar + ")\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + entryVar + ";\n"); foreach(Yielding statement in Statements) statement.Emit(sourceCode); sourceCode.AppendFront("if(" + ascendingVar + ") ++" + entryVar + "; else --" + entryVar + ";\n"); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
/// <summary> /// Generates memory pooling code for matching tasks of class given by it's name /// </summary> private void GenerateTasksMemoryPool(SourceBuilder sb, String className, bool isAlternative, bool isIterationBreaking, int branchingFactor) { // getNewTask method handing out new task from pool or creating task if pool is empty if(isAlternative) sb.AppendFront("public static " + className + " getNewTask(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv_, " + "Stack<GRGEN_LGSP.LGSPSubpatternAction> openTasks_, GRGEN_LGSP.PatternGraph[] patternGraphs_) {\n"); else sb.AppendFront("public static " + className + " getNewTask(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv_, " + "Stack<GRGEN_LGSP.LGSPSubpatternAction> openTasks_) {\n"); sb.Indent(); sb.AppendFront(className + " newTask;\n"); sb.AppendFront("if(numFreeTasks>0) {\n"); sb.Indent(); sb.AppendFront("newTask = freeListHead;\n"); sb.AppendFront("newTask.actionEnv = actionEnv_; newTask.openTasks = openTasks_;\n"); if(isAlternative) sb.AppendFront("newTask.patternGraphs = patternGraphs_;\n"); else if(isIterationBreaking) sb.AppendFront("newTask.breakIteration = false;\n"); sb.AppendFront("freeListHead = newTask.next;\n"); sb.AppendFront("newTask.next = null;\n"); sb.AppendFront("--numFreeTasks;\n"); sb.Unindent(); sb.AppendFront("} else {\n"); sb.Indent(); if(isAlternative) sb.AppendFront("newTask = new " + className + "(actionEnv_, openTasks_, patternGraphs_);\n"); else sb.AppendFront("newTask = new " + className + "(actionEnv_, openTasks_);\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return newTask;\n"); sb.Unindent(); sb.AppendFront("}\n\n"); // releaseTask method recycling task into pool if pool is not full sb.AppendFront("public static void releaseTask(" + className + " oldTask) {\n"); sb.Indent(); sb.AppendFront("if(numFreeTasks<MAX_NUM_FREE_TASKS) {\n"); sb.Indent(); sb.AppendFront("oldTask.next = freeListHead;\n"); sb.AppendFront("oldTask.actionEnv = null; oldTask.openTasks = null;\n"); sb.AppendFront("freeListHead = oldTask;\n"); sb.AppendFront("++numFreeTasks;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.Unindent(); sb.AppendFront("}\n\n"); // tasks pool administration data sb.AppendFront("private static " + className + " freeListHead = null;\n"); sb.AppendFront("private static int numFreeTasks = 0;\n"); sb.AppendFront("private const int MAX_NUM_FREE_TASKS = 100;\n\n"); // todo: compute antiproportional to pattern size sb.AppendFront("private " + className + " next = null;\n\n"); // for parallelized subpatterns/alternatives/iterateds we need a freelist per thread if(branchingFactor > 1) { // getNewTask method handing out new task from pool or creating task if pool is empty if(isAlternative) sb.AppendFront("public static " + className + " getNewTask(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv_, " + "Stack<GRGEN_LGSP.LGSPSubpatternAction> openTasks_, GRGEN_LGSP.PatternGraph[] patternGraphs_, int threadId) {\n"); else sb.AppendFront("public static " + className + " getNewTask(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv_, " + "Stack<GRGEN_LGSP.LGSPSubpatternAction> openTasks_, int threadId) {\n"); sb.Indent(); sb.AppendFront(className + " newTask;\n"); sb.AppendFront("if(numFreeTasks_perWorker[threadId]>0) {\n"); sb.Indent(); sb.AppendFront("newTask = freeListHead_perWorker[threadId];\n"); sb.AppendFront("newTask.actionEnv = actionEnv_; newTask.openTasks = openTasks_;\n"); if(isAlternative) sb.AppendFront("newTask.patternGraphs = patternGraphs_;\n"); else if(isIterationBreaking) sb.AppendFront("newTask.breakIteration = false;\n"); sb.AppendFront("freeListHead_perWorker[threadId] = newTask.next;\n"); sb.AppendFront("newTask.next = null;\n"); sb.AppendFront("--numFreeTasks_perWorker[threadId];\n"); sb.Unindent(); sb.AppendFront("} else {\n"); sb.Indent(); if(isAlternative) sb.AppendFront("newTask = new " + className + "(actionEnv_, openTasks_, patternGraphs_);\n"); else sb.AppendFront("newTask = new " + className + "(actionEnv_, openTasks_);\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return newTask;\n"); sb.Unindent(); sb.AppendFront("}\n\n"); // releaseTask method recycling task into pool if pool is not full sb.AppendFront("public static void releaseTask(" + className + " oldTask, int threadId) {\n"); sb.Indent(); sb.AppendFront("if(numFreeTasks_perWorker[threadId]<MAX_NUM_FREE_TASKS/2) {\n"); sb.Indent(); sb.AppendFront("oldTask.next = freeListHead_perWorker[threadId];\n"); sb.AppendFront("oldTask.actionEnv = null; oldTask.openTasks = null;\n"); sb.AppendFront("freeListHead_perWorker[threadId] = oldTask;\n"); sb.AppendFront("++numFreeTasks_perWorker[threadId];\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.Unindent(); sb.AppendFront("}\n\n"); // tasks pool administration data sb.AppendFront("private static " + className + "[] freeListHead_perWorker = new " + className + "[Math.Min(" + branchingFactor + ", Environment.ProcessorCount)];\n"); sb.AppendFront("private static int[] numFreeTasks_perWorker = new int[Math.Min(" + branchingFactor + ", Environment.ProcessorCount)];\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 EmitSequenceCall(SequenceSequenceCall seqSeq, SourceBuilder source) { SequenceInvocationParameterBindings paramBindings = seqSeq.ParamBindings; String parameterDeclarations = null; String parameters = null; if(paramBindings.Subgraph != null) parameters = BuildParametersInDeclarations(paramBindings, out parameterDeclarations); else parameters = BuildParameters(paramBindings); String outParameterDeclarations; String outArguments; String outAssignments; BuildOutParameters(paramBindings, out outParameterDeclarations, out outArguments, out outAssignments); 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"); } if(outParameterDeclarations.Length != 0) source.AppendFront(outParameterDeclarations + "\n"); source.AppendFront("if(" + TypesHelper.GetPackagePrefixDot(paramBindings.Package) + "Sequence_" + paramBindings.Name + ".ApplyXGRS_" + paramBindings.Name + "(procEnv" + parameters + outArguments + ")) {\n"); source.Indent(); if(outAssignments.Length != 0) source.AppendFront(outAssignments + "\n"); source.AppendFront(SetResultVar(seqSeq, "true")); source.Unindent(); source.AppendFront("} else {\n"); source.Indent(); source.AppendFront(SetResultVar(seqSeq, "false")); source.Unindent(); source.AppendFront("}\n"); if(paramBindings.Subgraph != null) { source.AppendFront("procEnv.ReturnFromSubgraph();\n"); source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\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 override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFront("switch("); SwitchExpression.Emit(sourceCode); sourceCode.Append(") {\n"); foreach(CaseStatement statement in CaseStatements) statement.Emit(sourceCode); sourceCode.AppendFront("}\n"); }
public override void Emit(SourceBuilder sourceCode) { String recordVar = "emit_value_" + fetchId().ToString(); sourceCode.AppendFront("object " + recordVar + " = "); ToRecordExpression.Emit(sourceCode); sourceCode.Append(";\n"); sourceCode.AppendFront("if(" + recordVar + " != null)\n"); sourceCode.AppendFront("((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv).Recorder.Write(" + "GRGEN_LIBGR.EmitHelper.ToStringNonNull(" + recordVar + ", graph));\n"); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFront("if("); Condition.Emit(sourceCode); sourceCode.Append(") {\n"); foreach(Yielding statement in TrueCaseStatements) statement.Emit(sourceCode); if(FalseCaseStatements != null) { sourceCode.AppendFront("} else {\n"); foreach(Yielding statement in FalseCaseStatements) statement.Emit(sourceCode); } sourceCode.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); 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"); }
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); } }
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) { if(CaseConstExpression != null) { sourceCode.AppendFront("case "); CaseConstExpression.Emit(sourceCode); sourceCode.Append(": "); } else sourceCode.AppendFront("default: "); sourceCode.Append("{\n"); foreach(Yielding statement in Statements) statement.Emit(sourceCode); sourceCode.AppendFront("break;\n"); sourceCode.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"); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFront("do {\n"); foreach(Yielding statement in LoopedStatements) statement.Emit(sourceCode); sourceCode.AppendFront("} while("); Condition.Emit(sourceCode); sourceCode.Append(");\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"); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFront(Type + " " + NamesOfEntities.Variable(Name)); if(Initialization != null) { sourceCode.Append(" = "); Initialization.Emit(sourceCode); } sourceCode.Append(";\n"); }
/// <summary> /// Generates matcher class tail source code /// </summary> public void GenerateMatcherClassTail(SourceBuilder sb, bool containedInPackage) { sb.Unindent(); sb.AppendFront("}\n"); if(containedInPackage) { sb.Unindent(); sb.AppendFront("}\n"); } sb.AppendFront("\n"); }
/// <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"); }
public override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFront("continue;\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"); }
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"); }
/// <summary> /// Generates file header for actions file into given source builer /// </summary> public void GenerateFileHeaderForActionsFile(SourceBuilder sb, String namespaceOfModel, String namespaceOfRulePatterns) { sb.AppendFront("using System;\n" + "using System.Collections.Generic;\n" + "using System.Collections;\n" + "using System.Text;\n" + "using System.Threading;\n" + "using GRGEN_LIBGR = de.unika.ipd.grGen.libGr;\n" + "using GRGEN_EXPR = de.unika.ipd.grGen.expression;\n" + "using GRGEN_LGSP = de.unika.ipd.grGen.lgsp;\n" + "using GRGEN_MODEL = " + namespaceOfModel + ";\n" + "using GRGEN_ACTIONS = " + namespaceOfRulePatterns + ";\n" + "using " + namespaceOfRulePatterns + ";\n\n"); sb.AppendFront("namespace de.unika.ipd.grGen.lgspActions\n"); sb.AppendFront("{\n"); sb.Indent(); // namespace level }
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"); }
/// <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 highlightValuesArray = "highlight_values_" + fetchId().ToString(); sourceCode.AppendFront("List<object> " + highlightValuesArray + " = new List<object>();"); String highlightSourceNamesArray = "highlight_source_names_" + fetchId().ToString(); sourceCode.AppendFront("List<string> " + highlightSourceNamesArray + " = new List<string>();"); foreach(Expression value in Values) { sourceCode.AppendFront(highlightValuesArray + ".Add("); value.Emit(sourceCode); sourceCode.Append(");\n"); } foreach(Expression sourceName in SourceNames) { sourceCode.AppendFront(highlightSourceNamesArray + ".Add((string)"); sourceName.Emit(sourceCode); sourceCode.Append(");\n"); } sourceCode.AppendFront("((GRGEN_LGSP.LGSPSubactionAndOutputAdditionEnvironment)actionEnv).DebugHighlighting("); Message.Emit(sourceCode); sourceCode.Append(", " + highlightValuesArray + ", " + highlightSourceNamesArray); sourceCode.Append(");\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"); }