本文整理汇总了C#中de.unika.ipd.grGen.lgsp.SourceBuilder.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# SourceBuilder.ToString方法的具体用法?C# SourceBuilder.ToString怎么用?C# SourceBuilder.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类de.unika.ipd.grGen.lgsp.SourceBuilder
的用法示例。
在下文中一共展示了SourceBuilder.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EmitSequenceComputation
//.........这里部分代码省略.........
source.AppendFront("List<object> values = new List<object>();\n");
source.AppendFront("List<string> annotations = new List<string>();\n");
for(int i = 1; i < seqDebug.ArgExprs.Count; ++i)
{
if(i % 2 == 1)
source.AppendFront("values.Add(" + GetSequenceExpression(seqDebug.ArgExprs[i], source) + ");\n");
else
source.AppendFront("annotations.Add((string)" + GetSequenceExpression(seqDebug.ArgExprs[i], source) + ");\n");
}
source.AppendFront("procEnv.DebugHighlighting(" + GetSequenceExpression(seqDebug.ArgExprs[0], source) + ", values, annotations);\n");
source.AppendFront(SetResultVar(seqDebug, "null"));
break;
}
case SequenceComputationType.Emit:
{
SequenceComputationEmit seqEmit = (SequenceComputationEmit)seqComp;
bool declarationEmitted = false;
for(int i = 0; i < seqEmit.Expressions.Count; ++i)
{
if(!(seqEmit.Expressions[i] is SequenceExpressionConstant))
{
string emitVal = "emitval_" + seqEmit.Id;
if(!declarationEmitted) {
source.AppendFront("object " + emitVal + ";\n");
declarationEmitted = true;
}
source.AppendFront(emitVal + " = " + GetSequenceExpression(seqEmit.Expressions[i], source) + ";\n");
if(seqEmit.Expressions[i].Type(env) == ""
|| seqEmit.Expressions[i].Type(env).StartsWith("set<") || seqEmit.Expressions[i].Type(env).StartsWith("map<")
|| seqEmit.Expressions[i].Type(env).StartsWith("array<") || seqEmit.Expressions[i].Type(env).StartsWith("deque<"))
{
source.AppendFront("if(" + emitVal + " is IDictionary)\n");
source.AppendFront("\tprocEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString((IDictionary)" + emitVal + ", graph));\n");
source.AppendFront("else if(" + emitVal + " is IList)\n");
source.AppendFront("\tprocEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString((IList)" + emitVal + ", graph));\n");
source.AppendFront("else if(" + emitVal + " is GRGEN_LIBGR.IDeque)\n");
source.AppendFront("\tprocEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString((GRGEN_LIBGR.IDeque)" + emitVal + ", graph));\n");
source.AppendFront("else\n\t");
}
source.AppendFront("procEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString(" + emitVal + ", graph));\n");
}
else
{
SequenceExpressionConstant constant = (SequenceExpressionConstant)seqEmit.Expressions[i];
if(constant.Constant is string)
{
String text = (string)constant.Constant;
text = text.Replace("\n", "\\n");
text = text.Replace("\r", "\\r");
text = text.Replace("\t", "\\t");
source.AppendFront("procEnv.EmitWriter.Write(\"" + text + "\");\n");
}
else
source.AppendFront("procEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToString(" + GetSequenceExpression(seqEmit.Expressions[i], source) + ", graph));\n");
}
}
source.AppendFront(SetResultVar(seqEmit, "null"));
break;
}
case SequenceComputationType.Record:
{
SequenceComputationRecord seqRec = (SequenceComputationRecord)seqComp;
if(!(seqRec.Expression is SequenceExpressionConstant))
{
示例2: GetSequenceExpression
//.........这里部分代码省略.........
}
else
{
container = GetSequenceExpression(seqIn.ContainerExpr, source);
ContainerType = seqIn.ContainerExpr.Type(env);
}
if(ContainerType == "")
{
SourceBuilder sb = new SourceBuilder();
string sourceExpr = GetSequenceExpression(seqIn.Expr, source);
string containerVar = "tmp_eval_once_" + seqIn.Id;
source.AppendFront("object " + containerVar + " = null;\n");
sb.AppendFront("((" + containerVar + " = " + container + ") is IList ? ");
string array = "((System.Collections.IList)" + containerVar + ")";
sb.AppendFront(array + ".Contains(" + sourceExpr + ")");
sb.AppendFront(" : ");
sb.AppendFront(containerVar + " is GRGEN_LIBGR.IDeque ? ");
string deque = "((GRGEN_LIBGR.IDeque)" + containerVar + ")";
sb.AppendFront(deque + ".Contains(" + sourceExpr + ")");
sb.AppendFront(" : ");
string dictionary = "((System.Collections.IDictionary)" + containerVar + ")";
sb.AppendFront(dictionary + ".Contains(" + sourceExpr + ")");
sb.AppendFront(")");
return sb.ToString();
}
else if(ContainerType.StartsWith("array"))
{
string array = container;
string arrayValueType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(ContainerType), model);
string sourceExpr = "((" + arrayValueType + ")" + GetSequenceExpression(seqIn.Expr, source) + ")";
return array + ".Contains(" + sourceExpr + ")";
}
else if(ContainerType.StartsWith("deque"))
{
string deque = container;
string dequeValueType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(ContainerType), model);
string sourceExpr = "((" + dequeValueType + ")" + GetSequenceExpression(seqIn.Expr, source) + ")";
return deque + ".Contains(" + sourceExpr + ")";
}
else
{
string dictionary = container;
string dictSrcType = TypesHelper.XgrsTypeToCSharpType(TypesHelper.ExtractSrc(ContainerType), model);
string sourceExpr = "((" + dictSrcType + ")" + GetSequenceExpression(seqIn.Expr, source) + ")";
return dictionary + ".ContainsKey(" + sourceExpr + ")";
}
}
case SequenceExpressionType.IsVisited:
{
SequenceExpressionIsVisited seqIsVisited = (SequenceExpressionIsVisited)expr;
return "graph.IsVisited("
+ "(GRGEN_LIBGR.IGraphElement)" + GetVar(seqIsVisited.GraphElementVar)
+ ", (int)" + GetSequenceExpression(seqIsVisited.VisitedFlagExpr, source)
+ ")";
}
示例3: ToString
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 + ")";
}
示例4: CompileComparisonMatchers
private static void CompileComparisonMatchers()
{
for(int i = GraphMatchingState.candidatesForCompilation.Count - 1; i >= 0; --i)
{
LGSPGraph graph = GraphMatchingState.candidatesForCompilation[i];
if(graph.matchingState.changesCounterAtInterpretationPlanBuilding != graph.ChangesCounter)
GraphMatchingState.candidatesForCompilation.RemoveAt(i);
}
SourceBuilder sourceCode = new SourceBuilder();
sourceCode.AppendFront("using System;\n"
+ "using System.Collections.Generic;\n"
+ "using GRGEN_LIBGR = de.unika.ipd.grGen.libGr;\n"
+ "using GRGEN_LGSP = de.unika.ipd.grGen.lgsp;\n\n");
sourceCode.AppendFront("namespace de.unika.ipd.grGen.lgspComparisonMatchers\n");
sourceCode.AppendFront("{\n");
sourceCode.Indent();
foreach(LGSPGraph graph in GraphMatchingState.candidatesForCompilation)
((InterpretationPlanStart)graph.matchingState.interpretationPlan).Emit(sourceCode);
sourceCode.Append("}");
#if DUMP_COMPILED_MATCHER
using(StreamWriter sw = new StreamWriter("comparison_matcher_" + GraphMatchingState.candidatesForCompilation[0].GraphId + ".cs"))
sw.Write(sourceCode.ToString());
#endif
// set up compiler
CSharpCodeProvider compiler = new CSharpCodeProvider();
CompilerParameters compParams = new CompilerParameters();
compParams.ReferencedAssemblies.Add("System.dll");
compParams.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(BaseGraph)).Location);
compParams.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(LGSPGraph)).Location);
compParams.GenerateInMemory = true;
compParams.CompilerOptions = "/optimize";
// building methods with MSIL would be highly preferable, but is much harder of course
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 C# source code produced for graph comparison: " + errorMsg);
}
// create comparison matcher instances
foreach(LGSPGraph graph in GraphMatchingState.candidatesForCompilation)
{
graph.matchingState.compiledMatcher = (GraphComparisonMatcher)compResults.CompiledAssembly.CreateInstance(
"de.unika.ipd.grGen.lgspComparisonMatchers.ComparisonMatcher_" + graph.graphID);
if(graph.matchingState.compiledMatcher == null)
throw new ArgumentException("Internal error: Generated assembly does not contain comparison matcher 'ComparisonMatcher_" + graph.graphID + "'!");
++GraphMatchingState.numCompiledMatchers;
}
GraphMatchingState.candidatesForCompilation.Clear();
++GraphMatchingState.numCompilationPasses;
}
示例5: GenerateAction
/// <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;
}
示例6: Custom
//.........这里部分代码省略.........
foreach(LGSPAction action in actions.Values)
{
oldActions[i] = action;
++i;
}
}
else
{
oldActions = new LGSPAction[args.Length - 1];
for(int i = 0; i < oldActions.Length; i++)
{
oldActions[i] = (LGSPAction)GetAction((String)args[i + 1]);
if(oldActions[i] == null)
throw new ArgumentException("'" + (String)args[i + 1] + "' is not the name of an action!\n"
+ "Please use 'show actions' to get a list of the available names.");
}
}
int startticks = Environment.TickCount;
matcherGenerator.LazyNegativeIndependentConditionEvaluation = LazyNIC;
matcherGenerator.InlineIndependents = InlineIndependents;
matcherGenerator.Profile = Profile;
LGSPAction[] newActions = matcherGenerator.GenerateActions(graph, modelAssemblyName,
actionsAssemblyName, oldActions);
int stopticks = Environment.TickCount;
Console.Write("Searchplans for actions ");
for(int i = 0; i < oldActions.Length; i++)
{
actions[oldActions[i].Name] = newActions[i];
if(i != 0) Console.Write(", ");
Console.Write("'" + oldActions[i].Name + "'");
}
Console.WriteLine(" generated in " + (stopticks - startticks) + " ms.");
return;
}
case "dump_sourcecode":
if(args.Length != 2)
throw new ArgumentException("Usage: dump_sourcecode <bool>\n"
+ "If <bool> == true, C# files will be dumped for new searchplans.");
if(!bool.TryParse((String) args[1], out matcherGenerator.DumpDynSourceCode))
throw new ArgumentException("Illegal bool value specified: \"" + (String) args[1] + "\"");
return;
case "dump_searchplan":
if(args.Length != 2)
throw new ArgumentException("Usage: dump_searchplan <bool>\n"
+ "If <bool> == true, VCG and TXT files will be dumped for new searchplans.");
if(!bool.TryParse((String) args[1], out matcherGenerator.DumpSearchPlan))
throw new ArgumentException("Illegal bool value specified: \"" + (String) args[1] + "\"");
return;
case "explain":
{
if(args.Length != 2)
throw new ArgumentException("Usage: explain <name>\n"
+ "Explains the searchplan of the given action.");
LGSPAction action = (LGSPAction)GetAction((String)args[1]);
if(action == null)
throw new ArgumentException("'" + (String)args[1] + "' is not the name of an action!\n"
+ "Please use 'show actions' to get a list of the available names.");
if(action.patternGraph.schedules[0] == null)
{
LGSPGraphStatistics graphStatistics = null;
if(StatisticsPath != null)
{
Console.WriteLine("static search plans from " + StatisticsPath);
graphStatistics = new LGSPGraphStatistics(graph.Model);
graphStatistics.Parse(StatisticsPath);
}
else
Console.WriteLine("static search plans");
LGSPMatcherGenerator matcherGen = new LGSPMatcherGenerator(graph.Model);
matcherGen.FillInStaticSearchPlans(graphStatistics, InlineIndependents, action);
}
SourceBuilder sb = new SourceBuilder();
foreach(KeyValuePair<LGSPMatchingPattern, LGSPMatchingPattern> usedSubpattern
in action.rulePattern.patternGraph.usedSubpatterns)
{
usedSubpattern.Key.patternGraph.Explain(sb, graph.Model);
}
action.patternGraph.Explain(sb, graph.Model);
Console.WriteLine(sb.ToString());
return;
}
}
invalidCommand:
throw new ArgumentException("Possible commands:\n"
+ "- gen_searchplan: Generates a new searchplan for a given action\n"
+ " depending on a previous graph analysis\n"
+ "- explain: explains the searchplan in use for a given action\n"
+ "- dump_sourcecode: Sets dumping of C# files for new searchplans\n"
+ "- dump_searchplan: Sets dumping of VCG and TXT files of new\n"
+ " searchplans (with some intermediate steps)");
}
示例7: buildParallelPickFromIndexSetup
/// <summary>
/// Search program operations implementing the
/// setup parallelized PickFromIndex search plan operation
/// are created and inserted into search program
/// </summary>
private SearchProgramOperation buildParallelPickFromIndexSetup(
SearchProgramOperation insertionPoint,
SearchPlanNode target,
IndexAccess index)
{
bool isNode = target.NodeType == PlanNodeType.Node;
string negativeIndependentNamePrefix = "";
PatternGraph patternGraph = patternGraphWithNestingPatterns.Peek();
string iterationType = TypesHelper.TypeName(index.Index is AttributeIndexDescription ?
((AttributeIndexDescription)index.Index).GraphElementType :
((IncidenceCountIndexDescription)index.Index).StartNodeType);
string indexSetType = NamesOfEntities.IndexSetType(model.ModelName);
// iterate available index elements
GetCandidateByIterationParallelSetup elementsIteration;
if(index is IndexAccessEquality)
{
IndexAccessEquality indexEquality = (IndexAccessEquality)index;
SourceBuilder equalityExpression = new SourceBuilder();
indexEquality.Expr.Emit(equalityExpression);
elementsIteration =
new GetCandidateByIterationParallelSetup(
GetCandidateByIterationType.IndexElements,
target.PatternElement.Name,
index.Index.Name,
iterationType,
indexSetType,
IndexAccessType.Equality,
equalityExpression.ToString(),
isNode,
rulePatternClassName,
patternGraph.name,
parameterNames,
wasIndependentInlined(patternGraph, indexOfSchedule),
emitProfiling,
packagePrefixedActionName,
!firstLoopPassed);
}
else if(index is IndexAccessAscending)
{
IndexAccessAscending indexAscending = (IndexAccessAscending)index;
SourceBuilder fromExpression = new SourceBuilder();
if(indexAscending.From != null)
indexAscending.From.Emit(fromExpression);
SourceBuilder toExpression = new SourceBuilder();
if(indexAscending.To != null)
indexAscending.To.Emit(toExpression);
elementsIteration =
new GetCandidateByIterationParallelSetup(
GetCandidateByIterationType.IndexElements,
target.PatternElement.Name,
index.Index.Name,
iterationType,
indexSetType,
IndexAccessType.Ascending,
indexAscending.From != null ? fromExpression.ToString() : null,
indexAscending.IncludingFrom,
indexAscending.To != null ? toExpression.ToString() : null,
indexAscending.IncludingTo,
isNode,
rulePatternClassName,
patternGraph.name,
parameterNames,
wasIndependentInlined(patternGraph, indexOfSchedule),
emitProfiling,
packagePrefixedActionName,
!firstLoopPassed);
}
else //if(index is IndexAccessDescending)
{
IndexAccessDescending indexDescending = (IndexAccessDescending)index;
SourceBuilder fromExpression = new SourceBuilder();
if(indexDescending.From != null)
indexDescending.From.Emit(fromExpression);
SourceBuilder toExpression = new SourceBuilder();
if(indexDescending.To != null)
indexDescending.To.Emit(toExpression);
elementsIteration =
new GetCandidateByIterationParallelSetup(
GetCandidateByIterationType.IndexElements,
target.PatternElement.Name,
index.Index.Name,
iterationType,
indexSetType,
IndexAccessType.Descending,
indexDescending.From != null ? fromExpression.ToString() : null,
indexDescending.IncludingFrom,
indexDescending.To != null ? toExpression.ToString() : null,
indexDescending.IncludingTo,
isNode,
rulePatternClassName,
patternGraph.name,
parameterNames,
wasIndependentInlined(patternGraph, indexOfSchedule),
emitProfiling,
//.........这里部分代码省略.........
示例8: GenerateSearchProgramAlternative
/// <summary>
/// Generates the search program for the given alternative
/// </summary>
SearchProgram GenerateSearchProgramAlternative(LGSPMatchingPattern matchingPattern, Alternative alt)
{
// build pass: build nested program from scheduled search plans of the alternative cases
SearchProgramBuilder searchProgramBuilder = new SearchProgramBuilder();
SearchProgram searchProgram = searchProgramBuilder.BuildSearchProgram(model, matchingPattern, alt, false, Profile);
#if DUMP_SEARCHPROGRAMS
// dump built search program for debugging
SourceBuilder builder = new SourceBuilder(CommentSourceCode);
searchProgram.Dump(builder);
StreamWriter writer = new StreamWriter(matchingPattern.name + "_" + alt.name + "_" + searchProgram.Name + "_built_dump.txt");
writer.Write(builder.ToString());
writer.Close();
#endif
// complete pass: complete check operations in all search programs
SearchProgramCompleter searchProgramCompleter = new SearchProgramCompleter();
searchProgramCompleter.CompleteCheckOperationsInAllSearchPrograms(searchProgram);
#if DUMP_SEARCHPROGRAMS
// dump completed search program for debugging
builder = new SourceBuilder(CommentSourceCode);
searchProgram.Dump(builder);
writer = new StreamWriter(matchingPattern.name + "_" + alt.name + "_" + searchProgram.Name + "_completed_dump.txt");
writer.Write(builder.ToString());
writer.Close();
#endif
return searchProgram;
}
示例9: insertVariableDeclarationsNegIdpt
private SearchProgramOperation insertVariableDeclarationsNegIdpt(SearchProgramOperation insertionPoint, PatternGraph patternGraph)
{
foreach(PatternNode node in patternGraph.nodesPlusInlined)
{
if(node.defToBeYieldedTo && patternGraph.WasInlinedHere(node.originalSubpatternEmbedding))
{
insertionPoint = insertionPoint.Append(
new DeclareDefElement(EntityType.Node, "GRGEN_LGSP.LGSPNode", node.Name, "null")
);
}
}
foreach(PatternEdge edge in patternGraph.edgesPlusInlined)
{
if(edge.defToBeYieldedTo && patternGraph.WasInlinedHere(edge.originalSubpatternEmbedding))
{
insertionPoint = insertionPoint.Append(
new DeclareDefElement(EntityType.Edge, "GRGEN_LGSP.LGSPEdge", edge.Name, "null")
);
}
}
foreach(PatternVariable var in patternGraph.variablesPlusInlined)
{
if(var.defToBeYieldedTo && patternGraph.WasInlinedHere(var.originalSubpatternEmbedding))
{
String initializationExpression;
if(var.initialization != null)
{
SourceBuilder builder = new SourceBuilder();
var.initialization.Emit(builder);
initializationExpression = builder.ToString();
}
else
{
string typeName = TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(var.type), model);
initializationExpression = TypesHelper.DefaultValueString(typeName, model);
}
insertionPoint = insertionPoint.Append(
new DeclareDefElement(EntityType.Variable, TypesHelper.TypeName(var.type), var.Name,
initializationExpression)
);
}
}
return insertionPoint;
}
示例10: buildCondition
/// <summary>
/// Search program operations implementing the
/// Condition search plan operation
/// are created and inserted into search program
/// </summary>
private SearchProgramOperation buildCondition(
SearchProgramOperation insertionPoint,
int currentOperationIndex,
PatternCondition condition)
{
// generate c#-code-string out of condition expression ast
SourceBuilder conditionExpression = new SourceBuilder();
condition.ConditionExpression.Emit(conditionExpression);
// check condition with current partial match
CheckPartialMatchByCondition checkCondition =
new CheckPartialMatchByCondition(conditionExpression.ToString(),
condition.NeededNodes,
condition.NeededEdges,
condition.NeededVariables);
insertionPoint = insertionPoint.Append(checkCondition);
//---------------------------------------------------------------------------
// build next operation
insertionPoint = BuildScheduledSearchPlanOperationIntoSearchProgram(
currentOperationIndex + 1,
insertionPoint);
//---------------------------------------------------------------------------
return insertionPoint;
}
示例11: buildAssignVar
/// <summary>
/// Search program operations implementing the
/// AssignVar search plan operation
/// are created and inserted into search program
/// </summary>
private SearchProgramOperation buildAssignVar(
SearchProgramOperation insertionPoint,
int currentOperationIndex,
PatternVariable variable,
Expression expression)
{
// generate c#-code-string out of condition expression ast
SourceBuilder assignmentExpression = new SourceBuilder();
expression.Emit(assignmentExpression);
// get candidate from other element (the cast is simply the following type check)
AssignVariableFromExpression assignVar =
new AssignVariableFromExpression(
variable.Name,
TypesHelper.TypeName(variable.type),
assignmentExpression.ToString());
insertionPoint = insertionPoint.Append(assignVar);
//---------------------------------------------------------------------------
// build next operation
insertionPoint = BuildScheduledSearchPlanOperationIntoSearchProgram(
currentOperationIndex + 1,
insertionPoint);
//---------------------------------------------------------------------------
return insertionPoint;
}
示例12: buildPickByUnique
/// <summary>
/// Search program operations implementing the
/// PickByUnique or PickByUniqueDependent search plan operation
/// are created and inserted into search program
/// </summary>
private SearchProgramOperation buildPickByUnique(
SearchProgramOperation insertionPoint,
int currentOperationIndex,
SearchPlanNode target,
UniqueLookup uniqueLookup,
IsomorphyInformation isomorphy)
{
bool isNode = target.NodeType == PlanNodeType.Node;
string negativeIndependentNamePrefix = NegativeIndependentNamePrefix(patternGraphWithNestingPatterns.Peek());
SourceBuilder expression = new SourceBuilder();
uniqueLookup.Expr.Emit(expression);
// get candidate from unique index, only creates variable to hold it, get is fused with check for index membership
GetCandidateByDrawing elementByUnique =
new GetCandidateByDrawing(
GetCandidateByDrawingType.MapByUnique,
target.PatternElement.Name,
expression.ToString(),
isNode);
insertionPoint = insertionPoint.Append(elementByUnique);
// check existence of candidate in unique map
CheckCandidateMapByUnique checkElementInUniqueMap =
new CheckCandidateMapByUnique(
target.PatternElement.Name,
isNode);
insertionPoint = insertionPoint.Append(checkElementInUniqueMap);
// check type of candidate
insertionPoint = decideOnAndInsertCheckType(insertionPoint, target);
// check connectedness of candidate
SearchProgramOperation continuationPointAfterConnectednessCheck;
if(isNode)
{
insertionPoint = decideOnAndInsertCheckConnectednessOfNodeFromLookupOrPickOrMap(
insertionPoint, (SearchPlanNodeNode)target, out continuationPointAfterConnectednessCheck);
}
else
{
insertionPoint = decideOnAndInsertCheckConnectednessOfEdgeFromLookupOrPickOrMap(
insertionPoint, (SearchPlanEdgeNode)target, out continuationPointAfterConnectednessCheck);
}
if(continuationPointAfterConnectednessCheck == insertionPoint)
continuationPointAfterConnectednessCheck = null;
// check candidate for isomorphy
if(isomorphy.CheckIsMatchedBit)
{
CheckCandidateForIsomorphy checkIsomorphy =
new CheckCandidateForIsomorphy(
target.PatternElement.Name,
isomorphy.PatternElementsToCheckAgainstAsListOfStrings(),
negativeIndependentNamePrefix,
isNode,
isoSpaceNeverAboveMaxIsoSpace,
isomorphy.Parallel,
isomorphy.LockForAllThreads);
insertionPoint = insertionPoint.Append(checkIsomorphy);
}
// check candidate for global isomorphy
if(programType == SearchProgramType.Subpattern
|| programType == SearchProgramType.AlternativeCase
|| programType == SearchProgramType.Iterated)
{
if(!isomorphy.TotallyHomomorph)
{
CheckCandidateForIsomorphyGlobal checkIsomorphy =
new CheckCandidateForIsomorphyGlobal(
target.PatternElement.Name,
isomorphy.GloballyHomomorphPatternElementsAsListOfStrings(),
isNode,
isoSpaceNeverAboveMaxIsoSpace,
isomorphy.Parallel);
insertionPoint = insertionPoint.Append(checkIsomorphy);
}
}
// check candidate for pattern path isomorphy
if(patternGraphWithNestingPatterns.Peek().isPatternGraphOnPathFromEnclosingPatternpath)
{
CheckCandidateForIsomorphyPatternPath checkIsomorphy =
new CheckCandidateForIsomorphyPatternPath(
target.PatternElement.Name,
isNode,
patternGraphWithNestingPatterns.Peek().isPatternpathLocked,
getCurrentLastMatchAtPreviousNestingLevel());
insertionPoint = insertionPoint.Append(checkIsomorphy);
}
// accept candidate (write isomorphy information)
if(isomorphy.SetIsMatchedBit)
{
//.........这里部分代码省略.........
示例13: buildDefToBeYieldedTo
/// <summary>
/// Search program operations implementing the
/// DefElementToBeYieldedTo search plan operation
/// are created and inserted into search program
/// </summary>
private SearchProgramOperation buildDefToBeYieldedTo(
SearchProgramOperation insertionPoint,
int currentOperationIndex,
object target)
{
if(target is PatternVariable)
{
PatternVariable var = (PatternVariable)target;
String initializationExpression;
if(var.initialization != null)
{
SourceBuilder builder = new SourceBuilder();
var.initialization.Emit(builder);
initializationExpression = builder.ToString();
}
else
{
string typeName = TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(var.type), model);
initializationExpression = TypesHelper.DefaultValueString(typeName, model);
}
insertionPoint = insertionPoint.Append(
new DeclareDefElement(EntityType.Variable, TypesHelper.TypeName(var.type), var.Name,
initializationExpression)
);
}
else
{
if(((SearchPlanNode)target).PatternElement is PatternNode)
{
PatternNode node = (PatternNode)((SearchPlanNode)target).PatternElement;
String initializationExpression;
if(node.initialization != null)
{
SourceBuilder builder = new SourceBuilder();
node.initialization.Emit(builder);
initializationExpression = builder.ToString();
}
else
{
initializationExpression = "null";
}
insertionPoint = insertionPoint.Append(
new DeclareDefElement(EntityType.Node, "GRGEN_LGSP.LGSPNode", node.Name, initializationExpression)
);
}
else
{
PatternEdge edge = (PatternEdge)((SearchPlanNode)target).PatternElement;
String initializationExpression;
if(edge.initialization != null)
{
SourceBuilder builder = new SourceBuilder();
edge.initialization.Emit(builder);
initializationExpression = builder.ToString();
}
else
{
initializationExpression = "null";
}
insertionPoint = insertionPoint.Append(
new DeclareDefElement(EntityType.Edge, "GRGEN_LGSP.LGSPEdge", edge.Name, initializationExpression)
);
}
}
//---------------------------------------------------------------------------
// build next operation
insertionPoint = BuildScheduledSearchPlanOperationIntoSearchProgram(
currentOperationIndex + 1,
insertionPoint);
//---------------------------------------------------------------------------
return insertionPoint;
}
示例14: DumpScheduledSearchPlan
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;
}
}*/
}
示例15: buildParallelPickFromIndex
/// <summary>
/// Search program operations implementing the
/// parallelized PickFromIndex search plan operation
/// are created and inserted into search program
/// </summary>
private SearchProgramOperation buildParallelPickFromIndex(
SearchProgramOperation insertionPoint,
int currentOperationIndex,
SearchPlanNode target,
IndexAccess index,
IsomorphyInformation isomorphy)
{
bool isNode = target.NodeType == PlanNodeType.Node;
string negativeIndependentNamePrefix = "";
string iterationType = TypesHelper.TypeName(index.Index is AttributeIndexDescription ?
((AttributeIndexDescription)index.Index).GraphElementType :
((IncidenceCountIndexDescription)index.Index).StartNodeType);
string indexSetType = NamesOfEntities.IndexSetType(model.ModelName);
// iterate available index elements
GetCandidateByIterationParallel elementsIteration;
if(index is IndexAccessEquality)
{
IndexAccessEquality indexEquality = (IndexAccessEquality)index;
SourceBuilder equalityExpression = new SourceBuilder();
indexEquality.Expr.Emit(equalityExpression);
elementsIteration =
new GetCandidateByIterationParallel(
GetCandidateByIterationType.IndexElements,
target.PatternElement.Name,
index.Index.Name,
iterationType,
indexSetType,
IndexAccessType.Equality,
equalityExpression.ToString(),
isNode,
emitProfiling,
packagePrefixedActionName,
!firstLoopPassed);
}
else if(index is IndexAccessAscending)
{
IndexAccessAscending indexAscending = (IndexAccessAscending)index;
SourceBuilder fromExpression = new SourceBuilder();
if(indexAscending.From != null)
indexAscending.From.Emit(fromExpression);
SourceBuilder toExpression = new SourceBuilder();
if(indexAscending.To != null)
indexAscending.To.Emit(toExpression);
elementsIteration =
new GetCandidateByIterationParallel(
GetCandidateByIterationType.IndexElements,
target.PatternElement.Name,
index.Index.Name,
iterationType,
indexSetType,
IndexAccessType.Ascending,
indexAscending.From != null ? fromExpression.ToString() : null,
indexAscending.IncludingFrom,
indexAscending.To != null ? toExpression.ToString() : null,
indexAscending.IncludingTo,
isNode,
emitProfiling,
packagePrefixedActionName,
!firstLoopPassed);
}
else //if(index is IndexAccessDescending)
{
IndexAccessDescending indexDescending = (IndexAccessDescending)index;
SourceBuilder fromExpression = new SourceBuilder();
if(indexDescending.From != null)
indexDescending.From.Emit(fromExpression);
SourceBuilder toExpression = new SourceBuilder();
if(indexDescending.To != null)
indexDescending.To.Emit(toExpression);
elementsIteration =
new GetCandidateByIterationParallel(
GetCandidateByIterationType.IndexElements,
target.PatternElement.Name,
index.Index.Name,
iterationType,
indexSetType,
IndexAccessType.Descending,
indexDescending.From != null ? fromExpression.ToString() : null,
indexDescending.IncludingFrom,
indexDescending.To != null ? toExpression.ToString() : null,
indexDescending.IncludingTo,
isNode,
emitProfiling,
packagePrefixedActionName,
!firstLoopPassed);
}
firstLoopPassed = true;
SearchProgramOperation continuationPoint =
insertionPoint.Append(elementsIteration);
elementsIteration.NestedOperationsList =
new SearchProgramList(elementsIteration);
insertionPoint = elementsIteration.NestedOperationsList;
//.........这里部分代码省略.........