Пример #1
0
        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();
            }
        }
Пример #2
0
 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();
     }
 }
Пример #3
0
        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");
        }
Пример #4
0
        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);
        }
Пример #5
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.Append(IsVar ? NamesOfEntities.Variable(Left) : NamesOfEntities.CandidateVariable(Left));
     sourceCode.Append(" = ");
     sourceCode.Append("(" + TargetType + ")");
     Right.Emit(sourceCode);
     sourceCode.Append(";\n");
 }
Пример #6
0
        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");
        }
Пример #7
0
        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");
        }
Пример #8
0
 void EmitHashComputation(SourceBuilder sourceCode, int i)
 {
     if (i < 0)
     {
         sourceCode.Append("23");
     }
     else
     {
         sourceCode.Append("(");
         EmitHashComputation(sourceCode, i - 1);
         sourceCode.AppendFormat("*17 + {0}.GetHashCode()",
                                 NamesOfEntities.CandidateVariable(NeededElements[i]));
         sourceCode.Append(")");
     }
 }
Пример #9
0
        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)
 {
     builder.AppendFront("AdjustListHeads ");
     if (Type == AdjustListHeadsTypes.GraphElements)
     {
         builder.Append("GraphElements ");
         builder.AppendFormat("on {0} node:{1} {2}\n",
                              PatternElementName, IsNode, Parallel ? "Parallel " : "");
     }
     else // Type==AdjustListHeadsTypes.IncidentEdges
     {
         builder.Append("IncidentEdges ");
         builder.AppendFormat("on {0} from:{1} incident type:{2} {3}\n",
                              PatternElementName, StartingPointNodeName, IncidentType.ToString(), Parallel ? "Parallel " : "");
     }
 }
Пример #11
0
 private int EmitMaybeNullDispatching(SourceBuilder sourceCode, int conditionLevel, int emittedCounter)
 {
     if (conditionLevel < DispatchConditions.Length)
     {
         sourceCode.AppendFrontFormat("if({0}!=null) {{\n", DispatchConditions[conditionLevel]);
         sourceCode.Indent();
         emittedCounter = EmitMaybeNullDispatching(sourceCode, conditionLevel + 1, emittedCounter);
         sourceCode.Unindent();
         sourceCode.AppendFront("} else {\n");
         sourceCode.Indent();
         emittedCounter = EmitMaybeNullDispatching(sourceCode, conditionLevel + 1, emittedCounter);
         sourceCode.Unindent();
         sourceCode.AppendFront("}\n");
     }
     else
     {
         if (emittedCounter > 0) // first entry are we ourselves, don't call, just nop
         {
             sourceCode.AppendFrontFormat("return {0}(actionEnv, maxMatches", SuffixedMatcherNames[emittedCounter]);
             foreach (string argument in Arguments[emittedCounter])
             {
                 sourceCode.AppendFormat(", {0}", argument);
             }
             sourceCode.Append(");\n");
         }
         ++emittedCounter;
     }
     return(emittedCounter);
 }
 public override void Dump(SourceBuilder builder)
 {
     builder.AppendFront("RandomizeListHeads ");
     if (Type == RandomizeListHeadsTypes.GraphElements)
     {
         builder.Append("GraphElements ");
         builder.AppendFormat("on {0} node:{1}\n",
                              PatternElementName, IsNode);
     }
     else // Type==RandomizeListHeadsTypes.IncidentEdges
     {
         builder.Append("IncidentEdges ");
         builder.AppendFormat("on {0} from:{1} incoming:{2}\n",
                              PatternElementName, StartingPointNodeName, IsIncoming);
     }
 }
Пример #13
0
        private void GenerateInternalDefinedSequenceApplicationMethodStub(SourceBuilder source, DefinedSequenceInfo sequence, String externalActionsExtensionFilename)
        {
            source.AppendFrontFormat("// You must implement the following function in the same partial class in ./{0}\n", externalActionsExtensionFilename);

            source.AppendFront("//public static bool ApplyXGRS_" + sequence.Name + "(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv");
            for (int i = 0; i < sequence.Parameters.Length; ++i)
            {
                source.Append(", " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i]), model) + " var_");
                source.Append(sequence.Parameters[i]);
            }
            for (int i = 0; i < sequence.OutParameters.Length; ++i)
            {
                source.Append(", ref " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model) + " var_");
                source.Append(sequence.OutParameters[i]);
            }
            source.Append(")\n");
        }
