コード例 #1
0
 private void ProcessVariableReference(VariableReference VarRef, string VarName)
 {
     var VarAssignment = new VarAssignment();
     VarAssignment.SrcName = VarRef.Name;
     VarAssignment.VarName = VarName;
     _smells.AssignmentList.Add(VarAssignment);
 }
コード例 #2
0
 public void visit(VariableReference node)
 {
     Symbol var = symboltable.resolve(node.Name);
     if (var == null)
         throw new SemanticError("Reference to undefined identifier "
             + node.Name + " on row " + node.Row + ".");
     else
         operandtypes.Push(var.Type);
 }
コード例 #3
0
        public void It_renders_the_named_value_from_the_context()
        {
            var a = new VariableReference("a");
            var writer = new StringWriter();
            var context = new RenderContext(null, new { a = "b" }, writer, null);

            a.Render(context);

            Assert.AreEqual("b", writer.GetStringBuilder().ToString());
        }
コード例 #4
0
        public void It_supports_accessing_members_of_child_objects()
        {
            var a = new VariableReference("a.b");
            var writer = new StringWriter();
            var context = new RenderContext(null, new { a = new { b = "c" } }, writer, null);

            a.Render(context);

            Assert.AreEqual("c", writer.GetStringBuilder().ToString());
        }
コード例 #5
0
        public void It_checks_for_keys_containing_dots_before_splitting()
        {
            var a = new VariableReference("a.b");
            var writer = new StringWriter();
            var context = new RenderContext(null, new Dictionary<string, string> { { "a.b", "c" } }, writer, null);

            a.Render(context);

            Assert.AreEqual("c", writer.GetStringBuilder().ToString());
        }
コード例 #6
0
        public void InvalidRange()
        {
            var stringlit = new StringLiteral("foo", 0);
            var range = new Range(stringlit, stringlit, 0);
            var variabledecl = new VariableDeclaration("foo", "int", 0);
            var variable = new VariableReference("foo", 0);
            var loop = new Loop(variable, range, new List<Statement>(), 0);
            statementlist.Add(variabledecl);
            statementlist.Add(loop);
            var parsetree = new Program(statementlist);

            Assert.Throws<SemanticError>(() => symbolTableBuilder.BuildSymbolTableAndTypeCheck(parsetree));
        }
コード例 #7
0
        public void NonIntegerLoopVariable(string type)
        {
            var variabledecl = new VariableDeclaration("foo", type, 0);
            statementlist.Add(variabledecl);
            var variable = new VariableReference("foo", 0);
            var integer = new IntegerLiteral("5", 0);
            var range = new Range(integer, integer, 0);
            var variabledecl2 = new VariableDeclaration("bar", "int", 0);
            var loopbody = new List<Statement>();
            loopbody.Add(variabledecl2);
            var loop = new Loop(variable, range, loopbody, 0);
            statementlist.Add(loop);
            var parsetree = new Program(statementlist);

            Assert.Throws<SemanticError>(() => symbolTableBuilder.BuildSymbolTableAndTypeCheck(parsetree));
        }
コード例 #8
0
        private bool IsOnlyUsedOnce(VariableReference variable, out TypeReference type)
        {
            type = null;
            StackVariableDefineUseInfo defineUseInfo;

            if (!context.MethodContext.StackData.VariableToDefineUseInfo.TryGetValue(variable.Resolve(), out defineUseInfo))
            {
                throw new Exception("Define/use info not found.");
            }

            if (defineUseInfo.UsedAt.Count != 1)
            {
                return(false);
            }

            int instructionOffset        = First(defineUseInfo.UsedAt);
            UsedAsTypeHelper uath        = new UsedAsTypeHelper(context.MethodContext);
            Instruction      instruction = context.MethodContext.ControlFlowGraph.OffsetToInstruction[instructionOffset];

            type = uath.GetUseExpressionTypeNode(instruction, offsetToExpression[instructionOffset], variable);
            return(true);
        }
コード例 #9
0
        protected override void RenderDictionary(StringBuilder builder, VariableReference variable, IDictionary variableValue, bool first)
        {
            bool firstElement = true;

            foreach (DictionaryEntry entry in variableValue)
            {
                if (variable.Composite)
                {
                    builder.Append('.');
                    AppendText(builder, variable, entry.Key.ToString(), true);
                    builder.Append('=');
                    AppendText(builder, variable, entry.Value.ToString(), true);
                }
                else
                {
                    RenderElement(builder, variable, entry.Key, first, firstElement);
                    RenderElement(builder, variable, entry.Value, first, false);
                }

                firstElement = false;
            }
        }
コード例 #10
0
 private void VisitAssignExpression(BinaryExpression node)
 {
     this.currentVariable = null;
     this.states.Push(1);
     this.Visit(node.get_Left());
     dummyVar0 = this.states.Pop();
     if (this.processStep == RemoveConditionOnlyVariables.ProcessStep.Search)
     {
         this.SetVariableAssignmentExpression(node.get_Right());
     }
     if (node.get_Right().get_CodeNodeType() == 22 && this.currentVariable != null)
     {
         V_0 = this.GetValue(this.currentVariable);
         if (V_0 != null && V_0.get_VariableState() != RemoveConditionOnlyVariables.VariableState.Declaration)
         {
             stackVariable29 = V_0;
             stackVariable29.set_NumberOfTimesAssigned(stackVariable29.get_NumberOfTimesAssigned() + 1);
         }
     }
     this.Visit(node.get_Right());
     return;
 }
コード例 #11
0
            bool VisitVariableReferenceExpression(Expression node)
            {
                var variable_reference_expression = node as VariableReferenceExpression;

                if (variable_reference_expression == null)
                {
                    return(false);
                }

                switch (state)
                {
                case State.Begin:
                    this.enumerator = variable_reference_expression.Variable;
                    break;

                case State.WhileBody:
                    this.variable = variable_reference_expression.Variable as VariableDefinition;
                    break;
                }

                return(true);
            }
コード例 #12
0
ファイル: ParserStatements.cs プロジェクト: tmakij/MiniPascal
 private IStatement CallRead()
 {
     if (Accept(Symbol.ReadProcedure))
     {
         Require(Symbol.ClosureOpen);
         Read read = new Read();
         do
         {
             Identifier ident = Identifier();
             if (ident == null)
             {
                 throw new SyntaxException(expIdentifier, current);
             }
             VariableReference  varRef    = ReadVariableReference(ident);
             AssigmentStatement assigment = new AssigmentStatement(varRef, new Reading(ident));
             read.Add(assigment);
         } while (Accept(Symbol.Comma));
         Require(Symbol.ClosureClose);
         return(read);
     }
     return(null);
 }
コード例 #13
0
        private void RenderElement(StringBuilder builder, VariableReference variable, object variableValue, bool firstVariable, bool firstElement)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            if (variableValue == null)
            {
                throw new ArgumentNullException("variableValue");
            }

            if (firstElement || variable.Composite)
            {
                builder.Append('.');
            }
            else if (!firstElement)
            {
                builder.Append(',');
            }

            AppendText(builder, variable, variableValue.ToString(), true);
        }
コード例 #14
0
ファイル: VSCodeThread.cs プロジェクト: Ourpalm/ILRuntime
        public VSCodeVariable[] EnumChildren(int dwTimeout)
        {
            var thread   = frame.Thread;
            var c        = thread.Engine.EnumChildren(GetVariableReference(), thread.ThreadID, frame.Index, (uint)Math.Max(dwTimeout, 5000));
            var children = new VSCodeVariable[c.Length];

            for (int i = 0; i < c.Length; i++)
            {
                var            vi = c[i];
                VSCodeVariable v  = new VSCodeVariable(frame, vi);
                if (vi.Type == VariableTypes.IndexAccess)
                {
                    v.Parameters = new VariableReference[] { VariableReference.GetInteger(vi.Offset) }
                }
                ;
                v.Parent = this;
                frame.RegisterVariable(v);
                children[i] = v;
            }

            return(children);
        }
