public ProblemMetadata(int sourceExpressionId, SourceContext sourceContext, Fragment expectedFragment, Fragment givenFragment)
        {
            ArgumentUtility.CheckNotNull ("givenFragment", givenFragment);

              _sourceExpressionId = sourceExpressionId;
              _sourceContext = ArgumentUtility.CheckNotNull ("sourceContext", sourceContext);
              _expectedFragment = expectedFragment;
              _givenFragment = givenFragment;
        }
 public State(
     ITestResponder <T1> responder,
     Func <T1, T2> selector,
     SourceContext sourceContext)
     : base(sourceContext)
 {
     this.responder     = responder.CreateState();
     this.selector      = selector;
     this.sourceContext = sourceContext;
 }
Exemple #3
0
 private void AutoAssignId(Resource resource, JToken jToken, SourceContext sourceContext)
 {
     if (sourceContext is ResourceSourceContext resourceSourceContext)
     {
         if (jToken is JObject jObj && !jObj.ContainsKey("id") && !resourceSourceContext.DefaultIdMap.ContainsKey(jToken))
         {
             resourceSourceContext.DefaultIdMap.Add(jToken, resource.Id);
         }
     }
 }
        public literal create_format_string_const(string text, SourceContext sc)
        {
            literal lt;

            text = ReplaceSpecialSymbols(text.Substring(2, text.Length - 3));
            lt   = new string_const(text);
            (lt as string_const).IsInterpolated = true;
            lt.source_context = sc;
            return(lt);
        }
        public List <statement> GetDeconstructionDefinitions(SourceContext patternContext)
        {
            var result = new List <statement>();

            result.Add(CastVariableDefinition);
            result.Add(new desugared_deconstruction(DeconstructionVariables, CastVariable, patternContext));
            result.Add(SuccessVariableDefinition);

            return(result);
        }
Exemple #6
0
 public State(
     ITestWaitCondition <TFirst> first,
     Func <TFirst, ITestWaitCondition <TSecond> > continuation,
     SourceContext sourceContext)
     : base(sourceContext)
 {
     this.first        = first.CreateState();
     this.continuation = new Continuation <TFirst, TSecond>(
         firstResult => continuation(firstResult).CreateState());
 }
        public async Task <StageResultContext> GetResultAsync(ImportContext context, Func <ImportContext, Task <StageResultContext> > next)
        {
            //var result = await context.SourceContext.Source;
            ////var result = await this.GetResultAsync(context);
            //if (result.IsCompleted)
            //    return result;
            var sourceContext = new SourceContext(() => this.GetResultAsync(context));

            return(await next(new ImportContext(sourceContext, new TargetContext())));
        }
        public override void visit(function_lambda_definition lambdaDefinition)
        {
            if (lambdaDefinition.formal_parameters != null && lambdaDefinition.formal_parameters.params_list != null && lambdaDefinition.formal_parameters.params_list.Count != 0)
            {
                var varDefsList = new List <statement>();
                for (var i = 0; i < lambdaDefinition.formal_parameters.params_list.Count; i++)
                {
                    var varType = lambdaDefinition.formal_parameters.params_list[i].vars_type is lambda_inferred_type?
                                  LambdaHelper.ConvertSemanticTypeToSyntaxType((type_node)((lambda_inferred_type)lambdaDefinition.formal_parameters.params_list[i].vars_type).real_type) :
                                      lambdaDefinition.formal_parameters.params_list[i].vars_type;

                    for (var j = 0; j < lambdaDefinition.formal_parameters.params_list[i].idents.idents.Count; j++)
                    {
                        var           varName = "<>" + lambdaDefinition.formal_parameters.params_list[i].idents.idents[j].name;
                        SourceContext sc      = lambdaDefinition.formal_parameters.params_list[i].idents.idents[j].source_context;
                        var           vds     = new var_def_statement(new ident(lambdaDefinition.formal_parameters.params_list[i].idents.idents[j].name, sc), varType, sc);
                        vds.inital_value = new ident(varName, sc);
                        lambdaDefinition.formal_parameters.params_list[i].idents.idents[j].name = varName;
                        varDefsList.Add(new var_statement(vds, sc));
                    }
                }

                ((statement_list)lambdaDefinition.proc_body).subnodes.InsertRange(0, varDefsList);
            }

            var procDecl = LambdaHelper.ConvertLambdaNodeToProcDefNode(lambdaDefinition);

            _visitor.body_exists = true;
            _visitor.hard_node_test_and_visit(procDecl.proc_header);

            var newTreeNode = new CapturedVariablesTreeNodeLambdaScope(_currentTreeNode,
                                                                       lambdaDefinition,
                                                                       _visitor.context.func_stack.top().scope.ScopeNum, lambdaDefinition);

            _currentTreeNode.LambdasDefinedInScope.Add(newTreeNode);
            _currentLambdaScopeNodeStack.Push(newTreeNode);

            if (_currentTreeNode != null)
            {
                _currentTreeNode.ChildNodes.Add(newTreeNode);
            }
            _currentTreeNode = newTreeNode;
            _scopesCapturedVarsNodesDictionary.Add(_currentTreeNode.ScopeIndex, _currentTreeNode);

            VisitProcParameters(procDecl.proc_header.parameters);
            ProcessNode(procDecl.proc_body);

            _visitor.context.leave_block();
            _visitor.context.remove_lambda_function(procDecl.proc_header.name.meth_name.name, false);

            _currentTreeNode = _currentTreeNode.ParentNode;
            _currentLambdaScopeNodeStack.Pop();

            LambdaHelper.RemoveLambdaInfoFromCompilationContext(_visitor.context, lambdaDefinition);
        }
 public UntilResponder(
     IOptionalTestResponder responder,
     ITestWaitCondition <T> condition,
     SourceContext sourceContext)
     : base(() => new UntilResponderState <T>(
                "UNTIL",
                responder.CreateState(),
                condition.CreateState(),
                sourceContext))
 {
 }
 public UntilReadyToResponder(
     IOptionalTestResponder respondTo,
     ITestResponder <T> untilReady,
     SourceContext sourceContext)
     : base(() => new UntilResponderState <ITestOperationState <T> >(
                "UNTIL READY TO",
                respondTo.CreateState(),
                untilReady.CreateState(),
                sourceContext))
 {
 }
Exemple #11
0
 public State(
     string objectDescription,
     Func <T> getObject,
     IConstraint constraint,
     SourceContext sourceContext)
     : base(sourceContext)
 {
     this.getObject   = getObject;
     this.constraint  = constraint;
     this.Description = $"{objectDescription}: {this.constraint.Description}";
 }
Exemple #12
0
 private void SafeRun(Action action, SourceContext sourceContext, CleanupRule rule)
 {
     try
     {
         action();
     }
     catch (Exception e)
     {
         sourceContext.AddErrorForSourceColumn(rule.ColumnName, e, SourceContext.ErrorTypeCleanup);
     }
 }
Exemple #13
0
        public EntityFrameworkSourceTestContext()
        {
            var sourceContext    = new SourceContext(Database.TestConnectionString);
            var configuration    = new TestConfiguration();
            var templateProvider = new AttributeModelTemplateProvider(configuration);

            Repository = new SourcesRepository(
                sourceContext,
                new EntityFactory(new TunnelVisionLabsUriTemplateExpander(templateProvider), configuration),
                new TunnelVisionLabsUriTemplateMatcher(templateProvider));
        }
Exemple #14
0
        internal TerminalMatch(SourceContext matchEnd, string matchedData)
        {
            if (matchEnd == null)
            {
                throw new ArgumentNullException("matchEnd");
            }

            Success     = true;
            MatchEnd    = matchEnd;
            MatchedData = matchedData;
        }
 public override void Run(object context)
 {
     try
     {
         _sc = (SourceContext)context;
     }
     catch (Exception ex)
     {
         Logger.Log.Error(true, "SourceFunctionFromKafka:", ex);
     }
 }
        public ident create_ident(string text, SourceContext sc)
        {
            if (text[0] == '&')
            {
                text = text.Substring(1);
            }
            ident id = new ident(text);

            id.source_context = sc;
            return(id);
        }
 public UntilResponderState(
     string untilDescription,
     ITestOperationState <IMultipleTaskSource <ITestOperationState <object> > > respondTo,
     ITestOperationState <T> until,
     SourceContext sourceContext)
     : base(sourceContext)
 {
     this.untilDescription = untilDescription;
     this.respondTo        = respondTo;
     this.until            = until;
 }
Exemple #18
0
 public ArrayInstance(Expression type, Expression[] dimensionSizes, SourceContext context)
 {
     this.SourceContext  = context;
     this.Type           = ((TypeExpression)type).Type;
     this.Dimension      = (ushort)(dimensionSizes.Length + 1);
     this.DimensionSizes = dimensionSizes;
     foreach (Expression dimensionSize in dimensionSizes)
     {
         this.AddNode(dimensionSize);
     }
 }
Exemple #19
0
 public State(
     string description,
     ITestWaitCondition <TArg> waitCondition,
     Func <TArg, ITestInstruction <T> > makeInstruction,
     SourceContext sourceContext)
     : base(sourceContext)
 {
     this.Description     = description;
     this.waitCondition   = waitCondition.CreateState();
     this.makeInstruction = makeInstruction;
 }
Exemple #20
0
        public override bool Validate(SourceContext sourceContext)
        {
            var success = ImplementingIntrinsic <IFunction>(sourceContext) != null;

            if (!(Body is Terminal))
            {
                sourceContext.LogError(20, $"Intrinsic function '{Location}' cannot have a body");
                success = false;
            }

            return(success);
        }
Exemple #21
0
 private void SafeRun(Action action, SourceContext sourceContext, TransformationMap map)
 {
     try
     {
         action();
     }
     catch (Exception e)
     {
         SetEmptyOutput(sourceContext, map);
         sourceContext.AddErrorForDestinationColumn(map.Output, e, SourceContext.ErrorTypeCleanup);
     }
 }
Exemple #22
0
        public override bool Validate(SourceContext sourceContext)
        {
            var success = base.Validate(sourceContext);

            if (Body is Terminal)
            {
                sourceContext.LogError(21, $"Non intrinsic function '{Location}' must have a body");
                success = false;
            }

            return(success);
        }
Exemple #23
0
        public MethodInvokationExpression(string name, Expression[] parameters, SourceContext context)
        {
            this.Name          = name;
            this.SourceContext = context;
            this.Parameters    = CreateParameterInstances(parameters);
            this.ArgCount      = (ushort)parameters.Length;

            foreach (Expression parameter in parameters)
            {
                this.AddNode(parameter);
            }
        }
Exemple #24
0
        private void ApplyConditionalCleanup(CleanupRule rule, SourceContext sourceContext, string stringValue,
                                             SingleCleanupRuleResult result, EvaluatedValue evaluation)
        {
            switch (rule.Action)
            {
            case CleanupAction.Replace:
            {
                sourceContext.Source[rule.ColumnName] = evaluation.Value;
            }
            break;

            case CleanupAction.ReplaceMatched:
            {
                if (_matched.ContainsKey(rule.ColumnName) && !string.IsNullOrEmpty(_matched[rule.ColumnName]))
                {
                    if (string.IsNullOrEmpty(stringValue))
                    {
                        sourceContext.Source[rule.ColumnName] = evaluation.Value;
                    }
                    else
                    {
                        sourceContext.Source[rule.ColumnName] = stringValue.Replace(_matched[rule.ColumnName], evaluation.Value);
                    }
                }
            }
            break;

            case CleanupAction.Remove:
            {
                result.IsDeleted = true;
            }
            break;

            case CleanupAction.StartLoad:
            {
                _frameState.StartLoad();
            }
            break;

            case CleanupAction.StartLoadExclude:
            {
                _frameState.StartLoadExclude();
            }
            break;

            case CleanupAction.StopLoad:
            {
                _frameState.StopLoad();
            }
            break;
            }
        }