Пример #14
0
        public override void Emit(SourceBuilder sourceCode)
        {
            // emit check decision
            string variableContainingCandidate = NamesOfEntities.CandidateVariable(PatternElementName);

            if (Type == CheckCandidateForTypeType.ByIsAllowedType)
            {
                string isAllowedTypeArrayMemberOfRulePattern =
                    IsAllowedArrayName + "_IsAllowedType";
                sourceCode.AppendFrontFormat("if(!{0}.{1}[{2}.lgspType.TypeID]) ",
                                             RulePatternTypeName, isAllowedTypeArrayMemberOfRulePattern,
                                             variableContainingCandidate);
            }
            else if (Type == CheckCandidateForTypeType.ByIsMyType)
            {
                sourceCode.AppendFrontFormat("if(!{0}.isMyType[{1}.lgspType.TypeID]) ",
                                             TypeName, variableContainingCandidate);
            }
            else // Type == CheckCandidateForTypeType.ByTypeID)
            {
                sourceCode.AppendFront("if(");
                bool first = true;
                foreach (string typeID in TypeIDs)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        sourceCode.Append(" && ");
                    }

                    sourceCode.AppendFormat("{0}.lgspType.TypeID!={1}",
                                            variableContainingCandidate, typeID);
                }
                sourceCode.Append(") ");
            }
            // emit check failed code
            sourceCode.Append("{\n");
            sourceCode.Indent();
            CheckFailedOperations.Emit(sourceCode);
            sourceCode.Unindent();
            sourceCode.AppendFront("}\n");
        }
Пример #15
0
        private static void DumpScheduledSearchPlan(ScheduledSearchPlan ssp, IGraphModel model, String dumpname)
        {
            StreamWriter  sw = new StreamWriter(dumpname + "-scheduledsp.txt", false);
            SourceBuilder sb = new SourceBuilder();

            ScheduleExplainer.Explain(ssp, sb, model);
            sb.Append("\n");
            sw.WriteLine(sb.ToString());
            sw.Close();
        }
Пример #16
0
 public override void Dump(SourceBuilder builder)
 {
     // first dump local content
     builder.AppendFront("FillPartialMatchForDuplicateChecking with ");
     foreach (string neededElement in NeededElements)
     {
         builder.AppendFormat("{0} ", neededElement);
     }
     builder.Append("\n");
 }
        public static void EmitPreMatchEventFiring(SourceBuilder source, SequenceRuleCallMatcherGenerator[] ruleMatcherGenerators)
        {
            source.AppendFront("procEnv.PreMatched(");
            bool first = true;

            foreach (SequenceRuleCallMatcherGenerator ruleMatcherGenerator in ruleMatcherGenerators)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    source.Append(",");
                }
                source.AppendFormat("{0}", ruleMatcherGenerator.matchesName);
            }
            source.Append(");\n");
        }
Пример #18
0
        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");
        }
Пример #19
0
        public override void Emit(SourceBuilder sourceCode)
        {
            if (sourceCode.CommentSourceCode)
            {
                sourceCode.AppendFront("// Condition \n");
            }

            // open decision
            sourceCode.AppendFront("if(");
            // emit condition expression
            sourceCode.AppendFormat("!({0})", ConditionExpression);
            // close decision
            sourceCode.Append(") ");

            // emit check failed code
            sourceCode.Append("{\n");
            sourceCode.Indent();
            CheckFailedOperations.Emit(sourceCode);
            sourceCode.Unindent();
            sourceCode.AppendFront("}\n");
        }
 public override void Dump(SourceBuilder builder)
 {
     builder.AppendFront("ContinueOperation ");
     if (Type == ContinueOperationType.ByReturn)
     {
         builder.Append("ByReturn ");
         if (InParallelizedBody)
         {
             builder.Append("InParallelizedBody ");
         }
         builder.AppendFormat("return matches:{0}\n", ReturnMatches);
     }
     else if (Type == ContinueOperationType.ByContinue)
     {
         builder.AppendFormat("ByContinue {0}\n", ContinueAtParallelizedLoop ? "AtParallelizedLoop" : "");
     }
     else // Type==ContinueOperationType.ByGoto
     {
         builder.Append("ByGoto ");
         builder.AppendFormat("{0}\n", LabelName);
     }
 }