コード例 #15
0
        public VariableReference GetVariableReference()
        {
            if (info != null)
            {
                VariableReference res = new VariableReference();
                res.Address = info.Address;
                res.Name    = info.Name;
                res.Type    = info.Type;
                res.Offset  = info.Offset;
                if (Parent != null)
                {
                    res.Parent = Parent.GetVariableReference();
                }
                res.Parameters = Parameters;

                return(res);
            }
            else
            {
                return(null);
            }
        }
コード例 #16
0
        protected override void RenderElement(StringBuilder builder, VariableReference variable, object variableValue, bool first)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            if (variableValue == null)
            {
                throw new ArgumentNullException("variableValue");
            }

            if (first)
            {
                builder.Append('#');
            }
            if (!first)
            {
                builder.Append(',');
            }

            AppendText(builder, variable, variableValue.ToString(), false);
        }
コード例 #17
0
        public bool VisitDropNode(DropNode dropNode)
        {
            VariableReference input = dropNode.InputTerminals[0].GetTrueVariable();
            var    inputAllocation  = (LocalAllocationValueSource)_variableValues[input];
            NIType inputType        = input.Type;

            if (inputType.TypeHasDropTrait())
            {
                CreateDropCall(inputType, inputAllocation.AllocationPointer);
                return(true);
            }

            NIType innerType;

            if (inputType.TryDestructureVectorType(out innerType))
            {
                // TODO
                return(true);
            }
            if (inputType.TryDestructureOptionType(out innerType) && innerType.TypeHasDropTrait())
            {
                // TODO: turn this into a monomorphized generic function call
                LLVMValueRef isSomePtr = _builder.CreateStructGEP(inputAllocation.AllocationPointer, 0u, "isSomePtr"),
                             isSome    = _builder.CreateLoad(isSomePtr, "isSome");
                LLVMBasicBlockRef optionDropIsSomeBlock = _topLevelFunction.AppendBasicBlock("optionDropIsSome"),
                                  optionDropEndBlock    = _topLevelFunction.AppendBasicBlock("optionDropEnd");
                _builder.CreateCondBr(isSome, optionDropIsSomeBlock, optionDropEndBlock);

                _builder.PositionBuilderAtEnd(optionDropIsSomeBlock);
                LLVMValueRef innerValuePtr = _builder.CreateStructGEP(inputAllocation.AllocationPointer, 1u, "innerValuePtr");
                CreateDropCall(innerType, innerValuePtr);
                _builder.CreateBr(optionDropEndBlock);

                _builder.PositionBuilderAtEnd(optionDropEndBlock);
                return(true);
            }
            return(true);
        }
コード例 #18
0
        public override void VisitThrowStatement(IThrowStatement stmt, IList <IStatement> body)
        {
            if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionBefore))
            {
                body.Add(EmptyCompletionExpression);
            }

            IVariableReference varRef = new VariableReference();

            if (stmt.Semicolon == null && IsTargetMatch(stmt, CompletionCase.EmptyCompletionAfter))
            {
                varRef = new VariableReference {
                    Identifier = _nameGen.GetNextVariableName()
                };
                body.Add(
                    new VariableDeclaration
                {
                    Type      = Names.Type("System.Exception, mscorlib, 4.0.0.0"),
                    Reference = varRef
                });
                body.Add(new Assignment {
                    Reference = varRef, Expression = new CompletionExpression()
                });
            }
            else if (stmt.Exception != null)
            {
                varRef = _exprVisitor.ToVariableRef(stmt.Exception, body);
            }

            body.Add(new ThrowStatement {
                Reference = varRef
            });

            if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionAfter))
            {
                body.Add(EmptyCompletionExpression);
            }
        }
コード例 #19
0
        /// <summary>
        /// Create the foreach statement syntax for a foreach loop with a reference as enumerable.
        /// </summary>
        /// <param name="variableName">Name of the variable.</param>
        /// <param name="varialeType">The variable type.</param>
        /// <param name="enumerableReference">Reference to the enumerable.</param>
        /// <param name="body">Body of the foreach loop.</param>
        /// <param name="useVar">If we should use the var keyword instead of the type.</param>
        /// <returns>The declared foreach statement syntax.</returns>
        public ForEachStatementSyntax ForEach(string variableName, Type varialeType, VariableReference enumerableReference, BlockSyntax body, bool useVar = true)
        {
            if (string.IsNullOrEmpty(variableName))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(variableName));
            }

            if (varialeType == null)
            {
                throw new ArgumentNullException(nameof(varialeType));
            }

            if (enumerableReference == null)
            {
                throw new ArgumentNullException(nameof(enumerableReference));
            }

            return(ForEachStatement(
                       useVar ? IdentifierName("var") : TypeGenerator.Create(varialeType),
                       Identifier(variableName),
                       ReferenceGenerator.Create(enumerableReference),
                       body));
        }
コード例 #20
0
        public void BranchedMutableWire_SetVariableTypes_AllSinkVariablesAreMutable()
        {
            NIType         signatureType = Signatures.MutablePassthroughType;
            DfirRoot       dfirRoot      = DfirRoot.Create();
            FunctionalNode firstSink     = new FunctionalNode(dfirRoot.BlockDiagram, signatureType),
                           secondSink    = new FunctionalNode(dfirRoot.BlockDiagram, signatureType);
            Constant constant            = Constant.Create(dfirRoot.BlockDiagram, 0, NITypes.Int32);

            constant.OutputTerminal.WireTogether(firstSink.InputTerminals[0], SourceModelIdSource.NoSourceModelId);
            constant.OutputTerminal.WireTogether(secondSink.InputTerminals[0], SourceModelIdSource.NoSourceModelId);
            Wire branchedWire = (Wire)constant.OutputTerminal.ConnectedTerminal.ParentNode;

            branchedWire.SetWireBeginsMutableVariable(true);

            RunSemanticAnalysisUpToSetVariableTypes(dfirRoot);

            VariableReference firstSinkVariable = firstSink.InputTerminals[0].GetFacadeVariable();

            Assert.IsTrue(firstSinkVariable.Mutable);
            VariableReference secondSinkVariable = secondSink.InputTerminals[0].GetFacadeVariable();

            Assert.IsTrue(secondSinkVariable.Mutable);
        }
コード例 #21
0
        /// <summary>
        /// Check if the local variable has a name which was generated by the compiler.
        /// Note that this will return true for all variables if debugging information is not present.
        /// </summary>
        /// <param name="self">The VariableReference on which the extension method can be called.</param>
        /// <returns>True if the field name was generated by the compiler, False otherwise</returns>
        public static bool IsGeneratedName(this VariableReference self, MethodBody body)
        {
            if (self == null)
            {
                return(false);
            }

            var def = self.Resolve();

            if (def == null)
            {
                return(false);
            }

            string name = GetVariableName(def, body);

            if (String.IsNullOrEmpty(name))
            {
                return(true);
            }

            return((name [0] == '<') || (name.IndexOf('$') != -1));
        }
コード例 #22
0
        private static WireRenderInfoEnumerable CreateVariableIdentityRenderInfo(VariableReference variable, StockDiagramUIResources stockResources)
        {
            NIType innerType = variable.Type.IsRebarReferenceType()
                ? variable.Type.GetUnderlyingTypeFromRebarType()
                : variable.Type;
            int id = variable.Id;
            ITypeAssetProvider innerTypeAssetProvider = new VariableIdentityTypeAssetProvider(
                stockResources.GetTypeAssets((Element)null, variable.Type).GetShortName(innerType),
                VariableIdentityTypeAssetProvider.GetColor(id));
            ITypeAssetProvider outerTypeAssetProvider;

            if (variable.Type.IsMutableReferenceType())
            {
                outerTypeAssetProvider = new MutableReferenceTypeAssetProvider(
                    innerTypeAssetProvider,
                    0);
            }
            else if (variable.Type.IsImmutableReferenceType())
            {
                outerTypeAssetProvider = new ImmutableReferenceTypeAssetProvider(
                    innerTypeAssetProvider,
                    0);
            }
            else if (variable.Mutable)
            {
                outerTypeAssetProvider = new MutableValueTypeAssetProvider(
                    innerTypeAssetProvider,
                    0);
            }
            else
            {
                outerTypeAssetProvider = new ImmutableValueTypeAssetProvider(
                    innerTypeAssetProvider,
                    0);
            }
            return(outerTypeAssetProvider.GetWireRenderInfo(0));
        }