Exemple #25
0
        public Statement ParseForLoopStatement()
        {
            if (!Match(tkFor))
            {
                return(new ErroredStatement(new ReservedWordExpected("for", Lexer.CurrentToken)));
            }
            Lexer.GetNextToken();

            if (!Match(tkLpar))
            {
                return(new ErroredStatement(new MissingLpar(Lexer.CurrentToken)));
            }
            Lexer.GetNextToken();

            SourceContext loopContext = new SourceContext();

            loopContext.FilePath = CurrentParsingFile;
            loopContext.StartsAt = new Position(Lexer.CurrentToken);

            Statement loopInit;

            if (Match(tkType))
            {
                loopInit = ParseDeclarationStatement();
            }
            else
            {
                loopInit = ParseAssignmentStatement();
            }

            Expression loopCondition = ParseBooleanExpression();

            if (!Match(tkSemicolon))
            {
                return(new ErroredStatement(new MissingSemi(Lexer.CurrentToken)));
            }
            Lexer.GetNextToken();

            Statement loopStep = ParseAssignmentStatement();

            if (!Match(tkRpar))
            {
                return(new ErroredStatement(new MissingRpar(Lexer.CurrentToken)));
            }
            Lexer.GetNextToken();

            Statement loopBody = ParseEmbeddedStatement();

            loopContext.EndsAt = new Position(Lexer.CurrentToken);

            return(new ForLoopStatement(loopInit, loopCondition, loopStep, loopBody, loopContext));
        }
        /// <summary>
        /// Resolves a ref to the actual object.
        /// </summary>
        /// <param name="refToken">reference.</param>
        /// <param name="sourceContext">source context to build debugger source map.</param>
        /// <returns>resolved object the reference refers to.</returns>
        public async Task <JToken> ResolveRefAsync(JToken refToken, SourceContext sourceContext)
        {
            var refTarget = GetRefTarget(refToken);

            if (string.IsNullOrEmpty(refTarget))
            {
                throw new InvalidOperationException("Failed to resolve reference, $copy property not present");
            }

            // see if there is a dialog file for this resource.id
            if (!this.TryGetResource($"{refTarget}.dialog", out Resource resource))
            {
                // if not, try loading the resource directly.
                if (!this.TryGetResource(refTarget, out resource))
                {
                    throw new FileNotFoundException($"Failed to find resource named {refTarget}.dialog or {refTarget}.");
                }
            }

            var(json, range) = await ReadTokenRangeAsync(resource, sourceContext);

            foreach (JProperty prop in refToken.Children <JProperty>())
            {
                if (prop.Name != "$ref")
                {
                    // JToken is an object, so we merge objects
                    if (json[prop.Name] != null && json[prop.Name].Type == JTokenType.Object)
                    {
                        JObject targetProperty = json[prop.Name] as JObject;
                        targetProperty.Merge(prop.Value);
                    }

                    // JToken is an object, so we merge objects
                    else if (json[prop.Name] != null && json[prop.Name].Type == JTokenType.Array)
                    {
                        JArray targetArray = json[prop.Name] as JArray;
                        targetArray.Merge(prop.Value);
                    }

                    // JToken is a value, simply assign
                    else
                    {
                        json[prop.Name] = prop.Value;
                    }
                }
            }

            // if we have a source range for the resource, then make it available to InterfaceConverter
            DebugSupport.SourceMap.Add(json, range);

            return(json);
        }
Exemple #27
0
 private void OutputContextPosition(SourceContext context)
 {
     if (context != null)
     {
         m_writer.WriteAttributeString("srcLine", context.StartLineNumber.ToStringInvariant());
         m_writer.WriteAttributeString("srcCol", (context.StartColumn + 1).ToStringInvariant());
         if (context.OutputLine > 0)
         {
             m_writer.WriteAttributeString("dstLine", context.OutputLine.ToStringInvariant());
             m_writer.WriteAttributeString("dstCol", (context.OutputColumn + 1).ToStringInvariant());
         }
     }
 }
        private string TrailingUseMasterName(SparkViewDescriptor descriptor)
        {
            string        lastTemplate  = descriptor.Templates.Last();
            SourceContext sourceContext = AbstractSyntaxProvider.CreateSourceContext(lastTemplate, _engine.ViewFolder);

            if (sourceContext == null)
            {
                return(null);
            }
            ParseResult <string> result = ParseUseMaster(new Position(sourceContext));

            return(result == null ? null : result.Value);
        }
Exemple #29
0
 /// <summary>
 /// Initiates the asynchronous execution to get all the remaining results from DynamoDB.
 /// </summary>
 /// <param name="callback">The callback that will be invoked when the asynchronous operation completes.</param>
 /// <param name="asyncOptions">An instance of AsyncOptions that specifies how the async method should be executed.</param>
 public void GetRemainingAsync(AmazonDynamoDBCallback <List <T> > callback, AsyncOptions asyncOptions = null)
 {
     asyncOptions = asyncOptions ?? new AsyncOptions();
     DynamoDBAsyncExecutor.ExecuteAsync <List <T> >(
         () =>
     {
         var documents  = DocumentSearch.GetRemainingHelper(true);
         List <T> items = SourceContext.FromDocumentsHelper <T>(documents, Config).ToList();
         return(items);
     },
         asyncOptions,
         callback);
 }
Exemple #30
0
        public void Read(SourceContext context)
        {
            TryToInit();

            if (_headers == null)
            {
                ReadHeaders();
            }

            var line = _sr.ReadLine();

            context.UpdateSource(CsvParser.Parse(line, _headers));
        }
Exemple #31
0
 private bool CheckMandatory(DataSourceSchemaItem item, SourceContext context)
 {
     if (!item.IsRequired)
     {
         return(true);
     }
     if (!context.Source.ContainsKey(item.ColumnName) || context.Source[item.ColumnName] == null ||
         context.Source[item.ColumnName].ToString() == "")
     {
         return(false);
     }
     return(true);
 }
