private int EmitMaybeNullDispatching(SourceBuilder sourceCode, int conditionLevel, int emittedCounter) { if (conditionLevel < DispatchConditions.Length) { sourceCode.AppendFrontFormat("if({0}!=null) {{\n", DispatchConditions[conditionLevel]); sourceCode.Indent(); emittedCounter = EmitMaybeNullDispatching(sourceCode, conditionLevel + 1, emittedCounter); sourceCode.Unindent(); sourceCode.AppendFront("} else {\n"); sourceCode.Indent(); emittedCounter = EmitMaybeNullDispatching(sourceCode, conditionLevel + 1, emittedCounter); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); } else { if (emittedCounter > 0) // first entry are we ourselves, don't call, just nop { sourceCode.AppendFrontFormat("return {0}(actionEnv, maxMatches", SuffixedMatcherNames[emittedCounter]); foreach (string argument in Arguments[emittedCounter]) { sourceCode.AppendFormat(", {0}", argument); } sourceCode.Append(");\n"); } ++emittedCounter; } return(emittedCounter); }
public void Emit(SourceBuilder source, SequenceGenerator seqGen, bool fireDebugEvents) { source.AppendFront(COMP_HELPER.SetResultVar(seqFor, "true")); 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.AppendFront(matchesName + " = (" + matchesType + ")" + matchesName + ".Clone();\n"); if (fireDebugEvents) { source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n"); } String returnParameterDeclarations; String returnArguments; String returnAssignments; String returnParameterDeclarationsAllCall; String intermediateReturnAssignmentsAllCall; String returnAssignmentsAllCall; seqHelper.BuildReturnParameters(seqRule, ReturnVars, out returnParameterDeclarations, out returnArguments, out returnAssignments, out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall); // 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(seqHelper.SetVar(seqFor.Var, matchName)); seqGen.EmitSequence(seqFor.Seq, source); source.AppendFront(COMP_HELPER.SetResultVar(seqFor, COMP_HELPER.GetResultVar(seqFor) + " & " + COMP_HELPER.GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); }
private void GenerateGenericExternalDefinedSequenceApplicationMethod(SourceBuilder source, DefinedSequenceInfo sequence) { source.AppendFront("public override bool Apply(GRGEN_LIBGR.IGraphProcessingEnvironment procEnv, object[] arguments, out object[] returnValues)"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("GRGEN_LGSP.LGSPGraph graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n"); for (int i = 0; i < sequence.Parameters.Length; ++i) { string typeName = TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i]), model); source.AppendFront(typeName + " var_" + sequence.Parameters[i]); source.Append(" = (" + typeName + ")arguments[" + i + "];\n"); } for (int i = 0; i < sequence.OutParameters.Length; ++i) { string typeName = TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model); source.AppendFront(typeName + " var_" + 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"); source.AppendFront("returnValues = ReturnValues;\n"); if (sequence.OutParameters.Length > 0) { source.AppendFront("if(result) {\n"); source.Indent(); for (int i = 0; i < sequence.OutParameters.Length; ++i) { source.AppendFront("returnValues[" + i + "] = var_" + sequence.OutParameters[i] + ";\n"); } source.Unindent(); source.AppendFront("}\n"); } source.AppendFront("return result;\n"); source.Unindent(); source.AppendFront("}\n"); }
public void EmitRewritingRuleAllCallRandomSequenceRandom(SourceBuilder source, String firstRewrite, bool fireDebugEvents) { // for the match selected: rewrite it if (returnParameterDeclarations.Length != 0) { source.AppendFront(returnParameterDeclarationsAllCall + "\n"); } String enumeratorName = "enum_" + ruleCallRewritingGenerator.seqRule.Id; source.AppendFront("IEnumerator<" + matchType + "> " + enumeratorName + " = " + matchesName + ".GetEnumeratorExact();\n"); source.AppendFront("while(" + enumeratorName + ".MoveNext())\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(" + curTotalMatch + "==" + totalMatchToApply + ") {\n"); source.Indent(); source.AppendFront(matchType + " " + matchName + " = " + enumeratorName + ".Current;\n"); if (fireDebugEvents) { source.AppendFront("procEnv.Matched(" + matchesName + ", null, " + specialStr + ");\n"); } if (fireDebugEvents) { source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n"); } source.AppendFront("if(!" + firstRewrite + ") procEnv.RewritingNextMatch();\n"); if (returnParameterDeclarations.Length != 0) { source.AppendFront(returnParameterDeclarations + "\n"); } source.AppendFront(ruleCallRewritingGenerator.ruleName + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if (returnAssignments.Length != 0) { source.AppendFront(intermediateReturnAssignmentsAllCall + "\n"); } source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed++;\n"); source.AppendFront(firstRewrite + " = false;\n"); if (fireDebugEvents) { source.AppendFront("procEnv.Finished(" + matchesName + ", " + specialStr + ");\n"); } source.Unindent(); source.AppendFront("}\n"); if (returnAssignments.Length != 0) { source.AppendFront(returnAssignmentsAllCall + "\n"); } source.AppendFront("++" + curTotalMatch + ";\n"); source.Unindent(); source.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) { sourceCode.AppendFrontFormat("if({0} != null)\n", NamesOfEntities.FoundMatchesForFilteringVariable()); sourceCode.AppendFront("{\n"); sourceCode.Indent(); // emit check whether hash is contained in found matches hash map sourceCode.AppendFrontFormat("if(!{0}.ContainsKey({1}))\n", NamesOfEntities.FoundMatchesForFilteringVariable(), NamesOfEntities.DuplicateMatchHashVariable()); sourceCode.AppendFront("{\n"); sourceCode.Indent(); // if not, just insert it sourceCode.AppendFrontFormat("{0}[{1}] = match;\n", NamesOfEntities.FoundMatchesForFilteringVariable(), NamesOfEntities.DuplicateMatchHashVariable()); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); sourceCode.AppendFront("else\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); // otherwise loop till end of collision list of the hash set, insert there sourceCode.AppendFrontFormat("{0} {1} = {2}[{3}];\n", RulePatternClassName + "." + NamesOfEntities.MatchClassName(PatternName), NamesOfEntities.DuplicateMatchCandidateVariable(), NamesOfEntities.FoundMatchesForFilteringVariable(), NamesOfEntities.DuplicateMatchHashVariable()); sourceCode.AppendFrontFormat("while({0}.nextWithSameHash != null) {0} = {0}.nextWithSameHash;\n", NamesOfEntities.DuplicateMatchCandidateVariable()); sourceCode.AppendFrontFormat("{0}.nextWithSameHash = match;\n", NamesOfEntities.DuplicateMatchCandidateVariable()); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); if (ParallelizedAction) { sourceCode.AppendFrontFormat("match.{0} = {0};\n", NamesOfEntities.DuplicateMatchHashVariable()); } sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
public bool GenerateExternalDefinedSequence(SourceBuilder source, ExternalDefinedSequenceInfo sequence) { // exact sequence definition compiled class source.Append("\n"); source.AppendFront("public partial class Sequence_" + sequence.Name + " : GRGEN_LIBGR.SequenceDefinitionCompiled\n"); source.AppendFront("{\n"); source.Indent(); GenerateSequenceDefinedSingleton(source, sequence); source.Append("\n"); GenerateGenericMethodReturnValues(source, sequence); source.Append("\n"); GenerateExactExternalDefinedSequenceApplicationMethod(source, sequence); source.Append("\n"); GenerateGenericExternalDefinedSequenceApplicationMethod(source, sequence); // end of exact sequence definition compiled class source.Unindent(); source.AppendFront("}\n"); return(true); }
public void EmitRewritingRuleCountAllCallOrRuleAllCallNonRandom(SourceBuilder source) { // iterate through matches, use Modify on each, fire the next match event after the first if (returnParameterDeclarations.Length != 0) { source.AppendFront(returnParameterDeclarationsAllCall + "\n"); } String enumeratorName = "enum_" + ruleCallGen.seqRule.Id; source.AppendFront("IEnumerator<" + matchType + "> " + enumeratorName + " = " + matchesName + ".GetEnumeratorExact();\n"); source.AppendFront("while(" + enumeratorName + ".MoveNext())\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront(matchType + " " + matchName + " = " + enumeratorName + ".Current;\n"); source.AppendFront("if(" + matchName + "!=" + matchesName + ".FirstExact) procEnv.RewritingNextMatch();\n"); if (returnParameterDeclarations.Length != 0) { source.AppendFront(returnParameterDeclarations + "\n"); } source.AppendFront(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 ForIsomorphy "); builder.AppendFormat("on {0} negNamePrefix:{1} node:{2} ", PatternElementName, NegativeIndependentNamePrefix, IsNode); if (NamesOfPatternElementsToCheckAgainst != null) { builder.Append("against "); foreach (string name in NamesOfPatternElementsToCheckAgainst) { builder.AppendFormat("{0} ", name); } } builder.AppendFormat("parallel:{0} first for all:{1} ", Parallel, LockForAllThreads); builder.Append("\n"); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public override void Emit(SourceBuilder sourceCode) { // open decision whether to fail sourceCode.AppendFront("if("); // fail if graph element contained within candidate was already matched // (previously on the pattern derivation path to another pattern element) // as this would cause a inter-pattern-homomorphic match string variableContainingCandidate = NamesOfEntities.CandidateVariable(PatternElementName); string isMatchedBySomeBit = "(uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED_BY_SOME_ENCLOSING_PATTERN"; if (!Always) { sourceCode.Append("searchPatternpath && "); } sourceCode.AppendFormat("({0}.lgspFlags & {1})=={1} && GRGEN_LGSP.PatternpathIsomorphyChecker.IsMatched({0}, {2})", variableContainingCandidate, isMatchedBySomeBit, LastMatchAtPreviousNestingLevel); sourceCode.Append(")\n"); // emit check failed code sourceCode.AppendFront("{\n"); sourceCode.Indent(); CheckFailedOperations.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
public override void Emit(SourceBuilder sourceCode) { // emit initialization with element mapped from storage string variableContainingStorage = NamesOfEntities.Variable(StorageName); string variableContainingSourceElement = NamesOfEntities.CandidateVariable(SourcePatternElementName); string tempVariableForMapResult = NamesOfEntities.MapWithStorageTemporary(PatternElementName); sourceCode.AppendFrontFormat("if(!{0}.TryGetValue(({1}){2}, out {3})) ", variableContainingStorage, StorageKeyTypeName, variableContainingSourceElement, tempVariableForMapResult); // emit check failed code sourceCode.Append("{\n"); sourceCode.Indent(); CheckFailedOperations.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); // assign the value to the candidate variable, cast it to the variable type string typeOfVariableContainingCandidate = "GRGEN_LGSP." + (IsNode ? "LGSPNode" : "LGSPEdge"); string variableContainingCandidate = NamesOfEntities.CandidateVariable(PatternElementName); sourceCode.AppendFrontFormat("{0} = ({1}){2};\n", variableContainingCandidate, typeOfVariableContainingCandidate, tempVariableForMapResult); }
public override void Dump(SourceBuilder builder) { // first dump check builder.AppendFront("CheckCandidate ForType "); if (Type == CheckCandidateForTypeType.ByIsAllowedType) { builder.Append("ByIsAllowedType "); builder.AppendFormat("on {0} in {1} node:{2}\n", PatternElementName, RulePatternTypeName, IsNode); } else if (Type == CheckCandidateForTypeType.ByIsMyType) { builder.Append("ByIsMyType "); builder.AppendFormat("on {0} in {1} node:{2}\n", PatternElementName, TypeName, IsNode); } else // Type == CheckCandidateForTypeType.ByTypeID { builder.Append("ByTypeID "); builder.AppendFormat("on {0} ids:{1} node:{2}\n", PatternElementName, string.Join(",", TypeIDs), IsNode); } // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public void EmitAddRange(SourceBuilder source, String matchListName) { source.AppendFront("if(" + matchesName + ".Count != 0) {\n"); source.Indent(); source.AppendFrontFormat("{0}.AddRange({1});\n", matchListName, matchesName); source.Unindent(); source.AppendFront("}\n"); }
public void EmitCloning(SourceBuilder source, SequenceGenerator seqGen, String matchListName, String originalToCloneName) { source.AppendFront("if(" + matchesName + ".Count != 0) {\n"); source.Indent(); source.AppendFrontFormat("{0} = ({1}){0}.Clone({2});\n", matchesName, matchesType, originalToCloneName); source.Unindent(); source.AppendFront("}\n"); }
public void Emit(SourceBuilder source, SequenceGenerator seqGen, bool fireDebugEvents) { source.AppendFront(COMP_HELPER.SetResultVar(seqFor, "true")); seqMatcherGen.EmitMatchingAndCloning(source, "procEnv.MaxMatches"); SequenceRuleCallMatcherGenerator.EmitPreMatchEventFiring(source, matchesName); seqMatcherGen.EmitFiltering(source); source.AppendFront("if(" + matchesName + ".Count != 0) {\n"); source.Indent(); if (fireDebugEvents) { source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n"); } String returnParameterDeclarations; String returnArguments; String returnAssignments; String returnParameterDeclarationsAllCall; String intermediateReturnAssignmentsAllCall; String returnAssignmentsAllCall; seqHelper.BuildReturnParameters(seqRule, ReturnVars, out returnParameterDeclarations, out returnArguments, out returnAssignments, out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall); // 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(seqHelper.SetVar(seqFor.Var, matchName)); seqGen.EmitSequence(seqFor.Seq, source); source.AppendFront(COMP_HELPER.SetResultVar(seqFor, COMP_HELPER.GetResultVar(seqFor) + " & " + COMP_HELPER.GetResultVar(seqFor.Seq))); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); }
public void EmitCloning(SourceBuilder source) { source.AppendFront("if(" + matchesName + ".Count != 0) {\n"); source.Indent(); source.AppendFront(matchesName + " = (" + matchesType + ")" + matchesName + ".Clone();\n"); source.Unindent(); source.AppendFront("}\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 override void Emit(SourceBuilder sourceCode) { sourceCode.AppendFront("{ // " + Name + "\n"); sourceCode.Indent(); NestedOperationsList.Emit(sourceCode); sourceCode.Unindent(); sourceCode.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 void EmitRewriting(SourceBuilder source, SequenceGenerator seqGen, String matchListName, String enumeratorName, bool fireDebugEvents) { source.AppendFrontFormat("case \"{0}\":\n", plainRuleName); source.AppendFront("{\n"); source.Indent(); source.AppendFront(matchType + " " + matchName + " = (" + matchType + ")" + enumeratorName + ".Current;\n"); String returnParameterDeclarations; String returnArguments; String returnAssignments; String returnParameterDeclarationsAllCall; String intermediateReturnAssignmentsAllCall; String returnAssignmentsAllCall; seqHelper.BuildReturnParameters(seqRule, ReturnVars, out returnParameterDeclarations, out returnArguments, out returnAssignments, out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall); // start a transaction if (fireDebugEvents) { source.AppendFront("procEnv.Matched(" + matchesName + ", " + matchName + ", " + specialStr + ");\n"); } if (fireDebugEvents) { source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n"); } if (returnParameterDeclarations.Length != 0) { source.AppendFront(returnParameterDeclarations + "\n"); } source.AppendFront(ruleName + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if (returnAssignments.Length != 0) { source.AppendFront(returnAssignments + "\n"); } source.AppendFront("++procEnv.PerformanceInfo.RewritesPerformed;\n"); if (fireDebugEvents) { source.AppendFront("procEnv.Finished(" + matchesName + ", " + specialStr + ");\n"); } // rule applied, now execute the sequence seqGen.EmitSequence(seqSeq, source); source.AppendFront(COMP_HELPER.SetResultVar(seqMulti, COMP_HELPER.GetResultVar(seqSeq))); source.AppendFront("break;\n"); source.Unindent(); source.AppendFront("}\n"); }
public void GenerateExternalDefinedSequencePlaceholder(SourceBuilder source, ExternalDefinedSequenceInfo sequence, String externalActionsExtensionFilename) { source.Append("\n"); source.AppendFront("public partial class Sequence_" + sequence.Name + "\n"); source.AppendFront("{\n"); source.Indent(); GenerateInternalDefinedSequenceApplicationMethodStub(source, sequence, externalActionsExtensionFilename); source.Unindent(); source.AppendFront("}\n"); }
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 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 local content builder.AppendFrontFormat("BubbleUpYieldIterated on {0}\n", NestedMatchObjectName); // then nested content if (NestedOperationsList != null) { builder.Indent(); NestedOperationsList.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 local content builder.AppendFrontFormat("YieldingBlock {0}\n", Name); // then nested content if (NestedOperationsList != null) { builder.Indent(); NestedOperationsList.Dump(builder); builder.Unindent(); } }
/// <summary> /// Dumps search program /// </summary> public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFrontFormat("Search program {0} of alternative case\n", Parallel ? Name + "_parallelized" : Name); // then nested content if (OperationsList != null) { builder.Indent(); OperationsList.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump 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 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.Append("CheckCandidate ForIdentity "); builder.AppendFormat("by {0} == {1}\n", PatternElementName, OtherPatternElementName); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
void GenerateKeepSameFilter(SourceBuilder source, LGSPRulePattern rulePattern, String filterVariable, bool sameAsFirst) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = sameAsFirst ? "keepSameAsFirst_" + filterVariable : "keepSameAsLast_" + filterVariable; source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); if(sameAsFirst) { source.AppendFront("int pos = 0 + 1;\n"); source.AppendFrontFormat("while(pos < matchesArray.Count && matchesArray[pos].{0} == matchesArray[0].{0})\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.AppendFront("{\n"); source.AppendFront("\t++pos;\n"); source.AppendFront("}\n"); source.AppendFront("for(; pos < matchesArray.Count; ++pos)\n"); source.AppendFront("{\n"); source.AppendFront("\tmatchesArray[pos] = null;\n"); source.AppendFront("}\n"); } else { source.AppendFront("int pos = matchesArray.Count-1 - 1;\n"); source.AppendFrontFormat("while(pos >= 0 && matchesArray[pos].{0} == matchesArray[matchesArray.Count-1].{0})\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.AppendFront("{\n"); source.AppendFront("\t--pos;\n"); source.AppendFront("}\n"); source.AppendFront("for(; pos >= 0; --pos)\n"); source.AppendFront("{\n"); source.AppendFront("\tmatchesArray[pos] = null;\n"); source.AppendFront("}\n"); } source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); }
/// <summary> /// Generates matcher class head source code for the 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"); }
/// <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 }
/// <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) { 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"); }
public void GenerateFilters(SourceBuilder source, LGSPRulePattern rulePattern) { foreach(IFilter f in rulePattern.Filters) { if(f is IFilterAutoGenerated) { IFilterAutoGenerated filter = (IFilterAutoGenerated)f; if(filter.Package != null) { source.AppendFrontFormat("namespace {0}\n", filter.Package); source.AppendFront("{\n"); source.Indent(); } source.AppendFront("public partial class MatchFilters\n"); source.AppendFront("{\n"); source.Indent(); if(filter.Name == "auto") GenerateAutomorphyFilter(source, rulePattern); else { if(filter.Name == "orderAscendingBy") GenerateOrderByFilter(source, rulePattern, filter.Entity, true); if(filter.Name == "orderDescendingBy") GenerateOrderByFilter(source, rulePattern, filter.Entity, false); if(filter.Name == "groupBy") GenerateGroupByFilter(source, rulePattern, filter.Entity); if(filter.Name == "keepSameAsFirst") GenerateKeepSameFilter(source, rulePattern, filter.Entity, true); if(filter.Name == "keepSameAsLast") GenerateKeepSameFilter(source, rulePattern, filter.Entity, false); if(filter.Name == "keepOneForEach") GenerateKeepOneForEachFilter(source, rulePattern, filter.Entity); } source.Unindent(); source.AppendFront("}\n"); if(filter.Package != null) { source.Unindent(); source.AppendFront("}\n"); } } } }
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"); }
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"); }
private static void GenerateAutomorphyFilter(SourceBuilder source, LGSPRulePattern rulePattern) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchClassName = rulePatternClassName + "." + NamesOfEntities.MatchClassName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = "auto"; source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(matches.Count < 2)\n"); source.AppendFront("\treturn;\n"); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); source.AppendFrontFormat("if(matches.Count < 5 || {0}.Instance.patternGraph.nodes.Length + {0}.Instance.patternGraph.edges.Length < 1)\n", rulePatternClassName); source.AppendFront("{\n"); source.Indent(); source.AppendFront("for(int i = 0; i < matchesArray.Count; ++i)\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(matchesArray[i] == null)\n"); source.AppendFront("\tcontinue;\n"); source.AppendFront("for(int j = i + 1; j < matchesArray.Count; ++j)\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(matchesArray[j] == null)\n"); source.AppendFront("\tcontinue;\n"); source.AppendFront("if(GRGEN_LIBGR.SymmetryChecker.AreSymmetric(matchesArray[i], matchesArray[j], procEnv.graph))\n"); source.AppendFront("\tmatchesArray[j] = null;\n"); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("Dictionary<int, {0}> foundMatchesOfSameMainPatternHash = new Dictionary<int, {0}>();\n", matchClassName); source.AppendFront("for(int i = 0; i < matchesArray.Count; ++i)\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} match = ({0})matchesArray[i];\n", matchClassName); source.AppendFront("int duplicateMatchHash = 0;\n"); source.AppendFront("for(int j = 0; j < match.NumberOfNodes; ++j) duplicateMatchHash ^= match.getNodeAt(j).GetHashCode();\n"); source.AppendFront("for(int j = 0; j < match.NumberOfEdges; ++j) duplicateMatchHash ^= match.getEdgeAt(j).GetHashCode();\n"); source.AppendFront("bool contained = foundMatchesOfSameMainPatternHash.ContainsKey(duplicateMatchHash);\n"); source.AppendFront("if(contained)\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} duplicateMatchCandidate = foundMatchesOfSameMainPatternHash[duplicateMatchHash];\n", matchClassName); source.AppendFront("do\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(GRGEN_LIBGR.SymmetryChecker.AreSymmetric(match, duplicateMatchCandidate, procEnv.graph))\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("matchesArray[i] = null;\n"); source.AppendFrontFormat("goto label_auto_{0};\n", rulePatternClassName.Replace('.', '_')); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("while((duplicateMatchCandidate = duplicateMatchCandidate.nextWithSameHash) != null);\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("if(!contained)\n"); source.AppendFront("\tfoundMatchesOfSameMainPatternHash[duplicateMatchHash] = match;\n"); source.AppendFront("else\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} duplicateMatchCandidate = foundMatchesOfSameMainPatternHash[duplicateMatchHash];\n", matchClassName); source.AppendFront("while(duplicateMatchCandidate.nextWithSameHash != null) duplicateMatchCandidate = duplicateMatchCandidate.nextWithSameHash;\n"); source.AppendFront("duplicateMatchCandidate.nextWithSameHash = match;\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFormat("label_auto_{0}: ;\n", rulePatternClassName.Replace('.', '_')); source.Unindent(); source.AppendFront("}\n"); source.AppendFrontFormat("foreach({0} toClean in foundMatchesOfSameMainPatternHash.Values) toClean.CleanNextWithSameHash();\n", matchClassName); source.Unindent(); source.AppendFront("}\n"); source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); }
void 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"); }
private static void GenerateOrderByFilter(SourceBuilder source, LGSPRulePattern rulePattern, String filterVariable, bool ascending) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = ascending ? "orderAscendingBy_" + filterVariable : "orderDescendingBy_" + filterVariable; source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); source.AppendFrontFormat("matchesArray.Sort(new Comparer_{0}_{1}());\n", rulePattern.name, filterName); source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFrontFormat("class Comparer_{0}_{1} : Comparer<{2}>\n", rulePattern.name, filterName, matchInterfaceName); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("public override int Compare({0} left, {0} right)\n", matchInterfaceName); source.AppendFront("{\n"); source.Indent(); if(ascending) source.AppendFrontFormat("return left.{0}.CompareTo(right.{0});\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); else source.AppendFrontFormat("return -left.{0}.CompareTo(right.{0});\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); }
/// <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 bool GenerateDefinedSequence(SourceBuilder source, DefinedSequenceInfo sequence) { Dictionary<String, String> varDecls = new Dictionary<String, String>(); for(int i = 0; i < sequence.Parameters.Length; i++) { varDecls.Add(sequence.Parameters[i], TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i])); } for(int i = 0; i < sequence.OutParameters.Length; i++) { varDecls.Add(sequence.OutParameters[i], TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i])); } Sequence seq; try { List<string> warnings = new List<string>(); seq = SequenceParser.ParseSequence(sequence.XGRS, sequence.Package, ruleNames, sequenceNames, procedureNames, functionNames, functionOutputTypes, filterFunctionNames, varDecls, model, warnings); foreach(string warning in warnings) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" reported back:\n" + warning); } seq.Check(env); seq.SetNeedForProfilingRecursive(gen.EmitProfiling); } catch(ParseException ex) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" caused the following error:\n" + ex.Message); return false; } catch(SequenceParserException ex) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" caused the following error:\n"); HandleSequenceParserException(ex); return false; } // exact sequence definition compiled class source.Append("\n"); if(sequence.Package != null) { source.AppendFrontFormat("namespace {0}\n", sequence.Package); source.AppendFront("{\n"); source.Indent(); } source.AppendFront("public class Sequence_" + sequence.Name + " : GRGEN_LIBGR.SequenceDefinitionCompiled\n"); source.AppendFront("{\n"); source.Indent(); GenerateSequenceDefinedSingleton(source, sequence); source.Append("\n"); GenerateInternalDefinedSequenceApplicationMethod(source, sequence, seq); source.Append("\n"); GenerateExactExternalDefinedSequenceApplicationMethod(source, sequence); source.Append("\n"); GenerateGenericExternalDefinedSequenceApplicationMethod(source, sequence); // end of exact sequence definition compiled class source.Unindent(); source.AppendFront("}\n"); if(sequence.Package != null) { source.Unindent(); source.AppendFront("}\n"); } return true; }
/// <summary> // generate implementation of the exact action interface, // delegate calls of the inexact action interface IAction to the exact action interface /// </summary> void GenerateActionImplementation(SourceBuilder sb, LGSPRulePattern matchingPattern) { StringBuilder sbInParameters = new StringBuilder(); StringBuilder sbInArguments = new StringBuilder(); StringBuilder sbInArgumentsFromArray = new StringBuilder(); for(int i = 0; i < matchingPattern.Inputs.Length; ++i) { sbInParameters.Append(", "); sbInParameters.Append(TypesHelper.TypeName(matchingPattern.Inputs[i])); sbInParameters.Append(" "); sbInParameters.Append(matchingPattern.InputNames[i]); sbInArguments.Append(", "); sbInArguments.Append(matchingPattern.InputNames[i]); sbInArgumentsFromArray.Append(", ("); sbInArgumentsFromArray.Append(TypesHelper.TypeName(matchingPattern.Inputs[i])); sbInArgumentsFromArray.Append(") parameters["); sbInArgumentsFromArray.Append(i); sbInArgumentsFromArray.Append("]"); } String inParameters = sbInParameters.ToString(); String inArguments = sbInArguments.ToString(); String inArgumentsFromArray = sbInArgumentsFromArray.ToString(); StringBuilder sbOutParameters = new StringBuilder(); StringBuilder sbRefParameters = new StringBuilder(); StringBuilder sbOutLocals = new StringBuilder(); StringBuilder sbRefLocals = new StringBuilder(); StringBuilder sbOutArguments = new StringBuilder(); StringBuilder sbRefArguments = new StringBuilder(); StringBuilder sbOutIntermediateLocalsAll = new StringBuilder(); StringBuilder sbOutParametersAll = new StringBuilder(); StringBuilder sbOutArgumentsAll = new StringBuilder(); StringBuilder sbIntermediateLocalArgumentsAll = new StringBuilder(); StringBuilder sbOutClassArgumentsAll = new StringBuilder(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sbOutParameters.Append(", out "); sbOutParameters.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbOutParameters.Append(" output_"); sbOutParameters.Append(i); sbRefParameters.Append(", ref "); sbRefParameters.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbRefParameters.Append(" output_"); sbRefParameters.Append(i); sbOutLocals.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbOutLocals.Append(" output_"); sbOutLocals.Append(i); sbOutLocals.Append("; "); sbRefLocals.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbRefLocals.Append(" output_"); sbRefLocals.Append(i); sbRefLocals.Append(" = "); sbRefLocals.Append(TypesHelper.DefaultValueString(matchingPattern.Outputs[i].PackagePrefixedName, model)); sbRefLocals.Append("; "); sbOutArguments.Append(", out output_"); sbOutArguments.Append(i); sbRefArguments.Append(", ref output_"); sbRefArguments.Append(i); sbOutIntermediateLocalsAll.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbOutIntermediateLocalsAll.Append(" output_local_"); sbOutIntermediateLocalsAll.Append(i); sbOutIntermediateLocalsAll.Append("; "); sbOutParametersAll.Append(", List<"); sbOutParametersAll.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sbOutParametersAll.Append("> output_"); sbOutParametersAll.Append(i); sbOutArgumentsAll.Append(", output_"); sbOutArgumentsAll.Append(i); sbIntermediateLocalArgumentsAll.Append(", out output_local_"); sbIntermediateLocalArgumentsAll.Append(i); sbOutClassArgumentsAll.Append(", output_list_"); sbOutClassArgumentsAll.Append(i); } String outParameters = sbOutParameters.ToString(); String refParameters = sbRefParameters.ToString(); String outLocals = sbOutLocals.ToString(); String refLocals = sbRefLocals.ToString(); String outArguments = sbOutArguments.ToString(); String refArguments = sbRefArguments.ToString(); String outIntermediateLocalsAll = sbOutIntermediateLocalsAll.ToString(); String outParametersAll = sbOutParametersAll.ToString(); String outArgumentsAll = sbOutArgumentsAll.ToString(); String intermediateLocalArgumentsAll = sbIntermediateLocalArgumentsAll.ToString(); String outClassArgumentsAll = sbOutClassArgumentsAll.ToString(); String matchingPatternClassName = matchingPattern.GetType().Name; String patternName = matchingPattern.name; String matchType = matchingPatternClassName + "." + NamesOfEntities.MatchInterfaceName(patternName); String matchesType = "GRGEN_LIBGR.IMatchesExact<" + matchType + ">"; // implementation of exact action interface sb.AppendFront("/// <summary> Type of the matcher method (with parameters processing environment containing host graph, maximum number of matches to search for (zero=unlimited), and rule parameters; returning found matches). </summary>\n"); sb.AppendFrontFormat("public delegate {0} MatchInvoker(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv, int maxMatches{1});\n", matchesType, inParameters); sb.AppendFront("/// <summary> A delegate pointing to the current matcher program for this rule. </summary>\n"); sb.AppendFront("public MatchInvoker DynamicMatch;\n"); sb.AppendFront("/// <summary> The RulePattern object from which this LGSPAction object has been created. </summary>\n"); sb.AppendFront("public GRGEN_LIBGR.IRulePattern RulePattern { get { return _rulePattern; } }\n"); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFront("List<"); sb.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sb.Append("> output_list_"); sb.Append(i.ToString()); sb.Append(" = new List<"); sb.Append(TypesHelper.TypeName(matchingPattern.Outputs[i])); sb.Append(">();\n"); } sb.AppendFrontFormat("public {0} Match(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int maxMatches{1})\n", matchesType, inParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, maxMatches{0});\n", inArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public void Modify(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, {0} match{1})\n", matchType, outParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, match{0});\n", outArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public void ModifyAll(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, {0} matches{1})\n", matchesType, outParametersAll); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("foreach({0} match in matches)\n", matchType); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0}\n", outIntermediateLocalsAll); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, match{0});\n", intermediateLocalArgumentsAll); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("output_{0}.Add(output_local_{0});\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public bool Apply(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0}{1})\n", inParameters, refParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{1});\n", matchesType, inArguments); sb.AppendFront("if(matches.Count <= 0) return false;\n"); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, matches.First{0});\n", outArguments); sb.AppendFront("return true;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public int ApplyAll(int maxMatches, GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0}{1})\n", inParameters, outParametersAll); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, maxMatches{1});\n", matchesType, inArguments); sb.AppendFront("if(matches.Count <= 0) return 0;\n"); sb.AppendFrontFormat("foreach({0} match in matches)\n", matchType); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0}\n", outIntermediateLocalsAll); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, match{0});\n", intermediateLocalArgumentsAll); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("output_{0}.Add(output_local_{0});\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return matches.Count;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public bool ApplyStar(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0})\n", inParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches;\n", matchesType); sb.AppendFrontFormat("{0}\n", outLocals); sb.AppendFront("while(true)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{0});\n", inArguments); sb.AppendFront("if(matches.Count <= 0) return true;\n"); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, matches.First{0});\n", outArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public bool ApplyPlus(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv{0})\n", inParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{1});\n", matchesType, inArguments); sb.AppendFront("if(matches.Count <= 0) return false;\n"); sb.AppendFrontFormat("{0}\n", outLocals); sb.AppendFront("do\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, matches.First{0});\n", outArguments); sb.AppendFrontFormat("matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{0});\n", inArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("while(matches.Count > 0) ;\n"); sb.AppendFront("return true;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFrontFormat("public bool ApplyMinMax(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int min, int max{0})\n", inParameters); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0} matches;\n", matchesType); sb.AppendFrontFormat("{0}\n", outLocals); sb.AppendFront("for(int i = 0; i < max; i++)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("matches = DynamicMatch((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, 1{0});\n", inArguments); sb.AppendFront("if(matches.Count <= 0) return i >= min;\n"); sb.AppendFrontFormat("_rulePattern.Modify((GRGEN_LGSP.LGSPActionExecutionEnvironment)actionEnv, matches.First{0});\n", outArguments); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return true;\n"); sb.Unindent(); sb.AppendFront("}\n"); // implementation of inexact action interface by delegation to exact action interface sb.AppendFront("// implementation of inexact action interface by delegation to exact action interface\n"); sb.AppendFront("public GRGEN_LIBGR.IMatches Match(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int maxMatches, object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return Match(actionEnv, maxMatches{0});\n", inArgumentsFromArray); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("public object[] Modify(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, GRGEN_LIBGR.IMatch match)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0}\n", outLocals); sb.AppendFrontFormat("Modify(actionEnv, ({0})match{1});\n", matchType, outArguments); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArray[{0}] = output_{0};\n", i); } sb.AppendFront("return ReturnArray;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("public List<object[]> ModifyAll(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, GRGEN_LIBGR.IMatches matches)\n"); sb.AppendFront("{\n"); sb.Indent(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFront("output_list_"); sb.Append(i.ToString()); sb.Append(".Clear();\n"); } sb.AppendFrontFormat("ModifyAll(actionEnv, ({0})matches{1});\n", matchesType, outClassArgumentsAll); sb.AppendFront("while(AvailableReturnArrays.Count < matches.Count) AvailableReturnArrays.Add(new object[" + matchingPattern.Outputs.Length + "]);\n"); sb.AppendFront("ReturnArrayListForAll.Clear();\n"); sb.AppendFront("for(int i=0; i<matches.Count; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("ReturnArrayListForAll.Add(AvailableReturnArrays[i]);\n"); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArrayListForAll[i][{0}] = output_list_{0}[i];\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return ReturnArrayListForAll;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("object[] GRGEN_LIBGR.IAction.Apply(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) { sb.AppendFrontFormat("{0}\n", refLocals); sb.AppendFrontFormat("if(Apply(actionEnv{0})) ", refArguments); sb.Append("{\n"); sb.Indent(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArray[{0}] = output_{0};\n", i); } sb.AppendFront("return ReturnArray;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("else return null;\n"); } else sb.AppendFront("throw new Exception();\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("object[] GRGEN_LIBGR.IAction.Apply(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("{0}\n", refLocals); sb.AppendFrontFormat("if(Apply(actionEnv{0}{1})) ", inArgumentsFromArray, refArguments); sb.Append("{\n"); sb.Indent(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArray[{0}] = output_{0};\n", i); } sb.AppendFront("return ReturnArray;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("else return null;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("public List<object[]> Reserve(int numReturns)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("while(AvailableReturnArrays.Count < numReturns) AvailableReturnArrays.Add(new object[" + matchingPattern.Outputs.Length + "]);\n"); sb.AppendFront("ReturnArrayListForAll.Clear();\n"); sb.AppendFront("for(int i=0; i<numReturns; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("ReturnArrayListForAll.Add(AvailableReturnArrays[i]);\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return ReturnArrayListForAll;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("List<object[]> GRGEN_LIBGR.IAction.ApplyAll(int maxMatches, GRGEN_LIBGR.IActionExecutionEnvironment actionEnv)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) { for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFront("output_list_"); sb.Append(i.ToString()); sb.Append(".Clear();\n"); } sb.AppendFrontFormat("int matchesCount = ApplyAll(maxMatches, actionEnv{0});\n", outClassArgumentsAll); sb.AppendFront("while(AvailableReturnArrays.Count < matchesCount) AvailableReturnArrays.Add(new object[" + matchingPattern.Outputs.Length + "]);\n"); sb.AppendFront("ReturnArrayListForAll.Clear();\n"); sb.AppendFront("for(int i=0; i<matchesCount; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("ReturnArrayListForAll.Add(AvailableReturnArrays[i]);\n"); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArrayListForAll[i][{0}] = output_list_{0}[i];\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return ReturnArrayListForAll;\n"); } else sb.AppendFront("throw new Exception();\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("List<object[]> GRGEN_LIBGR.IAction.ApplyAll(int maxMatches, GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFront("output_list_"); sb.Append(i.ToString()); sb.Append(".Clear();\n"); } sb.AppendFrontFormat("int matchesCount = ApplyAll(maxMatches, actionEnv{0}{1});\n", inArgumentsFromArray, outClassArgumentsAll); sb.AppendFront("while(AvailableReturnArrays.Count < matchesCount) AvailableReturnArrays.Add(new object[" + matchingPattern.Outputs.Length + "]);\n"); sb.AppendFront("ReturnArrayListForAll.Clear();\n"); sb.AppendFront("for(int i=0; i<matchesCount; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("ReturnArrayListForAll.Add(AvailableReturnArrays[i]);\n"); for(int i = 0; i < matchingPattern.Outputs.Length; ++i) { sb.AppendFrontFormat("ReturnArrayListForAll[i][{0}] = output_list_{0}[i];\n", i); } sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return ReturnArrayListForAll;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyStar(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) sb.AppendFront("return ApplyStar(actionEnv);\n"); else sb.AppendFront("throw new Exception(); return false;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyStar(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return ApplyStar(actionEnv{0});\n", inArgumentsFromArray); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyPlus(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) sb.AppendFront("return ApplyPlus(actionEnv);\n"); else sb.AppendFront("throw new Exception(); return false;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyPlus(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return ApplyPlus(actionEnv{0});\n", inArgumentsFromArray); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyMinMax(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int min, int max)\n"); sb.AppendFront("{\n"); sb.Indent(); if(matchingPattern.Inputs.Length == 0) sb.AppendFront("return ApplyMinMax(actionEnv, min, max);\n"); else sb.AppendFront("throw new Exception(); return false;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("bool GRGEN_LIBGR.IAction.ApplyMinMax(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, int min, int max, params object[] parameters)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFrontFormat("return ApplyMinMax(actionEnv, min, max{0});\n", inArgumentsFromArray); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("void GRGEN_LIBGR.IAction.Filter(GRGEN_LIBGR.IActionExecutionEnvironment actionEnv, GRGEN_LIBGR.IMatches matches, GRGEN_LIBGR.FilterCall filter)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("if(filter.IsAutoSupplied) {\n"); sb.Indent(); sb.AppendFront("switch(filter.Name) {\n"); sb.Indent(); sb.AppendFront("case \"keepFirst\": matches.FilterKeepFirst((int)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"keepLast\": matches.FilterKeepLast((int)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"keepFirstFraction\": matches.FilterKeepFirstFraction((double)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"keepLastFraction\": matches.FilterKeepLastFraction((double)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"removeFirst\": matches.FilterRemoveFirst((int)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"removeLast\": matches.FilterRemoveLast((int)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"removeFirstFraction\": matches.FilterRemoveFirstFraction((double)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("case \"removeLastFraction\": matches.FilterRemoveLastFraction((double)(filter.ArgumentExpressions[0]!=null ? filter.ArgumentExpressions[0].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[0])); break;\n"); sb.AppendFront("default: throw new Exception(\"Unknown auto supplied filter name!\");\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("return;\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("switch(filter.FullName) {\n"); sb.Indent(); foreach(IFilter filter in matchingPattern.Filters) { if(filter is IFilterAutoGenerated) { if(((IFilterAutoGenerated)filter).Entity != null) { sb.AppendFrontFormat("case \"{1}<{2}>\": GRGEN_ACTIONS.{4}MatchFilters.Filter_{0}_{1}_{2}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({3})matches); break;\n", patternName, filter.Name, ((IFilterAutoGenerated)filter).Entity, matchesType, TypesHelper.GetPackagePrefixDot(filter.Package)); if(filter.Package != null) sb.AppendFrontFormat("case \"{5}{1}<{2}>\": GRGEN_ACTIONS.{4}MatchFilters.Filter_{0}_{1}_{2}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({3})matches); break;\n", patternName, filter.Name, ((IFilterAutoGenerated)filter).Entity, matchesType, filter.Package + ".", filter.Package + "::"); } else // auto { sb.AppendFrontFormat("case \"{1}\": GRGEN_ACTIONS.{3}MatchFilters.Filter_{0}_{1}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({2})matches); break;\n", patternName, filter.Name, matchesType, TypesHelper.GetPackagePrefixDot(filter.Package)); if(filter.Package != null) sb.AppendFrontFormat("case \"{4}{1}\": GRGEN_ACTIONS.{3}MatchFilters.Filter_{0}_{1}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({2})matches); break;\n", patternName, filter.Name, matchesType, filter.Package + ".", filter.Package + "::"); } } else { IFilterFunction filterFunction = (IFilterFunction)filter; sb.AppendFrontFormat("case \"{0}\": GRGEN_ACTIONS.{1}MatchFilters.Filter_{2}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({3})matches", filterFunction.Name, TypesHelper.GetPackagePrefixDot(filterFunction.Package), filterFunction.Name, matchesType); for(int i=0; i<filterFunction.Inputs.Length; ++i) { sb.AppendFormat(", ({0})(filter.ArgumentExpressions[{1}]!=null ? filter.ArgumentExpressions[{1}].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[{1}])", TypesHelper.TypeName(filterFunction.Inputs[i]), i); } sb.Append("); break;\n"); if(filter.Package != null) { sb.AppendFrontFormat("case \"{4}{0}\": GRGEN_ACTIONS.{1}MatchFilters.Filter_{2}((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv, ({3})matches", filterFunction.Name, TypesHelper.GetPackagePrefixDot(filterFunction.Package), filterFunction.Name, matchesType, filter.Package + "::"); for(int i = 0; i < filterFunction.Inputs.Length; ++i) { sb.AppendFormat(", ({0})(filter.ArgumentExpressions[{1}]!=null ? filter.ArgumentExpressions[{1}].Evaluate((GRGEN_LIBGR.IGraphProcessingEnvironment)actionEnv) : filter.Arguments[{1}])", TypesHelper.TypeName(filterFunction.Inputs[i]), i); } sb.Append("); break;\n"); } } } sb.AppendFront("default: throw new Exception(\"Unknown filter name!\");\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.Unindent(); sb.AppendFront("}\n"); }
void 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); } }
/// <summary> /// Generates matcher class head source code for the pattern of the rulePattern into given source builder /// isInitialStatic tells whether the initial static version or a dynamic version after analyze is to be generated. /// </summary> void GenerateMatcherClassHeadAction(SourceBuilder sb, LGSPRulePattern rulePattern, bool isInitialStatic, SearchProgram searchProgram) { PatternGraph patternGraph = (PatternGraph)rulePattern.PatternGraph; String namePrefix = (isInitialStatic ? "" : "Dyn") + "Action_"; String className = namePrefix + rulePattern.name; String rulePatternClassName = rulePattern.GetType().Name; String matchClassName = rulePatternClassName + "." + "Match_" + rulePattern.name; String matchInterfaceName = rulePatternClassName + "." + "IMatch_" + rulePattern.name; String actionInterfaceName = "IAction_" + rulePattern.name; if(patternGraph.Package != null) { sb.AppendFrontFormat("namespace {0}\n", patternGraph.Package); sb.AppendFront("{\n"); sb.Indent(); } sb.AppendFront("public class " + className + " : GRGEN_LGSP.LGSPAction, " + "GRGEN_LIBGR.IAction, " + actionInterfaceName + "\n"); sb.AppendFront("{\n"); sb.Indent(); // class level sb.AppendFront("public " + className + "() {\n"); sb.Indent(); // method body level sb.AppendFront("_rulePattern = " + rulePatternClassName + ".Instance;\n"); sb.AppendFront("patternGraph = _rulePattern.patternGraph;\n"); if(rulePattern.patternGraph.branchingFactor < 2) { sb.AppendFront("DynamicMatch = myMatch;\n"); if(!isInitialStatic) sb.AppendFrontFormat("GRGEN_ACTIONS.Action_{0}.Instance.DynamicMatch = myMatch;\n", rulePattern.name); } else { sb.AppendFront("if(Environment.ProcessorCount == 1)\n"); sb.AppendFront("{\n"); sb.AppendFront("\tDynamicMatch = myMatch;\n"); if(!isInitialStatic) sb.AppendFrontFormat("\tGRGEN_ACTIONS.Action_{0}.Instance.DynamicMatch = myMatch;\n", rulePattern.name); sb.AppendFront("}\n"); sb.AppendFront("else\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("DynamicMatch = myMatch_parallelized;\n"); if(!isInitialStatic) sb.AppendFrontFormat("GRGEN_ACTIONS.Action_{0}.Instance.DynamicMatch = myMatch_parallelized;\n", rulePattern.name); sb.AppendFrontFormat("numWorkerThreads = GRGEN_LGSP.WorkerPool.EnsurePoolSize({0});\n", rulePattern.patternGraph.branchingFactor); sb.AppendFrontFormat("parallelTaskMatches = new GRGEN_LGSP.LGSPMatchesList<{0}, {1}>[numWorkerThreads];\n", matchClassName, matchInterfaceName); sb.AppendFront("moveHeadAfterNodes = new List<GRGEN_LGSP.LGSPNode>[numWorkerThreads];\n"); sb.AppendFront("moveHeadAfterEdges = new List<GRGEN_LGSP.LGSPEdge>[numWorkerThreads];\n"); sb.AppendFront("moveOutHeadAfter = new List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>[numWorkerThreads];\n"); sb.AppendFront("moveInHeadAfter = new List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>[numWorkerThreads];\n"); sb.AppendFront("for(int i=0; i<numWorkerThreads; ++i)\n"); sb.AppendFront("{\n"); sb.Indent(); sb.AppendFront("moveHeadAfterNodes[i] = new List<GRGEN_LGSP.LGSPNode>();\n"); sb.AppendFront("moveHeadAfterEdges[i] = new List<GRGEN_LGSP.LGSPEdge>();\n"); sb.AppendFront("moveOutHeadAfter[i] = new List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>();\n"); sb.AppendFront("moveInHeadAfter[i] = new List<KeyValuePair<GRGEN_LGSP.LGSPNode, GRGEN_LGSP.LGSPEdge>>();\n"); sb.Unindent(); sb.AppendFront("}\n"); sb.AppendFront("for(int i=0; i<parallelTaskMatches.Length; ++i)\n"); sb.AppendFrontFormat("\tparallelTaskMatches[i] = new GRGEN_LGSP.LGSPMatchesList<{0}, {1}>(this);\n", matchClassName, matchInterfaceName); sb.Unindent(); sb.AppendFront("}\n"); } sb.AppendFrontFormat("ReturnArray = new object[{0}];\n", rulePattern.Outputs.Length); sb.AppendFront("matches = new GRGEN_LGSP.LGSPMatchesList<" + matchClassName +", " + matchInterfaceName + ">(this);\n"); sb.Unindent(); // class level sb.AppendFront("}\n\n"); sb.AppendFront("public " + rulePatternClassName + " _rulePattern;\n"); sb.AppendFront("public override GRGEN_LGSP.LGSPRulePattern rulePattern { get { return _rulePattern; } }\n"); sb.AppendFront("public override string Name { get { return \"" + rulePattern.name + "\"; } }\n"); sb.AppendFront("private GRGEN_LGSP.LGSPMatchesList<" + matchClassName + ", " + matchInterfaceName + "> matches;\n\n"); if (isInitialStatic) { sb.AppendFront("public static " + className + " Instance { get { return instance; } set { instance = value; } }\n"); sb.AppendFront("private static " + className + " instance = new " + className + "();\n"); } GenerateIndependentsMatchObjects(sb, rulePattern, patternGraph); sb.AppendFront("\n"); GenerateParallelizationSetupAsNeeded(sb, rulePattern, searchProgram); }
public override void Emit(SourceBuilder sourceCode) { String id = fetchId().ToString(); if(ContainerType.StartsWith("List")) { sourceCode.AppendFrontFormat("{0} entry_{1} = ({0}) " + NamesOfEntities.Variable(Container) + ";\n", ContainerType, id); sourceCode.AppendFrontFormat("for(int index_{0}=0; index_{0}<entry_{0}.Count; ++index_{0})\n", id); sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Index != null) { sourceCode.AppendFront(IndexType + " " + NamesOfEntities.Variable(Index) + " = index_" + id + ";\n"); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + "[index_" + id + "];\n"); } else { sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + "[index_" + id + "];\n"); } } else if(ContainerType.StartsWith("GRGEN_LIBGR.Deque")) { sourceCode.AppendFrontFormat("{0} entry_{1} = ({0}) " + NamesOfEntities.Variable(Container) + ";\n", ContainerType, id); sourceCode.AppendFrontFormat("for(int index_{0}=0; index_{0}<entry_{0}.Count; ++index_{0})\n", id); sourceCode.AppendFront("{\n"); sourceCode.Indent(); if(Index != null) { sourceCode.AppendFront(IndexType + " " + NamesOfEntities.Variable(Index) + " = index_" + id + ";\n"); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + "[index_" + id + "];\n"); } else { sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + "[index_" + id + "];\n"); } } else if(ContainerType.StartsWith("Dictionary") && ContainerType.Contains("SetValueType")) { sourceCode.AppendFrontFormat("foreach(KeyValuePair<{0},GRGEN_LIBGR.SetValueType> entry_{1} in {2})\n", VariableType, id, NamesOfEntities.Variable(Container)); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + ".Key;\n"); } else { sourceCode.AppendFrontFormat("foreach(KeyValuePair<{0},{1}> entry_{2} in {3})\n", IndexType, VariableType, id, NamesOfEntities.Variable(Container)); sourceCode.AppendFront("{\n"); sourceCode.Indent(); sourceCode.AppendFront(IndexType + " " + NamesOfEntities.Variable(Index) + " = entry_" + id + ".Key;\n"); sourceCode.AppendFront(VariableType + " " + NamesOfEntities.Variable(Variable) + " = " + " entry_" + id + ".Value;\n"); } foreach(Yielding statement in Statements) statement.Emit(sourceCode); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); }
/// <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"); }
private void GenerateGenericExternalDefinedSequenceApplicationMethod(SourceBuilder source, DefinedSequenceInfo sequence) { source.AppendFront("public override bool Apply(GRGEN_LIBGR.SequenceInvocationParameterBindings sequenceInvocation, GRGEN_LIBGR.IGraphProcessingEnvironment procEnv)"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("GRGEN_LGSP.LGSPGraph graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n"); for(int i = 0; i < sequence.Parameters.Length; ++i) { string typeName = TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i]), model); source.AppendFront(typeName + " var_" + sequence.Parameters[i]); source.Append(" = (" + typeName + ")sequenceInvocation.ArgumentExpressions[" + i + "].Evaluate((GRGEN_LGSP.LGSPGraphProcessingEnvironment)procEnv);\n"); } for(int i = 0; i < sequence.OutParameters.Length; ++i) { string typeName = TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model); source.AppendFront(typeName + " var_" + sequence.OutParameters[i]); source.Append(" = " + TypesHelper.DefaultValueString(typeName, model) + ";\n"); } source.AppendFront("if(sequenceInvocation.Subgraph!=null)\n"); source.AppendFront("\t{ procEnv.SwitchToSubgraph((GRGEN_LIBGR.IGraph)sequenceInvocation.Subgraph.GetVariableValue(procEnv)); graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph; }\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"); source.AppendFront("if(sequenceInvocation.Subgraph!=null)\n"); source.AppendFront("\t{ procEnv.ReturnFromSubgraph(); graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph; }\n"); if(sequence.OutParameters.Length > 0) { source.AppendFront("if(result) {\n"); source.Indent(); for(int i = 0; i < sequence.OutParameters.Length; ++i) { source.AppendFront("sequenceInvocation.ReturnVars[" + i + "].SetVariableValue(var_" + sequence.OutParameters[i] + ", procEnv);\n"); } source.Unindent(); source.AppendFront("}\n"); } source.AppendFront("return result;\n"); source.Unindent(); source.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 EmitRuleOrRuleAllCall(SequenceRuleCall seqRule, SourceBuilder source) { RuleInvocationParameterBindings paramBindings = seqRule.ParamBindings; String specialStr = seqRule.Special ? "true" : "false"; String parameterDeclarations = null; String parameters = null; if(paramBindings.Subgraph != null) parameters = BuildParametersInDeclarations(paramBindings, out parameterDeclarations); else parameters = BuildParameters(paramBindings); String matchingPatternClassName = TypesHelper.GetPackagePrefixDot(paramBindings.Package) + "Rule_" + paramBindings.Name; String patternName = paramBindings.Name; String matchType = matchingPatternClassName + "." + NamesOfEntities.MatchInterfaceName(patternName); String matchName = "match_" + seqRule.Id; String matchesType = "GRGEN_LIBGR.IMatchesExact<" + matchType + ">"; String matchesName = "matches_" + seqRule.Id; if(paramBindings.Subgraph != null) { source.AppendFront(parameterDeclarations + "\n"); source.AppendFront("procEnv.SwitchToSubgraph((GRGEN_LIBGR.IGraph)" + GetVar(paramBindings.Subgraph) + ");\n"); source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n"); } source.AppendFront(matchesType + " " + matchesName + " = rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Match(procEnv, " + (seqRule.SequenceType == SequenceType.RuleCall ? "1" : "procEnv.MaxMatches") + parameters + ");\n"); for(int i = 0; i < seqRule.Filters.Count; ++i) { EmitFilterCall(source, seqRule.Filters[i], patternName, matchesName); } if(gen.FireDebugEvents) source.AppendFront("procEnv.Matched(" + matchesName + ", null, " + specialStr + ");\n"); if(seqRule is SequenceRuleCountAllCall) { SequenceRuleCountAllCall seqRuleCountAll = (SequenceRuleCountAllCall)seqRule; source.AppendFront(SetVar(seqRuleCountAll.CountResult, matchesName + ".Count")); } if(seqRule is SequenceRuleAllCall && ((SequenceRuleAllCall)seqRule).ChooseRandom && ((SequenceRuleAllCall)seqRule).MinSpecified) { SequenceRuleAllCall seqRuleAll = (SequenceRuleAllCall)seqRule; source.AppendFrontFormat("int minmatchesvar_{0} = (int){1};\n", seqRuleAll.Id, GetVar(seqRuleAll.MinVarChooseRandom)); source.AppendFrontFormat("if({0}.Count < minmatchesvar_{1}) {{\n", matchesName, seqRuleAll.Id); } else { source.AppendFront("if(" + matchesName + ".Count==0) {\n"); } source.Indent(); source.AppendFront(SetResultVar(seqRule, "false")); source.Unindent(); source.AppendFront("} else {\n"); source.Indent(); source.AppendFront(SetResultVar(seqRule, "true")); source.AppendFront("procEnv.PerformanceInfo.MatchesFound += " + matchesName + ".Count;\n"); if(gen.FireDebugEvents) source.AppendFront("procEnv.Finishing(" + matchesName + ", " + specialStr + ");\n"); String returnParameterDeclarations; String returnArguments; String returnAssignments; String returnParameterDeclarationsAllCall; String intermediateReturnAssignmentsAllCall; String returnAssignmentsAllCall; BuildReturnParameters(paramBindings, out returnParameterDeclarations, out returnArguments, out returnAssignments, out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall); if(seqRule.SequenceType == SequenceType.RuleCall) { source.AppendFront(matchType + " " + matchName + " = " + matchesName + ".FirstExact;\n"); if(returnParameterDeclarations.Length!=0) source.AppendFront(returnParameterDeclarations + "\n"); source.AppendFront("rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if(returnAssignments.Length != 0) source.AppendFront(returnAssignments + "\n"); source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed++;\n"); } else if(seqRule.SequenceType == SequenceType.RuleCountAllCall || !((SequenceRuleAllCall)seqRule).ChooseRandom) // seq.SequenceType == SequenceType.RuleAll { // iterate through matches, use Modify on each, fire the next match event after the first if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarationsAllCall + "\n"); String enumeratorName = "enum_" + seqRule.Id; source.AppendFront("IEnumerator<" + matchType + "> " + enumeratorName + " = " + matchesName + ".GetEnumeratorExact();\n"); source.AppendFront("while(" + enumeratorName + ".MoveNext())\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront(matchType + " " + matchName + " = " + enumeratorName + ".Current;\n"); source.AppendFront("if(" + matchName + "!=" + matchesName + ".FirstExact) procEnv.RewritingNextMatch();\n"); if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarations + "\n"); source.AppendFront("rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if(returnAssignments.Length != 0) source.AppendFront(intermediateReturnAssignmentsAllCall + "\n"); source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed++;\n"); source.Unindent(); source.AppendFront("}\n"); if(returnAssignments.Length != 0) source.AppendFront(returnAssignmentsAllCall + "\n"); } else // seq.SequenceType == SequenceType.RuleAll && ((SequenceRuleAll)seqRule).ChooseRandom { // as long as a further rewrite has to be selected: randomly choose next match, rewrite it and remove it from available matches; fire the next match event after the first SequenceRuleAllCall seqRuleAll = (SequenceRuleAllCall)seqRule; if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarationsAllCall + "\n"); source.AppendFrontFormat("int numchooserandomvar_{0} = (int){1};\n", seqRuleAll.Id, seqRuleAll.MaxVarChooseRandom != null ? GetVar(seqRuleAll.MaxVarChooseRandom) : (seqRuleAll.MinSpecified ? "2147483647" : "1")); source.AppendFrontFormat("if({0}.Count < numchooserandomvar_{1}) numchooserandomvar_{1} = {0}.Count;\n", matchesName, seqRule.Id); source.AppendFrontFormat("for(int i = 0; i < numchooserandomvar_{0}; ++i)\n", seqRule.Id); source.AppendFront("{\n"); source.Indent(); source.AppendFront("if(i != 0) procEnv.RewritingNextMatch();\n"); source.AppendFront(matchType + " " + matchName + " = " + matchesName + ".RemoveMatchExact(GRGEN_LIBGR.Sequence.randomGenerator.Next(" + matchesName + ".Count));\n"); if(returnParameterDeclarations.Length != 0) source.AppendFront(returnParameterDeclarations + "\n"); source.AppendFront("rule_" + TypesHelper.PackagePrefixedNameUnderscore(paramBindings.Package, paramBindings.Name) + ".Modify(procEnv, " + matchName + returnArguments + ");\n"); if(returnAssignments.Length != 0) source.AppendFront(intermediateReturnAssignmentsAllCall + "\n"); source.AppendFront("procEnv.PerformanceInfo.RewritesPerformed++;\n"); source.Unindent(); source.AppendFront("}\n"); if(returnAssignments.Length != 0) source.AppendFront(returnAssignmentsAllCall + "\n"); } if(gen.FireDebugEvents) source.AppendFront("procEnv.Finished(" + matchesName + ", " + specialStr + ");\n"); source.Unindent(); source.AppendFront("}\n"); if(paramBindings.Subgraph != null) { source.AppendFront("procEnv.ReturnFromSubgraph();\n"); source.AppendFront("graph = ((GRGEN_LGSP.LGSPActionExecutionEnvironment)procEnv).graph;\n"); } }
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"); }
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"); }
private void GenerateInternalDefinedSequenceApplicationMethod(SourceBuilder source, DefinedSequenceInfo sequence, Sequence seq) { source.AppendFront("public static bool ApplyXGRS_" + sequence.Name + "(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv"); for(int i = 0; i < sequence.Parameters.Length; ++i) { source.Append(", " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i]), model) + " var_"); source.Append(sequence.Parameters[i]); } for(int i = 0; i < sequence.OutParameters.Length; ++i) { source.Append(", ref " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model) + " var_"); source.Append(sequence.OutParameters[i]); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("GRGEN_LGSP.LGSPGraph graph = procEnv.graph;\n"); source.AppendFront("GRGEN_LGSP.LGSPActions actions = procEnv.curActions;\n"); knownRules.Clear(); if(gen.FireDebugEvents) { source.AppendFrontFormat("procEnv.DebugEntering(\"{0}\"", sequence.Name); for(int i = 0; i < sequence.Parameters.Length; ++i) { source.Append(", var_"); source.Append(sequence.Parameters[i]); } source.Append(");\n"); } EmitNeededVarAndRuleEntities(seq, source); EmitSequence(seq, source); if(gen.FireDebugEvents) { source.AppendFrontFormat("procEnv.DebugExiting(\"{0}\"", sequence.Name); for(int i = 0; i < sequence.OutParameters.Length; ++i) { source.Append(", var_"); source.Append(sequence.OutParameters[i]); } source.Append(");\n"); } source.AppendFront("return " + GetResultVar(seq) + ";\n"); source.Unindent(); source.AppendFront("}\n"); List<SequenceExpressionContainerConstructor> containerConstructors = new List<SequenceExpressionContainerConstructor>(); Dictionary<SequenceVariable, SetValueType> variables = new Dictionary<SequenceVariable, SetValueType>(); seq.GetLocalVariables(variables, containerConstructors, null); foreach(SequenceExpressionContainerConstructor cc in containerConstructors) { GenerateContainerConstructor(cc, source); } }
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"); }
public bool GenerateExternalDefinedSequence(SourceBuilder source, ExternalDefinedSequenceInfo sequence) { // exact sequence definition compiled class source.Append("\n"); source.AppendFront("public partial class Sequence_" + sequence.Name + " : GRGEN_LIBGR.SequenceDefinitionCompiled\n"); source.AppendFront("{\n"); source.Indent(); GenerateSequenceDefinedSingleton(source, sequence); source.Append("\n"); GenerateExactExternalDefinedSequenceApplicationMethod(source, sequence); source.Append("\n"); GenerateGenericExternalDefinedSequenceApplicationMethod(source, sequence); // end of exact sequence definition compiled class source.Unindent(); source.AppendFront("}\n"); return true; }
void GenerateGroupByFilter(SourceBuilder source, LGSPRulePattern rulePattern, String filterVariable) { String rulePatternClassName = TypesHelper.GetPackagePrefixDot(rulePattern.PatternGraph.Package) + rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; String filterName = "groupBy_" + filterVariable; if(true) // does the type of the variable to group-by support ordering? then order, is more efficient than equality comparisons { source.AppendFrontFormat("public static void Filter_{0}_{1}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {2} matches)\n", rulePattern.name, filterName, matchesListType); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("List<{0}> matchesArray = matches.ToList();\n", matchInterfaceName); source.AppendFrontFormat("matchesArray.Sort(new Comparer_{0}_{1}());\n", rulePattern.name, filterName); source.AppendFront("matches.FromList();\n"); source.Unindent(); source.AppendFront("}\n"); source.AppendFrontFormat("class Comparer_{0}_{1} : Comparer<{2}>\n", rulePattern.name, filterName, matchInterfaceName); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("public override int Compare({0} left, {0} right)\n", matchInterfaceName); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("return left.{0}.CompareTo(right.{0});\n", NamesOfEntities.MatchName(filterVariable, EntityType.Variable)); source.Unindent(); source.AppendFront("}\n"); source.Unindent(); source.AppendFront("}\n"); } else { // ensure that if two elements are equal, they are neighbours or only separated by equal elements // not needed yet, as of now we only support numerical types and string, that support ordering in addition to equality comparison /*List<T> matchesArray; for(int i = 0; i < matchesArray.Count - 1; ++i) { for(int j = i + 1; j < matchesArray.Count; ++j) { if(matchesArray[i] == matchesArray[j]) { T tmp = matchesArray[i + 1]; matchesArray[i + 1] = matchesArray[j]; matchesArray[j] = tmp; break; } } }*/ } }
public void GenerateFilterStubs(SourceBuilder source, LGSPRulePattern rulePattern) { String rulePatternClassName = rulePattern.GetType().Name; String matchInterfaceName = rulePatternClassName + "." + NamesOfEntities.MatchInterfaceName(rulePattern.name); String matchesListType = "GRGEN_LIBGR.IMatchesExact<" + matchInterfaceName + ">"; foreach(IFilter filter in rulePattern.Filters) { if(filter is IFilterAutoGenerated) continue; IFilterFunction filterFunction = (IFilterFunction)filter; if(!filterFunction.IsExternal) continue; if(filter.Package != null) { source.AppendFrontFormat("namespace {0}\n", filter.Package); source.AppendFront("{\n"); source.Indent(); } source.AppendFront("public partial class MatchFilters\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("//public static void Filter_{0}(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, {1} matches", filter.Name, matchesListType); for(int i = 0; i < filterFunction.Inputs.Length; ++i) { source.AppendFormat(", {0} {1}", TypesHelper.TypeName(filterFunction.Inputs[i]), filterFunction.InputNames[i]); } source.Append(")\n"); source.Unindent(); source.AppendFront("}\n"); if(filter.Package != null) { source.Unindent(); source.AppendFront("}\n"); } } }
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"); } }