public override void Visit(DeclareVariableStatement node)
 {
     foreach (var decalaration in node.Declarations)
     {
         variableNames.Add(decalaration.VariableName.Value);
     }
 }
 public void ProcessDeclareVariableStatement(DeclareVariableStatement Statement)
 {
     foreach (DeclareVariableElement variable in Statement.Declarations)
     {
         _smells.ProcessTsqlFragment(variable);
     }
 }
예제 #3
0
 public override void ExplicitVisit(DeclareVariableStatement node)
 {
     foreach (DeclareVariableElement declaration in node.Declarations)
     {
         string parameterName = declaration.VariableName.Value.TrimStart('@');
         if (Parameters.TryGetValue(parameterName, out object parameterValue))
         {
             if (declaration.Value is StringLiteral stringLiteral)
             {
                 stringLiteral.Value = (string)parameterValue;
             }
             else if (declaration.Value is IntegerLiteral integerLiteral)
             {
                 integerLiteral.Value = (string)parameterValue;
             }
             else if (declaration.Value is NumericLiteral numericLiteral)
             {
                 numericLiteral.Value = (string)parameterValue;
             }
             else if (declaration.Value is MoneyLiteral moneyLiteral)
             {
                 moneyLiteral.Value = (string)parameterValue;
             }
         }
         else
         {
             Parameters.Add("\"" + parameterName + "\" : \"" + declaration.DataType.Name.BaseIdentifier.Value + "\"", null);
         }
     }
     base.ExplicitVisit(node);
 }
예제 #4
0
 public void ProcessDeclareVariableStatement(DeclareVariableStatement Statement)
 {
     foreach (DeclareVariableElement variable in Statement.Declarations)
     {
         _smells.ProcessTsqlFragment(variable);
     }
 }
예제 #5
0
    public override void Interpret(Script script)
    {
        MaxProgress = script.Entries.Count;
        for (int i = 0; i < script.Entries.Count; i++)
        {
            if (!Engine.Working)
            {
                System.Threading.Thread.CurrentThread.Abort();
            }
            CurProgress = i;
            var entry = script.Entries[i];

            DeclareVariableStatement relationVal = new DeclareVariableStatement();
            relationVal.IsReturn       = true;
            relationVal.Name           = "relation";
            relationVal.Type           = typeof(float);
            relationVal.InitExpression = "0";
            CreateEventFunction(entry.Identifier as string, entry.Context, codeType, delegateMethod, relationVal);
        }
        CurProgress = MaxProgress;

        CSharpCodeProvider   provider = new CSharpCodeProvider();
        CodeGeneratorOptions options  = new CodeGeneratorOptions();
        var writer = new StringWriter();

        provider.GenerateCodeFromNamespace(cNamespace, writer, options);
        Engine.GetPlugin <ScriptCompiler>().AddSource(writer.ToString());
    }
예제 #6
0
        public static ValidateLogic FirstTestLogic()
        {
            ValidateLogic            VL  = new ValidateLogic();
            DeclareVariableStatement dvs = new DeclareVariableStatement("Times", typeof(INumber));
            SetVariableStatement     svs = new SetVariableStatement(new LongVar("Times"), new LongConst(0));
            Execute initialEx            = new Execute();

            initialEx.Statements.Add(dvs);
            initialEx.Statements.Add(svs);
            SetVariableStatement svs2 = new SetVariableStatement(new LongVar("Times"),
                                                                 new ArithmeticExpression(new LongVar("Times"), null, Operator.PlusOne));
            Execute           ex2      = new Execute(svs2);
            CompareExpression AtLeast2 = new CompareExpression(new LongVar("Times"), new LongConst(2), Operator.GreaterThanOrEqualTo);
            Area ar1 = new Area(null, null, VL);

            VL.Areas.Add(ar1);
            AreaStart ap1 = new AreaStart(ar1);

            VL.StartNode       = initialEx;
            initialEx.NextNode = ap1;

            CharsToIntegerPart stip = new CharsToIntegerPart();

            ar1.StartNode = stip;
            UnitSet us1 = new UnitSet(CharUnits.Comma);

            us1.Units.Add(CharUnits.WhiteSpace);
            stip.NextNode = us1;
            CharsToIntegerPart stip2 = new CharsToIntegerPart();

            us1.NextNode = stip2;
            UnitSet us2 = new UnitSet(CharUnits.WhiteSpace);

            stip2.NextNode = us2;
            CharsToIntegerPart stip3 = new CharsToIntegerPart();

            us2.NextNode   = stip3;
            stip3.NextNode = EndNode.Instance;

            UnitSet us3 = " CH".ToUnitSet();

            us3.Units.Add(CharUnits.AtoZ);
            Status st = new Status();

            ap1.NextNode = us3;
            UnitSet CRLF = "\r\n".ToUnitSet();

            st.Choices.Add(new Choice(CRLF));
            st.Choices.Add(new Choice(EndNode.Instance, AtLeast2));
            us3.NextNode  = st;
            CRLF.NextNode = ex2;
            ex2.NextNode  = ap1;
            //12, 56 70 CHA
            //08, 32 45 CHR
            //98, -3 45 CHD
            return(VL);
        }
예제 #7
0
    public Expr InterpretClosure(Expression expression, FunctionBlock block, Type closureType)
    {
        //Debug.LogFormat ("Interpret {0} as closure", expression);
        StringBuilder closureBuilder = new StringBuilder();
        var           methodInfo     = closureType.GetMethod("Invoke");
        var           args           = methodInfo.GetParameters();
        FunctionBlock lambdaBlock    = new FunctionBlock(block, block.Method, block.Type);

        if (args.Length > 0)
        {
            lambdaBlock.DefaultScope = args[0].Name;
        }
        else
        {
            lambdaBlock.DefaultScope = block.FindStatement <DeclareVariableStatement>(v => v.Type == typeof(GameObject) && v.IsContext && !v.IsTemp).Name;
        }
        closureBuilder.Append("(");
        DeclareVariableStatement lastArg = null;

        foreach (var param in args)
        {
            var argVar = new DeclareVariableStatement();
            lastArg      = argVar;
            argVar.Name  = param.Name;
            argVar.IsArg = true;
            argVar.Type  = param.ParameterType;
            lambdaBlock.Statements.Add(argVar);
            closureBuilder.Append(param.ParameterType).Append(" ").Append(param.Name).Append(",");
        }
        if (lastArg != null)
        {
            lastArg.IsContext = true;
        }
        if (closureBuilder [closureBuilder.Length - 1] == ',')
        {
            closureBuilder.Length -= 1;
        }
        closureBuilder.Append(")=>{");
        var internals = InterpretExpression(expression, lambdaBlock);

        foreach (var statement in lambdaBlock.Statements)
        {
            closureBuilder.Append(statement).Append(";").Append(Environment.NewLine);
        }
        if (methodInfo.ReturnType != null)
        {
            closureBuilder.Append("return ");
        }
        closureBuilder.Append(internals.ExprString).Append(";");
        closureBuilder.Append("}");

        return(new Expr()
        {
            ExprString = closureBuilder.ToString()
        });
        //return InterpretExpression (expression, block);
    }
        public static void DeclareVariable(this IRequest request, string varName, SqlType varType, bool notNull, bool constant, SqlExpression defaultExpression)
        {
            var statement = new DeclareVariableStatement(varName, varType)
            {
                IsNotNull         = notNull,
                IsConstant        = constant,
                DefaultExpression = defaultExpression
            };

            request.ExecuteStatement(statement);
        }
예제 #9
0
        public static EngineResult Evaluate(DeclareVariableStatement declare, Scope scope)
        {
            foreach (var declaration in declare.Declarations)
            {
                scope.Env.Vars.Declare(
                    declaration.VariableName.Value,
                    declaration.Value == null ? null : Evaluate(declaration.Value, NullArgument.It, scope));
            }

            return(null);
        }
 private void AnalyzeDeclareVariableStatement(DeclareVariableStatement declareVariableStatement, ParserResults results)
 {
     foreach (DeclareVariableElement element in declareVariableStatement.Declarations)
     {
         if (element.Value is ScalarSubquery scalarSubquery)
         {
             var items = ExtractTablesFromScalarSubQuery(scalarSubquery);
             results.AddIfNotExists(items);
         }
     }
 }