コード例 #23
0
ファイル: Resolver.cs プロジェクト: o2xli/Fluent.Net
        /**
         * Resolve a reference to a variable
         *
         * @param   {Object} env
         *    Resolver environment object.
         * @param   {Object} expr
         *    An expression to be resolved.
         * @param   {String} expr.name
         *    Name of an argument to be returned.
         * @returns {FluentType}
         * @private
         */
        static IFluentType VariableReference(ResolverEnvironment env, VariableReference varReference)
        {
            object arg;

            if (env.Arguments == null ||
                !env.Arguments.TryGetValue(varReference.Name, out arg))
            {
                env.Errors?.Add(new ReferenceError($"Unknown variable: ${varReference.Name}"));
                return(new FluentNone(varReference.Name));
            }

            // Return early if the argument already is an instance of IFluentType.
            if (arg is IFluentType ft)
            {
                return(ft);
            }

            // Convert the argument to a Fluent type.
            if (arg is string str)
            {
                return(new FluentString(str));
            }
            if (arg is sbyte || arg is short || arg is int || arg is long ||
                arg is byte || arg is ushort || arg is uint || arg is ulong ||
                arg is float || arg is double || arg is decimal)
            {
                return(new FluentNumber(arg.ToString()));
            }
            if (arg is DateTime dt)
            {
                return(new FluentDateTime(dt));
            }

            env.Errors?.Add(new TypeError(
                                $"Unsupported variable type: {varReference.Name}, {arg?.GetType()?.ToString() ?? "null"}"));
            return(new FluentNone(varReference.Name));
        }
コード例 #24
0
        /// <summary>
        /// Create the expression statement syntax to assign a reference to another expression.
        /// </summary>
        /// <param name="reference">Reference that should be assigned.</param>
        /// <param name="expressionSyntax">Expression that we should assign to reference.</param>
        /// <param name="castTo">If we should do a cast while assign the variable.</param>
        /// <returns>The generated assign declaration syntax.</returns>
        public ExpressionStatementSyntax Assign(VariableReference reference, ExpressionSyntax expressionSyntax, Type castTo = null)
        {
            if (reference == null)
            {
                throw new ArgumentNullException(nameof(reference));
            }

            if (expressionSyntax == null)
            {
                throw new ArgumentNullException(nameof(expressionSyntax));
            }

            if (castTo != null && castTo != typeof(void))
            {
                expressionSyntax = CastExpression(TypeGenerator.Create(castTo), expressionSyntax);
            }

            return
                (ExpressionStatement(
                     AssignmentExpression(
                         SyntaxKind.SimpleAssignmentExpression,
                         ReferenceGenerator.Create(reference),
                         expressionSyntax)));
        }
コード例 #25
0
        /// <summary>
        /// Create the for statement syntax for a for loop with a reference for start and stop.
        /// </summary>
        /// <param name="start">Reference for start.</param>
        /// <param name="end">Reference for end.</param>
        /// <param name="variableName">Variable name in loop.</param>
        /// <param name="body">Body inside loop.</param>
        /// <returns>The declared for statement syntax.</returns>
        public ForStatementSyntax For(VariableReference start, VariableReference end, string variableName, BlockSyntax body)
        {
            if (start == null)
            {
                throw new ArgumentNullException(nameof(start));
            }

            if (end == null)
            {
                throw new ArgumentNullException(nameof(end));
            }

            if (string.IsNullOrEmpty(variableName))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(variableName));
            }

            return(ForStatement(
                       VariableDeclaration(
                           PredefinedType(Token(SyntaxKind.IntKeyword)), SeparatedList(new[]
            {
                VariableDeclarator(
                    Identifier(variableName),
                    null,
                    EqualsValueClause(ReferenceGenerator.Create(start)))
            })),
                       SeparatedList <ExpressionSyntax>(),
                       BinaryExpression(
                           SyntaxKind.LessThanExpression,
                           IdentifierName(variableName),
                           ReferenceGenerator.Create(end)),
                       SeparatedList <ExpressionSyntax>(new[]
            {
                PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, IdentifierName(variableName))
            }), body));
        }
コード例 #26
0
        private int CheckNewArrayInitializationAndSize(Statement statement, VariableReference arrayVariable)
        {
            if (!statement.IsAssignmentStatement())
            {
                throw new Exception(InvalidStatementExceptionString);
            }

            BinaryExpression arrayInitialization = (statement as ExpressionStatement).Expression as BinaryExpression;

            if (arrayInitialization.Left.CodeNodeType != CodeNodeType.VariableReferenceExpression ||
                (arrayInitialization.Left as VariableReferenceExpression).Variable != arrayVariable)
            {
                throw new Exception(InvalidStatementExceptionString);
            }

            if (arrayInitialization.Right.CodeNodeType != CodeNodeType.ArrayCreationExpression ||
                (arrayInitialization.Right as ArrayCreationExpression).Dimensions.Count != 1 ||
                (arrayInitialization.Right as ArrayCreationExpression).Dimensions[0].CodeNodeType != CodeNodeType.LiteralExpression)
            {
                throw new Exception(InvalidStatementExceptionString);
            }

            return(Convert.ToInt32(((arrayInitialization.Right as ArrayCreationExpression).Dimensions[0] as LiteralExpression).Value));
        }
コード例 #27
0
            private LinqQueryExpression ProcessExtensionMethodChain(IEnumerable <MethodInvocationExpression> methodInvocations, MethodInvocationExpression topInvoke, bool queryable)
            {
                this.currentIdentifier = null;
                this.clauses.Clear();

                foreach (MethodInvocationExpression methodInvoke in methodInvocations)
                {
                    bool success = true;
                    switch (methodInvoke.MethodExpression.MethodDefinition.Name)
                    {
                    case "Select":
                        success = TryProcessSelectMethod(methodInvoke, queryable);
                        break;

                    case "SelectMany":
                        success = TryProcessSelectManyMethod(methodInvoke, queryable);
                        break;

                    case "Where":
                        success = TryProcessWhereMethod(methodInvoke, queryable);
                        break;

                    case "OrderBy":
                        success = TryProcessOrderByMethod(methodInvoke, true, queryable);
                        break;

                    case "OrderByDescending":
                        success = TryProcessOrderByMethod(methodInvoke, false, queryable);
                        break;

                    case "ThenBy":
                        success = TryProcessThenByMethod(methodInvoke, true, queryable);
                        break;

                    case "ThenByDescending":
                        success = TryProcessThenByMethod(methodInvoke, false, queryable);
                        break;

                    case "Join":
                        success = TryProcessJoinMethod(methodInvoke, false, queryable);
                        break;

                    case "GroupJoin":
                        success = TryProcessJoinMethod(methodInvoke, true, queryable);
                        break;

                    case "GroupBy":
                        success = TryProcessGroupByMethod(methodInvoke, queryable);
                        break;

                    default:
                        return(null);
                    }

                    if (!success)
                    {
                        return(null);
                    }
                }

                if (this.clauses.Count == 0)
                {
                    return(null);
                }

                if (this.currentIdentifier != null)
                {
                    clauses.Add(new SelectClause(new VariableReferenceExpression(this.currentIdentifier, null), null));
                }

                return(new LinqQueryExpression(new List <QueryClause>(this.clauses), topInvoke.ExpressionType, topInvoke.UnderlyingSameMethodInstructions));
            }
