private void Apply_Click(object sender, EventArgs e)
        {
            mIsUpdateTextDirty = true;

            if (ResetOnApplyCheckBox.Checked)
            {
                ResetClick(null, null);
            }

            mClassLevelCodeContext = new CodeContext(null);

            try
            {
                ApplyRichTextBoxScript(ClassScopeTextBox);
            }
            catch
            {
                MessageBox.Show("Error parsing Class Scope script");
            }

            try
            {
                mClassLevelCodeContext.AddVariableStack();
                ApplyRichTextBoxScript(InitializeTextBox);

                mClassLevelCodeContext.RemoveVariableStack();
            }
            catch
            {
                MessageBox.Show("Error parsing Initialize script");
            }
        }
示例#2
0
        private object EvaluateUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, CodeContext context)
        {
            ExpressionParseType referenceOrValue;
            var operatorType = unaryOperatorExpression.Operator;
            if(operatorType == UnaryOperatorType.PostDecrement ||
                operatorType == UnaryOperatorType.PostIncrement ||
                operatorType == UnaryOperatorType.Decrement ||
                operatorType == UnaryOperatorType.Increment)
            {
                referenceOrValue = ExpressionParseType.GetReference;
            }
            else
            {
                referenceOrValue = ExpressionParseType.Evaluate;
            }
            // We need to get referene so that the 
            object value = EvaluateExpression(unaryOperatorExpression.Expression, context, referenceOrValue);
            if (value == null)
            {
                return value;
            }
            else
            {

                return PrimitiveOperationManager.Self.ApplyUnaryOperation(unaryOperatorExpression.Operator, value, referenceOrValue);
            }

        }
 public ExecuteScriptInstruction(CodeContext context, string script)
 {
     mCodeContext = context;
     mScript = script;
 }
        public CustomVariable CreateCustomVariableFor(string newVariableDeclarationType, string leftOfEquals, string rightOfEquals, ElementRuntime elementRuntime, CodeContext codeContext)
        {
            IElement element = null;
            CustomVariable toReturn = null;
            if (elementRuntime != null)
            {
                element = elementRuntime.AssociatedIElement;
                toReturn = element.GetCustomVariableRecursively(leftOfEquals);
            }
            // See if there is already a CustomVariable for this:

            if (toReturn != null)
            {
                toReturn = toReturn.Clone();
            }

            if (toReturn == null)
            {
                // If there's no event, we gotta create one
                toReturn = new CustomVariable();
                toReturn.Name = leftOfEquals;

                // If the left side has a period, that means the user is setting a variable on a contained object (because this. will already have been stripped)
                if (leftOfEquals.Contains('.'))
                {
                    int indexOfDot = leftOfEquals.IndexOf('.');
                    toReturn.SourceObject = leftOfEquals.Substring(0, indexOfDot);
                    toReturn.SourceObjectProperty = leftOfEquals.Substring(indexOfDot + 1, leftOfEquals.Length - (indexOfDot + 1));
                }


                if (newVariableDeclarationType == null)
                {
                    Type throwaway = null;
                    toReturn.Type = GetTypeStringForValue(leftOfEquals, elementRuntime, codeContext, out throwaway);
                }
                else
                {
                    toReturn.Type = newVariableDeclarationType;
                }

            }

            object valueToAssign = null;

            if (!string.IsNullOrEmpty(rightOfEquals))
            {
                valueToAssign = mExpressionParser.EvaluateExpression(rightOfEquals, codeContext);
            }

            if (toReturn.Type == null && valueToAssign != null)
            {
                toReturn.Type = valueToAssign.GetType().FullName;
            }

            if (toReturn.Type != null)
            {


                if (toReturn.GetRuntimeType() == typeof(float))
                {
                    if (valueToAssign is double)
                    {
                        valueToAssign = (float)((double)valueToAssign);
                    }
                    else if (valueToAssign is int)
                    {
                        valueToAssign = (float)((int)valueToAssign);
                    }
                }


                if (valueToAssign is float && float.IsNaN( (float)valueToAssign ))
                {
                    int m = 3;
                }

                toReturn.DefaultValue = valueToAssign;
            }

            return toReturn;
        }
        public bool ApplyAssignment(CodeContext codeContext, string leftOfEquals, string rightOfEquals, string newVariableDeclarationType,
            AssignmentOperatorType assignmentOperator)
        {
            bool succeeded = false;
            if (newVariableDeclarationType == null && variables.Contains(leftOfEquals))
            {
                // Circular depenency detected!
                AddErrorText("Circular dependency detected on " + leftOfEquals);
            }
            else
            {

                variables.Add(leftOfEquals);

                try
                {
                    AssignValue(newVariableDeclarationType, leftOfEquals, rightOfEquals, codeContext, assignmentOperator);
                    succeeded = true;
                }
                catch (Exception exception)
                {
                    string combined = newVariableDeclarationType + " " + leftOfEquals + " assignment " + rightOfEquals;
                    AddErrorText("Parse error in:  " + combined);
                    mParserLog.AppendLine("Parse error for line " + combined + "\nException:\n" + exception);
                }
                variables.Remove(leftOfEquals);
            }

            return succeeded;
        }
        private bool ApplyAssignmentLine(AssignmentExpression expression, CodeContext codeContext)
        {
            bool succeeded = false;

            string leftOfEquals = expression.Left.GetText();
            string rightOfEquals = expression.Right.GetText();
            
            // Eventually we'll want to get rid of this, but a lot of the code parsing 
            // expects there to be no "this.", so let's get rid of this.:
            if (leftOfEquals.StartsWith("this."))
            {
                leftOfEquals = leftOfEquals.Substring("this.".Length);
            }

            string newVariableDeclarationType = null;
            // I don't know if this if statement can possibly evaluate to true anymore...
            if (leftOfEquals.Contains(' '))
            {
                newVariableDeclarationType = leftOfEquals.Substring(0, leftOfEquals.IndexOf(' '));
                leftOfEquals = leftOfEquals.Substring(leftOfEquals.IndexOf(' ') + 1, leftOfEquals.Length - (leftOfEquals.IndexOf(' ') + 1));
            }

            succeeded = ApplyAssignment(codeContext, leftOfEquals, rightOfEquals, newVariableDeclarationType, expression.Operator);

            return succeeded;
        }
        private bool ApplyConditionalBlocks(string[] allLines, IElement element, CodeContext codeContext, string fileName, ref int index)
        {
            bool succeeded = true;

            BlockType lastBlockType = BlockType.None;

            BlockType nextBlockType = ConditionalCodeBlock.GetBlockTypeStartingAt(allLines, index);

            List<ConditionalCodeBlock> conditionalBlocks = new List<ConditionalCodeBlock>();

            while (nextBlockType.LinksFromPreviousType(lastBlockType))
            {
                ConditionalCodeBlock ccb = ConditionalCodeBlock.GetConditionalBlockFrom(allLines, index);
                conditionalBlocks.Add(ccb);
                lastBlockType = nextBlockType;

                index += ccb.LineCountIncludingConditionLine;
                nextBlockType = ConditionalCodeBlock.GetBlockTypeStartingAt(allLines, index);

            }


            // Only one of these blocks can trigger
            foreach (ConditionalCodeBlock ccb in conditionalBlocks)
            {
                // This code context is for the contents of the condition.
                // For example, the i variable in a for-loop will have scope
                // limited to the application of the for-loop.
                codeContext.AddVariableStack();

                bool shouldExecute = BranchingParser.Self.DetermineIfShouldExecute(
                    this, codeContext, ccb, mExpressionParser, true);


                while (shouldExecute)
                {
                    codeContext.AddVariableStack();

                    int startBlock = ccb.FirstLineOfBlockIndex;
                    int blockLength = ccb.BlockLength;
                    if (ccb.IsBlockWrappedInBrackets)
                    {
                        startBlock++;
                        blockLength -= 2;
                    }
                    succeeded = ApplyLinesInternal(allLines, startBlock, blockLength, element, codeContext, fileName);

                    
                    shouldExecute = false;
                    if (succeeded)
                    {
                        if (ccb.BlockType == BlockType.For)
                        {
                            BranchingParser.Self.IncrementFor(codeContext, ccb, mExpressionParser);

                            shouldExecute = BranchingParser.Self.DetermineIfShouldExecute(
                                this, codeContext, ccb, mExpressionParser, false);
                        }
                        else if (ccb.BlockType == BlockType.While)
                        {
                            shouldExecute = BranchingParser.Self.DetermineIfShouldExecute(
                                this, codeContext, ccb, mExpressionParser, false);
                        }
                    }

                    codeContext.RemoveVariableStack();
                }
                codeContext.RemoveVariableStack();

            }

            return succeeded;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="lines"></param>
        /// <param name="startingIndex"></param>
        /// <param name="count"></param>
        /// <param name="element"></param>
        /// <param name="codeContext"></param>
        /// <param name="fileName"></param>
        /// <param name="addStackVariables"></param>
        /// <param name="removeStackVariables"></param>
        /// <returns>Whether the application succeeded.</returns>
        public bool ApplyLinesInternal(string[] lines, int startingIndex, int count, IElement element, 
            CodeContext codeContext, string fileName = null, bool addStackVariables = true, bool removeStackVariables = true)
        {
            LastErrorLine = -1;
            bool returnValue = true;
            mCallStackVariables.Add(new Dictionary<string, object>());
            for(int i = startingIndex; i < startingIndex + count && i < lines.Length; i++)
            {
                string line = lines[i];

                try
                {
                    int iBefore = i;
                    ApplyLine(line.Trim(), codeContext, lines, fileName, ref i);
                    if (iBefore != i)
                    {
                        // ApplyLine may increment the lines if in a 
                        // conditional code block.  If so we need to subtract
                        // 1 because our for-loop will automatically add one.
                        i--;
                    }


                }
                catch (StateSettingException e)
                {
                    string errorText = null;

                    if (string.IsNullOrEmpty(fileName))
                    {
                        errorText = "Error setting state for line:  ";
                    }
                    else
                    {
                        errorText = "Error setting state for line in the file " + fileName + ":  ";
                    }
                    AddErrorText(errorText + line);
                }
                catch (Exception)
                {
                    // There was a scripting error
                    // Eventually we want to log this
                    AddErrorText("Unknown line:  " + line);
                    returnValue = false;
                    LastErrorLine = i;
                    break;
                }
            }
            mCallStackVariables.Remove(TopOfVariableStack);
            return returnValue;
        }
示例#9
0
        private static void GetObjectFromContainerAndNameEvaluate(object container, string memberName, CodeContext codeContext, ref object foundValue, ref bool wasFound)
        {

            if (container is CsvEntry)
            {
                foundValue = (container as CsvEntry).GetValue(memberName);

            }

            if (codeContext.VariableStack.Count == 0)
            {
                throw new Exception("codeContext doesn't have any entries.  It needs to have at least one");
            }

            int index = -1;
            codeContext.GetVariableInformation(memberName, out index);

            if (index != -1)
            {
                foundValue = codeContext.VariableStack[index][memberName];
                wasFound = true;
            }

            if (wasFound == false && foundValue == null && container != null)
            {
                object instance = container;
                Type type = container.GetType();
                if (container is Type)
                {
                    instance = null;
                    type = container as Type;
                }

                // First let's do reflection
                if (container is ElementRuntime && (container as ElementRuntime).DirectObjectReference != null)
                {
                    ElementRuntime containerElementRuntime = container as ElementRuntime;

                    if (LateBinder.GetInstance(containerElementRuntime.DirectObjectReference.GetType()).TryGetValue(containerElementRuntime.DirectObjectReference, memberName, out foundValue))
                    {
                        // do nothing.
                        wasFound = true;
                    }
                }
                else
                {


                    if (LateBinder.GetInstance(type).TryGetValue(instance, memberName, out foundValue))
                    {
                        // do nothing.
                        wasFound = true;
                    }
                }

                if (foundValue == null && container is ElementRuntime)
                {
                    ElementRuntime containerElementRuntime = container as ElementRuntime;

                    IElement containerElement = (container as ElementRuntime).AssociatedIElement;


                    foundValue = TryToGetStateCategoryFromElement(memberName, containerElement);

                    if (foundValue == null)
                    {
                        foundValue = containerElementRuntime.GetContainedElementRuntime(memberName);
                    }

                    if (foundValue == null)
                    {
                        foundValue = containerElementRuntime.GetReferencedFileSaveRuntime(memberName);
                    }

                    if (foundValue == null && containerElement != null)
                    {
                        // Some values like X or Y are stored inside the element runtime
                        // (because it actually stores those values locally).  However, if
                        // a value doesn't have an underlying value, 
                        CustomVariable variable = containerElementRuntime.GetCustomVariable(memberName, VariableGetType.AsExistsAtRuntime);
                        //CustomVariable variable = containerElement.GetCustomVariableRecursively(memberName);
                        if (variable != null)
                        {
                            if (variable.GetIsCsv())
                            {
                                string rfsToLookFor = FileManager.RemoveExtension(variable.Type);
                                foundValue = containerElementRuntime.GetReferencedFileSaveRuntime(rfsToLookFor);
                                // if it's null, maybe it's a global file
                                if (foundValue == null)
                                {
                                    ReferencedFileSave rfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(variable.Type);
                                    if (rfs != null)
                                    {
                                        foundValue = GluxManager.GlobalContentFilesRuntime.LoadReferencedFileSave(rfs, true, containerElement);
                                    }
                                }

                                if (foundValue != null)
                                {
                                    foundValue = GetCsvEntryByRequiredKey(variable.DefaultValue as string, foundValue as RuntimeCsvRepresentation);
                                    // We have a RFS, so let's get values out of it
                                }
                            }
                            else
                            {
                                foundValue = variable.DefaultValue;
                                wasFound = true;
                            }
                        }
                    }
                    wasFound = foundValue != null;
                }
                else if (container is StateSaveCategory)
                {
                    foundValue = (container as StateSaveCategory).States.FirstOrDefault(state => state.Name == memberName);
                    wasFound = foundValue != null;
                }
                else if (container is IElement)
                {
                    foundValue = TryToGetStateCategoryFromElement(memberName, container as IElement);
                }

            }
            if (wasFound == false && foundValue == null)
            {
                foundValue = ObjectFinder.Self.GetElementUnqualified(memberName);
                wasFound = foundValue != null;
            }
            if (wasFound == false && foundValue == null)
            {
                foundValue = TypeManager.GetTypeFromString(memberName);

                wasFound = foundValue != null;


            }
        }
示例#10
0
        private static void GetObjectFromContainerAndNameReference(object container, string memberName, CodeContext codeContext, 
            ref object foundValue, ref bool wasFound)
        {
            object originalContainer = container;

            if (container == null)
            {
                int stackDepth = -1;
                codeContext.GetVariableInformation(memberName, out stackDepth);

                if (stackDepth != -1)
                {
                    StackVariableReference reference = new StackVariableReference();
                    reference.StackIndex = stackDepth;
                    reference.VariableName = memberName;
                    reference.CodeContext = codeContext;

                    foundValue = reference;
                    wasFound = foundValue != null;
                }
            }
            else
            {
                
                Type typeToGetFrom = null;

                if (container is IAssignableReference)
                {
                    container = ((IAssignableReference)container).CurrentValue;
                }

                if (container is Type)
                {
                    typeToGetFrom = container as Type;
                }
                else if (container != null)
                {
                    typeToGetFrom = container.GetType();
                }

                AssignableReference assignableReference = null;

                var fieldInfo = typeToGetFrom.GetField(memberName);
                if (fieldInfo != null)
                {
                    assignableReference = new AssignableReference();
                    assignableReference.FieldInfo = fieldInfo;
                    assignableReference.Owner = container;

                    if (originalContainer is IAssignableReference)
                    {
                        assignableReference.Parent = originalContainer as IAssignableReference;
                    }
                }
                else
                {
                    var propertyInfo = typeToGetFrom.GetProperty(memberName);
                    if (propertyInfo != null)
                    {
                        assignableReference = new AssignableReference();
                        assignableReference.PropertyInfo = propertyInfo;
                        assignableReference.Owner = container;

                        if (originalContainer is IAssignableReference)
                        {
                            assignableReference.Parent = originalContainer as IAssignableReference;
                        }
                    }
                }

                foundValue = assignableReference;
                wasFound = foundValue != null;
            }
        }
示例#11
0
        private static object GetObjectFromContainerAndMemberName(object container, string memberName, CodeContext codeContext, ExpressionParseType parseType)
        {
            object foundValue = null;
            bool wasFound = false;

            if (parseType == ExpressionParseType.Evaluate)
            {
                if (container is IAssignableReference)
                {
                    container = ((IAssignableReference)container).CurrentValue;
                }

                GetObjectFromContainerAndNameEvaluate(container, memberName, codeContext, ref foundValue, ref wasFound);
            }
            else
            {
                GetObjectFromContainerAndNameReference(container, memberName, codeContext, ref foundValue, ref wasFound);

            }
            return foundValue;
        }
示例#12
0
        private object EvaluateMemberReferenceExpression(ICSharpCode.NRefactory.CSharp.MemberReferenceExpression memberReferenceExpression, CodeContext codeContext, ExpressionParseType parseType)
        {
            object container = EvaluateExpression(memberReferenceExpression.Target, codeContext, ExpressionParseType.GetReference);
            if (container == null)
            {
                // Couldn't get a member reference, so it could be a variable on an Element, so let's try a non-reference get
                container = EvaluateExpression(memberReferenceExpression.Target, codeContext, ExpressionParseType.Evaluate);
            }
            string memberName = memberReferenceExpression.MemberName;

            object foundValue = GetObjectFromContainerAndMemberName(container, memberName, codeContext, parseType);

            return foundValue;
        }
示例#13
0
        private object EvaluateObjectCreateExpression(ICSharpCode.NRefactory.CSharp.ObjectCreateExpression objectCreateExpression, CodeContext codeContext)
        {

            string typeAsString = objectCreateExpression.Type.GetText();

            Type type = TypeManager.GetTypeFromString(typeAsString);

            if (type != null)
            {
                List<object> arguments = new List<object>();
                foreach (var argumentExpression in objectCreateExpression.Arguments)
                {
                    arguments.Add(EvaluateExpression(argumentExpression, codeContext));
                }

                return Activator.CreateInstance(type, arguments.ToArray());
            }
            else
            {
                return null;
            }
        }
示例#14
0
        private object EvaluateIndexerExpression(ICSharpCode.NRefactory.CSharp.IndexerExpression indexerExpression, CodeContext codeContext)
        {
            object evaluatedTarget = EvaluateExpression(indexerExpression.Target, codeContext);

            if (evaluatedTarget is RuntimeCsvRepresentation)
            {
                List<object> evaluatedArguments = new List<object>();
                foreach (var argument in indexerExpression.Arguments)
                {
                    evaluatedArguments.Add(EvaluateExpression(argument, codeContext));
                }
                string requiredKey = evaluatedArguments[0] as string;


                
                RuntimeCsvRepresentation rcr = evaluatedTarget as RuntimeCsvRepresentation;

                return GetCsvEntryByRequiredKey(requiredKey, rcr);

            }
            return null;
        }
示例#15
0
 private object EvaluateLambdaExpression(LambdaExpression lambdaExpression, CodeContext codeContext)
 {
     ExecuteScriptInstruction esi = new ExecuteScriptInstruction(codeContext, lambdaExpression.Body.GetText());
     return esi;
 }
示例#16
0
        private void ApplyEventResponseSave(ElementRuntime elementRuntime, EventResponseSave ers)
        {
            IElement element = elementRuntime.AssociatedIElement;
            string projectDirectory = FileManager.GetDirectory(GlueViewState.Self.CurrentGlueProjectFile);
            string[] lines = GetMethodLines(element, ers, projectDirectory);
            string fileName = EventResponseSave.GetSharedCodeFullFileName(element, projectDirectory);

            CodeContext codeContext = new CodeContext(elementRuntime);
            ApplyLinesInternal(lines, 0, lines.Length, element, codeContext, fileName);
        }
示例#17
0
        public void ApplyLines(string script, CodeContext codeContext = null)
        {
            lock (mStringsToApply)
            {
                ScriptAndContext toAdd = new ScriptAndContext();
                toAdd.Script = script;
                toAdd.Context = codeContext;

                mStringsToApply.Add(toAdd);
            }
        }
示例#18
0
        private object EvaluateInvocationExpression(ICSharpCode.NRefactory.CSharp.InvocationExpression invocationExpression, CodeContext codeContext)
        {
            List<object> argumentValues = new List<object>();
            foreach (var unevaluated in invocationExpression.Arguments)
            {
                argumentValues.Add(EvaluateExpression(unevaluated, codeContext));
            }

            return EvaluateInvocationExpression(invocationExpression.Target, argumentValues, codeContext);
        }
示例#19
0
        private void ApplyLine(string line, CodeContext codeContext, string[] allLines, string fileName, ref int index)
        {
            bool succeeded = true;

            mParserLog.AppendLine("--- " + line + " ---");
            

            if (string.IsNullOrEmpty(line))
            {
                // do nothing
                // This may be empty
                // because the split function
                // may have returned a line with
                // only a newline character.  If so
                // that becomes an empty line when trim
                // is called on it.  This could be a line
                // that was trimmed which is now empty.
            }
            else if (line.Trim().StartsWith("//"))
            {
                // comment, carry on
            }
            else if (line.Trim().StartsWith("#region") || line.Trim().StartsWith("#endregion"))
            {
                // we can skip region blocks
            }
            else if (ConditionalCodeBlock.GetBlockTypeStartingAt(allLines, index) != BlockType.None)
            {
                ElementRuntime elementRuntime = codeContext.ContainerInstance as ElementRuntime;

                IElement element = null;

                if (elementRuntime != null)
                {
                    element = elementRuntime.AssociatedIElement;
                }

                succeeded = ApplyConditionalBlocks(allLines, element, codeContext, fileName, ref index);

                if (!succeeded)
                {
                    throw new Exception();
                }
            }
            else
            {

                // here we want to identify how many lines make up the statement since
                // it could be something like
                // this.X = 3
                //       + 4;
                int numberOfLinesInStatement = GetNumberOfLinesInRegularStatement(allLines, index);

                string combined = CombineLines(allLines, index, numberOfLinesInStatement);

                string trimmedCombined = combined.Trim();
                if (trimmedCombined.StartsWith("{") && trimmedCombined.EndsWith("}"))
                {
                    combined = trimmedCombined.Substring(1, trimmedCombined.Length - 2);
                }
                CSharpParser parser = new CSharpParser();
                var statements = parser.ParseStatements(combined);



                // I can be incremented by this function by the number of lines.
                // If this value is incremented, then the calling function is responsible
                // for recognizing that in its loop and acting properly.  The calling function
                // assumes an increment of 1 so we won't do anything if there's only 1 line in this
                // statement.
                if (numberOfLinesInStatement != 1)
                {
                    index += numberOfLinesInStatement;
                }

                foreach (var statement in statements)
                {
                    if (statement is ExpressionStatement)
                    {
                        Expression expression = ((ExpressionStatement)statement).Expression;
                        if (expression is InvocationExpression || expression is UnaryOperatorExpression)
                        {
                            mExpressionParser.EvaluateExpression(expression, codeContext);
                        }
                        else if (expression is AssignmentExpression)
                        {
                            succeeded = ApplyAssignmentLine(expression as AssignmentExpression, codeContext);
                            if (!succeeded)
                            {
                                throw new Exception();
                            }
                        }
                        else if (expression is IdentifierExpression || expression is MemberReferenceExpression)
                        {
                            // This is probably an incomplete line, so let's tolerate it and move on...
                        }
                        else
                        {
                            throw new Exception();
                        }
                    }
                    else if (statement is VariableDeclarationStatement)
                    {
                        VariableDeclarationStatement vds = statement as VariableDeclarationStatement;

                        foreach (var child in vds.Children)
                        {
                            if (child is VariableInitializer)
                            {
                                VariableInitializer variableInitializer = child as VariableInitializer;
                                ApplyAssignment(variableInitializer, vds, codeContext);
                                //variableInitializer.
                            }
                        }
                        //ApplyAssignment(codeContext, vds.Variables.First().GetText(), vds.
                        //vds.E
                        //ApplyAssignmentLine(statement.ToString(), codeContext);
                    }
                    //if ( is AssignmentExpression || result is MemberReferenceExpression)
                    //{
                    //    ApplyAssignmentLine(combined, codeContext);
                    //}
                    //else if (result is InvocationExpression)
                    //{
                    //    ApplyMethodCall(combined, codeContext);
                    //}
                    else
                    {
                        AddErrorText("Unknown line(s):  " + combined);
                    }
                }
            }

        }
示例#20
0
        private object EvaluateInvocationExpression(Expression expression, List<object> argumentValues, CodeContext codeContext)
        {
            string invocation = expression.ToString();


            object lastObject = codeContext.ContainerInstance;
            if (invocation == "System.Math.Max" ||
                invocation == "Math.Max")
            {
                return PrimitiveOperationManager.Self.MaxObjects(argumentValues[0], argumentValues[1]);
            }
            else if (invocation == "GetFile" && argumentValues.Count == 1)
            {
                ElementRuntime elementRuntime = null;
                // We're going to have to assume the user means to call GetFile from the current element
                if (codeContext.ContainerInstance != null)
                {
                    if (codeContext.ContainerInstance is ElementRuntime)
                    {
                        elementRuntime = codeContext.ContainerInstance as ElementRuntime;
                    }
                }

                if (elementRuntime != null)
                {
                    return elementRuntime.GetReferencedFileSaveRuntime(argumentValues[0] as string);
                }
                else
                {
                    return null;
                }
            }
            else if (invocation == "System.Math.Min" ||
                invocation == "Math.Min")
            {
                return PrimitiveOperationManager.Self.MinObjects(argumentValues[0], argumentValues[1]);
            }
            else if (invocation == "InterpolateBetween" || invocation == "this.InterpolateBetween")
            {
                MethodCallParser.InterpolateBetween(lastObject as ElementRuntime, argumentValues[0], argumentValues[1], argumentValues[2]);
                return null;
            }
            else
            {
                object caller = GetCaller(expression, codeContext);

                MethodInfo methodInfo;

                object toReturn = null;

                Type[] argumentTypes = new Type[argumentValues.Count];

                for (int i = 0; i < argumentValues.Count; i++)
                {
                    if (argumentValues[i] != null)
                    {
                        argumentTypes[i] = argumentValues[i].GetType();
                    }
                }

                if (TryHandleSpecialCase(expression, argumentValues, argumentTypes, codeContext, invocation, caller, out toReturn))
                {
                    // do nothing, toReturn is set
                }
                else
                {
                    GetMethodInfo(expression, argumentValues, argumentTypes, codeContext, invocation, caller, out methodInfo);

                    if (methodInfo != null)
                    {
                        toReturn = methodInfo.Invoke(caller, argumentValues.ToArray());
                    }
                }
                return toReturn;
            }
            //else
            //{
            //    throw new NotImplementedException();
            //}
        }
示例#21
0
        private void ApplyMethodCall(string line, CodeContext codeContext)
        {
            
            mExpressionParser.EvaluateExpression(line, codeContext);
            mParserLog.AppendLine("Called method from line: " + line);

        }
示例#22
0
        private object GetCaller(ICSharpCode.NRefactory.CSharp.Expression expression, CodeContext codeContext)
        {
            object caller;
            if (expression is MemberReferenceExpression)
            {
                MemberReferenceExpression mre = expression as MemberReferenceExpression;


                caller = EvaluateExpression(mre.Target, codeContext);

                if (caller == null)
                {
                    Type type = TypeManager.GetTypeFromString(mre.Target.GetText());
                    if (type != null)
                    {
                        TypeReference typeReference = new TypeReference();
                        typeReference.Type = type;

                        caller = typeReference;
                    }
                        
                }


                if (caller == null)
                {
                    caller = codeContext.ContainerInstance;
                }


                return caller;


            }
            else if (expression is InvocationExpression)
            {
                return codeContext.ContainerInstance;
            }
            else if (expression is IdentifierExpression)
            {
                return codeContext.ContainerInstance;
            }
            else
            {
                return null;

            }
        }
示例#23
0
 public bool ApplyAssignment(VariableInitializer variableInitializer, VariableDeclarationStatement vds, CodeContext codeContext)
 {
     return ApplyAssignment(codeContext, variableInitializer.Name, variableInitializer.Initializer.GetText(),
         vds.Type.GetText(), AssignmentOperatorType.Assign);
 }
示例#24
0
        private bool TryHandleSpecialCase(Expression expression, List<object> argumentValues, Type[] argumentTypes, CodeContext codeContext, string invocation, object caller, out object result)
        {
            result = null;
            bool handled = false;
            if (expression is MemberReferenceExpression)
            {
                MemberReferenceExpression mre = expression as MemberReferenceExpression;

                if(mre.MemberName == "Call" &&
                        argumentValues.Count == 1 && argumentValues[0] is ExecuteScriptInstruction)
                {
                    if (caller != null && caller is PositionedObject)
                    {
                        // call the ExecuteScriptInstruction itself - it has a After method so it can handle whatever.
                        result = argumentValues[0];
                        handled = true;
                    }
                }

                if (!handled)
                {
                    if (caller != null && caller is ElementRuntime)
                    {
                        handled = TryHandleElementRuntimeSpecialCases(argumentValues, argumentTypes, caller as ElementRuntime, ref result, mre);
                    }
                }
                if (!handled && caller is IElement)
                {
                    if (mre.MemberName == "GetFile")
                    {
                        IElement element = caller as IElement;

                        //ReferencedFileSave rfs = element.GetReferencedFileSaveByInstanceName(argumentValues[0] as string);

                        IElement containerInstance = null;
                        if (codeContext.ContainerInstance != null)
                        {
                            if (codeContext.ContainerInstance is ElementRuntime)
                            {
                                containerInstance = (codeContext.ContainerInstance as ElementRuntime).AssociatedIElement;
                            }
                        }
                        if (element == containerInstance)
                        {
                            result = (codeContext.ContainerInstance as ElementRuntime).GetReferencedFileSaveRuntime(argumentValues[0] as string);
                            handled = true;
                        }
                    }
                }
                if (!handled && caller.GetType().Name == "SetHolder`1")
                {
                    MethodInfo methodInfo;

                    // let's invoke this regularly, but add it to the container
                    GetMethodInfo(expression, argumentValues, argumentTypes, codeContext, invocation, caller, out methodInfo);
                    if (methodInfo != null)
                    {
                        result = methodInfo.Invoke(caller, argumentValues.ToArray());

                        // no need to do anything?
                        //if (result is Instruction)
                        //{
                        //    ((result as Instruction).Target as IInstructable).Instructions.Add(result as Instruction);
                        //}
                        handled = true;
                    }
                }

            }

            return handled;
        }
示例#25
0
        private void AssignValue(string newVariableDeclarationType,  string leftOfEquals, string rightOfEquals, CodeContext codeContext,
            AssignmentOperatorType assignOperator)
        {
            ElementRuntime elementRuntime = codeContext.ContainerInstance as ElementRuntime;
            IElement element = null;

            if (elementRuntime != null)
            {
                element = elementRuntime.AssociatedIElement;
            }

            CustomVariable customVariable = CreateCustomVariableFor(newVariableDeclarationType, leftOfEquals, rightOfEquals, elementRuntime, codeContext);

            if (customVariable.Name.CountOf('.') > 1)
            {
                throw new Exception("Script parsing doesn't support setting properties/fields on properties/fields.  In other words, assigning something.X is okay, but not something.Position.x");
            }

            mParserLog.AppendLine("Left side:  " + leftOfEquals + "  RightSide:  " + rightOfEquals + "    Resulting variable:   " + customVariable);

            if (newVariableDeclarationType != null)
            {
                TopOfVariableStack[leftOfEquals] = customVariable.DefaultValue;
                codeContext.VariableStack.Last().Add(leftOfEquals, customVariable.DefaultValue);
            }
            else if (customVariable != null)
            {
                if (codeContext.ContainerInstance != null)
                {
                    ElementRuntime runtime = codeContext.ContainerInstance as ElementRuntime;
                    runtime.SetCustomVariable(customVariable, runtime.AssociatedIElement, customVariable.DefaultValue, true, VariableSettingOptions.LiteralSet );
                }
                else
                {
                    var reference = mExpressionParser.EvaluateExpression(leftOfEquals, codeContext, ExpressionParseType.GetReference);
                    bool wasAssigned = false;

                    wasAssigned = TryAssignIAssignableReference(assignOperator, customVariable, reference);

                    if (!wasAssigned)
                    {
                        throw new Exception("Could not assign the value");
                    }
                }
            }
        }
示例#26
0
        private void GetMethodInfo(ICSharpCode.NRefactory.CSharp.Expression expression, List<object> argumentValues, Type[] types, CodeContext codeContext, string invocation, object container, out MethodInfo methodInfo)
        {
            methodInfo = null;



            if (expression is ICSharpCode.NRefactory.CSharp.IdentifierExpression)
            {

                methodInfo = container.GetType().GetMethod(invocation, types);
            }
            else if (expression is ICSharpCode.NRefactory.CSharp.MemberReferenceExpression)
            {
                ICSharpCode.NRefactory.CSharp.MemberReferenceExpression mre = expression as ICSharpCode.NRefactory.CSharp.MemberReferenceExpression;

                bool doTypesHaveNull = false;
                foreach (var item in types)
                {
                    if (item == null)
                    {
                        doTypesHaveNull = true;
                    }
                }

                Type typeToCallGetMethodOn;

                if (container is Type)
                {
                    typeToCallGetMethodOn = (container as Type);
                }
                else if (container is TypeReference)
                {
                    typeToCallGetMethodOn = (container as TypeReference).Type;
                }
                else
                {
                    typeToCallGetMethodOn = container.GetType();
                }
                if (doTypesHaveNull)
                {
                    // Let's hope there's no ambiguity or else we're in trouble...
                    methodInfo = typeToCallGetMethodOn.GetMethod(mre.MemberName);
                }
                else
                {
                    bool shouldTryAgain = false; ;
                    try
                    {
                        methodInfo = typeToCallGetMethodOn.GetMethod(mre.MemberName, types);
                    }
                    catch
                    {
                        shouldTryAgain = true;
                    }
                    if(shouldTryAgain || methodInfo == null)
                    {
                        // The method doesn't exist, but it could be because
                        // the parser evaluated the types as one type (like int)
                        // but they are really of another type (like float).
                        var candidates = typeToCallGetMethodOn.GetMethods();
                        foreach (var candidate in candidates)
                        {

                            if (candidate.Name == mre.MemberName &&
                                    candidate.GetParameters().Length == types.Length)
                            {
                                methodInfo = candidate;
                                break;
                            }
                        }
                    }
                }
            }
            else if (expression is InvocationExpression)
            {
                InvocationExpression ie = expression as InvocationExpression;

                if (container is Type)
                {
                    methodInfo = (container as Type).GetMethod(ie.Target.GetText(), types);
                }
                else
                {
                    methodInfo = container.GetType().GetMethod(ie.Target.GetText(), types);
                }
            }
            else
            {
                throw new NotImplementedException();
            }
        }
示例#27
0
        public string GetTypeStringForValue(string leftOfEquals, ElementRuntime elementRuntime, CodeContext codeContext, out Type runtimeType)
        {
            // try using the new method:
            var leftReference = mExpressionParser.EvaluateExpression(leftOfEquals, codeContext, ExpressionParseType.GetReference);

            if (leftReference != null)
            {
                if (leftReference is IAssignableReference)
                {
                    Type type = ((IAssignableReference)leftReference).TypeOfReference;
                    runtimeType = type;
                    string toReturn = null;
                    if (runtimeType != null)
                    {
                        toReturn = runtimeType.FullName;
                    }
                    return toReturn;
                }
                else
                {
                    runtimeType = null;
                    return null;
                }

            }
            else
            {


                string leftSideRaw = leftOfEquals;
                string leftSideContainer = null;
                if (leftOfEquals.Contains('.'))
                {
                    // That means the user is setting a value on a contained object, so let's see what the raw variable is
                    int lastDot = leftOfEquals.LastIndexOf('.');

                    leftSideRaw = leftOfEquals.Substring(lastDot + 1, leftSideRaw.Length - (lastDot + 1));
                    leftSideContainer = leftOfEquals.Substring(0, lastDot);
                }

                if (leftSideContainer == null)
                {
                    if (elementRuntime != null)
                    {

                        if (IsStateVariable(leftSideRaw, elementRuntime))
                        {
                            runtimeType = typeof(string);
                            return "String";
                        }
                    }

                    FieldInfo fieldInfo = mAllFields.GetFieldByName(leftSideRaw);
                    if (fieldInfo != null)
                    {
                        runtimeType = fieldInfo.FieldType;
                        return fieldInfo.FieldType.ToString();
                    }

                    PropertyInfo propertyInfo = mAllProperties.GetPropertyByName(leftSideRaw);
                    if (propertyInfo != null)
                    {
                        runtimeType = propertyInfo.PropertyType;
                        return propertyInfo.PropertyType.ToString();
                    }
                }
                // reverse loop so we get the inner-most variables first
                for (int i = mCallStackVariables.Count - 1; i > -1; i--)
                {
                    Dictionary<string, object> variableDictionary = mCallStackVariables[i];


                    if (variableDictionary.ContainsKey(leftSideRaw))
                    {
                        runtimeType = variableDictionary[leftSideRaw].GetType();
                        return runtimeType.ToString();
                    }

                }

                if (leftSideContainer != null)
                {
                    ElementRuntime containerElementRuntime = elementRuntime.GetContainedElementRuntime(leftSideContainer);

                    if (containerElementRuntime != null)
                    {
                        return GetTypeStringForValue(leftSideRaw, containerElementRuntime, codeContext, out runtimeType);
                    }
                }

                // If we got this far we should try to get the type through reflection
                GetTypeFromReflection(leftOfEquals, out runtimeType, null);

                if (runtimeType != null)
                {
                    return runtimeType.ToString();
                }
                else
                {
                    return null;
                }
            }
        }
示例#28
0
        void HandleUpdate(object sender, EventArgs args)
        {
            lock (mStringsToApply)
            {
#if !UNIT_TESTS
                if (mControl.Enabled)
#endif
                {
                    foreach (var scriptAndContext in mStringsToApply)
                    {
                        CodeContext codeContext = scriptAndContext.Context;
                        if (codeContext == null)
                        {
                            codeContext = new CodeContext(GlueViewState.Self.CurrentElementRuntime);
                        }

                        ApplyLinesInternal(scriptAndContext.Script.Split(new char[]{'\n'}), 0, mStringsToApply.Count,
                            GlueViewState.Self.CurrentElement,
                            codeContext);
                    }
#if !UNIT_TESTS
                    mControl.FrameBasedUpdate();
#endif
                }
                mStringsToApply.Clear();
            }
        }
示例#29
0
        private void EvaluateFunctionGetStaticMember(ElementRuntime elementRuntime, FunctionArgs args, CodeContext codeContext)
        {

            string argument = (string)args.Parameters[0].ParsedExpression.ToString();

            string value = (string) mExpressionParser.EvaluateExpression(argument, codeContext);

            ReferencedFileSave rfs = elementRuntime.AssociatedIElement.GetReferencedFileSaveByInstanceNameRecursively(value);

            args.Result = elementRuntime.LoadReferencedFileSave(rfs, true, elementRuntime.AssociatedIElement);
        }
示例#30
0
        private object EvaluateCastExpression(CastExpression castExpression, CodeContext codeContext)
        {
            Type whatToCastTo = TypeManager.GetTypeFromString(castExpression.Type.ToString());
            object whatToCast = EvaluateExpression(castExpression.Expression, codeContext);

            // do we do anything here?
            return whatToCast;
        }