예제 #11
0
        private DeclareVariableStatement CreateDeclareVariableStatement(Identifier name, DataTypeReference type, ScalarExpression value)
        {
            DeclareVariableStatement statement = new DeclareVariableStatement();

            statement.Declarations.Add(new DeclareVariableElement()
            {
                Value        = value,
                DataType     = type,
                VariableName = name
            });
            return(statement);
        }
예제 #12
0
    public override void Interpret(Operator op, FunctionBlock block)
    {
        if (exprInterpreter == null)
        {
            exprInterpreter = Engine.GetPlugin <ExpressionInterpreter> ();
            ops             = Engine.GetPlugin <EventFunctionOperators> ();
        }
        if (op.Args.Count == 1)
        {
            //Shouldn't declare variable
            IfStatement ifStatement = new IfStatement();
            ifStatement.CheckExpression = exprInterpreter.InterpretExpression(op.Args [0], block).ExprString;
            ifStatement.TrueBlock       = new FunctionBlock(block, block.Method, block.Type);

            block.Statements.Add(ifStatement);
            foreach (var entry in (op.Context as Context).Entries)
            {
                var subOp = entry as Operator;
                if (subOp == null)
                {
                    continue;
                }
                var subInter = ops.GetInterpreter(subOp, ifStatement.TrueBlock);
                if (subInter == null)
                {
                    Debug.LogFormat("Can't interpret operator {0} in {1}", subOp.Identifier, block.Method.Name);
                    continue;
                }
                subInter.Interpret(subOp, ifStatement.TrueBlock);
            }
        }
        else if (op.Args.Count == 2)
        {
            DeclareVariableStatement declareVar = new DeclareVariableStatement();
            if (op.Args [1].Operands [0] is IdWrapper)
            {
                var id = ((IdWrapper)op.Args [1].Operands [0]).ToString();
                declareVar.Name           = id;
                declareVar.Type           = typeof(bool);
                declareVar.InitExpression = "false";
            }
            else
            {
                Debug.Log("Wrong definition of an if operator with a variable - variable is not an identifier");
                return;
            }

            block.Statements.Add(declareVar);

            //Should declare variable
        }
    }
예제 #13
0
 protected virtual void Visit(DeclareVariableStatement statement)
 {
     Write("DECLARE ");
     Visit(statement.Name);
     Write(' ');
     Visit(statement.Type);
     if (statement.Value != null)
     {
         Write(" = ");
         Visit(statement.Value);
     }
     Write(';');
 }
예제 #14
0
        public void DeclareVariable()
        {
            var statement = new DeclareVariableStatement("a", PrimitiveTypes.String());

            SerializeAndAssert(statement, (serialized, deserialized) => {
                Assert.IsNotNull(deserialized);
                Assert.IsNotNull(deserialized.VariableName);
                Assert.IsNotNull(deserialized.VariableType);

                Assert.AreEqual("a", deserialized.VariableName);
                Assert.IsInstanceOf <StringType>(deserialized.VariableType);
            });
        }
예제 #15
0
    public override void Interpret(Expression[] args, FunctionBlock block, Type contextType, string exprVal, out string newExprVal, out FunctionBlock newCurBlock, out Type newContextType, bool isLast)
    {
        if (ScriptEngine.AnalyzeDebug)
        {
            Debug.Log("fit scope");
        }
        IfStatement ifStatement = new IfStatement();
//		DeclareVariableStatement cmpStmt = new DeclareVariableStatement ();
//		ExprInter.CleanUpContextes.Add (cmpStmt);
//		cmpStmt.Name = "cmp" + DeclareVariableStatement.VariableId++;
//		cmpStmt.Type = Type;
        //cmpStmt.IsContext = true;
        string varName = block.FindStatement <DeclareVariableStatement> (v => v.IsContext).Name;
//		cmpStmt.InitExpression = String.Format ("{0}.GetComponent<{1}>()", varName, Type);
//		ifStatement.CheckExpression = String.Format ("{0} != null", cmpStmt.Name);
        FunctionBlock newBlock = new FunctionBlock(block, block.Method, block.Type);

        DeclareVariableStatement ifValue = new DeclareVariableStatement();

        ifValue.Name   = "ifResult" + DeclareVariableStatement.VariableId++;
        ifValue.IsTemp = true;
        ifValue.Type   = typeof(bool);
        block.Statements.Add(ifValue);
        ifStatement.CheckExpression = (ifValue.Name + " = ") + ExprInter.InterpretExpression(args [0], block).ExprString;

        ifStatement.TrueBlock = newBlock;
        //block.Statements.Add (cmpStmt);
        block.Statements.Add(ifStatement);
        newCurBlock    = newBlock;
        newExprVal     = exprVal;
        newContextType = contextType;
        if (isLast)
        {
            var res = block.FindStatement <DeclareVariableStatement> (v => v.IsResult);
            if (res != null)
            {
                res.Type           = typeof(List <>).MakeGenericType(contextType);
                res.InitExpression = String.Format("new {0}()", TypeName.NameOf(res.Type));
                newExprVal         = res.Name;
                newBlock.Statements.Add(String.Format("{0}.Add({1});", res.Name, varName));
            }
            else
            {
                newExprVal     = ifValue.Name;
                newContextType = typeof(bool);
            }
        }

        //ifStatement.CheckExpression = String.Format("{0}.GetComponen")
        //ifStatement.CheckExpression =
    }
예제 #16
0
    public Expr InterpretScopedList(Scope scope, FunctionBlock block)
    {
        FunctionBlock listBlock = new FunctionBlock(block, block.Method, block.Type);

        block.Statements.Add(listBlock);
        var listVar = new DeclareVariableStatement();

        listVar.Name = "scopedList" + DeclareVariableStatement.VariableId++;
        //listVar.InitExpression =



        return(new Expr());
    }
예제 #17
0
        protected override void BuildStatement(SqlCodeObjectBuilder builder)
        {
            var varType   = DataTypeBuilder.Build(builder.TypeResolver, Type);
            var statement = new DeclareVariableStatement(VariableName, varType);

            if (DefaultExpression != null)
            {
                statement.DefaultExpression = ExpressionBuilder.Build(DefaultExpression);
            }

            statement.IsConstant = IsConstant;
            statement.IsNotNull  = IsConstant || IsNotNull;
            builder.AddObject(statement);
        }
예제 #18
0
        private void CreateDeclareVariableDefinitionForParmeter(string name, SqlDataType type)
        {
            var declare        = new DeclareVariableStatement();
            var declareElement = new DeclareVariableElement();

            var dataType = GetDataType(type);

            declareElement.Value        = GetDefaultValue(dataType);
            declareElement.DataType     = dataType;
            declareElement.VariableName = name.ToIdentifier();
            declare.Declarations.Add(declareElement);

            _testProcedure.StatementList.Statements.Add(declare);
        }
예제 #19
0
    public override void Interpret(Operator op, FunctionBlock block)
    {
        DeclareVariableStatement stmt = new DeclareVariableStatement();

        stmt.Name = op.Identifier as string;
        var expr = Inter.InterpretExpression(op.Context as Expression, block);

        stmt.InitExpression = expr.ExprString;
        stmt.Type           = expr.Type;
        if (ScriptEngine.AnalyzeDebug)
        {
            Debug.Log(stmt);
        }
        block.Statements.Add(stmt);
    }
예제 #20
0
        private void ParseParameters(IList <ProcedureParameter> parameters)
        {
            Parameters.Clear();
            Declarations.Clear();

            foreach (ProcedureParameter parameter in parameters)
            {
                DeclareVariableStatement statement = CreateDeclareVariableStatement(
                    parameter.VariableName,
                    parameter.DataType,
                    parameter.Value);
                string sql = statement.ToSqlString();
                if (!sql.EndsWith(';'))
                {
                    sql += ";";
                }
                Declarations.Add(sql);

                Parameters.Add(parameter.VariableName.Value);
            }
        }