Exemple #32
0
        private bool ParseStatement(Block/*!*/ block)
        {
            //parse instructions and put in expression tree until an assignment, void call, branch target, or branch is encountered
            StatementList statementList = block.Statements;
            Expression expr = null;
            Statement statement = null;
            bool transferStatement = false;
            int startingAddress = 0;

            SourceContext sourceContext = new SourceContext();
            sourceContext.StartPos = this.counter;

            if (this.method.contextForOffset != null)
            {
                object sctx = this.method.contextForOffset[this.counter + 1];
                if (sctx != null) sourceContext = (SourceContext)sctx;
            }

            while (true)
            {
                bool isStatement = false;
                startingAddress = this.counter + 1; //Add one so that it is never zero (the latter means no entry to the TrivialHashtable)

                OpCode opCode = this.GetOpCode();

                switch (opCode)
                {
                    case OpCode.Nop: statement = new Statement(NodeType.Nop); goto done;
                    case OpCode.Break: statement = new Statement(NodeType.DebugBreak); goto done;
                    case OpCode.Ldarg_0: expr = this.Parameters(0); break;
                    case OpCode.Ldarg_1: expr = this.Parameters(1); break;
                    case OpCode.Ldarg_2: expr = this.Parameters(2); break;
                    case OpCode.Ldarg_3: expr = this.Parameters(3); break;
                    case OpCode.Ldloc_0: expr = this.locals[0]; break;
                    case OpCode.Ldloc_1: expr = this.locals[1]; break;
                    case OpCode.Ldloc_2: expr = this.locals[2]; break;
                    case OpCode.Ldloc_3: expr = this.locals[3]; break;
                    case OpCode.Stloc_0: statement = new AssignmentStatement(this.locals[0], PopOperand()); goto done;
                    case OpCode.Stloc_1: statement = new AssignmentStatement(this.locals[1], PopOperand()); goto done;
                    case OpCode.Stloc_2: statement = new AssignmentStatement(this.locals[2], PopOperand()); goto done;
                    case OpCode.Stloc_3: statement = new AssignmentStatement(this.locals[3], PopOperand()); goto done;
                    case OpCode.Ldarg_S: expr = this.Parameters(this.GetByte()); break;
                    case OpCode.Ldarga_S: expr = SetType(new UnaryExpression(this.Parameters(this.GetByte()), NodeType.AddressOf)); break;
                    case OpCode.Starg_S: statement = new AssignmentStatement(this.Parameters(this.GetByte()), PopOperand()); goto done;
                    case OpCode.Ldloc_S: expr = this.locals[this.GetByte()]; break;
                    case OpCode.Ldloca_S: expr = SetType(new UnaryExpression(this.locals[this.GetByte()], NodeType.AddressOf)); break;
                    case OpCode.Stloc_S: statement = new AssignmentStatement(this.locals[this.GetByte()], PopOperand()); goto done;
                    case OpCode.Ldnull: expr = new Literal(null, CoreSystemTypes.Object); break;
                    case OpCode.Ldc_I4_M1: expr = new Literal(-1, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_0: expr = new Literal(0, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_1: expr = new Literal(1, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_2: expr = new Literal(2, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_3: expr = new Literal(3, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_4: expr = new Literal(4, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_5: expr = new Literal(5, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_6: expr = new Literal(6, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_7: expr = new Literal(7, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_8: expr = new Literal(8, CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4_S: expr = new Literal((int)this.GetSByte(), CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I4: expr = new Literal(this.GetInt32(), CoreSystemTypes.Int32); break;
                    case OpCode.Ldc_I8: expr = new Literal(this.GetInt64(), CoreSystemTypes.Int64); break;
                    case OpCode.Ldc_R4: expr = new Literal(this.GetSingle(), CoreSystemTypes.Single); break;
                    case OpCode.Ldc_R8: expr = new Literal(this.GetDouble(), CoreSystemTypes.Double); break;
                    case OpCode.Dup: statement = new ExpressionStatement(new Expression(NodeType.Dup)); goto done;
                    case OpCode.Pop: statement = new ExpressionStatement(new UnaryExpression(PopOperand(), NodeType.Pop)); goto done;
                    case OpCode.Jmp: expr = this.ParseCall(NodeType.Jmp, out isStatement); if (isStatement) goto done; break;
                    case OpCode.Call: expr = this.ParseCall(NodeType.Call, out isStatement); if (isStatement) goto done; break;
                    case OpCode.Calli: expr = this.ParseCalli(out isStatement); if (isStatement) goto done; break;
                    case OpCode.Ret:
                        Expression retVal = BodyParser.TypeIsVoid(this.method.ReturnType) ? null : PopOperand();
                        statement = new Return(retVal);
                        transferStatement = true; goto done;
                    case OpCode.Br_S: statement = this.ParseBranch(NodeType.Nop, 0, true, false); transferStatement = true; goto done;
                    case OpCode.Brfalse_S: statement = this.ParseBranch(NodeType.LogicalNot, 1, true, false); transferStatement = true; goto done;
                    case OpCode.Brtrue_S: statement = this.ParseBranch(NodeType.Nop, 1, true, false); transferStatement = true; goto done;
                    case OpCode.Beq_S: statement = this.ParseBranch(NodeType.Eq, 2, true, false); transferStatement = true; goto done;
                    case OpCode.Bge_S: statement = this.ParseBranch(NodeType.Ge, 2, true, false); transferStatement = true; goto done;
                    case OpCode.Bgt_S: statement = this.ParseBranch(NodeType.Gt, 2, true, false); transferStatement = true; goto done;
                    case OpCode.Ble_S: statement = this.ParseBranch(NodeType.Le, 2, true, false); transferStatement = true; goto done;
                    case OpCode.Blt_S: statement = this.ParseBranch(NodeType.Lt, 2, true, false); transferStatement = true; goto done;
                    case OpCode.Bne_Un_S: statement = this.ParseBranch(NodeType.Ne, 2, true, true); transferStatement = true; goto done;
                    case OpCode.Bge_Un_S: statement = this.ParseBranch(NodeType.Ge, 2, true, true); transferStatement = true; goto done;
                    case OpCode.Bgt_Un_S: statement = this.ParseBranch(NodeType.Gt, 2, true, true); transferStatement = true; goto done;
                    case OpCode.Ble_Un_S: statement = this.ParseBranch(NodeType.Le, 2, true, true); transferStatement = true; goto done;
                    case OpCode.Blt_Un_S: statement = this.ParseBranch(NodeType.Lt, 2, true, true); transferStatement = true; goto done;
                    case OpCode.Br: statement = this.ParseBranch(NodeType.Nop, 0, false, false); transferStatement = true; goto done;
                    case OpCode.Brfalse: statement = this.ParseBranch(NodeType.LogicalNot, 1, false, false); transferStatement = true; goto done;
                    case OpCode.Brtrue: statement = this.ParseBranch(NodeType.Nop, 1, false, false); transferStatement = true; goto done;
                    case OpCode.Beq: statement = this.ParseBranch(NodeType.Eq, 2, false, false); transferStatement = true; goto done;
                    case OpCode.Bge: statement = this.ParseBranch(NodeType.Ge, 2, false, false); transferStatement = true; goto done;
                    case OpCode.Bgt: statement = this.ParseBranch(NodeType.Gt, 2, false, false); transferStatement = true; goto done;
                    case OpCode.Ble: statement = this.ParseBranch(NodeType.Le, 2, false, false); transferStatement = true; goto done;
                    case OpCode.Blt: statement = this.ParseBranch(NodeType.Lt, 2, false, false); transferStatement = true; goto done;
                    case OpCode.Bne_Un: statement = this.ParseBranch(NodeType.Ne, 2, false, true); transferStatement = true; goto done;
                    case OpCode.Bge_Un: statement = this.ParseBranch(NodeType.Ge, 2, false, true); transferStatement = true; goto done;
                    case OpCode.Bgt_Un: statement = this.ParseBranch(NodeType.Gt, 2, false, true); transferStatement = true; goto done;
                    case OpCode.Ble_Un: statement = this.ParseBranch(NodeType.Le, 2, false, true); transferStatement = true; goto done;
                    case OpCode.Blt_Un: statement = this.ParseBranch(NodeType.Lt, 2, false, true); transferStatement = true; goto done;
                    case OpCode.Switch: statement = this.ParseSwitchInstruction(); transferStatement = true; goto done;
                    case OpCode.Ldind_I1: expr = new AddressDereference(PopOperand(), CoreSystemTypes.Int8, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_U1: expr = new AddressDereference(PopOperand(), CoreSystemTypes.UInt8, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_I2: expr = new AddressDereference(PopOperand(), CoreSystemTypes.Int16, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_U2: expr = new AddressDereference(PopOperand(), CoreSystemTypes.UInt16, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_I4: expr = new AddressDereference(PopOperand(), CoreSystemTypes.Int32, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_U4: expr = new AddressDereference(PopOperand(), CoreSystemTypes.UInt32, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_I8: expr = new AddressDereference(PopOperand(), CoreSystemTypes.Int64, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_I: expr = new AddressDereference(PopOperand(), CoreSystemTypes.IntPtr, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_R4: expr = new AddressDereference(PopOperand(), CoreSystemTypes.Single, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_R8: expr = new AddressDereference(PopOperand(), CoreSystemTypes.Double, this.isVolatile, this.alignment); break;
                    case OpCode.Ldind_Ref: expr = new AddressDereference(PopOperand(), CoreSystemTypes.Object, this.isVolatile, this.alignment); break;
                    case OpCode.Stind_Ref: statement = this.ParseStoreIndirect(CoreSystemTypes.Object); goto done;
                    case OpCode.Stind_I1: statement = this.ParseStoreIndirect(CoreSystemTypes.Int8); goto done;
                    case OpCode.Stind_I2: statement = this.ParseStoreIndirect(CoreSystemTypes.Int16); goto done;
                    case OpCode.Stind_I4: statement = this.ParseStoreIndirect(CoreSystemTypes.Int32); goto done;
                    case OpCode.Stind_I8: statement = this.ParseStoreIndirect(CoreSystemTypes.Int64); goto done;
                    case OpCode.Stind_R4: statement = this.ParseStoreIndirect(CoreSystemTypes.Single); goto done;
                    case OpCode.Stind_R8: statement = this.ParseStoreIndirect(CoreSystemTypes.Double); goto done;
                    case OpCode.Add: expr = this.ParseBinaryOperation(NodeType.Add); break;
                    case OpCode.Sub: expr = this.ParseBinaryOperation(NodeType.Sub); break;
                    case OpCode.Mul: expr = this.ParseBinaryOperation(NodeType.Mul); break;
                    case OpCode.Div: expr = this.ParseBinaryOperation(NodeType.Div); break;
                    case OpCode.Div_Un: expr = this.ParseBinaryOperation(NodeType.Div_Un); break;
                    case OpCode.Rem: expr = this.ParseBinaryOperation(NodeType.Rem); break;
                    case OpCode.Rem_Un: expr = this.ParseBinaryOperation(NodeType.Rem_Un); break;
                    case OpCode.And: expr = this.ParseBinaryOperation(NodeType.And); break;
                    case OpCode.Or: expr = this.ParseBinaryOperation(NodeType.Or); break;
                    case OpCode.Xor: expr = this.ParseBinaryOperation(NodeType.Xor); break;
                    case OpCode.Shl: expr = this.ParseBinaryOperation(NodeType.Shl); break;
                    case OpCode.Shr: expr = this.ParseBinaryOperation(NodeType.Shr); break;
                    case OpCode.Shr_Un: expr = this.ParseBinaryOperation(NodeType.Shr_Un); break;
                    case OpCode.Neg: expr = this.ParseUnaryOperation(NodeType.Neg); break;
                    case OpCode.Not: expr = this.ParseUnaryOperation(NodeType.Not); break;
                    case OpCode.Conv_I1: expr = new UnaryExpression(PopOperand(), NodeType.Conv_I1, CoreSystemTypes.Int8); break;
                    case OpCode.Conv_I2: expr = new UnaryExpression(PopOperand(), NodeType.Conv_I2, CoreSystemTypes.Int16); break;
                    case OpCode.Conv_I4: expr = new UnaryExpression(PopOperand(), NodeType.Conv_I4, CoreSystemTypes.Int32); break;
                    case OpCode.Conv_I8: expr = new UnaryExpression(PopOperand(), NodeType.Conv_I8, CoreSystemTypes.Int64); break;
                    case OpCode.Conv_R4: expr = new UnaryExpression(PopOperand(), NodeType.Conv_R4, CoreSystemTypes.Single); break;
                    case OpCode.Conv_R8: expr = new UnaryExpression(PopOperand(), NodeType.Conv_R8, CoreSystemTypes.Double); break;
                    case OpCode.Conv_U4: expr = new UnaryExpression(PopOperand(), NodeType.Conv_U4, CoreSystemTypes.UInt32); break;
                    case OpCode.Conv_U8: expr = new UnaryExpression(PopOperand(), NodeType.Conv_U8, CoreSystemTypes.UInt64); break;
                    case OpCode.Callvirt: expr = this.ParseCall(NodeType.Callvirt, out isStatement); if (isStatement) goto done; break;
                    case OpCode.Cpobj: statement = this.ParseCopyObject(); goto done;
                    case OpCode.Ldobj: expr = new AddressDereference(PopOperand(), (TypeNode)this.GetMemberFromToken(), this.isVolatile, this.alignment); break;
                    case OpCode.Ldstr: expr = new Literal(this.GetStringFromToken(), CoreSystemTypes.String); break;
                    case OpCode.Newobj: expr = this.ParseConstruct(); break;
                    case OpCode.Castclass: expr = ParseTypeCheck(PopOperand(), (TypeNode)this.GetMemberFromToken(), NodeType.Castclass); break;
                    case OpCode.Isinst: expr = ParseTypeCheck(PopOperand(), (TypeNode)this.GetMemberFromToken(), NodeType.Isinst); break;
                    case OpCode.Conv_R_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_R_Un, CoreSystemTypes.Double); break;
                    case OpCode.Unbox: expr = ParseTypeCheck(PopOperand(), (TypeNode)this.GetMemberFromToken(), NodeType.Unbox); break;
                    case OpCode.Throw: statement = new Throw(PopOperand()); transferStatement = true; goto done;
                    case OpCode.Ldfld:
                        expr = new MemberBinding(PopOperand(), this.GetMemberFromToken(), this.isVolatile, this.alignment);
                        break;
                    case OpCode.Ldflda:
                        expr = SetType(new UnaryExpression(new MemberBinding(PopOperand(), this.GetMemberFromToken(), this.isVolatile, this.alignment), NodeType.AddressOf));
                        break;
                    case OpCode.Stfld: statement = this.ParseStoreField(); goto done;
                    case OpCode.Ldsfld: expr = new MemberBinding(null, this.GetMemberFromToken(), this.isVolatile, this.alignment); break;
                    case OpCode.Ldsflda: expr = SetType(new UnaryExpression(new MemberBinding(null, this.GetMemberFromToken(), this.isVolatile, this.alignment), NodeType.AddressOf)); break;
                    case OpCode.Stsfld: statement = new AssignmentStatement(new MemberBinding(null, this.GetMemberFromToken(), this.isVolatile, this.alignment), PopOperand()); goto done;
                    case OpCode.Stobj: statement = this.ParseStoreIndirect((TypeNode)this.GetMemberFromToken()); goto done;
                    case OpCode.Conv_Ovf_I1_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I1_Un, CoreSystemTypes.Int8); break;
                    case OpCode.Conv_Ovf_I2_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I2_Un, CoreSystemTypes.Int16); break;
                    case OpCode.Conv_Ovf_I4_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I4_Un, CoreSystemTypes.Int32); break;
                    case OpCode.Conv_Ovf_I8_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I8_Un, CoreSystemTypes.Int64); break;
                    case OpCode.Conv_Ovf_U1_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U1_Un, CoreSystemTypes.UInt8); break;
                    case OpCode.Conv_Ovf_U2_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U2_Un, CoreSystemTypes.UInt16); break;
                    case OpCode.Conv_Ovf_U4_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U4_Un, CoreSystemTypes.UInt32); break;
                    case OpCode.Conv_Ovf_U8_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U8_Un, CoreSystemTypes.UInt64); break;
                    case OpCode.Conv_Ovf_I_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I_Un, CoreSystemTypes.IntPtr); break;
                    case OpCode.Conv_Ovf_U_Un: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U_Un, CoreSystemTypes.UIntPtr); break;
                    case OpCode.Box:
                        TypeNode t = (TypeNode)this.GetMemberFromToken();
                        TypeNode bt = t is EnumNode ? CoreSystemTypes.Enum : CoreSystemTypes.ValueType;
                        expr = new BinaryExpression(PopOperand(), new Literal(t, CoreSystemTypes.Type), NodeType.Box, bt); break;
                    case OpCode.Newarr: expr = this.ParseNewArray(); break;
                    case OpCode.Ldlen: expr = new UnaryExpression(PopOperand(), NodeType.Ldlen, CoreSystemTypes.UIntPtr); break;
                    case OpCode.Ldelema: expr = this.ParseArrayElementLoadAddress(); break;
                    case OpCode.Ldelem_I1:
                    case OpCode.Ldelem_U1:
                    case OpCode.Ldelem_I2:
                    case OpCode.Ldelem_U2:
                    case OpCode.Ldelem_I4:
                    case OpCode.Ldelem_U4:
                    case OpCode.Ldelem_I8:
                    case OpCode.Ldelem_I:
                    case OpCode.Ldelem_R4:
                    case OpCode.Ldelem_R8:
                    case OpCode.Ldelem_Ref: expr = this.ParseArrayElementLoad(opCode, null); break;
                    case OpCode.Stelem_I:
                    case OpCode.Stelem_I1:
                    case OpCode.Stelem_I2:
                    case OpCode.Stelem_I4:
                    case OpCode.Stelem_I8:
                    case OpCode.Stelem_R4:
                    case OpCode.Stelem_R8:
                    case OpCode.Stelem_Ref: statement = this.ParseArrayElementAssignment(opCode); goto done;
                    case OpCode.Ldelem: expr = this.ParseArrayElementLoad(opCode, null); break;
                    case OpCode.Stelem: statement = this.ParseArrayElementAssignment(opCode); goto done;
                    case OpCode.Unbox_Any: expr = ParseTypeCheck(PopOperand(), (TypeNode)this.GetMemberFromToken(), NodeType.UnboxAny); break;
                    case OpCode.Conv_Ovf_I1: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I1, CoreSystemTypes.Int8); break;
                    case OpCode.Conv_Ovf_U1: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U1, CoreSystemTypes.UInt8); break;
                    case OpCode.Conv_Ovf_I2: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I2, CoreSystemTypes.Int16); break;
                    case OpCode.Conv_Ovf_U2: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U2, CoreSystemTypes.UInt16); break;
                    case OpCode.Conv_Ovf_I4: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I4, CoreSystemTypes.Int32); break;
                    case OpCode.Conv_Ovf_U4: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U4, CoreSystemTypes.UInt32); break;
                    case OpCode.Conv_Ovf_I8: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I8, CoreSystemTypes.Int64); break;
                    case OpCode.Conv_Ovf_U8: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U8, CoreSystemTypes.UInt64); break;
                    case OpCode.Refanyval: expr = new BinaryExpression(PopOperand(), new Literal(this.GetMemberFromToken(), CoreSystemTypes.Type), NodeType.Refanyval, CoreSystemTypes.IntPtr); break;
                    case OpCode.Ckfinite: expr = this.ParseUnaryOperation(NodeType.Ckfinite); break;
                    case OpCode.Mkrefany: expr = new BinaryExpression(PopOperand(), new Literal(this.GetMemberFromToken(), CoreSystemTypes.Type), NodeType.Mkrefany, CoreSystemTypes.DynamicallyTypedReference); break;
                    case OpCode.Ldtoken: expr = ParseLoadRuntimeMetadataToken(); break;
                    case OpCode.Conv_U2: expr = new UnaryExpression(PopOperand(), NodeType.Conv_U2, CoreSystemTypes.UInt16); break;
                    case OpCode.Conv_U1: expr = new UnaryExpression(PopOperand(), NodeType.Conv_U1, CoreSystemTypes.UInt8); break;
                    case OpCode.Conv_I: expr = new UnaryExpression(PopOperand(), NodeType.Conv_I, CoreSystemTypes.IntPtr); break;
                    case OpCode.Conv_Ovf_I: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_I, CoreSystemTypes.IntPtr); break;
                    case OpCode.Conv_Ovf_U: expr = new UnaryExpression(PopOperand(), NodeType.Conv_Ovf_U, CoreSystemTypes.UIntPtr); break;
                    case OpCode.Add_Ovf: expr = this.ParseBinaryOperation(NodeType.Add_Ovf); break;
                    case OpCode.Add_Ovf_Un: expr = this.ParseBinaryOperation(NodeType.Add_Ovf_Un); break;
                    case OpCode.Mul_Ovf: expr = this.ParseBinaryOperation(NodeType.Mul_Ovf); break;
                    case OpCode.Mul_Ovf_Un: expr = this.ParseBinaryOperation(NodeType.Mul_Ovf_Un); break;
                    case OpCode.Sub_Ovf: expr = this.ParseBinaryOperation(NodeType.Sub_Ovf); break;
                    case OpCode.Sub_Ovf_Un: expr = this.ParseBinaryOperation(NodeType.Sub_Ovf_Un); break;
                    case OpCode.Endfinally: statement = new EndFinally(); transferStatement = true; goto done;
                    case OpCode.Leave: statement = this.ParseBranch(NodeType.Nop, 0, false, false, true); transferStatement = true; goto done;
                    case OpCode.Leave_S: statement = this.ParseBranch(NodeType.Nop, 0, true, false, true); transferStatement = true; goto done;
                    case OpCode.Stind_I: statement = this.ParseStoreIndirect(CoreSystemTypes.IntPtr); goto done;
                    case OpCode.Conv_U: expr = new UnaryExpression(PopOperand(), NodeType.Conv_U, CoreSystemTypes.UIntPtr); break;
                    case OpCode.Arglist: expr = new Expression(NodeType.Arglist, CoreSystemTypes.ArgIterator); break;
                    case OpCode.Ceq: expr = this.ParseBinaryComparison(NodeType.Ceq); break;
                    case OpCode.Cgt: expr = this.ParseBinaryComparison(NodeType.Cgt); break;
                    case OpCode.Cgt_Un: expr = this.ParseBinaryComparison(NodeType.Cgt_Un); break;
                    case OpCode.Clt: expr = this.ParseBinaryComparison(NodeType.Clt); break;
                    case OpCode.Clt_Un: expr = this.ParseBinaryComparison(NodeType.Clt_Un); break;
                    case OpCode.Ldftn: expr = new UnaryExpression(new MemberBinding(null, this.GetMemberFromToken()), NodeType.Ldftn, CoreSystemTypes.IntPtr); break;
                    case OpCode.Ldvirtftn: expr = new BinaryExpression(PopOperand(), new MemberBinding(null, this.GetMemberFromToken()), NodeType.Ldvirtftn, CoreSystemTypes.IntPtr); break;
                    case OpCode.Ldarg: expr = this.Parameters((ushort)this.GetInt16()); break;
                    case OpCode.Ldarga: expr = SetType(new UnaryExpression(this.Parameters((ushort)this.GetInt16()), NodeType.AddressOf)); break;
                    case OpCode.Starg: statement = new AssignmentStatement(this.Parameters((ushort)this.GetInt16()), PopOperand()); goto done;
                    case OpCode.Ldloc: expr = this.locals[(ushort)this.GetInt16()]; break;
                    case OpCode.Ldloca: expr = SetType(new UnaryExpression(this.locals[(ushort)this.GetInt16()], NodeType.AddressOf)); break;
                    case OpCode.Stloc: statement = new AssignmentStatement(this.locals[(ushort)this.GetInt16()], PopOperand()); goto done;
                    case OpCode.Localloc: expr = new UnaryExpression(PopOperand(), NodeType.Localloc, CoreSystemTypes.Void); break;
                    case OpCode.Endfilter: statement = new EndFilter(PopOperand()); transferStatement = true; goto done;
                    case OpCode.Unaligned_: this.alignment = this.GetByte(); continue;
                    case OpCode.Volatile_: this.isVolatile = true; continue;
                    case OpCode.Tail_: this.isTailCall = true; continue;
                    case OpCode.Initobj: statement = this.ParseInitObject(); goto done;
                    case OpCode.Constrained_: this.constraint = this.GetMemberFromToken() as TypeNode; continue;
                    case OpCode.Cpblk: expr = this.ParseTernaryOperation(NodeType.Cpblk); goto done;
                    case OpCode.Initblk: expr = this.ParseTernaryOperation(NodeType.Initblk); goto done;
                    case OpCode.Rethrow: statement = new Throw(null); statement.NodeType = NodeType.Rethrow; transferStatement = true; goto done;
                    case OpCode.Sizeof: expr = new UnaryExpression(new Literal(this.GetMemberFromToken(), CoreSystemTypes.Type), NodeType.Sizeof, CoreSystemTypes.Int32); break;
                    case OpCode.Refanytype: expr = new UnaryExpression(PopOperand(), NodeType.Refanytype, CoreSystemTypes.RuntimeTypeHandle); break;
                    case OpCode.Readonly_: this.isReadOnly = true; continue;
                    default: throw new InvalidMetadataException(ExceptionStrings.UnknownOpCode);
                }
                if (this.blockMap[this.counter + 1] != null)
                {
                    transferStatement = true; //Falls through to the next basic block, so implicitly a "transfer" statement
                    goto done;
                }
                //^ assume expr != null;
                this.operandStack.Push(expr);
                this.isReadOnly = false;
                this.isVolatile = false;
                this.isTailCall = false;
                this.alignment = -1;
            }
        done:
            for (int i = 0; i <= this.operandStack.top; i++)
            {
                Expression e = this.operandStack.elements[i];
                //^ assume e != null;
                Statement s = new ExpressionStatement(e);
                statementList.Add(s);
            }

            this.operandStack.top = -1;

            if (statement == null)
                statement = new ExpressionStatement(expr);

            statement.SourceContext = sourceContext;
            statementList.Add(statement);
            if (transferStatement) return true;
            return this.blockMap[this.counter + 1] != null;
        }
 //This does not always produce the same context as would be produced by the parser had it parsed the entire changed document
 //since the edit could introduce an open multi-line comment or an open brace. This may be a feature rather than a mistake,
 //since it is not the common case for this erasing of subsequent members to be intentional. When the new method is asked for its body,
 //it will produce whatever will be produced by parsing the changed document. However, any "erased" members will still show up
 //until an edit occurs that causes a full symbol table update. For now, my guess is that this is acceptable.
 public virtual SourceContext GetMethodBodyContextInNewDocument(Document changedDocument, SourceContext methodBodyContext, 
   SourceContext spanningContextForChanges, int changeInLength){
   //get the lengths of the prefix and suffix that expand the spanning context into the full source context of the spanning method
   int originalLength = spanningContextForChanges.EndPos - spanningContextForChanges.StartPos;
   int prefixLength = spanningContextForChanges.StartPos - methodBodyContext.StartPos;
   if (prefixLength < 0){Debug.Assert(false); return methodBodyContext;}
   int suffixLength = methodBodyContext.EndPos - spanningContextForChanges.EndPos;
   if (suffixLength < 0){Debug.Assert(false); return methodBodyContext;}
   SourceContext newContext = new SourceContext();
   newContext.Document = changedDocument;
   newContext.StartPos = methodBodyContext.StartPos;
   newContext.EndPos = methodBodyContext.StartPos+prefixLength+originalLength+changeInLength+suffixLength;
   return newContext;
 }
