// throws VisitFailure public virtual void testTrue() { Logger expected = new Logger(); expected.log( new Event( idTrue, n0 ) ); IVisitable nodeReturned = new IfThenElse( new Identity(), logVisitor(idTrue), logVisitor(idFalse)).visit(n0); Assertion.AssertEquals(expected, logger); Assertion.AssertEquals(n0, nodeReturned); }
public static bool TryReadIfThenElse(this IScanner <Token> scanner, out IStatement result) { if (scanner.TryReadToken(Token.If)) { var condition = scanner.ReadCondition(); scanner.ReadToken(Token.Then); var then = scanner.ReadStatementExcludingNext(); if (scanner.TryReadToken(Token.Else)) { var @else = scanner.ReadStatementExcludingNext(); result = new IfThenElse(condition, then, @else); } else { result = new IfThenElse(condition, then); } return(true); } result = null; return(false); }
public static List <CondInfo> Create(IfThenElseVM ifThenElse) { List <CondInfo> condInfos = new List <CondInfo>(); IfThenElse ifThenElseModel = (IfThenElse)ifThenElse.Model; ConstructVM construct = ifThenElse.FindConstruct(ifThenElseModel.ThenConstructId); if (construct != null) { CondInfo condInfo = new CondInfo(); condInfo.TargetConstructId = construct.Id; condInfo.Code = ifThenElseModel.IfCondition.Code; condInfos.Add(condInfo); } foreach (ElseIf elseIf in ifThenElseModel.ElseIfs) { construct = ifThenElse.FindConstruct(elseIf.ThenConstructId); if (construct != null) { CondInfo condInfo = new CondInfo(); condInfo.TargetConstructId = construct.Id; condInfo.Code = elseIf.IfCondition.Code; condInfos.Add(condInfo); } } construct = ifThenElse.FindConstruct(ifThenElseModel.ElseConstructId); if (construct != null) { CondInfo condInfo = new CondInfo(); condInfo.TargetConstructId = ifThenElseModel.ElseConstructId; condInfo.Code = "ELSE"; condInfos.Add(condInfo); } return(condInfos); }
public void TestGetsIfThenElse() { XCRMParser parser = new XCRMParser(); System.Xml.XmlElement xmlelement = RoarExtensions.CreateXmlElement( "<if_then_else>" + "<if>" + "</if>" + "<then>" + "</then>" + "<else>" + "</else>" + "</if_then_else>" ); System.Xml.XmlNode if_node = xmlelement.SelectSingleNode("./if"); System.Xml.XmlNode then_node = xmlelement.SelectSingleNode("./then"); System.Xml.XmlNode else_node = xmlelement.SelectSingleNode("./else"); parser.crm = mockery.NewMock <IXCRMParser>(); List <Roar.DomainObjects.Requirement> mock_if_requirement_list = new List <Roar.DomainObjects.Requirement>(); List <Roar.DomainObjects.Modifier> mock_then_modifier_list = new List <Roar.DomainObjects.Modifier>(); List <Roar.DomainObjects.Modifier> mock_else_modifier_list = new List <Roar.DomainObjects.Modifier>(); Expect.AtLeastOnce.On(parser.crm).Method("ParseRequirementList").With(if_node).Will(Return.Value(mock_if_requirement_list)); Expect.AtLeastOnce.On(parser.crm).Method("ParseModifierList").With(then_node).Will(Return.Value(mock_then_modifier_list)); Expect.AtLeastOnce.On(parser.crm).Method("ParseModifierList").With(else_node).Will(Return.Value(mock_else_modifier_list)); IfThenElse m = parser.ParseAModifier(xmlelement) as IfThenElse; mockery.VerifyAllExpectationsHaveBeenMet(); Assert.IsNotNull(m); Assert.AreSame(m.if_, mock_if_requirement_list); Assert.AreSame(m.then_, mock_then_modifier_list); Assert.AreSame(m.else_, mock_else_modifier_list); }
public void SetToken(IfThenElse expr) { Contract.Requires(expr != null); this.SetToken(t => expr.tok = t); }
private void Initialize() { var add = new Addition(); var sub = new Subtraction(); var mul = new Multiplication(); var div = new Division(); var mean = new Average(); var sin = new Sine(); var cos = new Cosine(); var tan = new Tangent(); var log = new Logarithm(); var exp = new Exponential(); var @if = new IfThenElse(); var gt = new GreaterThan(); var lt = new LessThan(); var and = new And(); var or = new Or(); var not = new Not(); var constant = new Constant(); constant.MinValue = -20; constant.MaxValue = 20; variableSymbol = new HeuristicLab.Problems.DataAnalysis.Symbolic.Variable(); var allSymbols = new List <Symbol>() { add, sub, mul, div, mean, sin, cos, tan, log, exp, @if, gt, lt, and, or, not, constant, variableSymbol }; var unaryFunctionSymbols = new List <Symbol>() { sin, cos, tan, log, exp, not }; var binaryFunctionSymbols = new List <Symbol>() { gt, lt }; var functionSymbols = new List <Symbol>() { add, sub, mul, div, mean, and, or }; foreach (var symb in allSymbols) { AddSymbol(symb); } foreach (var funSymb in functionSymbols) { SetSubtreeCount(funSymb, 1, 3); } foreach (var funSymb in unaryFunctionSymbols) { SetSubtreeCount(funSymb, 1, 1); } foreach (var funSymb in binaryFunctionSymbols) { SetSubtreeCount(funSymb, 2, 2); } SetSubtreeCount(@if, 3, 3); SetSubtreeCount(constant, 0, 0); SetSubtreeCount(variableSymbol, 0, 0); // allow each symbol as child of the start symbol foreach (var symb in allSymbols) { AddAllowedChildSymbol(StartSymbol, symb, 0); } // allow each symbol as child of every other symbol (except for terminals that have maxSubtreeCount == 0) foreach (var parent in allSymbols) { for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) { foreach (var child in allSymbols) { AddAllowedChildSymbol(parent, child, i); } } } }
protected virtual void GenerateGetInstanceMethodCode(Function getInstanceMethod) { VariableDeclaration returnValue = new VariableDeclaration((VariableType)getInstanceMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_NoSuchInstance); returnValue.Type.Name = "err"; getInstanceMethod.Declarations.Add(returnValue); int instanceOidLength = 0; StringBuilder indexColumns = new StringBuilder(); foreach (SnmpScalarNode indexNode in this.indexNodes) { if (instanceOidLength >= 0) { if (indexNode.OidRepresentationLen >= 0) { instanceOidLength += indexNode.OidRepresentationLen; } else { // at least one index column has a variable length -> we cannot perform a static check instanceOidLength = -1; } } indexColumns.AppendFormat( " {0} ({1}, OID length = {2})\n", indexNode.Name, indexNode.DataType, (indexNode.OidRepresentationLen >= 0) ? indexNode.OidRepresentationLen.ToString() : "variable"); } if (indexColumns.Length > 0) { indexColumns.Length--; getInstanceMethod.Declarations.Insert(0, new Comment(String.Format( "The instance OID of this table consists of following (index) column(s):\n{0}", indexColumns))); } string augmentsHint = ""; if (!String.IsNullOrWhiteSpace(this.augmentedTableRow)) { augmentsHint = String.Format( "This table augments table '{0}'! Index columns therefore belong to table '{0}'!\n" + "You may simply call the '*{1}' method of this table.\n\n", (this.augmentedTableRow.ToLowerInvariant().EndsWith("entry")) ? this.augmentedTableRow.Substring(0, this.augmentedTableRow.Length - 5) : this.augmentedTableRow, LwipDefs.FnctSuffix_GetInstance); } CodeContainerBase ccb = getInstanceMethod; if (instanceOidLength > 0) { IfThenElse ite = new IfThenElse(String.Format("{0} == {1}", getInstanceMethod.Parameter[2].Name, instanceOidLength)); getInstanceMethod.AddElement(ite); ccb = ite; } ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[0].Name); ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[1].Name); if (instanceOidLength <= 0) { ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[2].Name); } ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[3].Name); ccb.AddElement(new Comment(String.Format( "TODO: check if '{0}'/'{1}' params contain a valid instance oid for a row\n" + "If so, set '{2} = {3};'\n\n" + "snmp_oid_* methods may be used for easier processing of oid\n\n" + "{4}" + "In order to avoid decoding OID a second time in subsequent get_value/set_test/set_value methods,\n" + "you may store an arbitrary value (like a pointer to target value object) in '{5}->reference'/'{5}->reference_len'.\n" + "But be aware that not always a subsequent method is called -> Do NOT allocate memory here and try to release it in subsequent methods!\n\n" + "You also may replace function pointers in '{5}' param for get/test/set methods which contain the default values from table definition,\n" + "in order to provide special methods, for the currently processed cell. Changed pointers are only valid for current request.", getInstanceMethod.Parameter[1].Name, getInstanceMethod.Parameter[2].Name, returnValue.Type.Name, LwipDefs.Def_ErrorCode_Ok, augmentsHint, getInstanceMethod.Parameter[3].Name ))); getInstanceMethod.AddCodeFormat("return {0};", returnValue.Type.Name); }
public void Save() { IfThenElse = SequenceUtils.CreateIfThenElse(ValidBranches); }
public void Visit(IfThenElse ifElse) => Result = Build(ifElse);
public IfThenElseVM(IfThenElse ifThenElse) : base(ifThenElse) { this.ifThenElse = ifThenElse; }
public virtual void Visit(IfThenElse ifElse) { ifElse.Condition.Accept(this); ifElse.TrueBody?.Accept(this); ifElse.FalseBody?.Accept(this); }
public bool Parse(Lexer lexer, Token token, Attributes attributes) { var successfullyParsed = true; Expression condition = null; try { ValidateToken(token, TokenType.ConditionalIf); var expressionAttributes = Attributes.Create(attributes.ToArray()); successfullyParsed &= ParserFactory.GetExpressionParser().Parse(lexer, lexer.GetNextToken(), expressionAttributes); // SEM: La condición en un IF no puede ser una expresión nula. if (expressionAttributes.ContainsAttribute("EXP")) { condition = expressionAttributes["EXP"] as Expression; // SEM: La condición en un IF no puede ser una expresión nula. if (condition != null) { // SEM: La condición en un IF sólo puede ser una expresión booleana if (condition.Type != DataType.Boolean) { LogTypeExpressionInvalid(token, DataType.Boolean, DataType.Integer); successfullyParsed = false; } } else { LogNullExpression(token, DataType.Boolean); successfullyParsed = false; } } else { LogNullExpression(token, DataType.Boolean); successfullyParsed = false; } ValidateToken(lexer.GetCurrentToken(), TokenType.ConditionalThen); var thenBodyAttributes = Attributes.Create(attributes["ENVS"], "ENVS"); var thenStatements = new Statements(); thenBodyAttributes.AddAttribute(thenStatements, "STMS"); successfullyParsed &= ParserFactory.GetBodyParser().Parse(lexer, lexer.GetNextToken(), thenBodyAttributes); token = lexer.GetCurrentToken(); if (token.Is(TokenType.ConditionalEnd)) { ValidateToken(lexer.GetNextToken(), TokenType.EndOfInstruction); var tree = new IfThen(); tree.Condition = condition; tree.Statements = thenStatements; attributes.AddAttribute(tree, "IF"); } else if (token.Is(TokenType.ConditionalElse)) { var elseBodyAttributes = Attributes.Create(attributes["ENVS"], "ENVS"); var elseStatements = new Statements(); elseBodyAttributes.AddAttribute(elseStatements, "STMS"); successfullyParsed &= ParserFactory.GetBodyParser().Parse(lexer, lexer.GetNextToken(), elseBodyAttributes); ValidateToken(lexer.GetCurrentToken(), TokenType.ConditionalEnd); ValidateToken(lexer.GetNextToken(), TokenType.EndOfInstruction); var tree = new IfThenElse(); tree.Condition = condition; tree.Then = thenStatements; tree.Else = elseStatements; attributes.AddAttribute(tree, "IF"); } } catch (Exception ex) { successfullyParsed = false; Logger(ex.Message); ErrorRecovery(lexer); } return(successfullyParsed); }
public Term Visit(IfThenElse ifThenElse) { throw new NotImplementedException(); }
/** * Compiles a statement. * * @param s the statement * @param tabs number of tabulations */ private void compileSTATEMENT(IStatement s, int tabs) { switch (s.getTAG()) { case (Token.T_VAR): Declaration d = (Declaration)s; Identifier ide = d.getIdentifier(); if (ide.getType().getType() != Token.T_FUN) { addTabs(tabs); buffer.Append(((is_global) ? "private static " : "") + ide.getType() + " " + ide.getName()); if (ide.isInit()) { if (ide.getType().getType() == Token.T_URL) { buffer.Append(" = new Uri( "); compileEXPR(d.getExpression(), 0); buffer.Append(" )"); } else { buffer.Append(" = "); compileEXPR(d.getExpression(), 0); } } buffer.Append(";\n"); ide.setFounded(); } else { if (ide.isInit()) { addTabs(tabs); Console.WriteLine("IDE: " + ide.getName()); buffer.Append(((is_global) ? "private static var " : "var ") + ide.getName() + " = "); compileEXPR(d.getExpression(), 0); buffer.Append(";\n\n"); ide.setFounded(); } else { if (ide.isModified()) { addTabs(tabs); buffer.Append(((is_global) ? "private static var " : "var ") + ide.getName() + " = " + "(" + ide.getType() + ") null;\n"); ide.setFounded(); } } } return; case (Token.T_FOR): addTabs(tabs); For f = (For)s; buffer.Append("for("); compileASSIGNMENT(f.getFirstAssignment(), false, false, 0); buffer.Append("; "); compileEXPR(f.getGuard(), 0); buffer.Append("; "); compileASSIGNMENT(f.getSecondAssignment(), false, false, 0); buffer.Append("){\n"); compileBLOCK(f.getBlock(), tabs + 1); addTabs(tabs); buffer.Append("}\n\n"); return; case (Token.T_WHILE): addTabs(tabs); While w = (While)s; buffer.Append("while("); compileEXPR(w.getGuard(), tabs); buffer.Append("){\n"); compileBLOCK(w.getBlock(), tabs + 1); addTabs(tabs); buffer.Append("}\n\n"); return; case (Token.T_IF): IfThenElse ite = (IfThenElse)s; buffer.Append("\n"); addTabs(tabs); buffer.Append("if("); compileEXPR(ite.getCondition(), tabs); buffer.Append("){\n"); compileBLOCK(ite.getThen(), tabs + 1); buffer.Append("\n"); addTabs(tabs); buffer.Append("}"); if (ite.getElse() != null) { buffer.Append("\n"); addTabs(tabs); buffer.Append("else{\n"); compileBLOCK(ite.getElse(), tabs + 1); buffer.Append("\n"); addTabs(tabs); buffer.Append("}\n"); } buffer.Append("\n"); return; case (Token.T_BLOCK): addTabs(tabs); buffer.Append("\n"); addTabs(tabs); buffer.Append("{\n"); compileBLOCK((Block)s, tabs + 1); addTabs(tabs); buffer.Append("}\n\n"); return; case (Token.T_CALL): addTabs(tabs); Call c = (Call)s; String name; if (!map.TryGetValue(c.getName(), out name)) { name = c.getName(); } buffer.Append(name + "("); List <IExpr> args = c.getArgs(); if (args != null) { buffer.Append(" "); for (int i = 0; i < args.Count; i++) { buffer.Append((i == 0) ? "" : ", "); compileEXPR(args[i], tabs); } buffer.Append(" "); } buffer.Append(")"); while ((args = c.getCall()) != null) { buffer.Append("( "); for (int i = 0; i < args.Count; i++) { buffer.Append((i == 0) ? "" : ", "); compileEXPR(args[i], 0); } buffer.Append(" )"); } buffer.Append(";\n"); return; case (Token.T_RETURN): addTabs(tabs); Return r = (Return)s; buffer.Append("return "); compileEXPR(r.getExpr(), tabs - 1); buffer.Append(";\n"); return; case (Token.T_ASYNC): buffer.Append("\n"); addTabs(tabs); buffer.Append("Task.Factory.StartNew(() =>\n"); addTabs(tabs + 1); buffer.Append("{\n"); Async a = (Async)s; inside_async = true; compileBLOCK(a.getBlock(), tabs + 2); inside_async = false; buffer.Append("\n"); addTabs(tabs + 1); buffer.Append("});\n"); return; case (Token.T_DASYNC): buffer.Append("\n"); addTabs(tabs); buffer.Append("Task.Factory.StartNew(() =>\n"); addTabs(tabs + 1); buffer.Append("{\n"); DAsync da = (DAsync)s; inside_async = true; List <IStatement> statements = da.getStatementsList(); if (statements != null) { for (int i = 0; i < statements.Count; i++) { if (statements[i].getTAG() == Token.T_RETURN) { addTabs(tabs + 2); buffer.Append("return client.getRemoteServer( " + ((Identifier)da.getRemoteAddress()).getName() + " )."); compileEXPR(((Return)statements[i]).getExpr(), 0); buffer.Append(";"); } else { compileSTATEMENT(statements[i], tabs + 2); } buffer.Append("\n"); } } inside_async = false; addTabs(tabs + 1); buffer.Append("});\n"); return; } addTabs(tabs); compileASSIGNMENT(s, true, true, tabs); }
public void ParseTestKo(string function) { var factory = IfThenElse.Parse(function); Assert.IsTrue(string.IsNullOrEmpty(factory)); }
public void ParseTestOk(string function) { var factory = IfThenElse.Parse(function); Assert.AreEqual("if(x1,x2,x3)", factory); }