コード例 #28
0
 public override void ExplicitVisit(VariableReference fragment)
 {
     _fragments.Add(fragment);
 }
コード例 #29
0
        public void LoopTest()
        {
            var loopvardecl = new VariableDeclaration("loopvariable", "int", 0);
            var loopvarref = new VariableReference("loopvariable", 0);
            var range = new Range(new IntegerLiteral("2", 0), new IntegerLiteral("5", 0), 0);
            var loopbody = new List<Statement>();
            var resultdecl = new VariableDeclaration("result", "int", 0);
            var resultref = new VariableReference("result", 0);
            loopbody.Add(new Assignment(resultref,
                new ArithmeticOp("+", resultref, loopvarref, 0), 0));
            var program = new List<Statement>();
            program.Add(resultdecl);
            program.Add(loopvardecl);
            program.Add(new Loop(loopvarref, range, loopbody, 0));

            var symboltable = new SymbolTable();
            symboltable.define(new Symbol("loopvariable", "int"));
            symboltable.define(new Symbol("result", "int"));
            var interpreter = new InterpretingNodeVisitor(symboltable);

            interpreter.Run(new Program(program));
            Assert.That(interpreter.Valuetable[symboltable.resolve("result")], Is.EqualTo(14));
        }
コード例 #30
0
        public void ValidRead(string type)
        {
            var variabledecl = new VariableDeclaration("foo", type, 0);
            statementlist.Add(variabledecl);
            var variable = new VariableReference("foo", 0);
            var print = new ExpressionStatement("read", variable, 0);
            statementlist.Add(print);
            var parsetree = new Program(statementlist);

            Assert.DoesNotThrow(() => symbolTableBuilder.BuildSymbolTableAndTypeCheck(parsetree));
        }
コード例 #31
0
        public void VariableDefinitionAndReferenceInAssignment()
        {
            var variableref = new VariableReference("foo", 0);
            var variabledecl = new VariableDeclaration("foo", "int", 0);
            var assignment = new Assignment(variabledecl, variableref, 0);
            statementlist.Add(assignment);
            var parsetree = new Program(statementlist);

            Assert.Throws<SemanticError>(() => symbolTableBuilder.BuildSymbolTableAndTypeCheck(parsetree));
        }
コード例 #32
0
            private bool TryProcessJoinMethod(MethodInvocationExpression methodInvoke, bool isGroupJoin, bool queryable)
            {
                MethodDefinition methodDef = methodInvoke.MethodExpression.MethodDefinition;

                if (methodDef.Parameters.Count != 5)
                {
                    return(false);
                }

                Expression innerCollection = (Expression) new LinqQueriesRebuilder(this.methodContext).Visit(methodInvoke.Arguments[1].Clone());

                LambdaExpression outerKeySelector = GetLambdaExpression(methodInvoke.Arguments[2], queryable);

                if (outerKeySelector == null || outerKeySelector.Arguments.Count != 1)
                {
                    return(false);
                }

                ProcessCurrentIdentifier(methodInvoke.Arguments[0], outerKeySelector.Parameters[0].Resolve());

                Expression outerKey = ProcessReturnExpression(outerKeySelector, new[] { this.currentIdentifier });

                if (outerKey == null)
                {
                    return(false);
                }

                LambdaExpression innerKeySelector = GetLambdaExpression(methodInvoke.Arguments[3], queryable);

                if (innerKeySelector == null || innerKeySelector.Arguments.Count != 1)
                {
                    return(false);
                }

                VariableReference innerIdentifier = CreateNewIdentifier(innerKeySelector.Parameters[0].Name, innerKeySelector.Parameters[0].ParameterType);

                Expression innerKey = ProcessReturnExpression(innerKeySelector, new[] { innerIdentifier });

                if (innerKey == null)
                {
                    return(false);
                }

                LambdaExpression resultSelector = GetLambdaExpression(methodInvoke.Arguments[4], queryable);

                if (resultSelector == null || resultSelector.Arguments.Count != 2)
                {
                    return(false);
                }

                ParameterReference[] resultSelectorParameters       = resultSelector.Parameters;
                VariableReference    resultSelectorSecondIdentifier =
                    isGroupJoin ? CreateNewIdentifier(resultSelectorParameters[1].Name, resultSelectorParameters[1].ParameterType) : innerIdentifier;

                Expression result = ProcessReturnExpression(resultSelector, new[] { this.currentIdentifier, resultSelectorSecondIdentifier });

                if (result == null)
                {
                    return(false);
                }

                clauses.Add(new JoinClause(GetIdentifierReference(innerIdentifier, ref innerCollection), innerCollection, outerKey, innerKey, null));

                if (isGroupJoin)
                {
                    clauses.Add(new IntoClause(new VariableReferenceExpression(resultSelectorSecondIdentifier, null), null));
                }

                clauses.Add(new SelectClause(result, null));
                this.currentIdentifier = null;

                return(true);
            }
コード例 #33
0
ファイル: Variables.cs プロジェクト: Shemetov/OneScript
 public static IVariable CreateIndexedPropertyReference(IRuntimeContextInstance context, IValue index)
 {
     var newVar = new VariableReference();
     newVar._refType = ReferenceType.IndexedProperty;
     newVar._context = context;
     newVar._index = index;
     return newVar;
 }
コード例 #34
0
ファイル: AllNodesVisitor.cs プロジェクト: yaakoviyun/sqlskim
 public override void Visit(VariableReference node) { this.action(node); }
コード例 #35
0
 private bool IsTransparentIdentifier(VariableReference identifier)
 {
     return(identifier.Name.StartsWith("<>h__TransparentIdentifier") || identifier.Name.StartsWith("$VB$"));
 }
コード例 #36
0
        public void UndefinedVariable()
        {
            var variable = new VariableReference("foo", 0);
            var integer = new IntegerLiteral("42", 0);
            var assignment = new Assignment(variable, integer, 0);
            statementlist.Add(assignment);
            var parsetree = new Program(statementlist);

            Assert.Throws<SemanticError>(() => symbolTableBuilder.BuildSymbolTableAndTypeCheck(parsetree));
        }
コード例 #37
0
ファイル: Variables.cs プロジェクト: Shemetov/OneScript
 public static IVariable CreateSimpleReference(IVariable var)
 {
     var newVar = new VariableReference();
     newVar._refType = ReferenceType.Simple;
     newVar._referencedValue = var;
     return newVar;
 }
コード例 #38
0
 public abstract void UnifyWithConnectedWireTypeAsNodeInput(VariableReference wireFacadeVariable, TerminalTypeUnificationResults unificationResults);
コード例 #39
0
        public void It_has_a_useful_ToString_method()
        {
            var a = new VariableReference("a");

            Assert.AreEqual("VariableReference(\"a\")", a.ToString());
        }