예제 #21
0
        private string buildChunkedDelete(DeleteSpecification delete)
        {

            var counter = new DeclareVariableStatement();
            var counterVariable = new DeclareVariableElement();
            counterVariable.DataType = new SqlDataTypeReference() {SqlDataTypeOption = SqlDataTypeOption.Int};
            counterVariable.VariableName = new Identifier() {Value = "@rowcount"};
            counterVariable.Value = new IntegerLiteral() {Value = "10000"};
            counter.Declarations.Add(counterVariable);
            
            delete.TopRowFilter = new TopRowFilter();
            delete.TopRowFilter.Expression = new ParenthesisExpression() {Expression = new IntegerLiteral() {Value = "10000"} };

            var setCounter = new SetVariableStatement();
            setCounter.Variable = new VariableReference() {Name = "@rowcount"};
            setCounter.Expression = new GlobalVariableExpression() {Name = "@@rowcount"};
            setCounter.AssignmentKind = AssignmentKind.Equals;

            var deleteStatement = new DeleteStatement();
            deleteStatement.DeleteSpecification = delete;

            var beginEnd = new BeginEndBlockStatement();
            beginEnd.StatementList = new StatementList();
            beginEnd.StatementList.Statements.Add(deleteStatement);
            beginEnd.StatementList.Statements.Add(setCounter);

            var whilePredicate = new BooleanComparisonExpression();
            whilePredicate.ComparisonType = BooleanComparisonType.GreaterThan;
            whilePredicate.FirstExpression = new VariableReference() {Name = "@rowcount"};
            whilePredicate.SecondExpression = new IntegerLiteral() {Value = "0"};

            var whileStatement = new WhileStatement();
            whileStatement.Predicate = whilePredicate;
            whileStatement.Statement = beginEnd;
            
            var text = ScriptDom.GenerateTSql(counter) + "\r\n" + ScriptDom.GenerateTSql(whileStatement);

            return text;
        }
예제 #22
0
    public override void Interpret(Expression[] args, FunctionBlock block, Type contextType, string exprVal, out string newExprVal, out FunctionBlock newCurBlock, out Type newContextType, bool isLast)
    {
        Debug.Log("Has component scope");
        IfStatement ifStatement          = new IfStatement();
        DeclareVariableStatement cmpStmt = new DeclareVariableStatement();

        cmpStmt.IsTemp    = true;
        cmpStmt.IsContext = true;
        ExprInter.CleanUpContextes.Push(cmpStmt);
        cmpStmt.Name = "cmp" + DeclareVariableStatement.VariableId++;
        cmpStmt.Type = Type;
        //cmpStmt.IsContext = true;
        var ctxVar = block.FindStatement <DeclareVariableStatement> (v => v.IsContext);

        string varName = ctxVar == null ? "root" : ctxVar.Name;

        cmpStmt.InitExpression      = String.Format("({1}){0}.GetComponent(typeof({1}))", varName, Type);
        ifStatement.CheckExpression = String.Format("{0} != null", cmpStmt.Name);
        FunctionBlock newBlock = new FunctionBlock(block, block.Method, block.Type);

        ifStatement.TrueBlock = newBlock;
        block.Statements.Add(cmpStmt);
        block.Statements.Add(ifStatement);
        newCurBlock    = newBlock;
        newExprVal     = exprVal;
        newContextType = contextType;
        if (isLast)
        {
            var res = block.FindStatement <DeclareVariableStatement> (v => v.IsResult);
            res.Type           = typeof(List <>).MakeGenericType(contextType);
            res.InitExpression = String.Format("new {0}()", TypeName.NameOf(res.Type));
            newExprVal         = res.Name;
            newBlock.Statements.Add(String.Format("{0}.Add({1});", res.Name, varName));
        }

        //ifStatement.CheckExpression = String.Format("{0}.GetComponen")
        //ifStatement.CheckExpression =
    }