Пример #21
0
        /// <summary>
        /// Dumps search program
        /// </summary>
        public override void Dump(SourceBuilder builder)
        {
            // first dump local content
            builder.AppendFrontFormat("Search program {0} of iterated\n", Parallel ? Name + "_parallelized" : Name);
            builder.Append("\n");

            // then nested content
            if (OperationsList != null)
            {
                builder.Indent();
                OperationsList.Dump(builder);
                builder.Unindent();
            }
        }
Пример #22
0
        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();
            }
        }
Пример #23
0
 public override void Dump(SourceBuilder builder)
 {
     // first dump check
     builder.AppendFront("CheckCandidate ForIsomorphyGlobal ");
     builder.AppendFormat("on {0} node:{1} ",
                          PatternElementName, IsNode);
     if (GloballyHomomorphElements != null)
     {
         builder.Append("but accept if ");
         foreach (string name in GloballyHomomorphElements)
         {
             builder.AppendFormat("{0} ", name);
         }
     }
     builder.Append("\n");
     // then operations for case check failed
     if (CheckFailedOperations != null)
     {
         builder.Indent();
         CheckFailedOperations.Dump(builder);
         builder.Unindent();
     }
 }
Пример #24
0
        public override void Dump(SourceBuilder builder)
        {
            if (Type == PushAndPopSubpatternTaskTypes.Subpattern)
            {
                builder.AppendFront("PushSubpatternTask Subpattern ");
            }
            else if (Type == PushAndPopSubpatternTaskTypes.Alternative)
            {
                builder.AppendFront("PushSubpatternTask Alternative ");
            }
            else // Type==PushAndPopSubpatternTaskTypes.Iterated
            {
                builder.AppendFront("PushSubpatternTask Iterated ");
            }

            if (Type == PushAndPopSubpatternTaskTypes.Subpattern)
            {
                builder.AppendFormat("{0} of {1} ", SubpatternElementName, SubpatternName);
            }
            else
            {
                builder.AppendFormat("{0}/{1} ", PathPrefix, AlternativeOrIteratedName);
            }

            if (Parallel)
            {
                builder.Append("Parallel ");
            }

            builder.Append("with ");
            for (int i = 0; i < ConnectionName.Length; ++i)
            {
                builder.AppendFormat("{0} <- {1} ",
                                     ConnectionName[i], ArgumentExpressions[i]);
            }
            builder.Append("\n");
        }
Пример #25
0
 public override void Dump(SourceBuilder builder)
 {
     // first dump check
     builder.AppendFront("CheckPartialMatch ByCondition ");
     builder.AppendFormat("{0} with ", ConditionExpression);
     foreach (string neededElement in NeededElements)
     {
         builder.Append(neededElement);
         builder.Append(" ");
     }
     foreach (string neededVar in NeededVariables)
     {
         builder.Append(neededVar);
         builder.Append(" ");
     }
     builder.Append("\n");
     // then operations for case check failed
     if (CheckFailedOperations != null)
     {
         builder.Indent();
         CheckFailedOperations.Dump(builder);
         builder.Unindent();
     }
 }
Пример #26
0
 public override void Dump(SourceBuilder builder)
 {
     // first dump check
     builder.AppendFront("CheckCandidate ForIsomorphyPatternPath ");
     builder.AppendFormat("on {0} node:{1} last match at previous nesting level in:{2}",
                          PatternElementName, IsNode, LastMatchAtPreviousNestingLevel);
     builder.Append("\n");
     // then operations for case check failed
     if (CheckFailedOperations != null)
     {
         builder.Indent();
         CheckFailedOperations.Dump(builder);
         builder.Unindent();
     }
 }