コード例 #40
0
ファイル: Script.cs プロジェクト: talestra/talestra
        public Instruction ParseSingle(ParseState ParseState)
        {
            var InstructionPosition = Stream.Position;
            var OpcodeNum = BinaryReader.ReadUInt16();
            if (!Opcodes.ContainsKey(OpcodeNum))
            {
                throw(new NotImplementedException(String.Format("Unhandled opcode 0x{0:X2}", OpcodeNum)));
            }
            var Opcode = Opcodes[OpcodeNum];
            var Params = new List<object>();

            foreach (var FormatChar in Opcode.Format)
            {
                switch (FormatChar)
                {
                    case '<': break;
                    case 's': Params.Add(ReadString()); break;
                    case 'S': Params.Add(ReadStringz()); break;
                    case '1': Params.Add(BinaryReader.ReadByte()); break;
                    case '7': Params.Add((AritmeticOps)BinaryReader.ReadByte()); break;
                    case '9': Params.Add((ComparisionOps)BinaryReader.ReadByte()); break;
                    case '2': Params.Add(BinaryReader.ReadInt16()); break;
                    case 'v': Params.Add(new VariableReference() { Index = BinaryReader.ReadUInt16() }); break;
                    case '4': Params.Add(BinaryReader.ReadUInt32()); break;
                    case 'L': Params.Add(new LabelReference() { Offset = BinaryReader.ReadUInt32() }); break;
                    case 'P':
                        {
                            var ParamType = BinaryReader.ReadByte();
                            object Value = null;
                            switch (ParamType)
                            {
                                case 0x00: Value = BinaryReader.ReadSByte(); break;
                                case 0x10: Value = BinaryReader.ReadByte(); break;
                                case 0x20: Value = BinaryReader.ReadInt16(); break;
                                case 0x40: Value = BinaryReader.ReadInt32(); break;
                                case 0x01: Value = new VariableReference() { Index = BinaryReader.ReadUInt16() }; break;
                                case 0x02: Value = new SpecialReference() { Index = BinaryReader.ReadUInt16() }; break;
                                default: throw (new NotImplementedException(String.Format("Invalid param type {0}", ParamType)));
                            }

                            Params.Add(Value);
                        }
                        break;
                    default:
                        throw(new NotImplementedException(String.Format("Invalid format '{0}'", FormatChar)));
                }
            }

            try
            {
                if (ParseState.Unindent.Contains((uint)InstructionPosition))
                {
                    ParseState.Indent--;
                }
                switch (Opcode.OpcodeName)
                {
                    case "JUMP_ALWAYS":
                        ParseState.Indent--;
                        break;
                }

                return new Instruction()
                {
                    Position = (uint)InstructionPosition,
                    Opcode = Opcode,
                    Parameters = Params.ToArray(),
                    Indent = ParseState.Indent,
                };
            }
            finally
            {
                switch (Opcode.OpcodeName)
                {
                    //case "FUNCTION_DEF":
                    case "JUMP_IF":
                        ParseState.Unindent.Add(((LabelReference)(Params.ToArray()[3])).Offset);
                        ParseState.Indent++;
                        break;
                    case "JUMP_ALWAYS":
                        ParseState.Unindent.Add(((LabelReference)(Params.ToArray()[0])).Offset);
                        ParseState.Indent += 2;
                        break;
                }
            }
        }
コード例 #41
0
        public void ReadBool()
        {
            var variabledecl = new VariableDeclaration("foo", "bool", 0);
            statementlist.Add(variabledecl);
            var variable = new VariableReference("foo", 0);
            var print = new ReadStatement(variable, 0);
            statementlist.Add(print);
            var parsetree = new Program(statementlist);

            Assert.Throws<SemanticError>(() => symbolTableBuilder.BuildSymbolTableAndTypeCheck(parsetree));
        }
コード例 #42
0
ファイル: Variables.cs プロジェクト: Shemetov/OneScript
 public static IVariable CreateContextPropertyReference(IRuntimeContextInstance context, int propertyNumber)
 {
     var newVar = new VariableReference();
     newVar._refType = ReferenceType.ContextProperty;
     newVar._context = context;
     newVar._contextPropertyNumber = propertyNumber;
     return newVar;
 }
コード例 #43
0
        public void SeveralVariableDeclarationsBeforeLoop(string type)
        {
            var intdeclaration = new VariableDeclaration("foo", "int", 0);
            var otherdeclaration = new VariableDeclaration("bar", type, 0);
            var variableref = new VariableReference("bar", 0);
            var integer = new IntegerLiteral("5", 0);
            var range = new Range(integer, integer, 0);
            var loop = new Loop(variableref, range, new List<Statement>(), 0);
            statementlist.Add(intdeclaration);
            statementlist.Add(otherdeclaration);
            statementlist.Add(loop);
            var parsetree = new Program(statementlist);

            Assert.Throws<SemanticError>(() => symbolTableBuilder.BuildSymbolTableAndTypeCheck(parsetree));
        }
コード例 #44
0
 /// <summary>
 /// Tries to get the variable that is used by the specified instruction.
 /// </summary>
 /// <param name="instruction"></param>
 /// <param name="varReference"></param>
 /// <returns>Flase if the instruction does not handle variables.</returns>
 private bool TryGetVariableFromInstruction(Instruction instruction, out VariableReference varReference)
 {
     return(StateMachineUtilities.TryGetVariableFromInstruction(instruction, moveNextMethodContext.Variables, out varReference));
 }
コード例 #45
0
 public ReadStatement(VariableReference variable, int row)
     : base(row)
 {
     Variable = variable;
 }
コード例 #46
0
            private LinqQueryExpression RemoveTransparentIdentifiers(LinqQueryExpression originalQuery)
            {
                LinqQueryExpression          linqQuery              = (LinqQueryExpression)originalQuery.Clone();
                List <VariableReference>     identifiers            = new List <VariableReference>();
                TransparentIdentifierCleaner cleaner                = new TransparentIdentifierCleaner();
                HashSet <VariableReference>  transparentIdentifiers = new HashSet <VariableReference>();

                for (int i = 0; i < linqQuery.Clauses.Count; i++)
                {
                    linqQuery.Clauses[i] = (QueryClause)cleaner.Visit(linqQuery.Clauses[i]);
                    QueryClause currentClause = linqQuery.Clauses[i];

                    if (currentClause.CodeNodeType == CodeNodeType.FromClause)
                    {
                        identifiers.Add(GetVariableReference((currentClause as FromClause).Identifier));
                    }
                    else if (currentClause.CodeNodeType == CodeNodeType.JoinClause)
                    {
                        if (linqQuery.Clauses[i + 1].CodeNodeType != CodeNodeType.IntoClause)
                        {
                            identifiers.Add(GetVariableReference((currentClause as JoinClause).InnerIdentifier));
                        }
                        else
                        {
                            identifiers.Add(((IntoClause)linqQuery.Clauses[i + 1]).Identifier.Variable);
                            i++;
                        }
                    }
                    else if (currentClause.CodeNodeType == CodeNodeType.SelectClause && i != linqQuery.Clauses.Count - 1)
                    {
                        VariableReference intoIdentifier = ((IntoClause)linqQuery.Clauses[i + 1]).Identifier.Variable;
                        if (IsTransparentIdentifier(intoIdentifier))
                        {
                            Dictionary <PropertyDefinition, Expression> propertyToValueMap = GetPropertyToValueMap((currentClause as SelectClause).Expression);
                            if (propertyToValueMap == null)
                            {
                                return(originalQuery);
                            }

                            if (identifiers.Count == 2)
                            {
                                if (!RemoveIdentifier(propertyToValueMap, identifiers))
                                {
                                    return(originalQuery);
                                }
                                linqQuery.Clauses.RemoveAt(i);
                                linqQuery.Clauses.RemoveAt(i);
                                i--;
                            }
                            else if (identifiers.Count == 1)
                            {
                                LetClause letClause = GenerateLetClause(propertyToValueMap, identifiers[0]);
                                if (letClause == null)
                                {
                                    return(originalQuery);
                                }
                                linqQuery.Clauses[i] = letClause;
                                linqQuery.Clauses.RemoveAt(i + 1);
                            }
                            else
                            {
                                return(originalQuery);
                            }

                            this.methodContext.VariablesToRename.Add(intoIdentifier.Resolve());
                            transparentIdentifiers.Add(intoIdentifier);
                            identifiers.Clear();
                            identifiers.Add(intoIdentifier);
                            UpdateCleaner(cleaner, intoIdentifier, propertyToValueMap);
                        }
                    }
                    else if (currentClause.CodeNodeType == CodeNodeType.IntoClause)
                    {
                        identifiers.Clear();
                        identifiers.Add(((IntoClause)currentClause).Identifier.Variable);
                    }
                }

                TransparentIdentifierFinder finder = new TransparentIdentifierFinder(transparentIdentifiers);

                if (finder.ContainsTransparentIdentifiers(linqQuery))
                {
                    return(originalQuery);
                }

                return(linqQuery);
            }