Exemple #34
0
 public virtual SourceContext GetPositionOfDefinition(Node definition) {
   TypeNode type = definition as TypeNode;
   Member member = definition as Member;
   Identifier name = null;
   if (type != null)
     name = type.Name;
   else if (member != null)
     name = member.Name;
   SourceContext result = new SourceContext();
   if (name != null) result = name.SourceContext;
   return result;
 }
 public virtual SourceContext GetSpanningContext(SourceChangeList changes, out int changedLength){
   changedLength = 0;
   int startPos = int.MaxValue;
   int endPos = int.MinValue;
   SourceContext result = new SourceContext();
   if (changes == null || changes.Count == 0) return result;
   result = changes[0].SourceContext;
   for (int i = 0, n = changes.Count; i < n; i++){
     SourceContext ctx = changes[i].SourceContext;
     if (ctx.StartPos < startPos) startPos = ctx.StartPos;
     if (ctx.EndPos > endPos) endPos = ctx.EndPos;          
     int originalLength = ctx.EndPos - ctx.StartPos;
     int newLength = changes[i].ChangedText == null ? 0 : changes[i].ChangedText.Length;
     changedLength += newLength - originalLength;
   }
   result.StartPos = startPos;
   result.EndPos = endPos;
   return result;
 }
Exemple #36
0
 public abstract void EndTemplateParameters(SourceContext context);