Пример #27
0
        public override void Emit(SourceBuilder sourceCode)
        {
            // emit check decision
            string variableContainingCandidate    = NamesOfEntities.CandidateVariable(PatternElementName);
            string variableContainingOtherElement = NamesOfEntities.CandidateVariable(OtherPatternElementName);

            sourceCode.AppendFrontFormat("if({0}!={1}) ",
                                         variableContainingCandidate, variableContainingOtherElement);

            // emit check failed code
            sourceCode.Append("{\n");
            sourceCode.Indent();
            CheckFailedOperations.Emit(sourceCode);
            sourceCode.Unindent();
            sourceCode.AppendFront("}\n");
        }
Пример #28
0
 public override void Dump(SourceBuilder builder)
 {
     // first dump local content
     builder.AppendFront("CheckPartialMatch ForDuplicate with ");
     foreach (string neededElement in NeededElements)
     {
         builder.AppendFormat("{0} ", neededElement);
     }
     builder.Append("\n");
     // then operations for case check failed
     if (CheckFailedOperations != null)
     {
         builder.Indent();
         CheckFailedOperations.Dump(builder);
         builder.Unindent();
     }
 }
Пример #29
0
        public override void Emit(SourceBuilder sourceCode)
        {
            if (sourceCode.CommentSourceCode)
            {
                sourceCode.AppendFront("// Check whether subpatterns were found \n");
            }

            // emit decision
            sourceCode.AppendFrontFormat("if({0}matchesList.Count>0) ", NegativeIndependentNamePrefix);

            // emit check failed code
            sourceCode.Append("{\n");
            sourceCode.Indent();
            CheckFailedOperations.Emit(sourceCode);
            sourceCode.Unindent();
            sourceCode.AppendFront("}\n");
        }
Пример #30
0
 public override void Dump(SourceBuilder builder)
 {
     Debug.Assert(CheckFailedOperations == null, "check negative without direct check failed code");
     // first dump local content
     builder.AppendFront("CheckPartialMatch ByNegative with ");
     foreach (string neededElement in NeededElements)
     {
         builder.AppendFormat("{0} ", neededElement);
     }
     builder.Append("\n");
     // then nested content
     if (NestedOperationsList != null)
     {
         builder.Indent();
         NestedOperationsList.Dump(builder);
         builder.Unindent();
     }
 }
Пример #31
0
        public override void Emit(SourceBuilder sourceCode)
        {
            if (ConnectednessType == CheckCandidateForConnectednessType.Source)
            {
                // emit check decision for is candidate connected to already found partial match, i.e. edge source equals node
                sourceCode.AppendFrontFormat("if({0}.lgspSource != {1}) ",
                                             NamesOfEntities.CandidateVariable(PatternEdgeName),
                                             NamesOfEntities.CandidateVariable(PatternNodeName));
            }
            else if (ConnectednessType == CheckCandidateForConnectednessType.Target)
            {
                // emit check decision for is candidate connected to already found partial match, i.e. edge target equals node
                sourceCode.AppendFrontFormat("if({0}.lgspTarget != {1}) ",
                                             NamesOfEntities.CandidateVariable(PatternEdgeName),
                                             NamesOfEntities.CandidateVariable(PatternNodeName));
            }
            else if (ConnectednessType == CheckCandidateForConnectednessType.SourceOrTarget)
            {
                // we've to check both node positions of the edge, we do so by checking source or target dependent on the direction run
                sourceCode.AppendFrontFormat("if( ({0}==0 ? {1}.lgspSource : {1}.lgspTarget) != {2}) ",
                                             NamesOfEntities.DirectionRunCounterVariable(PatternEdgeName),
                                             NamesOfEntities.CandidateVariable(PatternEdgeName),
                                             NamesOfEntities.CandidateVariable(PatternNodeName));
            }
            else //ConnectednessType == CheckCandidateForConnectednessType.TheOther
            {
                // we've to check the node position of the edge the first node is not assigned to
                sourceCode.AppendFrontFormat("if( ({0}=={1}.lgspSource ? {1}.lgspTarget : {1}.lgspSource) != {2}) ",
                                             NamesOfEntities.CandidateVariable(TheOtherPatternNodeName),
                                             NamesOfEntities.CandidateVariable(PatternEdgeName),
                                             NamesOfEntities.CandidateVariable(PatternNodeName));
            }

            // emit check failed code
            sourceCode.Append("{\n");
            sourceCode.Indent();
            CheckFailedOperations.Emit(sourceCode);
            sourceCode.Unindent();
            sourceCode.AppendFront("}\n");
        }
