internal override XElement CreateXml() { var xRoot = new XElement(XmlConstants.Brick); xRoot.SetAttributeValue(XmlConstants.Type, XmlConstants.XmlIfLogicBeginBrick); //TODO: Anstelle von einem <ifCondition>-Tag wird in der 093 ein formula element mit category="IF_CONDITION" verwendet if (IfCondition != null) { /*var xVariable1 = new XElement(XmlConstants.XmlIfLogicBeginBrick); * xVariable1.Add(IfCondition.CreateXml()); * xRoot.Add(xVariable1);*/ var xElement = IfCondition.CreateXml(); xElement.SetAttributeValue(XmlConstants.Category, XmlConstants.XmlIFCONDITION); var xFormulalist = new XElement(XmlConstants.FormulaList); xFormulalist.Add(xElement); xRoot.Add(xFormulalist); } //xRoot.Add(IfLogicElseBrickReference.CreateXml()); //xRoot.Add(IfLogicEndBrickReference.CreateXml()); return(xRoot); }
public override void GenerateBytecode(ClassesContainer container, ByteBlock context) { int jumpIndex = context.NextOpIndex; IfCondition.GenerateBytecode(container, context); JumpIfFalseCode jumpIfFalse = new JumpIfFalseCode(-1); context.Instructions.Add(jumpIfFalse); foreach (var statement in IfStatements) { statement.GenerateBytecode(container, context); } JumpCode jumpElseIfTrue = new JumpCode(-1); context.Instructions.Add(jumpElseIfTrue); jumpIfFalse.targetIndex = context.NextOpIndex; if (ElseStatements != null) { foreach (var statement in ElseStatements) { statement.GenerateBytecode(container, context); } } jumpElseIfTrue.targetIndex = context.NextOpIndex; }
public static async Task <ComposerStep> BuildComposerStepFromShape(DrawsomeShape shape) { var query = shape.Text; var luisResponse = await new LuisRecognizer("", "").GetPrediction(query); var content = GetContent(luisResponse); var shapeType = luisResponse.TopScoringIntent?.Intent; switch (shapeType) { case nameof(IfCondition): var ifStep = new IfCondition(content, shape); return(ifStep); case nameof(SetProperty): var setStep = new SetProperty(content ?? query, shape); return(setStep); case nameof(TextInput): var textStep = new TextInput(content ?? query, shape); return(textStep); case nameof(HttpRequest): var httpStep = new HttpRequest(content ?? query, shape); return(httpStep); case nameof(SendActivity): default: var sendStep = new SendActivity(content ?? query, shape); return(sendStep); } }
private List <ComposerStep> FindInBotInstanceAndGenerateNew(List <ComposerStep> steps, ComposerStep stepToFind) { var result = new List <ComposerStep>(); for (var i = 0; i < steps.Count; i++) { if (steps[i].RelatedShape.Equals(stepToFind.RelatedShape)) { var stepToReplace = steps[i]; var newStep = Replace(stepToReplace); result.Add(newStep); } else if (steps[i].Type == "Microsoft.IfCondition") { var ifStep = steps[i] as IfCondition; var newIfStep = new IfCondition(ifStep.Condition, ifStep.RelatedShape); newIfStep.Steps.AddRange(FindInBotInstanceAndGenerateNew(ifStep.Steps, stepToFind)); newIfStep.ElseSteps.AddRange(FindInBotInstanceAndGenerateNew(ifStep.ElseSteps, stepToFind)); result.Add(newIfStep); } else { result.Add(steps[i]); } } return(result); }
public override void GenerateCode(CodeGeneration.CodeGenerator cg) { Label endofif = cg.IlGenerator.DefineLabel(); IfCondition.GenerateCode(cg); cg.IlGenerator.Emit(OpCodes.Brfalse, endofif); ThenExpression.GenerateCode(cg); cg.IlGenerator.MarkLabel(endofif); }
/// <summary> /// Processes the conditional statements, executing the first that returns a true condition /// </summary> public void Process() { var success = IfCondition.RunCondition(); if (!success) { ElseCondition?.Invoke(); } }
/// <summary> /// Recursive function used to iterate and determine if a condition is to be met /// </summary> /// <returns> /// A <see cref="bool" /> indicating if a conditional was satisfied and method invoked /// </returns> public bool RunCondition() { if (IfCondition.Invoke()) { Method.Invoke(); return(true); } return(ElseIf != null && ElseIf.RunCondition()); }
public override void Run() { ifCondition = stepSetting as IfCondition; ConditionResult = ExecuteExpression();// 执行表达式结果 if (ConditionResult && statements != null) { foreach (var item in statements) { item.Run(); } } }
// return a list of step from cur root public static async Task <List <ComposerStep> > BuildFromStepUntil(DrawsomePic pic, DrawsomeObj root, DrawsomeObj target, List <ComposerStep> allSteps, HashSet <DrawsomeObj> visited) { var steps = new List <ComposerStep>(); if (root == target) { return(steps); } if (visited.Contains(root)) { return(steps); } visited.Add(root); // only one next if (root.Next.Count != 2) { if (root is DrawsomeShape) { var step = await BuildComposerStepFromShape(root as DrawsomeShape); steps.Add(step); allSteps.Add(step); steps.AddRange(await BuildFromStepUntil(pic, root.Next.FirstOrDefault(), target, allSteps, visited)); } else if (root is DrawsomeLine) { steps.AddRange(await BuildFromStepUntil(pic, root.Next.FirstOrDefault(), target, allSteps, visited)); } } if (root.Next.Count == 2) { if (root is DrawsomeShape) { var firstCommon = NearestObj(pic, root); var step = new IfCondition((root as DrawsomeShape).Text, root as DrawsomeShape); allSteps.Add(step); step.Steps = await BuildFromStepUntil(pic, root.Next.FirstOrDefault(), firstCommon, allSteps, visited); step.ElseSteps = await BuildFromStepUntil(pic, root.Next.LastOrDefault(), firstCommon, allSteps, visited); steps.Add(step); steps.AddRange(await BuildFromStepUntil(pic, firstCommon, target, allSteps, visited)); } } return(steps); }
void IConditional.AppendElseIf(Func <bool> condition, Action method) { if (IfCondition is null) { throw new NullReferenceException(); } if (method is null) { throw new ArgumentNullException(nameof(method)); } IfCondition.AddElseIf(condition, method); }
private static IfCondition CreateIfCondition(List <CondGroupVM> condGroups) { StringBuilder buf = new StringBuilder(); foreach (CondGroupVM condGroup in condGroups) { buf.Append(condGroup.Expression(BaseVM.EMPTY_VALUE)); } IfCondition ifCondition = new IfCondition(); ifCondition.Code = buf.ToString(); ifCondition.QuestionId = condGroups[0].FirstQuestionConstruct.Id; return(ifCondition); }
private static BranchVM CreateIfBranch(IfThenElse ifThenElse, CreateBranchWindowVM window) { BranchVM branch = new BranchVM(BranchVM.TYPE_IF_CODE) { Parent = window }; branch.Init(); branch.CondGroups.Clear(); IfCondition ifCondition = ifThenElse.IfCondition; CreateCondGroups(ifCondition.Code, branch, window.QuestionConstructs); branch.ThenConstruct = EDOUtils.Find(window.ThenConstructs, ifThenElse.ThenConstructId); return(branch); }
public override void LoadReference() { if (IfLogicElseBrickReference != null) { IfLogicElseBrickReference.LoadReference(); } if (IfLogicEndBrickReference != null) { IfLogicEndBrickReference.LoadReference(); } if (IfCondition != null) { IfCondition.LoadReference(); } }
public override void ValidateSemantics(SemanticsValidator validator) { IfCondition.ValidateSemantics(validator); foreach (var statement in IfStatements) { statement.ValidateSemantics(validator); } if (ElseStatements != null) { foreach (var st in ElseStatements) { st.ValidateSemantics(validator); } } }
private List <IDialog> BookSteps() { var steps = new List <IDialog>(); var userName = new TextInput { Property = "user.userProfile.Name", Prompt = new ActivityTemplate("[AskForName]") }; var cityInput = new TextInput { Property = "user.userProfile.destination", Prompt = new ActivityTemplate("[DestinationPrompt]") }; steps.Add(userName); steps.Add(new SendActivity("[AckName]")); steps.Add(cityInput); steps.Add(new SendActivity("[ConfirmInfo]")); var confirm = new ConfirmInput { Prompt = new ActivityTemplate("[ConfirmPrompt]"), Property = "turn.finalConfirmation" }; steps.Add(confirm); var condition = new IfCondition { Condition = "turn.finalConfirmation == true", Steps = new List <IDialog>() { new SendActivity("[ConfirmInfo]") }, ElseSteps = new List <IDialog> { new SendActivity("[NotConfirm]") } }; steps.Add(condition); steps.Add(new EndDialog()); return(steps); }
protected override string[] ifTr(IfCondition if_condition) { dynamic[] info = if_condition.getTranslatorInfo(); string condition = ((Expression)info[0]).expr; string[] if_instructions = instr2Lines((List <Instruction>)info[1]); string[] else_instructions = instr2Lines((List <Instruction>)info[2]); var if_instr_list = new List <string> { "if (" + condition + ") {" }; if_instr_list.AddRange(if_instructions); if_instr_list.Add("}"); if (else_instructions.Length > 0) { if_instr_list.Add("} else {"); if_instr_list.AddRange(else_instructions); if_instr_list.Add("}"); } return(if_instr_list.ToArray()); }
private Stmt ParseStmt() { Stmt result = null; if (this.index == this.tokens.Count) { throw new System.Exception("expected statement, got EOF"); } // <stmt> := print <expr> // <expr> := <string> // | <int> // | <arith_expr> // | <ident> if (this.tokens[this.index].Equals(languageSetting["End"])) { this.index++; } else if (this.tokens[this.index].Equals(languageSetting["Start"])) { this.index++; return(ParseStmt()); } else if (this.tokens[this.index].Equals(languageSetting["Print"])) { this.index++; Print print = new Print(); print.Expr = this.ParseExpr(); result = print; } else if (this.tokens[this.index] == Scanner.Call) { VoidMethodCall vmc = new VoidMethodCall(); vmc.Expr = this.ParseExpr(); result = vmc; } else if (this.tokens[this.index].Equals(languageSetting["VariableDeclaration"])) { this.index++; DeclareVar declareVar = new DeclareVar(); if (this.index < this.tokens.Count && this.tokens[this.index] is string) { declareVar.Ident = (string)this.tokens[this.index]; } else { throw new System.Exception("expected variable name after 'var'"); } this.index++; if (this.index == this.tokens.Count || this.tokens[this.index] != Scanner.Equal) { throw new System.Exception("expected = after 'var ident'"); } this.index++; declareVar.Expr = this.ParseExpr(); result = declareVar; } else if (this.tokens[this.index].Equals(languageSetting["if"])) { this.index++; IfCondition ifCon = new IfCondition(); ifCon.BooleanExp = this.ParseExpr(); if (!this.tokens[++this.index].Equals(languageSetting["Start"])) { throw new System.Exception("Start Expected"); } ifCon.Body = this.ParseStmt(); if (!this.tokens[this.index++].Equals(languageSetting["End"])) { throw new System.Exception("End Expected"); } result = ifCon; } else if (this.tokens[this.index].Equals(languageSetting["while"])) { this.index++; WhileLoop whileLoop = new WhileLoop(); whileLoop.BooleanExp = this.ParseExpr(); if (!this.tokens[++this.index].Equals(languageSetting["Start"])) { throw new System.Exception("Start Expected"); } whileLoop.Body = this.ParseStmt(); if (!this.tokens[this.index++].Equals(languageSetting["End"])) { throw new System.Exception("End Expected"); } result = whileLoop; } else if (this.tokens[this.index].Equals("read_int")) { this.index++; ReadInt readInt = new ReadInt(); if (this.index < this.tokens.Count && this.tokens[this.index] is string) { readInt.Ident = (string)this.tokens[this.index++]; result = readInt; } else { throw new System.Exception("expected variable name after 'read_int'"); } } else if (this.tokens[this.index].Equals("for")) { this.index++; ForLoop forLoop = new ForLoop(); if (this.index < this.tokens.Count && this.tokens[this.index] is string) { forLoop.Ident = (string)this.tokens[this.index]; } else { throw new System.Exception("expected identifier after 'for'"); } this.index++; if (this.index == this.tokens.Count || this.tokens[this.index] != Scanner.Equal) { throw new System.Exception("for missing '='"); } this.index++; forLoop.From = this.ParseSingleExpression(); if (this.index == this.tokens.Count || !this.tokens[this.index].Equals("to")) { throw new System.Exception("expected 'to' after for"); } this.index++; forLoop.To = this.ParseSingleExpression(); if (this.index == this.tokens.Count || !this.tokens[this.index].Equals("do")) { throw new System.Exception("expected 'do' after from expression in for loop"); } this.index++; forLoop.Body = this.ParseStmt(); result = forLoop; if (this.index == this.tokens.Count || !this.tokens[this.index].Equals("end")) { throw new System.Exception("unterminated 'for' loop body"); } this.index++; } else if (this.tokens[this.index] is string) { // assignment Assign assign = new Assign(); assign.Ident = (string)this.tokens[this.index++]; if (this.index == this.tokens.Count || this.tokens[this.index] != Scanner.Equal) { throw new System.Exception("expected '='"); } this.index++; assign.Expr = this.ParseExpr(); result = assign; } else { throw new System.Exception("parse error at token " + this.index + ": " + this.tokens[this.index]); } if (this.index < this.tokens.Count && this.tokens[this.index] == Scanner.Semi) { this.index++; if (this.index < this.tokens.Count && !this.tokens[this.index].Equals(languageSetting["End"])) { Sequence sequence = new Sequence(); sequence.First = result; sequence.Second = this.ParseStmt(); result = sequence; } } return(result); }
private void GenStmt(Stmt stmt) { if (stmt is Sequence) { Sequence seq = (Sequence)stmt; this.GenStmt(seq.First); this.GenStmt(seq.Second); } else if (stmt is DeclareVar) { // declare a local DeclareVar declare = (DeclareVar)stmt; this.symbolTable[declare.Ident] = this.il.DeclareLocal(this.TypeOfExpr(declare.Expr)); // set the initial value Assign assign = new Assign(); assign.Ident = declare.Ident; assign.Expr = declare.Expr; this.GenStmt(assign); } else if (stmt is Assign) { Assign assign = (Assign)stmt; if (this.typefieldList.ContainsKey(assign.Ident)) { if (!this.typefieldList[assign.Ident].IsStatic) { this.il.Emit(Emit.OpCodes.Ldarg_0); } } // if(assign.Ident this.GenExpr(assign.Expr, this.TypeOfExpr(assign.Expr)); this.Store(assign.Ident, this.TypeOfExpr(assign.Expr)); } else if (stmt is Print) { // the "print" statement is an alias for System.Console.WriteLine. // it uses the string case this.GenExpr(((Print)stmt).Expr, typeof(string)); this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) })); // this.il.Emit( } else if (stmt is VoidMethodCall) { this.GenerteMethodCallCode((MethodCall)((VoidMethodCall)stmt).Expr); } else if (stmt is IfCondition) { IfCondition ifCon = (IfCondition)stmt; this.GenExpr(ifCon.BooleanExp, /*harcoded for string */ typeof(string)); Emit.Label endOfIfBlock = this.il.DefineLabel(); if (((BinExpr)ifCon.BooleanExp).Op == BinOp.EqualTo) { this.il.Emit(Emit.OpCodes.Brfalse_S, endOfIfBlock); } else { this.il.Emit(Emit.OpCodes.Brtrue_S, endOfIfBlock); } this.GenStmt(ifCon.Body); this.il.MarkLabel(endOfIfBlock); // this.GenerteMethodCallCode((MethodCall)((VoidMethodCall)stmt).Expr); } else if (stmt is WhileLoop) { WhileLoop whileLoop = (WhileLoop)stmt; Emit.Label whileBodyStart = this.il.DefineLabel(); Emit.Label whileBodyEnd = this.il.DefineLabel(); Emit.Label whileCondition = this.il.DefineLabel(); this.il.Emit(Emit.OpCodes.Br_S, whileBodyEnd); this.il.MarkLabel(whileBodyStart); this.GenStmt(whileLoop.Body); this.il.MarkLabel(whileBodyEnd); this.GenExpr(whileLoop.BooleanExp, /*harcoded for int */ typeof(int)); if (((BinExpr)whileLoop.BooleanExp).Op == BinOp.EqualTo) { this.il.Emit(Emit.OpCodes.Brtrue_S, whileBodyStart); } else { this.il.Emit(Emit.OpCodes.Brfalse_S, whileBodyStart); } } // System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); else if (stmt is ReadInt) { this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("ReadLine", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { }, null)); this.il.Emit(Emit.OpCodes.Call, typeof(int).GetMethod("Parse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { typeof(string) }, null)); this.Store(((ReadInt)stmt).Ident, typeof(int)); } else if (stmt is ForLoop) { // example: // for x = 0 to 100 do // print "hello"; // end; // x = 0 ForLoop forLoop = (ForLoop)stmt; Assign assign = new Assign(); assign.Ident = forLoop.Ident; assign.Expr = forLoop.From; this.GenStmt(assign); // jump to the test Emit.Label test = this.il.DefineLabel(); this.il.Emit(Emit.OpCodes.Br, test); // statements in the body of the for loop Emit.Label body = this.il.DefineLabel(); this.il.MarkLabel(body); this.GenStmt(forLoop.Body); // to (increment the value of x) this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]); this.il.Emit(Emit.OpCodes.Ldc_I4, 1); this.il.Emit(Emit.OpCodes.Add); this.Store(forLoop.Ident, typeof(int)); // **test** does x equal 100? (do the test) this.il.MarkLabel(test); this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]); this.GenExpr(forLoop.To, typeof(int)); this.il.Emit(Emit.OpCodes.Blt, body); } else { throw new System.Exception("don't know how to gen a " + stmt.GetType().Name); } }
/// <summary> /// Generate python code to run this element. /// </summary> /// <param name="textWriter">TextWriter to write in.</param> public void WritePython(TextWriter textWriter) { Program.GenerateIndent(textWriter); textWriter.Write("if ("); if (IfCondition != null) { IfCondition.WritePython(textWriter); } else { textWriter.Write("True"); } textWriter.Write(") :\n"); foreach (var instruction in IfInstructions) { Program.Indent++; instruction.WritePython(textWriter); textWriter.Write("\n"); Program.Indent--; } if (IfInstructions.Count == 0) { Program.Indent++; Program.GenerateIndent(textWriter); textWriter.Write("pass\n"); Program.Indent--; } foreach (var elif in Elif) { Program.GenerateIndent(textWriter); textWriter.Write("elif"); IfCondition.WritePython(textWriter); textWriter.Write(") :\n"); foreach (var instruction in elif.Item2) { Program.Indent++; instruction.WritePython(textWriter); textWriter.Write("\n"); Program.Indent--; } if (elif.Item2.Count == 0) { Program.Indent++; Program.GenerateIndent(textWriter); textWriter.Write("pass\n"); Program.Indent--; } } if (ElseInstructions != null && ElseInstructions.Count > 0) { Program.GenerateIndent(textWriter); textWriter.Write("else:\n"); foreach (var instruction in ElseInstructions) { Program.Indent++; instruction.WritePython(textWriter); textWriter.Write("\n"); Program.Indent--; } } }
/// <summary> /// Generate ila code to for this element. /// </summary> /// <param name="textWriter">TextWriter to write in.</param> public void WriteILA(TextWriter textWriter) { Program.GenerateIndent(textWriter); textWriter.Write("si "); IfCondition.WriteILA(textWriter); textWriter.Write(" alors"); if (Comment != null && Comment.Length > 0) { textWriter.Write(" //"); textWriter.Write(Comment); } textWriter.WriteLine(); Program.Indent++; foreach (var item in IfInstructions) { item.WriteILA(textWriter); } Program.Indent--; for (int i = 0; i < Elif.Count; i++) { var item = Elif[i]; Program.GenerateIndent(textWriter); textWriter.Write("sinon si "); item.Item1.WriteILA(textWriter); textWriter.Write(" alors"); if (ElifComments[i] != null && ElifComments[i].Length > 0) { textWriter.Write(" //"); textWriter.Write(ElifComments[i]); } textWriter.WriteLine(); Program.Indent++; foreach (var item2 in item.Item2) { item2.WriteILA(textWriter); } Program.Indent--; } if (ElseInstructions != null && ElseInstructions.Count > 0) { Program.GenerateIndent(textWriter); textWriter.Write("sinon "); if (ElseComment != null && ElseComment.Length > 0) { textWriter.Write(" //"); textWriter.Write(ElseComment); } textWriter.WriteLine(); Program.Indent++; foreach (var item in ElseInstructions) { item.WriteILA(textWriter); } Program.Indent--; } Program.GenerateIndent(textWriter); textWriter.Write("fsi"); if (EndComment != null && EndComment.Length > 0) { textWriter.Write(" //"); textWriter.Write(EndComment); } textWriter.WriteLine(); }
protected abstract string[] ifTr(IfCondition if_condition);
private void ParsePreprocessArg(string arg, List <string> output, Stack <IfCondition> ifstack, bool inResponseFile) { if (arg.StartsWith("$endif")) { ifstack.Pop(); return; } if (ifstack.Count > 0) { foreach (var ifCondition in ifstack) { var expected = ifCondition.Value; string actual; if (!_properties.TryGetValue(ifCondition.Key, out actual)) { return; } if (expected != string.Empty && !expected.Equals(actual)) { return; } } } if (arg.StartsWith("$set ")) { if (!inResponseFile) { throw new Exception("$set is invalid outside of a response file."); } var words = arg.Substring(5).Split('='); var name = words[0].Trim(); var value = words.Length > 1 ? words[1].Trim() : string.Empty; _properties[name] = value; return; } if (arg.StartsWith("$if ")) { if (!inResponseFile) { throw new Exception("$if is invalid outside of a response file."); } var words = arg.Substring(4).Split('='); var name = words[0].Trim(); var value = words.Length > 1 ? words[1].Trim() : string.Empty; var condition = new IfCondition(name, value); ifstack.Push(condition); return; } if (arg.StartsWith("/define:") || arg.StartsWith("--define:")) { arg = arg.Substring(arg[0] == '/' ? 8 : 9); var words = arg.Split('='); var name = words[0]; var value = words.Length > 1 ? words[1] : string.Empty; _properties[name] = value; return; } if (arg.StartsWith("/@") || arg.StartsWith("--@") || arg.StartsWith("-@") || (arg.EndsWith(".mgcb"))) { var file = arg; if (file.StartsWith("/@") || file.StartsWith("-@")) { file = arg.Substring(3); } if (file.StartsWith("--@")) { file = arg.Substring(4); } file = Path.GetFullPath(file); if (!File.Exists(file)) { throw new Exception(string.Format("File '{0}' does not exist.", file)); } var prevDir = Directory.GetCurrentDirectory(); var dir = Path.GetDirectoryName(file); if (prevDir != dir) { // make sure the working dir is changed both during preprocessing and during execution Directory.SetCurrentDirectory(dir); output.Add("/workingDir:" + dir); } var lines = File.ReadAllLines(file); foreach (var line in lines) { if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#")) { continue; } ParsePreprocessArg(line, output, ifstack, true); } if (prevDir != dir) { Directory.SetCurrentDirectory(prevDir); output.Add("/workingDir:" + prevDir); } return; } output.Add(arg); }