コード例 #47
0
 public Loop(VariableReference variable, Range range, List<Statement> body, int row)
     : base(row)
 {
     Variable = variable;
     Range = range;
     LoopBody = body;
 }
コード例 #48
0
            private LetClause GenerateLetClause(Dictionary <PropertyDefinition, Expression> propertyToValueMap, VariableReference oldIdentifier)
            {
                PropertyDefinition oldIdentifierProperty = null;
                PropertyDefinition newIdentifierProperty = null;

                foreach (KeyValuePair <PropertyDefinition, Expression> pair in propertyToValueMap)
                {
                    if (pair.Key.Name == oldIdentifier.Name && pair.Value.CodeNodeType == CodeNodeType.VariableReferenceExpression &&
                        (pair.Value as VariableReferenceExpression).Variable == oldIdentifier)
                    {
                        oldIdentifierProperty = pair.Key;
                    }
                    else
                    {
                        newIdentifierProperty = pair.Key;
                    }
                }

                if (oldIdentifierProperty == null || newIdentifierProperty == null)
                {
                    return(null);
                }

                Expression newIdentifierValue = propertyToValueMap[newIdentifierProperty];

                VariableDefinition newIdentifier = CreateNewIdentifier(newIdentifierProperty.Name, newIdentifierValue.ExpressionType);

                LetClause result = new LetClause(new VariableReferenceExpression(newIdentifier, null), newIdentifierValue, null);

                propertyToValueMap[newIdentifierProperty] = result.Identifier;

                return(result);
            }
コード例 #49
0
        protected Instruction SetupSingleReturnPoint(Instruction suggestedSingleReturnPoint, VariableReference resultVar)
        {
            var proc = ILProcessorFactory.GetOrCreateProcessor(TargetMethod.Body);

            var rets = proc.Body.Instructions.Where(i => i.OpCode == OpCodes.Ret).ToList();

            if (rets.Count == 1)
            {
                if (!TargetMethod.ReturnType.IsTypeOf(typeof(void)))
                {
                    proc.SafeInsertBefore(rets.First(), proc.CreateOptimized(OpCodes.Stloc, resultVar.Index));
                }

                return(proc.SafeReplace(rets.First(), suggestedSingleReturnPoint));
            }

            foreach (var i in rets)
            {
                if (!TargetMethod.ReturnType.IsTypeOf(typeof(void)))
                {
                    proc.SafeInsertBefore(i, proc.CreateOptimized(OpCodes.Stloc, resultVar.Index));
                }

                proc.SafeReplace(i, proc.Create(OpCodes.Br, suggestedSingleReturnPoint)); //todo:: optimize
            }

            proc.SafeAppend(suggestedSingleReturnPoint);

            return(suggestedSingleReturnPoint);
        }
コード例 #50
0
        protected override async Task OnParametersSetAsync()
        {
            _renderFragments = new QueryDictionary <RenderFragment>();
            foreach (var column in GridComponent.Grid.Columns)
            {
                // Name must have a non empty value
                if (string.IsNullOrWhiteSpace(column.Name))
                {
                    column.Name = Guid.NewGuid().ToString();
                }

                if (((ICGridColumn)column).SubGrids != null)
                {
                    var values = ((ICGridColumn)column).GetSubGridKeyValues(Item);
                    var grid   = await((ICGridColumn)column).SubGrids(values.Values.ToArray(), false, true, false, true) as ICGrid;
                    grid.Direction   = GridComponent.Grid.Direction;
                    grid.FixedValues = values;
                    VariableReference reference = new VariableReference();
                    if (Children.ContainsKey(column.Name))
                    {
                        Children[column.Name] = reference;
                    }
                    else
                    {
                        Children.Add(column.Name, reference);
                    }
                    if (_renderFragments.ContainsKey(column.Name))
                    {
                        _renderFragments[column.Name] = CreateSubGridComponent(grid, reference);
                    }
                    else
                    {
                        _renderFragments.Add(column.Name, CreateSubGridComponent(grid, reference));
                    }
                }
                else if (column.DeleteComponentType != null)
                {
                    VariableReference reference = new VariableReference();
                    if (Children.ContainsKey(column.Name))
                    {
                        Children[column.Name] = reference;
                    }
                    else
                    {
                        Children.Add(column.Name, reference);
                    }
                    if (_renderFragments.ContainsKey(column.Name))
                    {
                        _renderFragments[column.Name] = GridCellComponent <T> .CreateComponent(_sequence,
                                                                                               GridComponent, column.DeleteComponentType, column, Item, null, true, reference);
                    }
                    else
                    {
                        _renderFragments.Add(column.Name, GridCellComponent <T> .CreateComponent(_sequence,
                                                                                                 GridComponent, column.DeleteComponentType, column, Item, null, true, reference));
                    }
                }
            }
            _tabGroups = GridComponent.Grid.Columns
                         .Where(r => !string.IsNullOrWhiteSpace(r.TabGroup) && _renderFragments.Keys.Any(s => s.Equals(r.Name)))
                         .Select(r => r.TabGroup).Distinct();

            if (((CGrid <T>)GridComponent.Grid).ButtonCrudComponents != null && ((CGrid <T>)GridComponent.Grid).ButtonCrudComponents.Count() > 0)
            {
                foreach (var key in ((CGrid <T>)GridComponent.Grid).ButtonCrudComponents.Keys)
                {
                    var buttonCrudComponent = ((CGrid <T>)GridComponent.Grid).ButtonCrudComponents.Get(key);
                    if ((buttonCrudComponent.DeleteMode != null && buttonCrudComponent.DeleteMode(Item)) ||
                        (buttonCrudComponent.DeleteModeAsync != null && await buttonCrudComponent.DeleteModeAsync(Item)) ||
                        (buttonCrudComponent.GridMode.HasFlag(GridMode.Delete)))
                    {
                        _buttonCrudComponentVisibility.Add(key, true);
                    }
                    else
                    {
                        _buttonCrudComponentVisibility.Add(key, false);
                    }
                }
            }

            _shouldRender = true;
        }
コード例 #51
0
        public void ValidLoop()
        {
            var integer1 = new IntegerLiteral("1", 0);
            var integer2 = new IntegerLiteral("5", 0);
            var range = new Range(integer1, integer2, 0);
            var variabledecl = new VariableDeclaration("foo", "int", 0);
            var variable = new VariableReference("foo", 0);
            var loop = new Loop(variable, range, new List<Statement>(), 0);
            statementlist.Add(variabledecl);
            statementlist.Add(loop);
            var parsetree = new Program(statementlist);

            Assert.DoesNotThrow(() => symbolTableBuilder.BuildSymbolTableAndTypeCheck(parsetree));
        }