Пример #32
0
        /// <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");
        }
Пример #33
0
        private void DumpScheduledSearchPlan(ScheduledSearchPlan ssp, String dumpname)
        {
            StreamWriter sw = new StreamWriter(dumpname + "-scheduledsp.txt", false);
            SourceBuilder sb = new SourceBuilder();
            ssp.Explain(sb, model);
            sb.Append("\n");
            sw.WriteLine(sb.ToString());
            sw.Close();

/*            StreamWriter sw = new StreamWriter(dumpname + "-scheduledsp.vcg", false);

            sw.WriteLine("graph:{\ninfoname 1: \"Attributes\"\ndisplay_edge_labels: no\nport_sharing: no\nsplines: no\n"
                + "\nmanhattan_edges: no\nsmanhattan_edges: no\norientation: bottom_to_top\nedges: yes\nnodes: yes\nclassname 1: \"normal\"");
            sw.WriteLine("node:{title:\"root\" label:\"ROOT\"}\n");
            SearchPlanNode root = new SearchPlanNode("root");

            sw.WriteLine("graph:{{title:\"pattern\" label:\"{0}\" status:clustered color:lightgrey", dumpname);

            foreach(SearchOperation op in ssp.Operations)
            {
                switch(op.Type)
                {
                    case SearchOperationType.Lookup:
                    case SearchOperationType.Incoming:
                    case SearchOperationType.Outgoing:
                    case SearchOperationType.ImplicitSource:
                    case SearchOperationType.ImplicitTarget:
                    {
                        SearchPlanNode spnode = (SearchPlanNode) op.Element;
                        DumpNode(sw, spnode);
                        SearchPlanNode src;
                        switch(op.Type)
                        {
                            case SearchOperationType.Lookup:
                            case SearchOperationType.ActionPreset:
                            case SearchOperationType.NegPreset:
                                src = root;
                                break;
                            default:
                                src = op.SourceSPNode;
                                break;
                        }
                        DumpEdge(sw, op.Type, src, spnode, op.CostToEnd, false);
                        break;
                    }
                    case SearchOperationType.Condition:
                        sw.WriteLine("node:{title:\"Condition\" label:\"CONDITION\"}\n");
                        break;
                    case SearchOperationType.NegativePattern:
                        sw.WriteLine("node:{title:\"NAC\" label:\"NAC\"}\n");
                        break;
                }
            }*/
        }
Пример #34
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.AppendFront(Type + " " + NamesOfEntities.Variable(Name));
     if(Initialization != null)
     {
         sourceCode.Append(" = ");
         Initialization.Emit(sourceCode);
     }
     sourceCode.Append(";\n");
 }
Пример #35
0
        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");
        }
Пример #36
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.Append(NamesOfEntities.Variable(Left));
     sourceCode.Append("[");
     Index.Emit(sourceCode);
     sourceCode.Append("] = ");
     Right.Emit(sourceCode);
     sourceCode.Append(";\n");
 }
Пример #37
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.Append(NamesOfEntities.Variable(Left));
     if(Index != null)
     {
         sourceCode.Append(".EnqueueAt(");
         Index.Emit(sourceCode);
         sourceCode.Append(", ");
         Right.Emit(sourceCode);
         sourceCode.Append(")");
         sourceCode.Append(";\n");
     }
     else
     {
         sourceCode.Append(".Enqueue(");
         Right.Emit(sourceCode);
         sourceCode.Append(")");
         sourceCode.Append(";\n");
     }
 }
Пример #38
0
        /// <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");
        }