Exemple #37
0
 public virtual string GetDataTipText(int line, int col, out SourceContext sourceContext){
   Node n;
   Scope scope;
   int identContext;
   this.languageService.SearchForNodeAtPosition(line + 1, col + 1, out n, out scope, out identContext);
   if (n == null){
     sourceContext = new SourceContext(); return null;
   }
   sourceContext = n.SourceContext;
   string helpText = null;
   MemberBinding mb = this.GetMemberBinding(n);
   string memberSignature = "";
   if (mb != null){
     sourceContext = mb.SourceContext;
     Member mem = mb.BoundMember;
     Method m = mem as Method;
     if (m != null && m.IsSpecialName && m.Name.ToString().StartsWith("get_")){
       TypeNode[] types = m.GetParameterTypes();
       Identifier propId = Identifier.For(m.Name.ToString().Substring(4));
       TypeNode ty = m.DeclaringType;
       while (ty != null){
         Property prop = ty.GetProperty(propId, types);
         if (prop != null){
           mem = prop;
           break;
         }
         ty = ty.BaseType;
       }
     }
     helpText = mem.HelpText;
     if (mb.TargetObject is ImplicitThis){
       if (mem.DeclaringType is BlockScope)
         memberSignature = this.languageService.errorHandler.GetLocalSignature(mem as Field);
       else if (mem is ParameterField)
         memberSignature = this.languageService.errorHandler.GetParameterSignature((ParameterField)mem);
       else if (mem is Field || mem is Property)
         memberSignature = this.languageService.errorHandler.GetInstanceMemberSignature(mb.BoundMember);
       else
         memberSignature = this.languageService.errorHandler.GetMemberSignature(mb.BoundMember, true);
     }else
       memberSignature = this.languageService.errorHandler.GetMemberSignature(mb.BoundMember, true);
     if (helpText == "" && mb.BoundMember is InstanceInitializer)
       helpText = mem.DeclaringType.HelpText;
   }else{
     TypeNode t = n as TypeNode;
     if (t == null && n is Expression) 
       t = ((Expression)n).Type;
     if (t != null){
       memberSignature = this.languageService.errorHandler.GetMemberSignature(t, true);
       helpText = t.HelpText;
     }else{
       t = this.GetQueryResultType(n);
       if (t != null)
         memberSignature = this.languageService.errorHandler.GetMemberSignature(t, false);
     }
   }
   if (helpText != null && helpText != "")
     return memberSignature + "\n" + helpText;
   else
     return memberSignature;
 }
 public MemberFinder(SourceContext sourceContext){
   this.Line = int.MinValue;
   this.SourceContext = sourceContext;
 }
 public virtual Compilation IncrementalSymbolTableUpdate(Compilation compilation, CompilationUnitSnippet compilationUnit, Document changedDocument, 
   Method method, SourceContext spanningContextForChanges, int changeInLength){
   if (compilation == null || compilationUnit == null || changedDocument == null || method == null || method.Body == null){Debug.Assert(false); return null;}
   //Record the fact that method has changed, so that subsequent edits do not have to search for it 
   //in an AST that now has source contexts with out of date positions (the line numbers are up to date, but not the positions).
   compilationUnit.ChangedMethod = method;
   compilationUnit.OriginalEndPosOfChangedMethod = method.SourceContext.EndPos;
   if (method.SourceContext.Document != null){
     //Contruct a new context for the method that refers to the new document
     SourceContext newCtx = this.GetMethodBodyContextInNewDocument(changedDocument, method.Body.SourceContext, spanningContextForChanges, changeInLength);
     //Now update the original document so that all nodes that follow method in the source will report their source lines relative to the changedDocument
     int oldNumLines = method.Body.SourceContext.EndLine - method.Body.SourceContext.StartLine;
     int newNumLines = newCtx.EndLine - newCtx.StartLine;
     method.SourceContext.Document.InsertOrDeleteLines(method.SourceContext.EndPos, newNumLines-oldNumLines);
     //Replace the method body context with the new context
     method.Body.SourceContext = newCtx;
   }
   //Get rid of the body statements (if present) that was constructed from the old context
   method.Body.Statements = null;
   return compilation;
 }
Exemple #40
0
    public override Statement VisitExpose(Expose Expose){
      if (Expose == null) return null;
      if (Expose.Instance == null)
        return this.VisitBlock(Expose.Body);
      TypeNode exposeInstanceType = TypeNode.StripModifiers(Expose.Instance.Type);
      if (exposeInstanceType == null)
        return this.VisitBlock(Expose.Body);
      SourceContext endContext = new SourceContext(Expose.SourceContext.Document, Expose.SourceContext.EndPos - 1, Expose.SourceContext.EndPos);

      string startMethodName = null;
      string endMethodName = null;
      Method startMethod = null;
      Method endMethod = null;

      InvariantList justToForceDeserialization = exposeInstanceType.Contract != null ? exposeInstanceType.Contract.Invariants : null;
      if (exposeInstanceType.Contract == null
        || exposeInstanceType.Contract.FramePropertyGetter == null
        ) {
        // If we're exposing an expression E of type T where T is not a guarded class,
        // then for the sake of downstream analysis tools (such as the Spec# Program Verifier) we emit the following code:
        // 
        // write|expose (E) S [alternatively, "write|expose (E at T) S"]
        //
        // is translated into
        //
        // T target = E;
        // Guard.StartWritingFrame(target, typeof(T)); [alternatively, Guard.StartWritingAtNop]
        // try{
        //   S
        // }finally{
        //   Guard.EndWritingFrame(target, typeof(T)); [alternatively, Guard.EndWritingAtNop]
        // }
        //
        // These methods are no-ops. For this reason,
        // combined with the fact that Boogie considers unchecked exceptions to be the end of the world,
        // we don't need to distinguish between checked and unchecked exceptions here.

        Block block = new Block(new StatementList());
        Local target = new Local(Identifier.Empty, exposeInstanceType, block);

        Literal typeArgument = null;
        if (Expose.IsLocal) {
          startMethodName = "StartWritingAtNop";
          endMethodName = "EndWritingAtNop";
        } else {
          startMethodName = "StartWritingFrame";
          endMethodName = "EndWritingFrame";
        }
        typeArgument = new Literal(exposeInstanceType, SystemTypes.Type);
        startMethod = 
          SystemTypes.Guard.GetMethod(Identifier.For(startMethodName), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Object), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type));
        endMethod = 
          SystemTypes.Guard.GetMethod(Identifier.For(endMethodName), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Object), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type));

        block.Statements.Add(new AssignmentStatement(target, Expose.Instance, Expose.Instance.SourceContext));
        block.Statements.Add(new ExpressionStatement(
          new MethodCall(new MemberBinding(null, startMethod), new ExpressionList(target, new UnaryExpression(typeArgument, NodeType.Typeof)),
          NodeType.Call, SystemTypes.Void), Expose.Instance.SourceContext));
        block.Statements.Add(new Try(
          Expose.Body,
          null,
          null,
          null,
          new Finally(new Block(new StatementList(new ExpressionStatement(new MethodCall(
           new MemberBinding(null, endMethod), new ExpressionList(target, new UnaryExpression(new Literal(exposeInstanceType, SystemTypes.Type), NodeType.Typeof)),
           NodeType.Call, SystemTypes.Void), endContext))))
        ));
        return (Statement) this.Visit(block);
      }

      // write|additive expose (E) S   [alternatively:  expose (E) S]
      //
      // is translated into
      //
      // Guard! rootFrame = E.FrameGuard.StartWritingTransitively(); [alternatively "StartWritingAtTransitively"]
      // Exception exception = null;
      // try {
      //     S
      // } catch (Exception e) {
      //     exception = e;
      //     throw;
      // } finally {
      //     if (exception == null || exception is ICheckedException)
      //         rootFrame.EndWritingTransitively(); [alternatively "EndWritingAtTransitively"]
      // }
      //
      // This is a hack; it would be better to statically have different code paths for
      // the normal completion case and the exceptional completion case.
      // However, that requires transforming returns, gotos, continues, breaks, etc.
      // Of course, all of the above can first be transformed into gotos.
      //
      // The "throw" in the catch clause is needed to allow the definite assignment
      // analysis to know that things assigned to in S are really assigned to
      // in the code following the finally block.
      // More importantly, who are we to eat up an exception, unless the exception
      // is checked and the object invariant doesn't hold.

      TypeNode staticInstanceType = exposeInstanceType;
      if (Expose.IsLocal) {
        startMethodName = "StartWritingAtTransitively";
        endMethodName = "EndWritingAtTransitively";
        startMethod =
          SystemTypes.Guard.GetMethod(Identifier.For(startMethodName), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type));
        endMethod =
          SystemTypes.Guard.GetMethod(Identifier.For(endMethodName), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type));
      } else {
        if (Expose.NodeType == NodeType.Read) {
          startMethodName = "StartReadingTransitively";
          endMethodName = "EndReadingTransitively";
        } else {
          startMethodName = "StartWritingTransitively";
          endMethodName = "EndWritingTransitively";
        }
        startMethod = SystemTypes.Guard.GetMethod(Identifier.For(startMethodName));
        endMethod = SystemTypes.Guard.GetMethod(Identifier.For(endMethodName));
      }

      TypeNode guardType = OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Guard);
      Method frameGetter = staticInstanceType.Contract.FramePropertyGetter;

      Block newBody = new Block();
      Local rootFrame = new Local(Identifier.For("SS$rootFrame"), guardType, newBody);
      Expression frameGetterCall = new MethodCall(new MemberBinding(Expose.Instance, frameGetter), null);

      // Need two independent argument lists. Otherwise, the processing of the first one disrupts the
      // second one.
      ExpressionList startFrameGetterExprArgs;
      ExpressionList endFrameGetterExprArgs;
      if (Expose.IsLocal) {
        startFrameGetterExprArgs = new ExpressionList(new UnaryExpression(new Literal(exposeInstanceType, SystemTypes.Type), NodeType.Typeof));
        endFrameGetterExprArgs = new ExpressionList(new UnaryExpression(new Literal(exposeInstanceType, SystemTypes.Type), NodeType.Typeof));
      } else {
        startFrameGetterExprArgs = null;
        endFrameGetterExprArgs = null;
      }
      Expression frameGetterExpr = new MethodCall(new MemberBinding(frameGetterCall, startMethod), startFrameGetterExprArgs, NodeType.Call, startMethod.ReturnType);

      Statement startCall = new AssignmentStatement(rootFrame, frameGetterExpr, Expose.Instance.SourceContext);

      // rootFrame.End(Reading|Writing)Transitively();
      Statement endCall = new ExpressionStatement(new MethodCall(new MemberBinding(rootFrame, endMethod), endFrameGetterExprArgs, NodeType.Call, SystemTypes.Void), endContext);
      Local exception = new Local(SystemTypes.Exception);
      CatchList catchList = new CatchList(1);
      Throw rethrow = new Throw();
      rethrow.NodeType = NodeType.Rethrow;
      Local e = new Local(SystemTypes.Exception);
      catchList.Add(new Catch(new Block(new StatementList(new AssignmentStatement(exception, e), rethrow)), e, SystemTypes.Exception));
      newBody.Statements = new StatementList(
        startCall,
        new AssignmentStatement(exception, new Literal(null, SystemTypes.Exception)),
        new Try(
        Expose.Body,
        catchList,
        null, null,
        new Finally(new Block(new StatementList(
        new If(
          new BinaryExpression(
            new BinaryExpression(exception, new Literal(null, SystemTypes.Exception), NodeType.Eq, SystemTypes.Boolean),
            new BinaryExpression(exception, new Literal(SystemTypes.ICheckedException, SystemTypes.Type), NodeType.Is, SystemTypes.Boolean),
            NodeType.LogicalOr,
            SystemTypes.Boolean),
        new Block(new StatementList(endCall)),
        null))))));
      return this.VisitBlock(newBody);
    }
 public virtual void OnItemChosen(int combo, int entry){
   SourceContext c = new SourceContext(null,1,1);
   if (combo == TypeAndMemberDropdownBars.DropClasses){
     if (this.sortedDropDownTypes != null && entry >= 0 && entry < this.sortedDropDownTypes.Length)
       c = this.sortedDropDownTypes[entry].SourceContext; 
   }else{
     if (this.sortedDropDownMembers != null && entry >= 0 && entry < this.sortedDropDownMembers.Length)
       c = this.sortedDropDownMembers[entry].SourceContext; 
   }
   if (c.Document != null && this.textView != null) {
     int line = c.StartLine-1;
     int col = c.StartColumn-1;
     try{
       textView.CenterLines(line, 16);
     }catch{}
     this.textView.SetCaretPos(line, col);
     NativeWindowHelper.SetFocus(this.textView.GetWindowHandle());
     this.SynchronizeDropdowns(this.textView, line, col);
   }
 }