コード例 #52
0
        public bool Process(AssemblyProcessorContext context)
        {
            var assembly         = context.Assembly;
            var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assembly);

            if (mscorlibAssembly == null)
            {
                throw new InvalidOperationException("Missing mscorlib.dll from assembly");
            }

            // For now, use import, but this can cause mixed framework versions when processing an assembly with a different framework version.
            voidType   = assembly.MainModule.TypeSystem.Void;
            stringType = assembly.MainModule.TypeSystem.String;
            objectType = assembly.MainModule.TypeSystem.Object;
            var propertyInfoType = assembly.MainModule.ImportReference(mscorlibAssembly.MainModule.GetTypeResolved(typeof(PropertyInfo).FullName));
            var typeType         = mscorlibAssembly.MainModule.GetTypeResolved(typeof(Type).FullName);


            TypeDefinition propertyChangedExtendedEventArgsType;

            ModuleDefinition xenkoCoreModule;

            try
            {
                xenkoCoreModule = assembly.GetXenkoCoreModule();
            }
            catch (Exception)
            {
                return(true);
            }

            propertyChangedExtendedEventArgsType = xenkoCoreModule.GetTypes().First(x => x.Name == "PropertyChangedExtendedEventArgs").Resolve();

            var typeTokenInfoEx         = mscorlibAssembly.MainModule.GetTypeResolved("System.Reflection.TypeInfo").Resolve();
            var getPropertyMethod       = typeTokenInfoEx.Methods.First(x => x.Name == "GetDeclaredProperty" && x.Parameters.Count == 1);
            var getTypeFromHandleMethod = typeType.Methods.First(x => x.Name == "GetTypeFromHandle");
            var getTokenInfoExMethod    = CecilExtensions.FindReflectionAssembly(assembly).MainModule.GetTypeResolved("System.Reflection.IntrospectionExtensions").Resolve().Methods.First(x => x.Name == "GetTypeInfo");

            var propertyChangedExtendedEventArgsConstructor = assembly.MainModule.ImportReference(propertyChangedExtendedEventArgsType.Methods.First(x => x.IsConstructor));

            bool modified = false;

            foreach (var type in assembly.MainModule.GetTypes())
            {
                MethodReference getPropertyChangedMethod;

                getPropertyChangedMethod = GetGetPropertyChangedMethod(assembly, type);
                //var propertyChangedField = GetPropertyChangedField(type);
                //if (propertyChangedField == null)
                //    continue;

                var propertyChangedField = GetPropertyChangedField(type);

                if (getPropertyChangedMethod == null && propertyChangedField == null)
                {
                    continue;
                }

                TypeReference propertyChangedFieldType;

                if (getPropertyChangedMethod == null)
                {
                    modified = true;
                    getPropertyChangedMethod = GetOrCreateGetPropertyChangedMethod(assembly, type, propertyChangedField);
                }

                if (propertyChangedField != null)
                {
                    propertyChangedField     = assembly.MainModule.ImportReference(propertyChangedField);
                    propertyChangedFieldType = propertyChangedField.FieldType;
                }
                else
                {
                    propertyChangedFieldType = getPropertyChangedMethod.ReturnType;
                }

                // Add generic to declaring type
                if (getPropertyChangedMethod.DeclaringType.HasGenericParameters)
                {
                    getPropertyChangedMethod = getPropertyChangedMethod.MakeGeneric(getPropertyChangedMethod.DeclaringType.GenericParameters.ToArray());
                }

                var propertyChangedInvoke = assembly.MainModule.ImportReference(propertyChangedFieldType.Resolve().Methods.First(x => x.Name == "Invoke"));

                foreach (var property in type.Properties)
                {
                    if (property.SetMethod == null || !property.HasThis)
                    {
                        continue;
                    }

                    MethodReference propertyGetMethod = property.GetMethod;

                    // Only patch properties that have a public Getter
                    var methodDefinition = propertyGetMethod.Resolve();
                    if ((methodDefinition.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
                    {
                        continue;
                    }

                    // Add generic to declaring type
                    if (propertyGetMethod.DeclaringType.HasGenericParameters)
                    {
                        propertyGetMethod = propertyGetMethod.MakeGeneric(propertyGetMethod.DeclaringType.GenericParameters.ToArray());
                    }

                    //var versionableAttribute = property.CustomAttributes.FirstOrDefault(x => x.AttributeType.FullName == typeof(VersionableAttribute).FullName);
                    //if (versionableAttribute == null)
                    //    continue;

                    modified = true;

                    FieldReference staticField = new FieldDefinition(property.Name + "PropertyInfo", FieldAttributes.Static | FieldAttributes.Private | FieldAttributes.InitOnly, propertyInfoType);
                    type.Fields.Add((FieldDefinition)staticField);

                    // Add generic to declaring type
                    if (staticField.DeclaringType.HasGenericParameters)
                    {
                        staticField = staticField.MakeGeneric(staticField.DeclaringType.GenericParameters.ToArray());
                    }

                    // In static constructor, find PropertyInfo and store it in static field
                    {
                        var staticConstructor = type.GetStaticConstructor();
                        if (staticConstructor == null)
                        {
                            staticConstructor = new MethodDefinition(".cctor",
                                                                     MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
                                                                     voidType);
                            staticConstructor.Body.GetILProcessor().Append(Instruction.Create(OpCodes.Ret));

                            type.Methods.Add(staticConstructor);
                        }


                        VariableReference localTokenEx = null;
                        int localTokenExIndex          = 0;
                        for (int i = 0; i < staticConstructor.Body.Variables.Count; i++)
                        {
                            var localVar = staticConstructor.Body.Variables[i];
                            if (localVar.VariableType.FullName == typeTokenInfoEx.FullName)
                            {
                                localTokenEx      = localVar;
                                localTokenExIndex = i;
                                break;
                            }
                        }

                        if (localTokenEx == null)
                        {
                            localTokenEx = new VariableDefinition(assembly.MainModule.ImportReference(typeTokenInfoEx));
                            staticConstructor.Body.Variables.Add((VariableDefinition)localTokenEx);
                            localTokenExIndex = staticConstructor.Body.Variables.Count - 1;
                        }

                        var ilProcessor       = staticConstructor.Body.GetILProcessor();
                        var returnInstruction = staticConstructor.Body.Instructions.Last();

                        var newReturnInstruction = Instruction.Create(returnInstruction.OpCode);
                        newReturnInstruction.Operand = returnInstruction.Operand;

                        returnInstruction.OpCode  = OpCodes.Nop;
                        returnInstruction.Operand = null;

                        // Find PropertyInfo and store it in static field
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldtoken, type));
                        ilProcessor.Append(Instruction.Create(OpCodes.Call, assembly.MainModule.ImportReference(getTypeFromHandleMethod)));
                        ilProcessor.Append(Instruction.Create(OpCodes.Call, assembly.MainModule.ImportReference(getTokenInfoExMethod)));
                        ilProcessor.Append(LocationToStloc(ilProcessor, localTokenExIndex));
                        ilProcessor.Append(ilProcessor.Create(OpCodes.Ldloca_S, (byte)localTokenExIndex));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldstr, property.Name));
                        ilProcessor.Append(Instruction.Create(OpCodes.Call, assembly.MainModule.ImportReference(getPropertyMethod)));
                        ilProcessor.Append(Instruction.Create(OpCodes.Stsfld, staticField));

                        ilProcessor.Append(newReturnInstruction);
                    }

                    {
                        var ilProcessor       = property.SetMethod.Body.GetILProcessor();
                        var returnInstruction = property.SetMethod.Body.Instructions.Last();

                        var firstInstruction = property.SetMethod.Body.Instructions[0];

                        if (property.SetMethod.Body.Instructions[0].OpCode != OpCodes.Nop)
                        {
                            ilProcessor.InsertBefore(property.SetMethod.Body.Instructions[0], Instruction.Create(OpCodes.Nop));
                        }

                        var newReturnInstruction = Instruction.Create(returnInstruction.OpCode);
                        newReturnInstruction.Operand = returnInstruction.Operand;

                        returnInstruction.OpCode  = OpCodes.Nop;
                        returnInstruction.Operand = null;

                        var propertyChangedVariable = new VariableDefinition(assembly.MainModule.ImportReference(propertyChangedFieldType));
                        property.SetMethod.Body.Variables.Add(propertyChangedVariable);

                        var oldValueVariable = new VariableDefinition(objectType);
                        property.SetMethod.Body.Variables.Add(oldValueVariable);

                        Instruction jump1, jump2;

                        // Prepend:
                        // var propertyChanged = GetPropertyChanged();
                        // var oldValue = propertyChanged != null ? (object)Property : null;
                        property.SetMethod.Body.SimplifyMacros();
                        ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Ldarg_0));
                        ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Call, getPropertyChangedMethod));
                        ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Stloc, propertyChangedVariable));
                        ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Ldloc, propertyChangedVariable));
                        ilProcessor.InsertBefore(firstInstruction, jump1 = Instruction.Create(OpCodes.Brtrue, Instruction.Create(OpCodes.Nop)));
                        ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Ldnull));
                        ilProcessor.InsertBefore(firstInstruction, jump2 = Instruction.Create(OpCodes.Br, Instruction.Create(OpCodes.Nop)));
                        ilProcessor.InsertBefore(firstInstruction, (Instruction)(jump1.Operand = Instruction.Create(OpCodes.Ldarg_0)));
                        ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Call, propertyGetMethod));
                        if (property.PropertyType.IsValueType)
                        {
                            ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Box, property.PropertyType));
                        }
                        ilProcessor.InsertBefore(firstInstruction, (Instruction)(jump2.Operand = Instruction.Create(OpCodes.Nop)));
                        ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Stloc, oldValueVariable));

                        // Append:
                        // if (propertyChanged != null)
                        //     propertyChanged(this, new PropertyChangedExtendedEventArgs("Property", oldValue, Property));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldloc, propertyChangedVariable));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldnull));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ceq));
                        ilProcessor.Append(Instruction.Create(OpCodes.Brtrue, newReturnInstruction));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldloc, propertyChangedVariable));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldarg_0));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldsfld, staticField));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldloc, oldValueVariable));
                        ilProcessor.Append(Instruction.Create(OpCodes.Ldarg_0));
                        ilProcessor.Append(Instruction.Create(OpCodes.Call, propertyGetMethod));
                        if (property.PropertyType.IsValueType)
                        {
                            ilProcessor.Append(Instruction.Create(OpCodes.Box, property.PropertyType));
                        }
                        ilProcessor.Append(Instruction.Create(OpCodes.Newobj, propertyChangedExtendedEventArgsConstructor));
                        ilProcessor.Append(Instruction.Create(OpCodes.Callvirt, propertyChangedInvoke));
                        ilProcessor.Append(Instruction.Create(OpCodes.Nop));
                        ilProcessor.Append(newReturnInstruction);
                        property.SetMethod.Body.OptimizeMacros();
                    }
                }
            }

            return(modified);
        }