Пример #39
0
        /// <summary>
        /// Generate new actions for the given actions, doing the same work, 
        /// but hopefully faster by taking graph analysis information into account
        /// </summary>
        public LGSPAction[] GenerateActions(LGSPGraph graph, String modelAssemblyName, String actionsAssemblyName, 
            params LGSPAction[] actions)
        {
            if(actions.Length == 0) throw new ArgumentException("No actions provided!");

            SourceBuilder sourceCode = new SourceBuilder(CommentSourceCode);
            GenerateFileHeaderForActionsFile(sourceCode, model.GetType().Namespace, actions[0].rulePattern.GetType().Namespace);

            // use domain of dictionary as set with rulepatterns of the subpatterns of the actions, get them from pattern graph
            Dictionary<LGSPMatchingPattern, LGSPMatchingPattern> subpatternMatchingPatterns 
                = new Dictionary<LGSPMatchingPattern, LGSPMatchingPattern>();
            foreach (LGSPAction action in actions)
            {
                foreach (KeyValuePair<LGSPMatchingPattern, LGSPMatchingPattern> usedSubpattern 
                    in action.rulePattern.patternGraph.usedSubpatterns)
                {
                    subpatternMatchingPatterns[usedSubpattern.Key] = usedSubpattern.Value;
                }
            }

            // generate code for subpatterns
            foreach (KeyValuePair<LGSPMatchingPattern, LGSPMatchingPattern> subpatternMatchingPattern in subpatternMatchingPatterns)
            {
                LGSPMatchingPattern smp = subpatternMatchingPattern.Key;

                GenerateScheduledSearchPlans(smp.patternGraph, graph, 
                    true, false, null);

                MergeNegativeAndIndependentSchedulesIntoEnclosingSchedules(smp.patternGraph);

                ParallelizeAsNeeded(smp);

                GenerateActionAndMatcher(sourceCode, smp, false);
            }

            // generate code for actions
            foreach(LGSPAction action in actions)
            {
                GenerateScheduledSearchPlans(action.rulePattern.patternGraph, graph,
                    false, false, null);

                MergeNegativeAndIndependentSchedulesIntoEnclosingSchedules(action.rulePattern.patternGraph);

                ParallelizeAsNeeded(action.rulePattern);

                GenerateActionAndMatcher(sourceCode, action.rulePattern, false);
            }

            // close namespace
            sourceCode.Append("}");

            if(DumpDynSourceCode)
            {
                using(StreamWriter writer = new StreamWriter("dynamic_" + actions[0].Name + ".cs"))
                    writer.Write(sourceCode.ToString());
            }

            // set up compiler
            CSharpCodeProvider compiler = new CSharpCodeProvider();
            CompilerParameters compParams = GetDynCompilerSetup(modelAssemblyName, actionsAssemblyName);
 
            // compile generated code
            CompilerResults compResults = compiler.CompileAssemblyFromSource(compParams, sourceCode.ToString());
            if(compResults.Errors.HasErrors)
            {
                String errorMsg = compResults.Errors.Count + " Errors:";
                foreach(CompilerError error in compResults.Errors)
                    errorMsg += Environment.NewLine + "Line: " + error.Line + " - " + error.ErrorText;
                throw new ArgumentException("Internal error: Illegal dynamic C# source code produced: " + errorMsg);
            }

            // create action instances
            LGSPAction[] newActions = new LGSPAction[actions.Length];
            for(int i = 0; i < actions.Length; i++)
            {
                newActions[i] = (LGSPAction) compResults.CompiledAssembly.CreateInstance(
                    "de.unika.ipd.grGen.lgspActions.DynAction_" + actions[i].Name);
                if(newActions[i] == null)
                    throw new ArgumentException("Internal error: Generated assembly does not contain action '"
                        + actions[i].Name + "'!");
            }
            return newActions;
        }
Пример #40
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.Append(NamesOfEntities.Variable(Left));
     sourceCode.Append(".Clear()");
     sourceCode.Append(";\n");
 }
Пример #41
0
 public override void Emit(SourceBuilder sourceCode)
 {
     String recordVar = "emit_value_" + fetchId().ToString();
     sourceCode.AppendFront("object " + recordVar + " = ");
     ToRecordExpression.Emit(sourceCode);
     sourceCode.Append(";\n");
     sourceCode.AppendFront("if(" + recordVar + " != null)\n");
     sourceCode.AppendFront("((GRGEN_LGSP.LGSPGraphProcessingEnvironment)actionEnv).Recorder.Write("
             + "GRGEN_LIBGR.EmitHelper.ToStringNonNull(" + recordVar + ", graph));\n");
 }
Пример #42
0
		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);
			}
		}