예제 #23
0
 public override void Interpret(Operator op, FunctionBlock block)
 {
     if (exprInter == null)
     {
         exprInter = Engine.GetPlugin <ExpressionInterpreter>();
     }
     if (op.Args.Count > 0 && op.Args[0].Operands[0] is ExprAtom &&
         (op.Args[0].Operands[0] as ExprAtom).Content is Scope &&
         ((op.Args[0].Operands[0] as ExprAtom).Content as Scope).Parts.Count == 1)
     {
         var part = ((op.Args[0].Operands[0] as ExprAtom).Content as Scope).Parts[0];
         if (!(part is string))
         {
             Debug.Log("Wrong remove_from definition");
             return;
         }
         var listName = NameTranslator.CSharpNameFromScript(part as string);
         DeclareVariableStatement declareVar = block.FindStatement <DeclareVariableStatement>(v => v.IsContext && v.Type.GetProperty(listName) != null);
         //Debug.Log (declareVar.DebugString ());
         if (declareVar == null)
         {
             Debug.Log("remove_from operator can't find context variable");
         }
         else
         {
             if (op.Context is Expression)
             {
                 var exprValue = exprInter.InterpretExpression(op.Context as Expression, block);
                 //block = exprValue.NotNullBlock;
                 block.Statements.Add(String.Format("{0}.{1}.Remove({2});", declareVar.Name, listName, exprValue.ExprString));
             }
         }
     }
     else
     {
         Debug.Log("Wrong remove_from definition");
     }
 }
    public override void Interpret(Operator op, FunctionBlock block)
    {
        interpret = false;
        if (exprInter == null)
        {
            switches  = Engine.GetPlugin <ContextSwitchesPlugin> ();
            ops       = Engine.GetPlugin <EventFunctionOperators> ();
            exprInter = Engine.GetPlugin <ExpressionInterpreter> ();
        }

        var varName = op.Identifier as string;

        if (ScriptEngine.AnalyzeDebug)
        {
            Debug.Log(block);
        }
        var sCtx    = block.FindStatement <ContextStatement> (v => v.InterpretInContext(op, block) != null && v.ContextVar.IsContext || v.ContextVar.IsArg);
        var context = sCtx != null ? sCtx.ContextVar : null;

        if (ScriptEngine.AnalyzeDebug)
        {
            Debug.LogFormat("FOUND COUNTEXT {0} for {1}", context, op.Identifier);
        }
        if (listT == null)
        {
            if (!(op.Context is Expression))
            {
                return;
            }
            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.Log("PROPERTY " + propName);
            }
            if (context == null)
            {
                block.Statements.Add(String.Format("root.{0} = ({2})({1});", propName, exprInter.InterpretExpression(op.Context as Expression, block).ExprString, TypeName.NameOf(propType)));
            }
            else
            {
                block.Statements.Add(String.Format("{2}.{0} = ({3})({1});", propName, exprInter.InterpretExpression(op.Context as Expression, block).ExprString, context.Name, TypeName.NameOf(propType)));
            }
        }
        else
        {
            Debug.Log("list of" + listT);
            ForStatement statement   = new ForStatement();
            string       listVarName = context == null ? "root." + propName : context.Name + "." + propName;
            string       iterName    = "i" + DeclareVariableStatement.VariableId++;
            statement.InsideExpr = String.Format("int {0} = 0; {1} != null && {0} < {1}.Count; {0}++", iterName,
                                                 listVarName);
            FunctionBlock repeatBlock = new FunctionBlock(block, block.Method, block.Type);
            statement.RepeatBlock = repeatBlock;
            block.Statements.Add(statement);
            Operator listVarOp = new Operator();

            DeclareVariableStatement listVar = new DeclareVariableStatement();
            listVar.Name           = "iter" + DeclareVariableStatement.VariableId++;
            listVar.IsContext      = true;
            listVar.IsNew          = true;
            listVar.Type           = listT;
            listVar.InitExpression = String.Format("{0}[{1}]", listVarName, iterName);

            statement.RepeatBlock.Statements.Add(listVar);
            var inter = switches.GetInterByType(listT);
            //Debug.Log(inter);
            inter.Interpret(op, repeatBlock);
        }
        interpret = true;
    }
    public override void Interpret(Operator op, FunctionBlock block)
    {
        if (ops == null)
        {
            ops = Engine.GetPlugin <EventFunctionOperators> ();
        }
        FunctionBlock contextBlock = new FunctionBlock(block, block.Method, block.Type);

        block.Statements.Add(contextBlock);
        DeclareVariableStatement addVar = block.FindStatement <DeclareVariableStatement> (v => v.Name == op.Identifier as string);
        bool setContext = false;

        if (addVar != null && !addVar.IsContext)
        {
            setContext = addVar.IsContext = true;
        }
        if (addVar == null)
        {
            addVar = block.FindStatement <DeclareVariableStatement> (v => v.IsContext && v.Type == contextType);
        }
        //TODO: probably will fail
        DeclareVariableStatement contextVar = contextType == typeof(GameObject)? addVar : block.FindStatement <DeclareVariableStatement> (v => v.IsContext && v.Type == typeof(GameObject) && v != addVar);
        DeclareVariableStatement declareVar = null;

        if (addVar == null)
        {
            declareVar           = new DeclareVariableStatement();
            declareVar.Type      = contextType;
            declareVar.Name      = "subContext" + DeclareVariableStatement.VariableId++;
            declareVar.IsContext = true;

            if (contextVar == null)
            {
                declareVar.InitExpression = String.Format("({0})root.GetComponent(typeof({0}))", contextType);
            }
            else
            {
                declareVar.InitExpression = String.Format("({0}){1}.GetComponent(typeof({0}))", contextType, contextVar.Name);
            }
            contextBlock.Statements.Add(declareVar);
        }
        else
        {
            declareVar = addVar;
        }

        contextBlock.Statements.Add(new ContextStatement()
        {
            ContextVar         = declareVar,
            InterpretInContext = InterpretInContext
        });
        IfStatement isNotNull = new IfStatement();

        isNotNull.CheckExpression = String.Format("{0} != null", declareVar.Name);
        isNotNull.TrueBlock       = new FunctionBlock(contextBlock);
        contextBlock.Statements.Add(isNotNull);
        contextBlock = isNotNull.TrueBlock;
        contextBlock.Statements.Add(new DeclareVariableStatement()
        {
            Name = declareVar.Name, IsArg = true, IsContext = true, Type = declareVar.Type
        });
        foreach (var entry in (op.Context as Context).Entries)
        {
            var subOp = entry as Operator;
            if (subOp == null)
            {
                continue;
            }
            FunctionOperatorInterpreter opInter = null;

            if ((opInter = ops.GetInterpreter(subOp, contextBlock)) == null)
            {
                if (!contextSwitches.TryGetValue(subOp.Identifier as string, out opInter))
                {
                    if (!functions.TryGetValue(subOp.Identifier as string, out opInter))
                    {
                        if (!properties.TryGetValue(subOp.Identifier as string, out opInter))
                        {
                            Debug.LogWarningFormat("Can't interpret context operator {1} in {0}", block.Method.Name, subOp.Identifier);
                            continue;
                        }
                    }
                }
            }
            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogFormat("Interpret {0} via {1}", subOp.Identifier, opInter);
            }
            opInter.Interpret(subOp, contextBlock);
        }

        if (setContext)
        {
            addVar.IsContext = false;
        }
    }
    public override void Interpret(Operator op, FunctionBlock block)
    {
        if (ScriptEngine.AnalyzeDebug)
        {
            Debug.LogWarning("Context function " + op.Identifier);
        }
        if (exprInter == null)
        {
            exprInter = Engine.GetPlugin <ExpressionInterpreter> ();
        }
        var any        = BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static;
        var sCtx       = block.FindStatement <ContextStatement> (v => v.InterpretInContext(op, block) != null && (v.ContextVar.IsContext || v.ContextVar.IsArg));
        var contextVar = sCtx != null ? sCtx.ContextVar : null;
        //var contextVar = block.FindStatement<DeclareVariableStatement> (v => );

        StringBuilder argsBuilder = new StringBuilder();

//		if (((op.Context is Expression) && op.Args.Count + 1 != argsDef.Length) ||
//		    ((op.Context is Context) && op.Args.Count != argsDef.Length))
//		{
//			Debug.Log ("Wrong amount of arguments");
//			return;
//		}
        for (int i = 0; i < op.Args.Count; i++)
        {
            if (argsDef [i].ParameterType.IsSubclassOf(typeof(Delegate)))
            {
                argsBuilder.Append(exprInter.InterpretClosure(op.Args [i], block, argsDef [i].ParameterType).ExprString).Append(",");
            }
            else if (argsDef [i].ParameterType == typeof(string))
            {
                argsBuilder.Append('(').Append(exprInter.InterpretExpression(op.Args [i], block).ExprString).Append(')').Append(".ToString()").Append(",");
            }
            else
            {
                argsBuilder.Append('(').Append(argsDef [i].ParameterType).Append(')').Append('(').Append(exprInter.InterpretExpression(op.Args [i], block).ExprString).Append(')').Append(",");
            }
        }
        if (op.Context is Expression)
        {
            if (argsDef [argsDef.Length - 1].ParameterType.IsSubclassOf(typeof(Delegate)))
            {
                argsBuilder.
                Append('(').
                Append(argsDef [argsDef.Length - 1].ParameterType).
                Append(')').
                Append('(').
                Append(exprInter.InterpretClosure(op.Context as Expression, block, argsDef [argsDef.Length - 1].ParameterType).ExprString).
                Append(')');
            }
            else if (argsDef [argsDef.Length - 1].ParameterType == typeof(string))
            {
                argsBuilder.Append('(').Append(exprInter.InterpretExpression(op.Context as Expression, block).ExprString).Append(')').Append(".ToString()");
            }
            else
            {
                argsBuilder.
                Append('(').
                Append(argsDef [argsDef.Length - 1].ParameterType).
                Append(')').
                Append('(').
                Append(exprInter.InterpretExpression(op.Context as Expression, block).ExprString).
                Append(')');
            }
            if (contextVar == null)
            {
                block.Statements.Add(string.Format("root.{0}({1});", funcName, argsBuilder));
            }
            else
            {
                block.Statements.Add(string.Format("{2}.{0}({1});", funcName, argsBuilder, contextVar.Name));
            }
        }
        else if (ctxInter != null)
        {
            if (op.Args.Count > 0)
            {
                argsBuilder.Length -= 1;
            }
            var           ctx          = op.Context as Context;
            FunctionBlock contextBlock = new FunctionBlock(block);
            block.Statements.Add(contextBlock);
            block = contextBlock;
            DeclareVariableStatement ctxVar = new DeclareVariableStatement();
            ctxVar.Name           = "FuncCtx" + DeclareVariableStatement.VariableId++;
            ctxVar.InitExpression = contextVar == null?string.Format("root.{0}({1});", funcName, argsBuilder) : string.Format("{2}.{0}({1});", funcName, argsBuilder, contextVar.Name);

            ctxVar.Type      = returnType;
            ctxVar.IsContext = true;

            ContextStatement stmt = new ContextStatement();
            stmt.ContextVar         = ctxVar;
            stmt.InterpretInContext = ctxInter.InterpretInContext;
            block.Statements.Add(ctxVar);
            block.Statements.Add(stmt);
            IfStatement isNotNull = new IfStatement();
            isNotNull.CheckExpression = String.Format("{0} != null", ctxVar.Name);
            isNotNull.TrueBlock       = new FunctionBlock(block);
            block.Statements.Add(isNotNull);
            block = isNotNull.TrueBlock;
            for (int i = 0; i < ctx.Entries.Count; i++)
            {
                ops.GetInterpreter(ctx.Entries [i] as Operator, block).Interpret(ctx.Entries [i] as Operator, block);
            }
        }
        else
        {
            //Func doesn't return a context, while maybe allows for either lambda as value or context addition
            var lastArg = argsDef.Length > 0 ? argsDef [argsDef.Length - 1] : null;
            if (lastArg != null)
            {
                if (typeof(Delegate).IsAssignableFrom(lastArg.ParameterType))
                {
                    Debug.Log("LAMBDA!");
                    //Interpret as lambda
                    LambdaStatement lambda = new LambdaStatement();
                    lambda.DelegateType = lastArg.ParameterType;
                    var method = lastArg.ParameterType.GetMethod("Invoke");
                    lambda.Params = method.GetParameters();
                    lambda.Name   = "Lambda" + DeclareVariableStatement.VariableId++;
                    block.Statements.Add(lambda);
                    lambda.Block = new FunctionBlock(block);

                    //DeclareVariableStatement lastVar = null;
                    foreach (var param in lambda.Params)
                    {
                        var argVar = new DeclareVariableStatement();
                        //	lastVar = argVar;
                        argVar.Name  = param.Name;
                        argVar.IsArg = true;
                        argVar.Type  = param.ParameterType;
                        lambda.Block.Statements.Add(argVar);
                    }
                    //if (lastVar != null)
                    //	lastVar.IsContext = true;

                    var  retType   = lambda.DelegateType.GetMethod("Invoke").ReturnType;
                    bool hasReturn = false;
                    if (retType != null && retType != typeof(void))
                    {
                        hasReturn = true;
                        lambda.Block.Statements.Add(new DeclareVariableStatement()
                        {
                            Name           = "return_value",
                            InitExpression = string.Format("default({0})", retType),
                            IsReturn       = true,
                            Type           = retType
                        });
                    }

                    foreach (var entry in (op.Context as Context).Entries)
                    {
                        var subOp = entry as Operator;
                        ops.GetInterpreter(subOp, lambda.Block).Interpret(subOp, lambda.Block);
                    }
                    if (hasReturn)
                    {
                        lambda.Block.Statements.Add("return return_value;");
                    }
                    //Don't forget to call a function and add an arugment
                    argsBuilder.Append(lambda.Name);
                    if (contextVar == null)
                    {
                        block.Statements.Add(string.Format("root.{0}({1});", funcName, argsBuilder));
                    }
                    else
                    {
                        block.Statements.Add(string.Format("{2}.{0}({1});", funcName, argsBuilder, contextVar.Name));
                    }
                }
                else if (addContextInter != null)
                {
                    //Interpret as new value
                    DeclareVariableStatement newVar = new DeclareVariableStatement();
                    newVar.Name      = "NewArg" + DeclareVariableStatement.VariableId++;
                    newVar.IsContext = true;
                    newVar.Type      = lastArg.ParameterType;
                    if (contextVar == null)
                    {
                        newVar.InitExpression = String.Format("root.AddComponent<{0}>()", newVar.Type);
                    }
                    else
                    {
                        newVar.InitExpression = String.Format("{0}.AddComponent<{0}>()", contextVar.Name, newVar.Type);
                    }
                    FunctionBlock contextBlock = new FunctionBlock(block);
                    contextBlock.Statements.Add(newVar);
                    addContextInter.Interpret(op, contextBlock);
                    argsBuilder.Append(newVar.Name);
                    if (contextVar == null)
                    {
                        contextBlock.Statements.Add(string.Format("root.{0}({1});", funcName, argsBuilder));
                    }
                    else
                    {
                        contextBlock.Statements.Add(string.Format("{2}.{0}({1});", funcName, argsBuilder, contextVar.Name));
                    }

                    block.Statements.Add(contextBlock);
                }
            }
        }
    }
    public override void Interpret(InternalDSL.Operator op, FunctionBlock block)
    {
        if (ops == null)
        {
            ctxs      = Engine.GetPlugin <ContextSwitchesPlugin> ();
            ops       = Engine.GetPlugin <EventFunctionOperators> ();
            exprInter = Engine.GetPlugin <ExpressionInterpreter> ();
        }
        if (op.Args.Count > 0)
        {
            var varName = ((op.Args [0].Operands [0] as ExprAtom).Content as Scope).Parts [0] as string;
            if (op.Context is Expression)
            {
                //cache(some_name) = expression
//				var varDecl = block.FindStatement<DeclareVariableStatement> (v => v.Name == varName);
//				varDecl.IsArg = true;

                var exprValue = exprInter.InterpretExpression(op.Context as Expression, block);
                Debug.Log(exprValue.ExprString);
                var field = new CodeMemberField(exprValue.Type, varName);
                field.UserData.Add("type", exprValue.Type);
                block.Type.Members.Add(field);
                block.Statements.Add(String.Format("{0} = {1};", varName, exprValue.ExprString));
                block.Statements.Add(new DeclareVariableStatement()
                {
                    Name = varName, IsArg = true, Type = exprValue.Type
                });
                //var varDecl = block.FindStatement<DeclareVariableStatement> (v => v.Name == varName);
            }
            else
            {
                //cache(some_name, scope) = { ... }
                var exprValue = exprInter.InterpretExpression(op.Args [1], block);
                var field     = new CodeMemberField(exprValue.Type, varName);
                field.UserData.Add("type", exprValue.Type);
                block.Type.Members.Add(field);
                DeclareVariableStatement cachedVar = new DeclareVariableStatement();
                cachedVar.Name      = varName;
                cachedVar.IsContext = true;
                cachedVar.Type      = exprValue.Type;
                cachedVar.IsArg     = true;
                block.Statements.Add(cachedVar);
                block.Statements.Add(String.Format("{0} = {1};", varName, exprValue.ExprString));
                block.Statements.Add(new DeclareVariableStatement()
                {
                    Name = varName, IsArg = true, Type = exprValue.Type
                });
                var inter = ctxs.GetInterByType(exprValue.Type);
                inter.Interpret(op, block);
            }
        }
        else
        {
            //cache = some_name

            var varName = (((op.Context as Expression).Operands [0] as ExprAtom).Content as Scope).Parts [0] as string;
            var varDecl = block.FindStatement <DeclareVariableStatement> (v => v.Name == varName);
            //varDecl.IsArg = true;
            varDecl.IsDeclaration = false;

            var field = new CodeMemberField(varDecl.Type, varDecl.Name);
            field.UserData.Add("type", varDecl.Type);
            block.Type.Members.Add(field);
            //block.Statements.Add (String.Format ("this.{0} = {0};", varName));
        }

        //new CodeMemberField()
        //block.Type.Members.Add ();
    }