Exemple #42
0
    public override Method VisitMethod(Method method) {
      if (method == null) return null;
      if (method.IsNormalized) return method;
      if (method.CciKind != CciMemberKind.Regular) {
        method.Attributes.Add(new AttributeNode(new MemberBinding(null, SystemTypes.CciMemberKindAttribute.GetConstructor(SystemTypes.CciMemberKind)), new ExpressionList(new Literal(method.CciKind, SystemTypes.CciMemberKind)), AttributeTargets.Method));
      }
      method.IsNormalized = true;
      method.Attributes = this.VisitAttributeList(method.Attributes);
      if (method.ReturnAttributes == null)
        method.ReturnAttributes = new AttributeList();
      else
        method.ReturnAttributes = this.VisitAttributeList(method.ReturnAttributes);
      AttributeList al = this.ExtractAttributes(method.Attributes, AttributeTargets.ReturnValue);
      for (int i = 0, n = al == null ? 0 : al.Count; i < n; i++){
        method.ReturnAttributes.Add(al[i]);
      }
      method.SecurityAttributes = this.VisitSecurityAttributeList(method.SecurityAttributes);
      if (method.Attributes != null && method.Attributes.Count > 0) {
        SecurityAttributeList secAttrs = method.SecurityAttributes;
        this.ExtractSecurityAttributes(method.Attributes, ref secAttrs);
        method.SecurityAttributes = secAttrs;
      }
      if (method.SecurityAttributes != null && method.SecurityAttributes.Count > 0)
        method.Flags |= MethodFlags.HasSecurity;
      Method savedMethod = this.currentMethod;
      This savedThisParameter = this.currentThisParameter;
      Local savedReturnLocal = this.currentReturnLocal;
      Block savedReturnLabel = this.currentReturnLabel;
      Local savedClosureLocal = this.currentClosureLocal;
      Block savedContractPrelude = this.currentContractPrelude;
      BlockList savedContractExceptionalTerminationChecks = this.currentContractExceptionalTerminationChecks;
      Local savedcurrentExceptionalTerminationException = this.currentExceptionalTerminationException;
      Block savedContractNormalTerminationCheck = this.currentContractNormalTerminationCheck;
      Block savedParentBlock = null;
      this.currentMethod = method;
      this.currentThisParameter = method.ThisParameter;
      if (method.ThisParameter != null) {
        method.ThisParameter.DeclaringMethod = method;
        if (method.DeclaringType != null && method.DeclaringType.IsValueType)
          method.ThisParameter.Type = method.DeclaringType.GetReferenceType();
      }
      this.currentReturnLabel = new Block(new StatementList());
      this.currentClosureLocal = null;
      this.currentContractPrelude = new Block(new StatementList());
      this.currentContractExceptionalTerminationChecks = new BlockList();
      this.currentExceptionalTerminationException = new Local(Identifier.For("SS$caught_exception"), SystemTypes.Exception);
      this.currentContractNormalTerminationCheck = new Block(new StatementList());
      if (TypeNode.StripModifiers(method.ReturnType) == SystemTypes.Void)
        this.currentReturnLocal = null;
      else
        this.currentReturnLocal = new Local(Identifier.For("return value"), method.ReturnType);
      method.Parameters = this.VisitParameterList(method.Parameters);
      method.TemplateArguments = this.VisitTypeReferenceList(method.TemplateArguments);
      method.TemplateParameters = this.VisitTypeParameterList(method.TemplateParameters);
      TypeNodeList tpars = method.TemplateParameters;
      if (!method.IsGeneric){
        for (int i = 0, n = tpars == null ? 0 : tpars.Count; i < n; i++){
          TypeNode tpar = tpars[i];
          if (tpar == null) continue;
          tpar.Name = new Identifier(method.Name+":"+tpar.Name, tpar.SourceContext);
          tpar.DeclaringType = method.DeclaringType;
          method.DeclaringType.Members.Add(tpar);
        }
      }
      if (method.Template == null) {
        // skip this part for instance methods.
        Block closureInit = null;
        bool methodHasClosure = method.Scope != null && method.Scope.CapturedForClosure;
        if (methodHasClosure) this.SetUpClosureClass(method);
        // Normalizer.VisitRequiresList needs to be called in case it wants to generate
        // some default preconditions (that are not injected by Checker in order to not
        // have these preconditions seen by any static checking tools). If there is
        // no contract on this method, then it won't get called, so create a dummy
        // contract and Requires list just so it will get a chance to do its stuff.
        if (method.Contract == null) {
          method.Contract = new MethodContract(method);
          method.Contract.Requires = new RequiresList();
        }
        if (!methodHasClosure || (method is InstanceInitializer)) {
          // ctors will construct the closure class instance after they call another ctor, since they need to pass in "this" as a parameter to the closure class constructor
          method.Contract = this.VisitMethodContract(method.Contract);
          method.Body = this.VisitBlock(method.Body);
        }else{
          method.Contract = this.VisitMethodContract(method.Contract);
          Block b = this.CreateClosureClassInstance(method);
          method.Body = this.VisitBlock(method.Body);
          savedParentBlock = method.Body;
          closureInit = b;
          if (method.Body != null){
            closureInit.SourceContext = method.Body.SourceContext;
            method.Body.HasLocals = true;
          }
        } {

        #region If this method has a contract, then modify its body to add the contracts at the right point
        if (method.Body != null && method.Body.Statements != null){
          if (this.currentContractExceptionalTerminationChecks.Count > 0){
            // then wrap the body into a try catch with these checks as the catch blocks
            Block b = new Block(new StatementList(this.currentContractExceptionalTerminationChecks.Count));
            b.HasLocals = true;
            for (int i = 0, n = this.currentContractExceptionalTerminationChecks.Count; i < n; i++) {
              b.Statements.Add(this.currentContractExceptionalTerminationChecks[i]);
            }
            #region Rethrow caught exception
            // last "functional" thing in the block is re-throw whatever exception we caught.
            Throw t = new Throw();
            t.NodeType = NodeType.Rethrow;
            b.Statements.Add(t);
            #endregion

            LocalList ls = new LocalList(1);
            this.currentExceptionalTerminationException.DeclaringBlock = b;
            ls.Add(this.currentExceptionalTerminationException);
            BlockList bs = new BlockList(1);
            bs.Add(b);
            Block newBody = CreateTryCatchBlock(method, method.Body, bs, ls);
            //Block newBody = CreateTryCatchBlock(method,method.Body,this.currentContractExceptionalTerminationChecks,this.currentContractExceptionalLocals);
            method.Body = newBody;
          }
          if (this.currentContractPrelude.Statements.Count > 0){
            Block newBody = new Block(new StatementList(3));
            // Wrap the contract prelude in a block with a dummy catch block.
            // It has a special handler type that lets downstream tools know
            // this block was not part of the original code.
            Throw t = new Throw();
            t.NodeType = NodeType.Rethrow;
            this.currentContractPrelude = CreateTryCatchBlock(
              method, 
              this.currentContractPrelude, // try body
              new Block(new StatementList(t)), // catch: just rethrow
              new Local(Identifier.For("SS$Contract Marker"), SystemTypes.ContractMarkerException)
              );
            newBody.Statements.Add(closureInit);
            closureInit = null;
            newBody.Statements.Add(this.currentContractPrelude);
            newBody.Statements.Add(method.Body);
            method.Body = newBody;
          }
        }
      }
        #endregion
        if (closureInit != null){
          closureInit.Statements.Add(method.Body);
          method.Body = closureInit;
        }

        if (method.Body != null && method.Body.Statements != null){
          Return r = new Return();
          r.Expression = this.currentReturnLocal;
          Block returnBlock = new Block(new StatementList());
          returnBlock.Statements.Add(this.currentReturnLabel); {
          InstanceInitializer ctor = method as InstanceInitializer;
          if (ctor != null && method.DeclaringType.Contract != null && method.DeclaringType.Contract.FrameField != null && !ctor.IsDeferringConstructor){
            // then add a Pack to the end
            // BUGBUG: if the programmer has indicated that this default shouldn't apply, then don't do this!
            SourceContext rightBrace = new SourceContext(method.SourceContext.Document, method.SourceContext.EndPos - 1, method.SourceContext.EndPos);
            returnBlock.Statements.Add(
              new ExpressionStatement(
              new MethodCall(new MemberBinding(new MethodCall(new MemberBinding(method.ThisParameter, method.DeclaringType.Contract.FramePropertyGetter), null, NodeType.Call, OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Guard)), SystemTypes.Guard.GetMethod(Identifier.For("EndWriting"))), null, NodeType.Call, SystemTypes.Void),
              rightBrace
              ));
          }
          if (this.currentContractNormalTerminationCheck.Statements.Count > 0){
            // Wrap the contract normal termination checks in a block with a dummy catch block.
            // It has a special handler type that lets downstream tools know this block was not
            // part of the original code.
            Throw t = new Throw();
            t.NodeType = NodeType.Rethrow;
            this.currentContractNormalTerminationCheck = CreateTryCatchBlock(
              method, 
              this.currentContractNormalTerminationCheck, // try body
              new Block(new StatementList(t)), // catch: just rethrow
              new Local(Identifier.For("SS$Contract Marker"),SystemTypes.ContractMarkerException)
              );
            returnBlock.Statements.Add(this.currentContractNormalTerminationCheck);
          }
        }
          if (this.currentReturnLocal != null){
            Local displayReturnLocal = new Local(Identifier.For("SS$Display Return Local"), method.ReturnType);
            returnBlock.Statements.Add(new AssignmentStatement(displayReturnLocal, this.currentReturnLocal));
            returnBlock.HasLocals = true;
          }
          returnBlock.Statements.Add(r);
          if (method.Body.SourceContext.Document != null){
            r.SourceContext = method.SourceContext;
            r.SourceContext.StartPos = method.Body.SourceContext.EndPos-1;
          }
          if (savedParentBlock != null){
            if (savedParentBlock.Statements == null) savedParentBlock.Statements = new StatementList(1);
            savedParentBlock.Statements.Add(returnBlock);
          }else
            method.Body.Statements.Add(returnBlock);
        }
        if (method.ImplementedInterfaceMethods != null && method.ImplementedInterfaceMethods.Count > 0 && method.ImplementedInterfaceMethods[0] != null){
          string typeName = method.ImplementedInterfaceMethods[0].DeclaringType.GetFullUnmangledNameWithTypeParameters();
          method.Name = new Identifier(typeName + "." + method.Name.ToString(), method.Name.SourceContext);
        }
        if (method.HasCompilerGeneratedSignature && method.Parameters != null){
          if (method.Parameters.Count == 1 && (method.Parameters[0].Attributes == null || method.Parameters[0].Attributes.Count == 0))
            method.Parameters[0].Attributes = this.ExtractAttributes(method.Attributes, AttributeTargets.Parameter);
          else if (method.Parameters.Count == 2 && (method.Parameters[1].Attributes == null || method.Parameters[1].Attributes.Count == 0))
            method.Parameters[1].Attributes = this.ExtractAttributes(method.Attributes, AttributeTargets.Parameter);
        }
      }
      this.currentMethod = savedMethod;
      this.currentThisParameter = savedThisParameter;
      this.currentReturnLocal = savedReturnLocal;
      this.currentReturnLabel = savedReturnLabel;
      this.currentClosureLocal = savedClosureLocal;
      this.currentContractPrelude = savedContractPrelude;
      this.currentContractExceptionalTerminationChecks = savedContractExceptionalTerminationChecks;
      this.currentExceptionalTerminationException = savedcurrentExceptionalTerminationException;
      this.currentContractNormalTerminationCheck = savedContractNormalTerminationCheck;
      return method;
    }
Exemple #43
0
 /// <summary>
 /// Serializes the expressions in toSerialize to an attribute determined by ctor, as if they come from module containingModule.
 /// Uses the SourceContext information of <param name="sc">sc</param> for the source context for the attribute. 
 /// <para><code>
 /// requires ctor != null &amp;&amp; toSerialize != null &amp;&amp; 0 &lt; toSerialize.Count &amp;&amp; sc != null;;
 /// </code></para>
 /// <para><code>
 /// requires ctor.DeclaringType &lt;: Microsoft.Contracts.AttributeWithContext;
 /// </code></para>
 /// </summary>
 /// <returns></returns>
 public static AttributeNode SerializeExpressions (InstanceInitializer/*!*/ ctor, ExpressionList/*!*/ toSerialize, SourceContext/*!*/ sc, Module containingModule) {
   return Checker.SerializeExpressions(ctor, null, toSerialize, sc, containingModule);
 }
Exemple #44
0
 /// <summary>
 /// QualifyName is called for each qualification with both
 /// the text span of the selector (e.g. ".")  and the text span 
 /// of the name ("WriteLine").
 /// </summary>
 public abstract void QualifyName(SourceContext selectorContext, Expression name);