Пример #43
0
 public override void Emit(SourceBuilder sourceCode)
 {
     if(CaseConstExpression != null)
     {
         sourceCode.AppendFront("case ");
         CaseConstExpression.Emit(sourceCode);
         sourceCode.Append(": ");
     }
     else
         sourceCode.AppendFront("default: ");
     sourceCode.Append("{\n");
     foreach(Yielding statement in Statements)
         statement.Emit(sourceCode);
     sourceCode.AppendFront("break;\n");
     sourceCode.AppendFront("}\n");
 }
Пример #44
0
        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");
        }
Пример #45
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.Append(NamesOfEntities.Variable(Left));
     sourceCode.Append(".RemoveAt(");
     if(Right==null)
         sourceCode.Append(NamesOfEntities.Variable(Left) + ".Count-1");
     else
         Right.Emit(sourceCode);
     sourceCode.Append(")");
     sourceCode.Append(";\n");
 }
Пример #46
0
        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");
        }
Пример #47
0
        /// <summary>
        /// Generates an LGSPAction object for the given scheduled search plan.
        /// </summary>
        /// <param name="action">Needed for the rule pattern and the name</param>
        /// <param name="sourceOutputFilename">null if no output file needed</param>
        public LGSPAction GenerateAction(ScheduledSearchPlan scheduledSearchPlan, LGSPAction action,
            String modelAssemblyLocation, String actionAssemblyLocation, String sourceOutputFilename)
        {
            SourceBuilder sourceCode = new SourceBuilder(CommentSourceCode);
            GenerateFileHeaderForActionsFile(sourceCode, model.GetType().Namespace, action.rulePattern.GetType().Namespace);

            // can't generate new subpattern matchers due to missing scheduled search plans for them / missing graph analyze data
            Debug.Assert(action.rulePattern.patternGraph.embeddedGraphsPlusInlined.Length == 0);

            GenerateActionAndMatcher(sourceCode, action.rulePattern, false);

            // close namespace
            sourceCode.Append("}");

            // write generated source to file if requested
            if(sourceOutputFilename != null)
            {
                StreamWriter writer = new StreamWriter(sourceOutputFilename);
                writer.Write(sourceCode.ToString());
                writer.Close();
            }

            // set up compiler
            CSharpCodeProvider compiler = new CSharpCodeProvider();
            CompilerParameters compParams = GetDynCompilerSetup(modelAssemblyLocation, actionAssemblyLocation);

//            Stopwatch compilerWatch = Stopwatch.StartNew();

            // compile generated code
            CompilerResults compResults = compiler.CompileAssemblyFromSource(compParams, sourceCode.ToString());
            if(compResults.Errors.HasErrors)
            {
                String errorMsg = compResults.Errors.Count + " Errors:";
                foreach(CompilerError error in compResults.Errors)
                    errorMsg += Environment.NewLine + "Line: " + error.Line + " - " + error.ErrorText;
                throw new ArgumentException("Illegal dynamic C# source code produced for actions \"" + action.Name + "\": " + errorMsg);
            }

            // create action instance
            Object obj = compResults.CompiledAssembly.CreateInstance("de.unika.ipd.grGen.lgspActions.DynAction_" + action.Name);

//            long compSourceTicks = compilerWatch.ElapsedTicks;
//            Console.WriteLine("GenMatcher: Compile source: {0} us", compSourceTicks / (Stopwatch.Frequency / 1000000));
            return (LGSPAction) obj;
        }
Пример #48
0
        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");
        }
Пример #49
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.AppendFront("do {\n");
     foreach(Yielding statement in LoopedStatements)
         statement.Emit(sourceCode);
     sourceCode.AppendFront("} while(");
     Condition.Emit(sourceCode);
     sourceCode.Append(");\n");
 }
Пример #50
0
        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");
        }
Пример #51
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.AppendFront("if(");
     Condition.Emit(sourceCode);
     sourceCode.Append(") {\n");
     foreach(Yielding statement in TrueCaseStatements)
         statement.Emit(sourceCode);
     if(FalseCaseStatements != null)
     {
         sourceCode.AppendFront("} else {\n");
         foreach(Yielding statement in FalseCaseStatements)
             statement.Emit(sourceCode);
     }
     sourceCode.AppendFront("}\n");
 }