예제 #28
0
 public override void Visit(DeclareVariableStatement node) { this.action(node); }
예제 #29
0
    public override void Interpret(Script script)
    {
        MaxProgress = script.Entries.Count;
        for (int i = 0; i < script.Entries.Count; i++)
        {
            if (!Engine.Working)
            {
                Thread.CurrentThread.Abort();
            }
            CurProgress = i;
            var entry = script.Entries [i];
            CodeTypeDeclaration codeType = new CodeTypeDeclaration();
            //codeType.CustomAttributes.
            codeType.BaseTypes.Add(new CodeTypeReference(typeof(EventAction)));
            codeType.Name = entry.Identifier as string;
            codeTypes.Add(codeType);

            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogWarning((entry.Identifier as string).ToUpper());
            }

            var ctx = entry.Context as Context;
            if (ctx == null)
            {
                continue;
            }
            var actionMethod = typeof(EventAction).GetMethod("Action");
            var utMethod     = typeof(EventAction).GetMethod("Utility");
            var scopeMethod  = typeof(EventAction).GetMethod("Filter");
            var interMethod  = typeof(EventAction).GetMethod("Interaction");
            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("EventActionAttribute");
            codeType.CustomAttributes.Add(attr);
            CodeAttributeArgument maxArg         = new CodeAttributeArgument("ShouldHaveMaxUtility", new CodeSnippetExpression("false"));
            CodeAttributeArgument onceArg        = new CodeAttributeArgument("OncePerObject", new CodeSnippetExpression("false"));
            CodeAttributeArgument oncePerTurnArg = new CodeAttributeArgument("OncePerTurn", new CodeSnippetExpression("false"));
            CodeAttributeArgument aiActionArg    = new CodeAttributeArgument("IsAIAction", new CodeSnippetExpression("false"));
            CodeAttributeArgument interactionArg = new CodeAttributeArgument("IsInteraction", new CodeSnippetExpression("false"));
            CodeAttributeArgument tooltipArg     = new CodeAttributeArgument("Tooltip", new CodeSnippetExpression("\"\""));
            CodeAttributeArgument onceInCategory = new CodeAttributeArgument("OnceInCategory", new CodeSnippetExpression("false"));
            attr.Arguments.Add(maxArg);
            attr.Arguments.Add(onceArg);
            attr.Arguments.Add(oncePerTurnArg);
            attr.Arguments.Add(aiActionArg);
            attr.Arguments.Add(tooltipArg);
            attr.Arguments.Add(onceInCategory);
            attr.Arguments.Add(interactionArg);
            FunctionBlock dependenciesBlock = new FunctionBlock(null, null, codeType);
            List <string> deps = new List <string>();
            for (int j = 0; j < ctx.Entries.Count; j++)
            {
                var op = ctx.Entries [j] as Operator;
                if (op == null)
                {
                    continue;
                }
                if (op.Identifier as string == "tooltip")
                {
                    tooltipArg.Value = new CodeSnippetExpression((op.Context as InternalDSL.Expression).Operands[0].ToString());
                }
                else if (op.Identifier as string == "ai_action")
                {
                    aiActionArg.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "once_per_category")
                {
                    onceInCategory.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "only_max_utility")
                {
                    maxArg.Value = new CodeSnippetExpression((op.Context as InternalDSL.Expression).Operands[0].ToString());
                }
                else if (op.Identifier as string == "category")
                {
                    var cat  = (((op.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts[0].ToString();
                    var type = Engine.FindType("ScriptedTypes." + cat);
                    if (type == null)
                    {
                        type = Engine.FindType(NameTranslator.CSharpNameFromScript(cat));
                    }
                    if (type != null)
                    {
                        var props = type.GetProperties();
                        codeType.BaseTypes.Add(type);

                        foreach (var propInfo in props)
                        {
                            var prop = new CodeMemberProperty();
                            prop.HasGet = true;
                            prop.HasSet = true;
                            prop.Name   = propInfo.Name;
                            prop.Type   = new CodeTypeReference(propInfo.PropertyType);
                            var fieldName = NameTranslator.ScriptNameFromCSharp(prop.Name);
                            prop.GetStatements.Add(new CodeSnippetStatement(String.Format("return {0}; ", fieldName)));
                            prop.SetStatements.Add(new CodeSnippetStatement(String.Format("{0} = value; ", fieldName)));
                            prop.PrivateImplementationType = new CodeTypeReference(type);
                            if (!codeType.UserData.Contains(fieldName))
                            {
                                var field = new CodeMemberField();
                                field.Name = fieldName;
                                field.Type = new CodeTypeReference(propInfo.PropertyType);
                                codeType.Members.Add(field);
                                codeType.UserData.Add(fieldName, field);
                                field.UserData.Add("type", propInfo.PropertyType);
                            }
                            codeType.Members.Add(prop);
                        }
                    }
                    else
                    {
                        if (!cNamespace.UserData.Contains(cat))
                        {
                            CodeTypeDeclaration catInterface = new CodeTypeDeclaration(cat);
                            catInterface.IsInterface = true;
                            cNamespace.Types.Add(catInterface);
                            cNamespace.UserData.Add(cat, catInterface);
                        }
                        codeType.BaseTypes.Add(cat);
                    }
                }
                else if (op.Identifier as string == "once_per_object")
                {
                    onceArg.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "once_per_turn")
                {
                    oncePerTurnArg.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "scope")
                {
                    //It's a filter function
                    //					Debug.Log (op.Context.GetType ());
                    if (ScriptEngine.AnalyzeDebug)
                    {
                        Debug.Log((op.Context as Expression).Operands[0].GetType());
                    }

                    (((op.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts.Add("true");
                    DeclareVariableStatement retVal = new DeclareVariableStatement();
                    retVal.IsReturn       = true;
                    retVal.Name           = "applicable";
                    retVal.Type           = typeof(bool);
                    retVal.InitExpression = "false";

                    CreateEventFunction("Filter", op.Context, codeType, scopeMethod, false, retVal);
                    //CreateFilterFunction (op.Context as Expression, codeType);
                }
                else if (op.Identifier as string == "interaction")
                {
                    //It's a filter function
                    //					Debug.Log (op.Context.GetType ());
                    if (ScriptEngine.AnalyzeDebug)
                    {
                        Debug.Log((op.Context as Expression).Operands[0].GetType());
                    }

                    (((op.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts.Add("true");
                    DeclareVariableStatement retVal = new DeclareVariableStatement();
                    retVal.IsReturn       = true;
                    retVal.Name           = "applicable";
                    retVal.Type           = typeof(bool);
                    retVal.InitExpression = "false";

                    CreateEventFunction("Interaction", op.Context, codeType, interMethod, false, retVal);
                    interactionArg.Value = new CodeSnippetExpression("true");
                    //CreateFilterFunction (op.Context as Expression, codeType);

                    var type  = typeof(EventInteraction);
                    var props = type.GetProperties();
                    codeType.BaseTypes.Add(type);

                    foreach (var propInfo in props)
                    {
                        var prop = new CodeMemberProperty();
                        prop.HasGet = true;
                        prop.HasSet = true;
                        prop.Name   = propInfo.Name;
                        prop.Type   = new CodeTypeReference(propInfo.PropertyType);
                        var fieldName = NameTranslator.ScriptNameFromCSharp(prop.Name);
                        prop.GetStatements.Add(new CodeSnippetStatement(String.Format("return {0}; ", fieldName)));
                        prop.SetStatements.Add(new CodeSnippetStatement(String.Format("{0} = value; ", fieldName)));
                        prop.PrivateImplementationType = new CodeTypeReference(type);
                        if (!codeType.UserData.Contains(fieldName))
                        {
                            var field = new CodeMemberField();
                            field.Name = fieldName;
                            field.Type = new CodeTypeReference(propInfo.PropertyType);
                            codeType.Members.Add(field);
                            codeType.UserData.Add(fieldName, field);
                            field.UserData.Add("type", propInfo.PropertyType);
                        }
                        codeType.Members.Add(prop);
                    }
                }
                else if (op.Identifier as string == "action")
                {
                    //It's an action function
                    CreateEventFunction(op.Identifier as string, op.Context, codeType, actionMethod, true);
                }
                else if (op.Identifier as string == "utility")
                {
                    DeclareVariableStatement utVal = new DeclareVariableStatement();
                    utVal.IsReturn       = true;
                    utVal.Name           = "ut";
                    utVal.Type           = typeof(float);
                    utVal.InitExpression = "0";
                    CreateEventFunction(op.Identifier as string, op.Context, codeType, utMethod, false, utVal);
                }
                else if (op.Identifier as string == "depends")
                {
                    //Debug.Log(op);
                    //Debug.Log(((op.Context as Expression).Operands[0] as ExprAtom).Content.GetType().Name);
                    var        ctor            = ((((op.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts[0] as FunctionCall);
                    var        type            = Engine.FindType(NameTranslator.CSharpNameFromScript(ctor.Name));
                    MethodInfo initMethod      = type.GetMethod("Init");
                    var        args            = initMethod.GetParameters();
                    bool       hasInteractable = false;
                    bool       hasInitiator    = false;
                    foreach (var param in args)
                    {
                        if (param.Name == "interactable")
                        {
                            hasInteractable = true;
                        }
                        else if (param.Name == "initiator")
                        {
                            hasInitiator = true;
                        }
                    }
                    builder.Length = 0;
                    builder.Append("new ");
                    builder.Append(type.FullName);
                    builder.Append("().Init");
                    builder.Append("(");
                    if (hasInteractable)
                    {
                        builder.Append("this.root");
                        builder.Append(",");
                    }
                    if (hasInitiator)
                    {
                        builder.Append("this.initiator");
                        builder.Append(",");
                    }

                    foreach (var funcArg in ctor.Args)
                    {
                        builder.Append(exprInter.InterpretExpression(funcArg, dependenciesBlock).ExprString);
                        builder.Append(",");
                    }
                    if (builder[builder.Length - 1] == ',')
                    {
                        builder.Length = builder.Length - 1;
                    }
                    builder.Append(")");
                    deps.Add(builder.ToString());
                }
                else
                {
                    //No idea
                }
            }
            if (deps.Count > 0)
            {
                CodeMemberMethod getDepsOverride = new CodeMemberMethod();
                getDepsOverride.ReturnType = new CodeTypeReference(typeof(List <Dependency>));
                getDepsOverride.Name       = "GetDependencies";
                getDepsOverride.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                codeType.Members.Add(getDepsOverride);
                string listName = "list" + DeclareVariableStatement.VariableId++;
                string listOp   = String.Format("var {0} = new System.Collections.Generic.List<Dependency>({1});", listName, deps.Count);
                dependenciesBlock.Statements.Add(listOp);
                var addToListBlock = new FunctionBlock(dependenciesBlock);
                foreach (var newDep in deps)
                {
                    addToListBlock.Statements.Add(String.Format("{0}.Add({1});", listName, newDep));
                }
                dependenciesBlock.Statements.Add(addToListBlock);
                dependenciesBlock.Statements.Add(String.Format("return {0};", listName));
                getDepsOverride.Statements.Add(new CodeSnippetStatement(dependenciesBlock.ToString()));
            }
            CodeMemberMethod initOverrideMethod = new CodeMemberMethod();
            initOverrideMethod.Name       = "Init";
            initOverrideMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            codeType.Members.Add(initOverrideMethod);
            builder.Length = 0;
            builder.Append("base.Init();").AppendLine();
            foreach (var member in codeType.Members)
            {
                var field = member as CodeMemberField;
                if (field != null)
                {
                    builder.Append("this.").Append(field.Name).Append(" = ").Append("default(").Append((field.UserData["type"] as Type).FullName).Append(");").AppendLine();
                }
            }
            initOverrideMethod.Statements.Add(new CodeSnippetStatement(builder.ToString()));
        }
        CurProgress = MaxProgress;
        foreach (var type in codeTypes)
        {
            cNamespace.Types.Add(type);
        }

        CSharpCodeProvider   provider = new CSharpCodeProvider();
        CodeGeneratorOptions options  = new CodeGeneratorOptions();
        var writer = new StringWriter();

        provider.GenerateCodeFromNamespace(cNamespace, writer, options);
        Engine.GetPlugin <ScriptCompiler> ().AddSource(writer.ToString());
    }
    public override void Interpret(Script script)
    {
        MaxProgress = script.Entries.Count;
        for (int i = 0; i < script.Entries.Count; i++)
        {
            if (!Engine.Working)
            {
                Thread.CurrentThread.Abort();
            }
            CurProgress = i;
            var entry = script.Entries [i];
            CodeTypeDeclaration codeType = new CodeTypeDeclaration();
            //codeType.CustomAttributes.
            codeType.BaseTypes.Add(new CodeTypeReference(typeof(EventAction)));
            codeType.Name = entry.Identifier as string;
            codeTypes.Add(codeType);

            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogWarning((entry.Identifier as string).ToUpper());
            }

            var ctx = entry.Context as Context;
            if (ctx == null)
            {
                continue;
            }
            var actionMethod = typeof(EventAction).GetMethod("Action");
            var utMethod     = typeof(EventAction).GetMethod("Utility");
            var scopeMethod  = typeof(EventAction).GetMethod("Filter");
            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("EventActionAttribute");
            codeType.CustomAttributes.Add(attr);
            CodeAttributeArgument maxArg         = new CodeAttributeArgument("ShouldHaveMaxUtility", new CodeSnippetExpression("false"));
            CodeAttributeArgument catArg         = new CodeAttributeArgument("Category", new CodeSnippetExpression("\"basic\""));
            CodeAttributeArgument onceArg        = new CodeAttributeArgument("OncePerObject", new CodeSnippetExpression("false"));
            CodeAttributeArgument oncePerTurnArg = new CodeAttributeArgument("OncePerTurn", new CodeSnippetExpression("false"));
            CodeAttributeArgument interactionArg = new CodeAttributeArgument("IsInteraction", new CodeSnippetExpression("false"));
            CodeAttributeArgument tooltipArg     = new CodeAttributeArgument("Tooltip", new CodeSnippetExpression("\"\""));
            CodeAttributeArgument onceInCategory = new CodeAttributeArgument("OnceInCategory", new CodeSnippetExpression("false"));
            attr.Arguments.Add(maxArg);
            attr.Arguments.Add(catArg);
            attr.Arguments.Add(onceArg);
            attr.Arguments.Add(oncePerTurnArg);
            attr.Arguments.Add(interactionArg);
            attr.Arguments.Add(tooltipArg);
            attr.Arguments.Add(onceInCategory);
            for (int j = 0; j < ctx.Entries.Count; j++)
            {
                var op = ctx.Entries [j] as Operator;
                if (op == null)
                {
                    continue;
                }
                if (op.Identifier as string == "tooltip")
                {
                    tooltipArg.Value = new CodeSnippetExpression((op.Context as InternalDSL.Expression).Operands[0].ToString());
                }
                else if (op.Identifier as string == "is_interaction")
                {
                    interactionArg.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "once_per_category")
                {
                    onceInCategory.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "only_max_utility")
                {
                    maxArg.Value = new CodeSnippetExpression((op.Context as InternalDSL.Expression).Operands[0].ToString());
                }
                else if (op.Identifier as string == "category")
                {
                    catArg.Value = new CodeSnippetExpression(String.Format("\"{0}\"", (((op.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts[0]));
                }
                else if (op.Identifier as string == "once_per_object")
                {
                    onceArg.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "once_per_turn")
                {
                    oncePerTurnArg.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "scope")
                {
                    //It's a filter function
                    //					Debug.Log (op.Context.GetType ());
                    if (ScriptEngine.AnalyzeDebug)
                    {
                        Debug.Log((op.Context as Expression).Operands [0].GetType());
                    }

                    (((op.Context as Expression).Operands [0] as ExprAtom).Content as Scope).Parts.Add("true");
                    DeclareVariableStatement retVal = new DeclareVariableStatement();
                    retVal.IsReturn       = true;
                    retVal.Name           = "applicable";
                    retVal.Type           = typeof(bool);
                    retVal.InitExpression = "false";

                    CreateEventFunction("Filter", op.Context, codeType, scopeMethod, retVal);
                    //CreateFilterFunction (op.Context as Expression, codeType);
                }
                else if (op.Identifier as string == "action")
                {
                    //It's an action function
                    CreateEventFunction(op.Identifier as string, op.Context, codeType, actionMethod);
                }
                else if (op.Identifier as string == "utility")
                {
                    DeclareVariableStatement utVal = new DeclareVariableStatement();
                    utVal.IsReturn       = true;
                    utVal.Name           = "ut";
                    utVal.Type           = typeof(float);
                    utVal.InitExpression = "0";
                    CreateEventFunction(op.Identifier as string, op.Context, codeType, utMethod, utVal);
                }
                else
                {
                    //No idea
                }
            }
        }
        CurProgress = MaxProgress;
        foreach (var type in codeTypes)
        {
            cNamespace.Types.Add(type);
        }

        CSharpCodeProvider   provider = new CSharpCodeProvider();
        CodeGeneratorOptions options  = new CodeGeneratorOptions();
        var writer = new StringWriter();

        provider.GenerateCodeFromNamespace(cNamespace, writer, options);
        Engine.GetPlugin <ScriptCompiler> ().AddSource(writer.ToString());
    }
    void CreateEventFunction(string name, object context, CodeTypeDeclaration codeType, MethodInfo baseMethod, params object[] initStatements)
    {
        CodeMemberMethod method = new CodeMemberMethod();

        method.Name       = NameTranslator.CSharpNameFromScript(name);
        method.Attributes = MemberAttributes.Override | MemberAttributes.Public;
        method.ReturnType = new CodeTypeReference(baseMethod.ReturnType);
        var           args  = baseMethod.GetParameters();
        FunctionBlock block = new FunctionBlock(null, method, codeType);

        block.Statements.Add("var root = this.root;");
        //block.Statements.Add ("UnityEngine.Debug.Log(root.ToString() + IfStatement.AntiMergeValue++);");
        var externVar = new DeclareVariableStatement()
        {
            Name  = "External",
            IsArg = true,
            Type  = Engine.GetType("External")
        };

        block.Statements.Add(externVar);
        block.Statements.Add(new ContextStatement()
        {
            ContextVar         = externVar,
            InterpretInContext = Engine.GetPlugin <ExternalFunctionsPlugin>().Ctx.InterpretInContext
        });
        foreach (var initStmt in initStatements)
        {
            block.Statements.Add(initStmt);
        }
        //bool hasRoot = false;
        foreach (var arg in args)
        {
            //if (arg.Name == "root")
            //	hasRoot = true;
            method.Parameters.Add(new CodeParameterDeclarationExpression(arg.ParameterType, arg.Name));
            var paramVar = new DeclareVariableStatement();
            paramVar.Name  = arg.Name;
            paramVar.Type  = arg.ParameterType;
            paramVar.IsArg = true;
            block.Statements.Add(paramVar);
        }
        var rootVar = new DeclareVariableStatement();

        rootVar.Name  = "root";
        rootVar.Type  = typeof(GameObject);
        rootVar.IsArg = true;

        block.Statements.Add(rootVar);


        foreach (var member in codeType.Members)
        {
            var field = member as CodeMemberField;
            if (field != null)
            {
                var cachedVar = new DeclareVariableStatement();
                cachedVar.Name  = field.Name;
                cachedVar.Type  = field.UserData ["type"] as Type;
                cachedVar.IsArg = true;

                block.Statements.Add(cachedVar);
            }
        }
        //if (!hasRoot)
        //{
        //	Debug.LogFormat ("Method {0} in {1} has no root arg", baseMethod.Name, codeType.Name);
        //	return;
        //}

        codeType.Members.Add(method);
        var table = context as Context;

        if (table != null)
        {
            foreach (var entry in table.Entries)
            {
                Operator op    = entry as Operator;
                var      inter = functionOperators.GetInterpreter(op, block);
                if (inter == null)
                {
                    Debug.LogFormat("Can't find interpreter for operator {0} in {1} of {2}", op.Identifier, baseMethod.Name, codeType.Name);
                    continue;
                }
                inter.Interpret(op, block);
            }
            var retVal = block.FindStatement <DeclareVariableStatement> (v => v.IsReturn);
            if (retVal != null)
            {
                block.Statements.Add(String.Format("return {0};", retVal.Name));
            }
        }
        else
        {
            var expr = context as Expression;

            var retVal = block.FindStatement <DeclareVariableStatement> (v => v.IsReturn);
            //retVal.IsArg = true;
            block.Statements.Add(String.Format("return ({1}){0};", exprInter.InterpretExpression(expr, block).ExprString, TypeName.NameOf(retVal.Type)));
        }

        method.Statements.Add(new CodeSnippetStatement(block.ToString()));
    }
예제 #32
0
    public override void Interpret(Operator op, FunctionBlock block)
    {
        if (components.Count == 0)
        {
            ops = Engine.GetPlugin <EventFunctionOperators> ();
            var cmpTypes = Engine.FindTypesCastableTo <MonoBehaviour> ();
            foreach (var type in cmpTypes)
            {
                components.Add(NameTranslator.ScriptNameFromCSharp(type.Name), type);
            }
        }
        var varName = ((op.Args [0].Operands [0] as ExprAtom).Content as Scope).Parts [0] as string;

        block.Statements.Add(new DeclareVariableStatement()
        {
            Name           = varName,
            InitExpression = String.Format("new {1}(\"{0}\")", varName, typeof(GameObject)),
            Type           = typeof(GameObject),
            IsContext      = false
        });

        var           ctx      = op.Context as Context;
        FunctionBlock subBlock = new FunctionBlock(block, block.Method, block.Type);

        block.Statements.Add(subBlock);
        subBlock.Statements.Add(new DeclareVariableStatement()
        {
            Name           = varName + DeclareVariableStatement.VariableId++,
            InitExpression = varName,
            Type           = typeof(GameObject),
            IsContext      = true
        });
        foreach (var entry in ctx.Entries)
        {
            var subOp      = entry as Operator;
            var subContext = subOp.Context as Context;
            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.Log(subOp.Identifier.GetType());
            }
            if (subOp.Identifier is string)
            {
                Type cmpType = null;
                if (components.TryGetValue(subOp.Identifier as string, out cmpType))
                {
                    DeclareVariableStatement addVar = new DeclareVariableStatement();
                    addVar.Name           = "AddContext" + DeclareVariableStatement.VariableId++;
                    addVar.IsNew          = true;
                    addVar.InitExpression = String.Format("({1}){0}.AddComponent(typeof({1}))", varName, cmpType);
                    addVar.IsContext      = true;
                    addVar.Type           = cmpType;
                    subBlock.Statements.Add(addVar);
                }
            }
            if (!IsYes(subOp.Context as Expression))
            {
                var inter = ops.GetInterpreter(subOp, subBlock);
                if (inter != null)
                {
                    inter.Interpret(subOp, subBlock);
                }
            }
        }
        block.Statements.Add(String.Format("UnityEngine.Object.FindObjectOfType<Generators>().Generate({0}, 0.1f);", varName));
    }
    public override void Interpret(Operator op, FunctionBlock block)
    {
        base.Interpret(op, block);
        if (interpret)
        {
            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogFormat("Property {0} was interpreted by ContextPropertyInterpreter {1} already", op, propName);
            }
            return;
        }
        if (!(op.Context is Context))
        {
            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogFormat("Property context switch {0} has no context", op);
            }
            return;
        }
        if (ops == null)
        {
            ops = Engine.GetPlugin <EventFunctionOperators> ();
        }
        var varName = op.Identifier as string;

        FunctionBlock contextBlock = new FunctionBlock(block, block.Method, block.Type);

        block.Statements.Add(contextBlock);
        DeclareVariableStatement declareVar = new DeclareVariableStatement();

        declareVar.Type      = propType;
        declareVar.Name      = "subContext" + DeclareVariableStatement.VariableId++;
        declareVar.IsContext = true;

        DeclareVariableStatement contextVar = block.FindStatement <DeclareVariableStatement> (v => v.Name == varName);

        if (contextVar == null)
        {
            var sCtx = block.FindStatement <ContextStatement> (v => v.InterpretInContext(op, block) != null && v.ContextVar.IsContext);
            contextVar = sCtx != null ? sCtx.ContextVar : null;
        }

        if (contextVar == null)
        {
            declareVar.InitExpression = String.Format("root.{0}", propName);
        }
        else
        {
            declareVar.InitExpression = String.Format("{1}.{0}", propName, contextVar.Name);
        }
        contextBlock.Statements.Add(declareVar);
        contextBlock.Statements.Add(new ContextStatement()
        {
            ContextVar         = declareVar,
            InterpretInContext = InterpretInContext
        });
        IfStatement isNotNull = new IfStatement();

        isNotNull.CheckExpression = String.Format("{0} != null", declareVar.Name);
        isNotNull.TrueBlock       = new FunctionBlock(contextBlock);
        contextBlock.Statements.Add(isNotNull);
        contextBlock = isNotNull.TrueBlock;
        foreach (var entry in (op.Context as Context).Entries)
        {
            //Debug.LogFormat("Interpreting {0} as part of {1} context", (entry as Operator).Identifier, op.Identifier);
            var subOp = entry as Operator;
            if (subOp == null)
            {
                continue;
            }
            FunctionOperatorInterpreter opInter = null;
            if ((opInter = ops.GetInterpreter(subOp, contextBlock)) == null)
            {
                if (!contextSwitches.TryGetValue(subOp.Identifier as string, out opInter))
                {
                    if (!functions.TryGetValue(subOp.Identifier as string, out opInter))
                    {
                        if (!properties.TryGetValue(subOp.Identifier as string, out opInter))
                        {
                            //Debug.LogFormat ("Can't interpret context operator {1} in {0}", block.Method.Name, subOp.Identifier);
                            continue;
                        }
                    }
                }
            }
            opInter.Interpret(subOp, contextBlock);
        }
    }
        private void CreateDeclareVariableDefinitionForParmeter(string name, SqlDataType type)
        {
            var declare = new DeclareVariableStatement();
            var declareElement = new DeclareVariableElement();

            var dataType = GetDataType(type);
            declareElement.Value = GetDefaultValue(dataType);
            declareElement.DataType = dataType;
            declareElement.VariableName = name.ToIdentifier();
            declare.Declarations.Add(declareElement);

            _testProcedure.StatementList.Statements.Add(declare);
        }
 public override void ExplicitVisit(DeclareVariableStatement fragment)
 {
     _fragments.Add(fragment);
 }