public void TestMethodSimpleAllOp1() { ResetTestState(); Console.WriteLine(MethodBase.GetCurrentMethod().Name); List <Tuple <string, double> > lst = new List <Tuple <string, double> >(); lst.Add(new Tuple <string, double>("var1", 3)); lst.Add(new Tuple <string, double>("var2", 4)); CExpression exp = CExpressionBuilder.Build("1 / 2 + var1 * var2 - 5.5 + 4^(1/2)", this); exp.SetArgIds(name => { return(lst.FindIndex(t => t.Item1 == name)); }); double res = exp.GetValue( (int id, out double value) => { value = 0; if (id < 0) { return(false); } value = lst[id].Item2; return(true); }, this); CheckInternalErrors(); Assert.AreEqual(res, 9); }
private void OnCurWaChanged() { curExprList = new List <CExpression>(); string errmsg; foreach (WeightFormula wf in curWa.FormulaList) { CExpression expr = CExpression.Parse(wf.Formula, out errmsg); if (expr == null) { string outmsg = "公式\"" + wf.Formula + "\"错误:" + errmsg; XLog.Write(outmsg); MessageBox.Show(outmsg); return; } curExprList.Add(expr); } curWaParas = curWa.GetParaList(); dataGridViewParaInput.Rows.Clear(); foreach (WeightParameter wp in curWaParas) { dataGridViewParaInput.Rows.Add(new object[] { wp.ParaName, wp.ParaValue, wp.ParaUnit, WeightParameter.ParaTypeList[wp.ParaType], wp.ParaRemark }); } btnCompute.Enabled = true; flowLayoutPanelParaImport.Enabled = true; flowLayoutPanelParaExport.Enabled = true; }
public void TestMethodOneInternalFunc2I() { ResetTestState(); Console.WriteLine(MethodBase.GetCurrentMethod().Name); CExpression exp = CExpressionBuilder.Build("Min(3, 2) * (Neg(var1) + 4)", this); double res = exp.GetValue( (int id, out double value) => { value = 3; return(true); }, this); CheckInternalErrors(); Assert.AreEqual(res, 2); res = exp.GetValue( (int id, out double value) => { value = -3; return(true); }, this); CheckInternalErrors(); Assert.AreEqual(res, 14); }
internal AssignmentStatement(ContextScope scope, Lexer lexer) : base(scope, lexer) { // VARIABLE = EXPR; // VARIABLE += EXPR; // VARIABLE -= EXPR; // VARIABLE *= EXPR; // VARIABLE /= EXPR; // VARIABLE %= EXPR; // VARIABLE &= EXPR; // VARIABLE |= EXPR; // TO DO: VARIABLE++/--; // or // EXPR; _scope = scope; switch (lexer.TokenType) { case TokenEnum.VARIABLE: { if (Parser.TypeTokens[lexer.TokenContents] != null) { DeclVariable d = new DeclVariable(scope, lexer); _varExpr = d; _varName = d.varName; } else { _varName = lexer.TokenContents; _varExpr = new IndexedExpression(scope, lexer).Get(); } _assigntype = lexer.TokenType; if (_assigntype == TokenEnum.ASSIGN || _assigntype == TokenEnum.PLUSASSIGN || _assigntype == TokenEnum.MINUSASSIGN || _assigntype == TokenEnum.ASTERISKASSIGN || _assigntype == TokenEnum.SLASHASSIGN || _assigntype == TokenEnum.PERCENTASSIGN || _assigntype == TokenEnum.AMPASSIGN || _assigntype == TokenEnum.PIPEASSIGN ) { lexer.Next(); //ASSIGN _value = new Expression(scope, lexer).Get(); } else { _assigntype = TokenEnum.NOTHING; } } break; default: { _assigntype = TokenEnum.NOTHING; _value = new Expression(scope, lexer).Get(); } break; } }
/// <summary> /// method /// US:902 /// validates the syntax and placeholders for the expression passed in /// </summary> /// <param name="exp"></param> /// <returns></returns> public CStatus Validate(CExpression exp) { CStatus status = ValidateSyntax(exp); if (!status.Status) { return(status); } status = ValidatePlaceHolders(exp.GetIf()); if (!status.Status) { return(status); } status = ValidateActions(exp.GetThen()); if (!status.Status) { return(status); } string strElse = exp.GetElse(); if (!string.IsNullOrEmpty(strElse)) { status = ValidateActions(exp.GetElse()); if (!status.Status) { return(status); } } return(status); }
public CExpression Application(CExpression fn, List<CExpression> list) { return new Application { Function = fn, Arguments = list }; }
public CFor(CStatement initial, CStatement update, CExpression predicate, CBlock body) { Initial = initial; Update = update; Predicate = predicate; Body = body; }
//expression ststment or return statment public CStatment(CExpression cExpression, bool ret = false) { if (ret) { if (cExpression == null) { Add(new OpCodeEmitter(OpCode.RET)); } else { //todo HANDEL RETURNING STRUCTS if (cExpression.Type.IsStruct) { throw new SemanticException("returning structs from functions is not implimented yet"); } Add(cExpression.ToRValue()); Add(new OpCodeEmitter(OpCode.RETV)); } } else { Add(cExpression); if (cExpression.Type.TypeClass != CTypeClass.CVoid) { Add(new OpCodeEmitter(OpCode.POPW)); } } }
public CConditionalStatement parseIfStatement(Queue <CMatchedData> matchedData) { CToken[] currTokens = matchedData.Dequeue().getTokens(); CExpression conditionExpression; CStatement ifTrueStatement; if (currTokens[0].tokenType != CTokenType.IF) { throw new System.ArgumentException("matchedData should start with an if statement!", "matchedData"); } conditionExpression = new CExpression(getText(currTokens, 2, currTokens.Length - 1)); ifTrueStatement = parseStatement(matchedData); /* Check if next statement is ELSE */ if (ifTrueStatement.nextStatement is CConditionalStatement && ((CConditionalStatement)ifTrueStatement.nextStatement).condition == null) { CStatement elseStatement = ((CConditionalStatement)ifTrueStatement.nextStatement).ifTrueStatement; return(new CConditionalStatement(conditionExpression, ifTrueStatement, elseStatement, ifTrueStatement.nextStatement.nextStatement)); } return(new CConditionalStatement(conditionExpression, ifTrueStatement, ifTrueStatement.nextStatement)); }
public CLabeledStatement(string codeString, CExpression caseExpression, CStatement labeledStatement) : base(caseExpression != null ? "case " + caseExpression.codeString : codeString, labeledStatement != null ? labeledStatement.nextStatement : null) { this.labeledStatement = labeledStatement; this.caseExpression = caseExpression; }
public CExpressionStatement parseExpressionStatement(Queue <CMatchedData> matchedData) { CToken[] currTokens = matchedData.Dequeue().getTokens(); CExpression currExpression = new CExpression(getText(currTokens, 0, currTokens.Length - 1)); return(new CExpressionStatement(currExpression, parseStatement(matchedData))); }
public override void ExitCastExpression(CParser.CastExpressionContext context) { if (context.typeName() != null) { //'(' typeName ')' castExpression SafeCall(context, () => CExpression.TypeCast(context.typeName().GetText())); } }
public int GetValue(CExpression cExpression) { if (cExpression != null) { value = Convert.ToInt32(cExpression.Accept(ceval)); } return value++; }
public CJumpStatement parseJumpStatement(Queue <CMatchedData> matchedData) { CToken[] currTokens = matchedData.Dequeue().getTokens(); CJumpStatement result; if (currTokens[0].tokenType == CTokenType.RETURN) { if (currTokens.Length > 1) { CExpression returnExpression = new CExpression(getText(currTokens, 1, currTokens.Length - 1)); result = new CJumpStatement(returnExpression, parseStatement(matchedData)); } else { result = new CJumpStatement("return", parseStatement(matchedData)); } this.returnJumps.Add(result); } else { result = new CJumpStatement(getText(currTokens, 0, currTokens.Length - 1), parseStatement(matchedData)); if (currTokens[0].tokenType == CTokenType.GOTO) { int i; /* Match goto with label */ for (i = 0; i < this.labels.Count; i++) { if (this.labels[i].codeString == result.targetIdentifier) { result.setTargetStatement(this.labels[i]); return(result); } } this.gotoJumps.Add(result); } else if (currTokens[0].tokenType == CTokenType.BREAK) { this.breakJumps.Add(result); } else if (currTokens[0].tokenType == CTokenType.CONTINUE) { this.continueJumps.Add(result); } else { throw new System.ArgumentException("matchedData does not represent a valid jump statement!", "matchedData"); } } return(result); }
public override void ExitPostfixExpression(CParser.PostfixExpressionContext context) { if (context.expression() != null) { //postfixExpression '[' expression ']' SafeCall(context, CExpression.SubscriptOperator); } else if (context.postfixExpression() != null && context.GetText().EndsWith(")")) { //postfixExpression '(' argumentExpressionList? ')' int numArgs = GetArgumentListLength(context.argumentExpressionList()); SafeCall(context, () => CExpression.FunctionCall(numArgs)); } else if (context.Identifier() != null) { int objStringLength = context.postfixExpression().GetText().Length; int idStringLength = context.Identifier().GetText().Length; int contextStringSize = context.GetText().Length; int operationStringSize = contextStringSize - (objStringLength + idStringLength); string idString = context.Identifier().GetText(); //'.' if (operationStringSize == 1) { //postfixExpression '.' Identifier SafeCall(context, () => CExpression.MemberAccess(idString)); } //'->' else { //postfixExpression '->' Identifier SafeCall(context, () => CExpression.MemberAccessThroughPointer(idString)); } } else if (context.GetText().EndsWith("++")) { //postfixExpression '++' SafeCall(context, CExpression.PostfixIncrementOperator); } else if (context.GetText().EndsWith("--")) { //postfixExpression '--' SafeCall(context, CExpression.PostfixDecrementOperator); } else if (context.initializerList() != null) { /* * '(' typeName ')' '{' initializerList '}' | '(' typeName ')' '{' initializerList ',' '}' | '__extension__' '(' typeName ')' '{' initializerList '}' | '__extension__' '(' typeName ')' '{' initializerList ',' '}' */ SematicError(context, "compound literals not supported"); } }
public CExpression PtrMemberAccess(CExpression e, string fieldName) { return new MemberExpression { Expression = e, Dereference = true, FieldName = fieldName, }; }
public CConditionalStatement(CExpression condition, CStatement trueStatement, CStatement nextStatement) : base(condition != null ? "if: " + condition.codeString : "", nextStatement) { this.condition = condition; this.ifTrueStatement = trueStatement; this.ifTrueStatement.setNextStatement(null); }
public virtual CExpression Bin(CTokenType op, CExpression left, CExpression right) { return new CBinaryExpression { Operation = op, Left = left, Right = right }; }
public static void PushEnumerator(string idString, bool hasConstant) { CEnumerator enumer = new CEnumerator(); enumer.Name = idString; enumer.ConstVal = hasConstant ? CExpression.PopExpression() : null; PushEnumerator(enumer); }
public static void EndWhileLoopStatement() { CExpression expr = CExpression.PopExpression(); CStatment stat = PopStatement(); //loopCheck: if(expression) goto loopBody; if (!expr.IsScalar) { throw new SemanticException("condition expression in loop must be scalar"); } CStatment gotoBody = new CStatment(loopBodyLabels.Peek()); CExpression.PushExpression(expr); PushStatement(gotoBody); IfStatement(false); CStatment ifCheckGotoBody = PopStatement(); ifCheckGotoBody.AddLabel(loopChechLabels.Peek().Name); //goto endloop: CStatment gotoEnd = new CStatment(endLoopLabels.Peek()); //loopBody: statment; CStatment loopBody = stat; loopBody.AddLabel(loopBodyLabels.Peek().Name); //goto loopCheck; CStatment gotoCheck = new CStatment(loopChechLabels.Peek()); //endLoop: {}; CStatment end = new CStatment(); end.AddLabel(endLoopLabels.Peek().Name); PushStatement(ifCheckGotoBody); PushStatement(gotoEnd); PushStatement(loopBody); PushStatement(gotoCheck); PushStatement(end); ExitLoop(); EndCompoundStatement(new List <CCompoundStatmentItemType> { CCompoundStatmentItemType.Statment, CCompoundStatmentItemType.Statment, CCompoundStatmentItemType.Statment, CCompoundStatmentItemType.Statment, CCompoundStatmentItemType.Statment } ); PushStatement(PopStatement()); }
/// <summary> /// override /// US:902 /// adds an expression to the list /// </summary> /// <param name="value"></param> /// <returns></returns> public override int Add(object value) { CExpression exp = value as CExpression; if (exp == null) { return(-1); } return(base.Add(value)); }
internal ForStatement(ContextScope scope, Lexer lexer) : base(scope, lexer) { // FOR ( STATEMENT; CONDEXPR; EXPR ) STATEMENT // FOR ( STATEMENT; CONDEXPR; EXPR ) { STATEMENT STATEMENT STATEMENT ... } // or // ASSIGNMENTEXPR if (lexer.TokenType == TokenEnum.FOR) { lexer.Next(); //FOR if (lexer.TokenType != TokenEnum.BRACKETOPEN) { throw new ParseException(lexer, TokenEnum.BRACKETOPEN); } lexer.Next(); //BRACKETOPEN _scope = scope.Next; _begin = new Statement(_scope, lexer).Get(); _condition = new Expression(_scope, lexer).Get(); if (lexer.TokenType != TokenEnum.SEMICOLON) { throw new ParseException(lexer, TokenEnum.SEMICOLON); } lexer.Next(); //SEMICOLON _next = new AssignmentStatement(_scope, lexer).Get(); if (lexer.TokenType != TokenEnum.BRACKETCLOSE) { throw new ParseException(lexer, TokenEnum.BRACKETCLOSE); } lexer.Next(); //BRACKETCLOSE if (lexer.TokenType == TokenEnum.BRACEOPEN) { lexer.Next(); //BRACEOPEN while (lexer.TokenType != TokenEnum.BRACECLOSE) { _actions.Add(new Statement(_scope, lexer).Get()); } lexer.Next(); //BRACECLOSE } else { _actions.Add(new Statement(scope, lexer).Get()); } } else { _actions.Add(GetNext(scope, lexer)); } }
public void TestMethodBracers() { ResetTestState(); Console.WriteLine(MethodBase.GetCurrentMethod().Name); CExpression exp = CExpressionBuilder.Build("(1 + 2) * ((3 + 4) - (5 + 1))", this); double res = exp.GetValue(this); CheckInternalErrors(); Assert.AreEqual(res, 3); }
public void TestMethodOneInternalFunc1() { ResetTestState(); Console.WriteLine(MethodBase.GetCurrentMethod().Name); CExpression exp = CExpressionBuilder.Build("Round(3.1)", this); double res = exp.GetValue(this); CheckInternalErrors(); Assert.AreEqual(res, 3); }
internal ForEachStatement(ContextScope scope, Lexer lexer) : base(scope, lexer) { // FOREACH ( DECL VAR IN EXPR ) STATEMENT // FOREACH ( DECL VAR IN EXPR ) { STATEMENT STATEMENT STATEMENT ... } // or // ASSIGNMENTEXPR if (lexer.TokenType == TokenEnum.FOREACH) { lexer.Next(); //FOREACH if (lexer.TokenType != TokenEnum.BRACKETOPEN) { throw new ParseException(lexer, TokenEnum.BRACKETOPEN); } lexer.Next(); //BRACKETOPEN _scope = scope.Next; _var = new DeclVariable(_scope, lexer); if (lexer.TokenType != TokenEnum.IN) { throw new ParseException(lexer, TokenEnum.IN); } lexer.Next(); //IN _enumerable = new Expression(_scope, lexer).Get(); if (lexer.TokenType != TokenEnum.BRACKETCLOSE) { throw new ParseException(lexer, TokenEnum.BRACKETCLOSE); } lexer.Next(); //BRACKETCLOSE if (lexer.TokenType == TokenEnum.BRACEOPEN) { lexer.Next(); //BRACEOPEN while (lexer.TokenType != TokenEnum.BRACECLOSE) { _actions.Add(new Statement(_scope, lexer).Get()); } lexer.Next(); //BRACECLOSE } else { _actions.Add(new Statement(scope, lexer).Get()); } } else { _actions.Add(GetNext(scope, lexer)); } }
public CSwitchStatement parseSwitchStatement(Queue <CMatchedData> matchedData) { CToken[] currTokens = matchedData.Dequeue().getTokens(); CExpression conditionExpression; CStatement switchStatement, nextStatement; CSwitchStatement result; List <CLabeledStatement> switchCases; int i; if (currTokens[0].tokenType != CTokenType.SWITCH) { throw new System.ArgumentException("matchedData should start with a switch statement!", "matchedData"); } conditionExpression = new CExpression(getText(currTokens, 2, currTokens.Length - 1)); switchCases = new List <CLabeledStatement>(); switchStatement = parseStatement(matchedData); nextStatement = switchStatement.nextStatement; for (i = 0; i < this.caseLabels.Count; i++) { if (switchStatement.contains(this.caseLabels[i])) { switchCases.Add(this.caseLabels[i]); this.caseLabels.RemoveAt(i); i--; } } result = new CSwitchStatement(conditionExpression, switchStatement, switchCases.ToArray(), nextStatement); for (i = 0; i < this.breakJumps.Count; i++) { if (switchStatement.contains(this.breakJumps[i])) { this.breakJumps[i].setTargetStatement(result.nextStatement as CLabeledStatement); this.breakJumps.RemoveAt(i); i--; } } return(result); }
public void TestMethodOneInternalFunc3() { ResetTestState(); Console.WriteLine(MethodBase.GetCurrentMethod().Name); CExpression exp = CExpressionBuilder.Build("Rand(1,100)", this); double res = exp.GetValue(this); CheckInternalErrors(); Assert.IsTrue(res >= 1 && res <= 100); }
public CSwitchStatement(CExpression condition, CStatement switchStatement, CLabeledStatement[] jumpTargets, CStatement nextStatement) : base(condition != null ? "switch: " + condition.codeString : "", new CLabeledStatement("switch break target", null, nextStatement != null ? nextStatement : new CExpressionStatement(new CExpression(";"), null))) { this.condition = condition; this.switchStatement = switchStatement; this.switchStatement.setNextStatement(null); this.jumpTargets = (CLabeledStatement[])jumpTargets.Clone(); }
//if statment public CStatment(CExpression cExpression, CStatment cStatment) { string ifBody = CIdentifier.AutoGenerateLabel("ifBody"); string EndIf = CIdentifier.AutoGenerateLabel("endIf"); Add(cExpression); Add(new OpCodeEmitter(OpCode.PUSHW, ifBody)); Add(new OpCodeEmitter(OpCode.JIF)); Add(new OpCodeEmitter(OpCode.PUSHW, EndIf)); Add(new OpCodeEmitter(OpCode.JMP)); Add(new LabelEmitter(ifBody)); Add(cStatment); Add(new LabelEmitter(EndIf)); }
//TODO clean this up //genertic ident private CIdentifier(CType type, string name, bool isMember, bool isLocal, int stackOffset, int structOffset) { this.type = type; this.name = name; this.isMember = isMember; this.islocal = isLocal; this.stackPointerOffset = stackOffset; this.structOffset = structOffset; if (!type.IsStruct && !type.IsArray && type.TypeClass != CTypeClass.CFunction && type.TypeClass != CTypeClass.CVoid) { CExpression.PushConstant("0"); m_init = new CInitilizer(CExpression.PopExpression()); } }
public CJumpStatement(string codeString, CStatement nextStatement) : base(codeString, nextStatement) { string[] parts = codeString.Split(' '); if (parts[0] == "goto" && parts.Length > 1) { this.targetIdentifier = parts[1]; } else { this.targetIdentifier = null; } this.returnedExpression = null; }
public void TestMethodOneValue2() { ResetTestState(); Console.WriteLine(MethodBase.GetCurrentMethod().Name); CExpression exp = CExpressionBuilder.Build("var1", this); Dictionary <string, double> dic = new Dictionary <string, double>(); dic.Add("var1", 3); double res = exp.GetValue(dic.TryGetValue, this); CheckInternalErrors(); Assert.AreEqual(res, 3); }
public CLabeledStatement parseLabeledStatement(Queue <CMatchedData> matchedData) { CToken[] currTokens = matchedData.Dequeue().getTokens(); string labelName = currTokens[0].tokenCode; CExpression caseExpression = null; CStatement labeled = parseStatement(matchedData); CLabeledStatement result; if (labelName == "case") { caseExpression = new CExpression(getText(currTokens, 1, currTokens.Length - 1)); } if (labeled == null) { throw new System.InvalidOperationException("error: label at end of compound statement!"); } result = new CLabeledStatement(labelName, caseExpression, labeled); if (labelName == "case" || labelName == "default") { this.caseLabels.Add(result); } else { int i; /* Match label with goto */ for (i = 0; i < this.gotoJumps.Count; i++) { if (this.gotoJumps[i].targetIdentifier == labelName) { this.gotoJumps[i].setTargetStatement(result); this.gotoJumps.RemoveAt(i); return(result); } } this.labels.Add(result); } return(result); }
public void PrintSimpleFunctionTest() { var ifStatement = new CIf((CExpression)5 != 3.2f, new CBlock( new CLabel("Start"), new CWhile(true), new CGoto("Start"), CExpression.Assign(new CVariable("Something")[5], "Thing") )); var procedure = new CMethod("test_a", (new CType("void", true), "a"), (new CType("int"), "b")) { IsStatic = true, Body = new CBlock(ifStatement) }; Console.WriteLine(procedure); } }
public CExpression Cast(CType type, CExpression exp) { return new CastExpression { Type = type, Expression = exp }; }
public CExpression PreIncrement(CTokenType token, CExpression uexpr) { throw new NotImplementedException(); }
public FieldDeclarator FieldDeclarator(Declarator decl, CExpression bitField) { return new FieldDeclarator { Declarator = decl, FieldSize = bitField }; }
public CExpression Application(CExpression e) { throw new NotImplementedException(); }
public Stat ExprStatement(CExpression expr) { return new ExprStat { Expression = expr }; }
public Stat IfStatement(CExpression expr, Stat consequence, Stat alternative) { throw new NotImplementedException(); }
public CExpression Conditional(CExpression cond, CExpression consequent, CExpression alternant) { return new ConditionalExpression { Condition = cond, Consequent = consequent, Alternative = alternant, }; }
public Enumerator Enumerator(string id, CExpression init) { return new Enumerator { Name = id, Value = init }; }
public Stat WhileStatement(CExpression expr, Stat whileBody) { return new WhileStat { Expression = expr, Body = whileBody }; }
public Declarator ArrayDeclarator(Declarator decl, CExpression expr) { return new ArrayDeclarator { Declarator = decl, Size = expr }; }
public CExpression ArrayAccess(CExpression e, CExpression idx) { throw new NotImplementedException(); }
public Stat DoWhileStatement(Stat doBody, CExpression expr) { return new DoWhileStat { Body = doBody, Expression = expr, }; }
public CExpression Unary(CTokenType operation, CExpression expr) { return new CUnaryExpression { Operation = operation, Expression = expr }; }
public CExpression Sizeof(CExpression sexp) { return new SizeofExpression { Expression = sexp }; }
internal Initializer ExpressionInitializer(CExpression expr) { return new ExpressionInitializer { Expression = expr }; }
public CExpression PostIncrement(CExpression e, CTokenType token) { return new IncrementExpression { Expression = e, Incrementor = token, Prefix = false }; }
public Stat ReturnStatement(CExpression expr) { return new ReturnStat { Expression = expr }; }
private bool If() { var at = Attributes.FirstOrDefault(x => x.Name == IfKey); var expression = at?.Value; if (string.IsNullOrEmpty(expression)) return true; if (_ifCache == null) _ifCache = new CExpression(expression, this); var e = _ifCache.Evaluate(); bool res; var couldConvert = bool.TryParse(e, out res); return couldConvert && res; }
public Stat SwitchStatement(CExpression expr, Stat switchBody) { throw new NotImplementedException(); }
public Stat ForStatement(Stat init, CExpression test, CExpression incr, Stat forBody) { return new ForStat { Initializer = init, Test = test, Update = incr, Body = forBody }; }
public Label CaseLabel(CExpression constExpr) { return new CaseLabel { Value = constExpr }; }