Пример #52
0
        public override void Emit(SourceBuilder sourceCode)
        {
            String highlightValuesArray = "highlight_values_" + fetchId().ToString();
		    sourceCode.AppendFront("List<object> " + highlightValuesArray + " = new List<object>();");
    	    String highlightSourceNamesArray = "highlight_source_names_" + fetchId().ToString();
		    sourceCode.AppendFront("List<string> " + highlightSourceNamesArray + " = new List<string>();");
            foreach(Expression value in Values)
            {
			    sourceCode.AppendFront(highlightValuesArray + ".Add(");
			    value.Emit(sourceCode);
			    sourceCode.Append(");\n");
            }
            foreach(Expression sourceName in SourceNames)
            {
                sourceCode.AppendFront(highlightSourceNamesArray + ".Add((string)");
                sourceName.Emit(sourceCode);
                sourceCode.Append(");\n");
            }
            sourceCode.AppendFront("((GRGEN_LGSP.LGSPSubactionAndOutputAdditionEnvironment)actionEnv).DebugHighlighting(");
            Message.Emit(sourceCode);
            sourceCode.Append(", " + highlightValuesArray + ", " + highlightSourceNamesArray);
            sourceCode.Append(");\n");
        }
Пример #53
0
        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");
                }
            }
        }
Пример #54
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.AppendFront("((GRGEN_LGSP.LGSPSubactionAndOutputAdditionEnvironment)actionEnv).DebugHalting(");
     Message.Emit(sourceCode);
     foreach(Expression value in Values)
     {
         sourceCode.Append(", ");
         value.Emit(sourceCode);
     }
     sourceCode.Append(");\n");
 }
Пример #55
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.Append("GRGEN_LIBGR.ContainerHelper.ExceptChanged(");
     sourceCode.Append(NamesOfEntities.Variable(Left));
     sourceCode.Append(", ");
     Right.Emit(sourceCode);
     sourceCode.Append(")");
     sourceCode.Append(";\n");
 }
Пример #56
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.Append(NamesOfEntities.Variable(Left));
     if(Right == null)
         sourceCode.Append(".Dequeue(");
     else
     {
         sourceCode.Append(".DequeueAt(");
         Right.Emit(sourceCode);
     }
     sourceCode.Append(")");
     sourceCode.Append(";\n");
 }
Пример #57
0
        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");
        }
Пример #58
0
 public override void Emit(SourceBuilder sourceCode)
 {
     sourceCode.AppendFront("switch(");
     SwitchExpression.Emit(sourceCode);
     sourceCode.Append(") {\n");
     foreach(CaseStatement statement in CaseStatements)
         statement.Emit(sourceCode);
     sourceCode.AppendFront("}\n");
 }
Пример #59
0
 public override string ToString()
 {
     String fromStr = "";
     SourceBuilder sbFrom = new SourceBuilder();
     if(From != null)
     {
         sbFrom.Append(Index.Name);
         if(IncludingFrom)
             sbFrom.Append("<=");
         else
             sbFrom.Append("<");
         From.Emit(sbFrom);
         fromStr = sbFrom.ToString();
     }
     String toStr = "";
     SourceBuilder sbTo = new SourceBuilder();
     if(To != null)
     {
         sbTo.Append(Index.Name);
         if(IncludingTo)
             sbTo.Append(">=");
         else
             sbTo.Append(">");
         To.Emit(sbTo);
         toStr = sbTo.ToString();
     }
     if(From == null && To == null)
         return "descending(" + Index.Name + ")";
     else
         return "descending(" + fromStr + " " + toStr + ")";
 }
Пример #60
0
        private void GenerateInternalDefinedSequenceApplicationMethodStub(SourceBuilder source, DefinedSequenceInfo sequence, String externalActionsExtensionFilename)
        {
            source.AppendFrontFormat("// You must implement the following function in the same partial class in ./{0}\n", externalActionsExtensionFilename);

            source.AppendFront("//public static bool ApplyXGRS_" + sequence.Name + "(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv");
            for(int i = 0; i < sequence.Parameters.Length; ++i)
            {
                source.Append(", " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i]), model) + " var_");
                source.Append(sequence.Parameters[i]);
            }
            for(int i = 0; i < sequence.OutParameters.Length; ++i)
            {
                source.Append(", ref " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model) + " var_");
                source.Append(sequence.OutParameters[i]);
            }
            source.Append(")\n");
        }