Exemple #45
0
 /// <summary>
 /// Matching tripples are used to highlight in bold a completed statement.  For example
 /// when you type the closing brace on a foreach statement VS highlights in bold the statement
 /// that was closed.  The first two source contexts are the beginning and ending of the statement that
 /// opens the block (for example, the span of the "foreach(...){" and the third source context
 /// is the closing brace for the block (e.g., the "}").
 /// </summary>
 public abstract void MatchTriple(SourceContext startContext, SourceContext middleContext, SourceContext endContext);
Exemple #46
0
 /// <summary>
 /// Whenever a matching pair is parsed, e.g. '{' and '}', this method is called
 /// with the text span of both the left and right item. The
 /// information is used when a user types "ctrl-]" in VS
 /// to find a matching brace and when auto-highlight matching
 /// braces is enabled.
 /// </summary>
 public abstract void MatchPair(SourceContext startContext, SourceContext endContext);
Exemple #47
0
 public virtual Statement VisitBranchCondition(Expression condition, Block target, SourceContext sctx){
   if (condition == null) return null;
   if (condition.NodeType == NodeType.Parentheses)
     return this.VisitBranchCondition(((UnaryExpression)condition).Operand, target, sctx);
   BinaryExpression bexpr = condition as BinaryExpression;
   if (bexpr != null){
     if (bexpr.Operand1 == null || bexpr.Operand1.Type == null || bexpr.Operand2 == null) return null;
     if (bexpr.NodeType == NodeType.Is){
       if (this.useGenerics && bexpr.Operand1.Type.IsTemplateParameter)
         bexpr.Operand1 = new BinaryExpression(bexpr.Operand1, new Literal(bexpr.Operand1.Type), NodeType.Box);
       bexpr.NodeType = NodeType.Isinst;
       if (bexpr.Operand2 is Literal)
         bexpr.Type = (TypeNode) ((Literal) bexpr.Operand2).Value;
       else
         bexpr.Type = (TypeNode)((MemberBinding)bexpr.Operand2).BoundMember;
       goto returnBranch;
     }
     if (bexpr.NodeType == NodeType.LogicalAnd){
       Block label = new Block();
       StatementList statements = new StatementList(4);
       statements.Add(this.VisitAndInvertBranchCondition(bexpr.Operand1, label, sctx));
       statements.Add(this.VisitAndInvertBranchCondition(bexpr.Operand2, label, new SourceContext()));
       statements.Add(new Branch(null, target));
       statements.Add(label);
       return new Block(statements);
     }
     if (bexpr.NodeType == NodeType.LogicalOr){
       Block label = new Block();
       StatementList statements = new StatementList(2);
       statements.Add(this.VisitBranchCondition(bexpr.Operand1, target, sctx));
       statements.Add(this.VisitBranchCondition(bexpr.Operand2, target, new SourceContext()));
       return new Block(statements);
     }
   }
   returnBranch:
     return new Branch(this.VisitBranchCondition(condition), target, sctx);
 }
Exemple #48
0
 public abstract void NextTemplateParameter(SourceContext context);
Exemple #49
0
        internal Instruction ParseInstruction()
        {
            if (this.counter >= this.size)
                return null;
            int offset = this.counter;

            if (this.method.contextForOffset != null)
            {
                object sctx = this.method.contextForOffset[offset + 1];
                if (sctx != null) this.sourceContext = (SourceContext)sctx;
            }

            object value = null;
            OpCode opCode = this.GetOpCode();
            switch (opCode)
            {
                case OpCode.Nop:
                case OpCode.Break:
                    break;
                case OpCode.Ldarg_0: value = this.Parameters(0); break;
                case OpCode.Ldarg_1: value = this.Parameters(1); break;
                case OpCode.Ldarg_2: value = this.Parameters(2); break;
                case OpCode.Ldarg_3: value = this.Parameters(3); break;
                case OpCode.Ldloc_0: value = this.locals[0]; break;
                case OpCode.Ldloc_1: value = this.locals[1]; break;
                case OpCode.Ldloc_2: value = this.locals[2]; break;
                case OpCode.Ldloc_3: value = this.locals[3]; break;
                case OpCode.Stloc_0: value = this.locals[0]; break;
                case OpCode.Stloc_1: value = this.locals[1]; break;
                case OpCode.Stloc_2: value = this.locals[2]; break;
                case OpCode.Stloc_3: value = this.locals[3]; break;
                case OpCode.Ldarg_S:
                case OpCode.Ldarga_S:
                case OpCode.Starg_S:
                    value = this.Parameters(this.GetByte()); break;
                case OpCode.Ldloc_S:
                case OpCode.Ldloca_S:
                case OpCode.Stloc_S:
                    value = this.locals[this.GetByte()]; break;
                case OpCode.Ldnull:
                    break;
                case OpCode.Ldc_I4_M1: value = (Int32)(-1); break;
                case OpCode.Ldc_I4_0: value = (Int32)0; break;
                case OpCode.Ldc_I4_1: value = (Int32)1; break;
                case OpCode.Ldc_I4_2: value = (Int32)2; break;
                case OpCode.Ldc_I4_3: value = (Int32)3; break;
                case OpCode.Ldc_I4_4: value = (Int32)4; break;
                case OpCode.Ldc_I4_5: value = (Int32)5; break;
                case OpCode.Ldc_I4_6: value = (Int32)6; break;
                case OpCode.Ldc_I4_7: value = (Int32)7; break;
                case OpCode.Ldc_I4_8: value = (Int32)8; break;
                case OpCode.Ldc_I4_S: value = (Int32)this.GetSByte(); break;
                case OpCode.Ldc_I4: value = this.GetInt32(); break;
                case OpCode.Ldc_I8: value = this.GetInt64(); break;
                case OpCode.Ldc_R4: value = this.GetSingle(); break;
                case OpCode.Ldc_R8: value = this.GetDouble(); break;
                case OpCode.Dup:
                case OpCode.Pop:
                    break;
                case OpCode.Jmp:
                case OpCode.Call:
                    value = (Method)this.GetMemberFromToken(); break;
                case OpCode.Calli:
                    value = (FunctionPointer)this.reader.GetCalliSignature(this.GetInt32()); break;
                case OpCode.Ret: break;
                case OpCode.Br_S:
                case OpCode.Brfalse_S:
                case OpCode.Brtrue_S:
                case OpCode.Beq_S:
                case OpCode.Bge_S:
                case OpCode.Bgt_S:
                case OpCode.Ble_S:
                case OpCode.Blt_S:
                case OpCode.Bne_Un_S:
                case OpCode.Bge_Un_S:
                case OpCode.Bgt_Un_S:
                case OpCode.Ble_Un_S:
                case OpCode.Blt_Un_S:
                    value = this.counter + 1 + this.GetSByte(); break;
                case OpCode.Br:
                case OpCode.Brfalse:
                case OpCode.Brtrue:
                case OpCode.Beq:
                case OpCode.Bge:
                case OpCode.Bgt:
                case OpCode.Ble:
                case OpCode.Blt:
                case OpCode.Bne_Un:
                case OpCode.Bge_Un:
                case OpCode.Bgt_Un:
                case OpCode.Ble_Un:
                case OpCode.Blt_Un:
                    value = this.counter + 4 + this.GetInt32(); break;
                case OpCode.Switch:
                    value = this.ParseSwitchInstruction(); break;
                case OpCode.Ldind_I1:
                case OpCode.Ldind_U1:
                case OpCode.Ldind_I2:
                case OpCode.Ldind_U2:
                case OpCode.Ldind_I4:
                case OpCode.Ldind_U4:
                case OpCode.Ldind_I8:
                case OpCode.Ldind_I:
                case OpCode.Ldind_R4:
                case OpCode.Ldind_R8:
                case OpCode.Ldind_Ref:
                case OpCode.Stind_Ref:
                case OpCode.Stind_I1:
                case OpCode.Stind_I2:
                case OpCode.Stind_I4:
                case OpCode.Stind_I8:
                case OpCode.Stind_R4:
                case OpCode.Stind_R8:
                case OpCode.Add:
                case OpCode.Sub:
                case OpCode.Mul:
                case OpCode.Div:
                case OpCode.Div_Un:
                case OpCode.Rem:
                case OpCode.Rem_Un:
                case OpCode.And:
                case OpCode.Or:
                case OpCode.Xor:
                case OpCode.Shl:
                case OpCode.Shr:
                case OpCode.Shr_Un:
                case OpCode.Neg:
                case OpCode.Not:
                case OpCode.Conv_I1:
                case OpCode.Conv_I2:
                case OpCode.Conv_I4:
                case OpCode.Conv_I8:
                case OpCode.Conv_R4:
                case OpCode.Conv_R8:
                case OpCode.Conv_U4:
                case OpCode.Conv_U8:
                    break;
                case OpCode.Callvirt: value = (Method)this.GetMemberFromToken(); break;
                case OpCode.Cpobj:
                case OpCode.Ldobj:
                    value = (TypeNode)this.GetMemberFromToken(); break;
                case OpCode.Ldstr: value = this.GetStringFromToken(); break;
                case OpCode.Newobj: value = (Method)this.GetMemberFromToken(); break;
                case OpCode.Castclass:
                case OpCode.Isinst:
                    value = (TypeNode)this.GetMemberFromToken(); break;
                case OpCode.Conv_R_Un: break;
                case OpCode.Unbox: value = (TypeNode)this.GetMemberFromToken(); break;
                case OpCode.Throw: break;
                case OpCode.Ldfld:
                case OpCode.Ldflda:
                case OpCode.Stfld:
                case OpCode.Ldsfld:
                case OpCode.Ldsflda:
                case OpCode.Stsfld:
                case OpCode.Stobj:
                    value = this.GetMemberFromToken(); break;
                case OpCode.Conv_Ovf_I1_Un:
                case OpCode.Conv_Ovf_I2_Un:
                case OpCode.Conv_Ovf_I4_Un:
                case OpCode.Conv_Ovf_I8_Un:
                case OpCode.Conv_Ovf_U1_Un:
                case OpCode.Conv_Ovf_U2_Un:
                case OpCode.Conv_Ovf_U4_Un:
                case OpCode.Conv_Ovf_U8_Un:
                case OpCode.Conv_Ovf_I_Un:
                case OpCode.Conv_Ovf_U_Un:
                    break;
                case OpCode.Box:
                case OpCode.Newarr: value = (TypeNode)this.GetMemberFromToken(); break;
                case OpCode.Ldlen: break;
                case OpCode.Ldelema: value = (TypeNode)this.GetMemberFromToken(); break;
                case OpCode.Ldelem_I1:
                case OpCode.Ldelem_U1:
                case OpCode.Ldelem_I2:
                case OpCode.Ldelem_U2:
                case OpCode.Ldelem_I4:
                case OpCode.Ldelem_U4:
                case OpCode.Ldelem_I8:
                case OpCode.Ldelem_I:
                case OpCode.Ldelem_R4:
                case OpCode.Ldelem_R8:
                case OpCode.Ldelem_Ref:
                case OpCode.Stelem_I:
                case OpCode.Stelem_I1:
                case OpCode.Stelem_I2:
                case OpCode.Stelem_I4:
                case OpCode.Stelem_I8:
                case OpCode.Stelem_R4:
                case OpCode.Stelem_R8:
                case OpCode.Stelem_Ref:
                    break;
                case OpCode.Ldelem:
                    value = (TypeNode)this.GetMemberFromToken();
                    break;
                case OpCode.Stelem: value = (TypeNode)this.GetMemberFromToken(); break;
                case OpCode.Unbox_Any: value = this.GetMemberFromToken(); break;
                case OpCode.Conv_Ovf_I1:
                case OpCode.Conv_Ovf_U1:
                case OpCode.Conv_Ovf_I2:
                case OpCode.Conv_Ovf_U2:
                case OpCode.Conv_Ovf_I4:
                case OpCode.Conv_Ovf_U4:
                case OpCode.Conv_Ovf_I8:
                case OpCode.Conv_Ovf_U8:
                    break;
                case OpCode.Refanyval: value = this.GetMemberFromToken(); break;
                case OpCode.Ckfinite: break;
                case OpCode.Mkrefany: value = this.GetMemberFromToken(); break;
                case OpCode.Ldtoken: value = this.GetMemberFromToken(); break;
                case OpCode.Conv_U2:
                case OpCode.Conv_U1:
                case OpCode.Conv_I:
                case OpCode.Conv_Ovf_I:
                case OpCode.Conv_Ovf_U:
                case OpCode.Add_Ovf:
                case OpCode.Add_Ovf_Un:
                case OpCode.Mul_Ovf:
                case OpCode.Mul_Ovf_Un:
                case OpCode.Sub_Ovf:
                case OpCode.Sub_Ovf_Un:
                case OpCode.Endfinally:
                    break;
                case OpCode.Leave: value = this.counter + 4 + this.GetInt32(); break;
                case OpCode.Leave_S: value = this.counter + 1 + this.GetSByte(); break;
                case OpCode.Stind_I:
                case OpCode.Conv_U:
                case OpCode.Prefix7:
                case OpCode.Prefix6:
                case OpCode.Prefix5:
                case OpCode.Prefix4:
                case OpCode.Prefix3:
                case OpCode.Prefix2:
                case OpCode.Prefix1:
                case OpCode.Arglist:
                case OpCode.Ceq:
                case OpCode.Cgt:
                case OpCode.Cgt_Un:
                case OpCode.Clt:
                case OpCode.Clt_Un:
                    break;
                case OpCode.Ldftn:
                case OpCode.Ldvirtftn:
                    value = this.GetMemberFromToken(); break;
                case OpCode.Ldarg:
                case OpCode.Ldarga:
                case OpCode.Starg:
                    value = this.Parameters(this.GetInt16()); break;
                case OpCode.Ldloc:
                case OpCode.Ldloca:
                case OpCode.Stloc:
                    value = this.locals[this.GetInt16()]; break;
                case OpCode.Localloc:
                case OpCode.Endfilter:
                    break;
                case OpCode.Unaligned_: value = this.GetByte(); break;
                case OpCode.Volatile_:
                case OpCode.Tail_:
                    break;
                case OpCode.Initobj: value = (TypeNode)this.GetMemberFromToken(); break;
                case OpCode.Constrained_: value = this.GetMemberFromToken() as TypeNode; break;
                case OpCode.Cpblk:
                case OpCode.Initblk:
                    break;
                case OpCode.Rethrow:
                    break;
                case OpCode.Sizeof: value = this.GetMemberFromToken(); break;
                case OpCode.Refanytype:
                case OpCode.Readonly_:
                    break;
                default: throw new InvalidMetadataException(String.Format(CultureInfo.CurrentCulture,
                  ExceptionStrings.UnknownOpCodeEncountered, opCode.ToString("x")));
            }
            Instruction instruction = new Instruction(opCode, offset, value);
            instruction.SourceContext = this.sourceContext;
            return instruction;
        }