コード例 #53
0
 public void FixtureSetUp()
 {
     var op1decl = new VariableDeclaration("op1", "int", 0);
     var op2decl = new VariableDeclaration("op2", "int", 0);
     resultdecl = new VariableDeclaration("result", "int", 0);
     op1assignment = new Assignment(op1decl, new IntegerLiteral("5", 0), 0);
     op2assignment = new Assignment(op2decl, new IntegerLiteral("2", 0), 0);
     op1 = new VariableReference("op1", 0);
     op2 = new VariableReference("op2", 0);
 }
コード例 #54
0
ファイル: Assign.cs プロジェクト: veler/AlgorithmSimulator
        /// <summary>
        /// Run the interpretation
        /// </summary>
        internal override void Execute()
        {
            int          indexValue   = -1;
            object       targetObject = null;
            object       leftValue    = null;
            object       rightValue;
            PropertyInfo propertyInfo;
            Variable     propertyVariable;
            IList        propertyVariableList;
            var          leftExpression  = Statement._leftExpression;
            var          rightExpression = Statement._rightExpression;

            if (DebugMode)
            {
                ParentInterpreter.Log(this, $"Assign '{leftExpression}' to '{rightExpression}'");

                if (!typeof(IAlgorithmAssignable).IsAssignableFrom(leftExpression.GetType()))
                {
                    ParentInterpreter.ChangeState(this, new AlgorithmInterpreterStateEventArgs(new Error(new NotAssignableException($"The left expression is not assignable."), Statement), ParentInterpreter.GetDebugInfo()));
                    return;
                }
            }

            switch (leftExpression.DomType)
            {
            case AlgorithmDomType.PropertyReferenceExpression:
                var propertyReferenceInterpreter = new PropertyReference(DebugMode, ParentInterpreter, leftExpression);
                leftValue    = propertyReferenceInterpreter.GetAssignableObject();
                targetObject = propertyReferenceInterpreter.TargetObject;
                break;

            case AlgorithmDomType.VariableReferenceExpression:
                leftValue = new VariableReference(DebugMode, ParentInterpreter, leftExpression).GetAssignableObject();
                break;

            case AlgorithmDomType.ArrayIndexerExpression:
                var arrayIndexerInterpreter = new ArrayIndexerExpression(DebugMode, ParentInterpreter, leftExpression);
                leftValue  = arrayIndexerInterpreter.GetAssignableObject();
                indexValue = arrayIndexerInterpreter.IndexValue;
                break;

            default:
                ParentInterpreter.ChangeState(this, new AlgorithmInterpreterStateEventArgs(new Error(new InvalidCastException($"Unable to find an interpreter for this expression : '{leftExpression.GetType().FullName}'"), Statement), ParentInterpreter.GetDebugInfo()));
                break;
            }

            if (ParentInterpreter.FailedOrStop)
            {
                return;
            }

            rightValue = ParentInterpreter.RunExpression(rightExpression);

            if (ParentInterpreter.FailedOrStop)
            {
                return;
            }

            propertyInfo = leftValue as PropertyInfo;
            if (propertyInfo != null)
            {
                if (!propertyInfo.CanWrite)
                {
                    ParentInterpreter.ChangeState(this, new AlgorithmInterpreterStateEventArgs(new Error(new NotAssignableException($"This core property is not assignable."), Statement), ParentInterpreter.GetDebugInfo()));
                    return;
                }
                propertyInfo.SetValue(targetObject, rightValue);
            }

            propertyVariable = leftValue as Variable;
            if (propertyVariable != null)
            {
                if (propertyVariable.IsArray && !(typeof(Array).IsAssignableFrom(rightValue.GetType()) || typeof(IList).IsAssignableFrom(rightValue.GetType())))
                {
                    ParentInterpreter.ChangeState(this, new AlgorithmInterpreterStateEventArgs(new Error(new NotAssignableException($"The left expression wait for an array, but the right value is not an array."), Statement), ParentInterpreter.GetDebugInfo()));
                    return;
                }
                if (!propertyVariable.IsArray && (typeof(Array).IsAssignableFrom(rightValue.GetType()) || typeof(IList).IsAssignableFrom(rightValue.GetType())))
                {
                    ParentInterpreter.ChangeState(this, new AlgorithmInterpreterStateEventArgs(new Error(new NotAssignableException($"The left expression does not support array value, but the right value is  an array."), Statement), ParentInterpreter.GetDebugInfo()));
                    return;
                }
                propertyVariable.Value = rightValue;
            }

            propertyVariableList = leftValue as IList;
            if (propertyVariableList != null)
            {
                if (indexValue < 0 || indexValue >= propertyVariableList.Count)
                {
                    ParentInterpreter.ChangeState(this, new AlgorithmInterpreterStateEventArgs(new Error(new IndexOutOfRangeException($"Unable to get the item number '{indexValue}' because the limit of the array is '{propertyVariableList.Count - 1}'."), Statement), ParentInterpreter.GetDebugInfo()));
                    return;
                }
                propertyVariableList[indexValue] = rightValue;
            }

            if (DebugMode)
            {
                ParentInterpreter.Log(this, "'{0}' is now equal to {1}", leftExpression.ToString(), rightValue == null ? "{null}" : $"'{rightValue}' (type:{rightValue.GetType().FullName})");
            }
        }
コード例 #55
0
        public void Visit(VariableReference variable)
        {
            var getter = context.CompiledGetter(variable.Path);
            getter = CompoundExpression.NullCheck(getter, "");
            getter = Expression.Call(getter, context.TargetType.GetMethod("ToString"));

            if (variable.Escaped)
            {
                parts.Add(Expression.Call(null, typeof(Encoders).GetMethod("DefaultHtmlEncode"), getter));
            }
            else
            {
                parts.Add(getter);
            }
        }