Exemple #50
0
 public virtual Statement VisitAndInvertBranchCondition(Expression condition, Block target, SourceContext sctx){
   if (condition == null) return null;
   if (condition.NodeType == NodeType.Parentheses)
     return this.VisitAndInvertBranchCondition(((UnaryExpression)condition).Operand, target, sctx);
   bool unordered = false;
   BinaryExpression bexpr = condition as BinaryExpression;
   if (bexpr != null){
     if (bexpr.Operand1 == null || bexpr.Operand2 == null) return null;
     if (bexpr.NodeType == NodeType.Is){
       bexpr.NodeType = NodeType.Isinst;
       if (this.useGenerics && bexpr.Operand1.Type != null && bexpr.Operand1.Type.IsTemplateParameter)
         bexpr.Operand1 = new BinaryExpression(bexpr.Operand1, new Literal(bexpr.Operand1.Type), NodeType.Box);
       condition = new UnaryExpression(this.VisitExpression(bexpr), NodeType.LogicalNot);
       goto returnBranch;
     }
     NodeType invertedOperator = this.InvertComparisonOperator(bexpr.NodeType);
     if (invertedOperator != bexpr.NodeType){
       TypeNode operand1Type = bexpr.Operand1.Type;
       unordered = operand1Type != null && (operand1Type.IsUnsignedPrimitiveNumeric || operand1Type == SystemTypes.Double || operand1Type == SystemTypes.Single);
       bexpr.Operand1 = this.VisitExpression(bexpr.Operand1);
       bexpr.Operand2 = this.VisitExpression(bexpr.Operand2);
       bexpr.NodeType = invertedOperator;
       condition = bexpr;
       goto returnBranch;
     }
     if (bexpr.NodeType == NodeType.LogicalAnd){
       StatementList statements = new StatementList(2);
       statements.Add(this.VisitAndInvertBranchCondition(bexpr.Operand1, target, sctx));
       statements.Add(this.VisitAndInvertBranchCondition(bexpr.Operand2, target, new SourceContext()));
       return new Block(statements);
     }
     if (bexpr.NodeType == NodeType.LogicalOr){
       Block label = new Block();
       StatementList statements = new StatementList(4);
       statements.Add(this.VisitBranchCondition(bexpr.Operand1, label, sctx));
       statements.Add(this.VisitBranchCondition(bexpr.Operand2, label, new SourceContext()));
       statements.Add(new Branch(null, target));
       statements.Add(label);
       return new Block(statements);
     }
   }
   UnaryExpression uexpr = condition as UnaryExpression;
   if (uexpr != null && uexpr.NodeType == NodeType.LogicalNot)
     return this.VisitBranchCondition(uexpr.Operand, target, sctx);
   else
     condition = new UnaryExpression(this.VisitExpression(condition), NodeType.LogicalNot, condition.SourceContext);
 returnBranch:
   return new Branch(condition, target, sctx, unordered);
 }
Exemple #51
0
 /// <summary>
 /// AutoExpression is in support of IVsLanguageDebugInfo.GetProximityExpressions.
 /// It is called for each expression that might be interesting for
 /// a user in the "Auto Debugging" window. All names that are
 /// set using StartName and QualifyName are already automatically
 /// added to the "Auto" window! This means that AutoExpression
 /// is rarely used.
 /// </summary>   
 public abstract void AutoExpression(SourceContext exprContext);
Exemple #52
0
 public virtual StatementList SerializeAssertion(Module currentModule, Expression condition, string message, SourceContext sourceContext, string methodName){
   Method method;
   bool useTwoArgumentCalls = true;
   if (methodName == "AssumeStatement") {
     method = this.GetTypeView(SystemTypes.AssertHelpers).GetMethod(Identifier.For(methodName), SystemTypes.String);
   } else {
     method = this.GetTypeView(SystemTypes.AssertHelpers).GetMethod(Identifier.For(methodName), SystemTypes.String, SystemTypes.String);
     #region Delete when LKG > 7301
     if (method == null) {
       method = this.GetTypeView(SystemTypes.AssertHelpers).GetMethod(Identifier.For(methodName), SystemTypes.String);
       useTwoArgumentCalls = false;
     }
     #endregion
   }
   ExpressionList el = Checker.SplitConjuncts(condition);
   StatementList sl = new StatementList();
   if (method == null) return sl;
   for (int j = 0, m = el.Count; j < m; j++) {
     Expression e_prime = el[j];
     ContractSerializer serializer = new ContractSerializer(currentModule, this.currentClosureLocal);
     serializer.Visit(e_prime);
     string conditionText = serializer.SerializedContract;
     ExpressionList args = new ExpressionList(new Literal(conditionText, SystemTypes.String));
     if (methodName != "AssumeStatement" && useTwoArgumentCalls) { // assume is a unary method
       if (string.IsNullOrEmpty(message)){
         // Can't have the source context passed in to the method in case the expression has been
         // split into different top level conjuncts.
         if (e_prime.SourceContext.Document != null) {
           args.Add(new Literal(e_prime.SourceContext.SourceText, SystemTypes.String));
         } else {
           args.Add(new Literal("Unknown source context", SystemTypes.String));
         }
       } else {
         args.Add(new Literal(message, SystemTypes.String));
       }
     }
     sl.Add(new ExpressionStatement(new MethodCall(new MemberBinding(null, method), args, NodeType.Call, SystemTypes.Void, sourceContext), sourceContext));
   }
   return sl;
 }
Exemple #53
0
 /// <summary>
 /// <para>
 /// Serializes the expressions in toSerialize to an attribute determined by ctor, as if they come from module containingModule.
 /// Uses the SourceContext information of <param name="sc">sc</param> for the source context for the attribute.
 /// </para>
 /// <para><code>
 /// requires ctor != null &amp;&amp; sc != null;
 /// </code></para>
 /// <para><code>
 /// requires ctor.DeclaringType &lt;: Microsoft.Contracts.AttributeWithContext;
 /// </code></para>
 /// </summary>
 /// <returns></returns>
 public static AttributeNode SerializeExpressions(InstanceInitializer/*!*/ ctor, ExpressionList dontSerialize, ExpressionList toSerialize, SourceContext/*!*/ sc, Module containingModule) {
   MemberBinding attrBinding = new MemberBinding(null, ctor);
   ExpressionList args = new ExpressionList();
   if (dontSerialize != null) {
     foreach (Expression e in dontSerialize) {
       args.Add(e);
     }
   }
   if (toSerialize != null) {
     foreach (Expression e in toSerialize) {
       ContractSerializer cs = new ContractSerializer(containingModule);
       cs.Visit(e);
       string val = cs.SerializedContract;
       args.Add(new Literal(val, SystemTypes.String));
     }
   }
   if (sc.SourceText != null) {
     args.Add(new NamedArgument(Identifier.For("Filename"), new Literal(sc.Document.Name, SystemTypes.String)));
     args.Add(new NamedArgument(Identifier.For("StartLine"), new Literal(sc.StartLine, SystemTypes.Int32)));
     args.Add(new NamedArgument(Identifier.For("StartColumn"), new Literal(sc.StartColumn, SystemTypes.Int32)));
     args.Add(new NamedArgument(Identifier.For("EndLine"), new Literal(sc.EndLine, SystemTypes.Int32)));
     args.Add(new NamedArgument(Identifier.For("EndColumn"), new Literal(sc.EndColumn, SystemTypes.Int32)));
     args.Add(new NamedArgument(Identifier.For("SourceText"), new Literal(sc.SourceText, SystemTypes.String)));
   }
   return new AttributeNode(attrBinding, args, (AttributeTargets)0);
 }    
Exemple #54
0
 /// <summary>
 /// CodeSpan is in support of IVsLanguageDebugInfo.ValidateBreakpointLocation.
 /// It is called for each region that contains "executable" code.
 /// This is used to validate breakpoints. Comments are
 /// automatically taken care of based on TokenInfo returned from scanner. 
 /// Normally this method is called when a procedure is started/ended.
 /// </summary>
 public abstract void CodeSpan(SourceContext spanContext);
 // returns the local variable for a specific stack depth
 private Variable get_stack_var(int depth, Expression expr, ref SourceContext ctxt) {
   System.Diagnostics.Debug.Assert(depth >= 0);
   return StackVariable.For(depth, expr, ref ctxt);
 }
Exemple #56
0
 /// <summary>
 /// The StartParameters, Parameter and EndParameter methods are
 /// called in support of method tip intellisense (ECMD_PARAMINFO).
 /// [StartParameters] is called when the parameters of a method
 /// are started, ie. "(".
 /// [NextParameter] is called on the start of a new parameter, ie. ",".
 /// [EndParameter] is called on the end of the paramters, ie. ")".
 /// REVIEW: perhaps this entire scheme should go away
 /// </summary>
 public abstract void StartParameters(SourceContext context);
Exemple #57
0
 public void SourceContextStandalone()
 {
     var message = new SourceContext { FileName = "foo.proto" };
     AssertJson("{ 'fileName': 'foo.proto' }", JsonFormatter.Default.Format(message));
 }
Exemple #58
0
 /// <summary>
 /// NextParameter is called after StartParameters on the start of each new parameter, ie. ",".
 /// </summary>
 public abstract void NextParameter(SourceContext context);
Exemple #59
0
 public abstract void AddCollapsibleRegion(SourceContext context, bool collapsed);
Exemple #60
0
 /// <summary>
 /// EndParameter is called on the end of the paramters, ie. ")".
 /// </summary>
 public abstract void EndParameters(SourceContext context);