コード例 #1
0
 public static void TestTryCombine([PexAssumeUnderTest] StatementLoopOverGroupItems target, IStatement statement)
 {
     var canComb = target.TryCombineStatement(statement, null);
     Assert.IsNotNull(statement, "Second statement null should cause a failure");
     var allSame = target.CodeItUp().Zip(statement.CodeItUp(), (f, s) => f == s).All(t => t);
     Assert.IsTrue(allSame == canComb || target.Statements.Count() == 0, "not expected combination!");
 }
    /// <summary>Determines whether this instance can handle the specified statement.</summary>
    /// <param name="statement">The statement.</param>
    /// <returns><c>true</c> if this instance can handle the specified statement; otherwise, <c>false</c>.</returns>
    public override bool CanHandle(IStatement statement)
    {
      var ifStatement = statement as IIfStatement;
      if (ifStatement == null)
      {
        return false;
      }

      var referenceExpression = ifStatement.Condition as IReferenceExpression;
      if (referenceExpression == null)
      {
        return false;
      }

      var resolveResult = referenceExpression.Reference.Resolve();
      if (!resolveResult.IsValid())
      {
        return false;
      }

      var declaredElement = resolveResult.DeclaredElement as ITypeMember;
      if (declaredElement == null)
      {
        return false;
      }

      return true;
    }
コード例 #3
0
 public static void TestTryCombine([PexAssumeUnderTest] StatementRecordPairValues target, IStatement statement)
 {
     var canComb = target.TryCombineStatement(statement, null);
     Assert.IsNotNull(statement, "Second statement null should cause a failure");
     var allSame = target.CodeItUp().Zip(statement.CodeItUp(), (f, s) => f == s).All(t => t);
     Assert.AreEqual(allSame, canComb, "not expected combination!");
 }
    /// <summary>Determines whether this instance can handle the specified statement.</summary>
    /// <param name="statement">The statement.</param>
    /// <returns><c>true</c> if this instance can handle the specified statement; otherwise, <c>false</c>.</returns>
    public override bool CanHandle(IStatement statement)
    {
      var ifStatement = statement as IIfStatement;
      if (ifStatement == null)
      {
        return false;
      }

      var equalityExpression = ifStatement.Condition as IEqualityExpression;
      if (equalityExpression == null)
      {
        return false;
      }

      var operand = equalityExpression.RightOperand;
      if (operand == null)
      {
        return false;
      }

      if (operand.GetText() == "null")
      {
        return true;
      }

      operand = equalityExpression.LeftOperand;
      if (operand == null)
      {
        return false;
      }

      return operand.GetText() == "null";
    }
コード例 #5
0
        public ReplacementRule(ProofLine templateLine)
        {
            if (templateLine == null)
                throw new ArgumentNullException ("templateLine");

            _Template = NormalizeRecursively(templateLine.Statement);
        }
コード例 #6
0
ファイル: CodeCompletion.cs プロジェクト: rainers/D_Parser
        public static ISyntaxRegion FindCurrentCaretContext(IEditorData editor, 
			ref IBlockNode currentScope, 
			out IStatement currentStatement,
			out bool isInsideNonCodeSegment)
        {
            isInsideNonCodeSegment = false;
            currentStatement = null;

            if(currentScope == null)
                currentScope = DResolver.SearchBlockAt (editor.SyntaxTree, editor.CaretLocation, out currentStatement);

            if (currentScope == null)
                return null;

            BlockStatement blockStmt;
            // Always skip lambdas as they're too quirky for accurate scope calculation // ISSUE: May be other anon symbols too?
            var dm = currentScope as DMethod;
            if (dm != null && (dm.SpecialType & DMethod.MethodType.Lambda) != 0)
                currentScope = dm.Parent as IBlockNode;

            if (currentScope is DMethod &&
                (blockStmt = (currentScope as DMethod).GetSubBlockAt (editor.CaretLocation)) != null) {
                blockStmt.UpdateBlockPartly (editor, out isInsideNonCodeSegment);
                currentScope = DResolver.SearchBlockAt (currentScope, editor.CaretLocation, out currentStatement);
            }else {
                while (currentScope is DMethod)
                    currentScope = currentScope.Parent as IBlockNode;
                if (currentScope == null)
                    return null;

                (currentScope as DBlockNode).UpdateBlockPartly (editor, out isInsideNonCodeSegment);
                currentScope = DResolver.SearchBlockAt (currentScope, editor.CaretLocation, out currentStatement);
            }
            return currentScope;
        }
    /// <summary>Handles the specified statement.</summary>
    /// <param name="statement">The statement.</param>
    /// <param name="scope">The scope.</param>
    /// <returns>Returns the string.</returns>
    public override StatementDescriptor Handle(IStatement statement, AutoTemplateScope scope)
    {
      var tryStatement = statement as ITryStatement;
      if (tryStatement == null)
      {
        return null;
      }

      var result = new StatementDescriptor(scope)
      {
        Template = string.Format("try {{ $END$ }}")
      };

      foreach (var catchClause in tryStatement.Catches)
      {
        var type = catchClause.ExceptionType;
        if (type == null)
        {
          result.Template += " catch { }";
          continue;
        }

        var typeName = type.GetLongPresentableName(tryStatement.Language);
        result.Template += string.Format(" catch ({0}) {{ }}", typeName);
      }

      return result;
    }
    /// <summary>Handles the specified statement.</summary>
    /// <param name="statement">The statement.</param>
    /// <returns>Returns the I enumerable.</returns>
    public override AutoTemplateScope Handle(IStatement statement)
    {
      var expressionStatement = statement as IExpressionStatement;
      if (expressionStatement == null)
      {
        return null;
      }

      var assignmentExpression = expressionStatement.Expression as IAssignmentExpression;
      if (assignmentExpression == null)
      {
        return null;
      }

      var scopeParameters = new Dictionary<string, string>();
      if (!HandleAssignment(assignmentExpression, scopeParameters))
      {
        return null;
      }

      string variableType;
      if (!scopeParameters.TryGetValue("FullName", out variableType))
      {
        variableType = "(unknown variable)";
      }

      var key = string.Format("After variable of type \"{0}\"", variableType);

      return new AutoTemplateScope(statement, key, scopeParameters);
    }
コード例 #9
0
ファイル: ForStatement.cs プロジェクト: langpavel/LPS-old
 public ForStatement(IExpression initialization, IExpression condition, IExpression step, IStatement statement)
     : base(statement)
 {
     this.initialization = initialization;
     this.condition = condition;
     this.step = step;
 }
コード例 #10
0
ファイル: MoveNext.cs プロジェクト: Refresh06/visualmutator
 private static IMethodBody/*?*/ FirstStatementIsIteratorCreation(IMetadataHost host, ISourceMethodBody possibleIterator, INameTable nameTable, IStatement statement) {
   ICreateObjectInstance createObjectInstance = GetICreateObjectInstance(statement);
   if (createObjectInstance == null) {
     // If the first statement in the method body is not the creation of iterator closure, return a dummy.
     // Possible corner case not handled: a local is used to hold the constant value for the initial state of the closure.
     return null;
   }
   ITypeReference closureType/*?*/ = createObjectInstance.MethodToCall.ContainingType;
   ITypeReference unspecializedClosureType = ContractHelper.Unspecialized(closureType);
   if (!AttributeHelper.Contains(unspecializedClosureType.Attributes, host.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute))
     return null;
   INestedTypeReference closureTypeAsNestedTypeReference = unspecializedClosureType as INestedTypeReference;
   if (closureTypeAsNestedTypeReference == null) return null;
   ITypeReference unspecializedClosureContainingType = ContractHelper.Unspecialized(closureTypeAsNestedTypeReference.ContainingType);
   if (closureType != null && TypeHelper.TypesAreEquivalent(possibleIterator.MethodDefinition.ContainingTypeDefinition, unspecializedClosureContainingType)) {
     IName MoveNextName = nameTable.GetNameFor("MoveNext");
     foreach (ITypeDefinitionMember member in closureType.ResolvedType.GetMembersNamed(MoveNextName, false)) {
       IMethodDefinition moveNext = member as IMethodDefinition;
       if (moveNext != null) {
         ISpecializedMethodDefinition moveNextGeneric = moveNext as ISpecializedMethodDefinition;
         if (moveNextGeneric != null)
           moveNext = moveNextGeneric.UnspecializedVersion.ResolvedMethod;
         return moveNext.Body;
       }
     }
   }
   return null;
 }
コード例 #11
0
        public void AddStatement(IStatement statement)
        {
            if (statement == null)
                throw new ArgumentNullException("statement");

            statements.Add(statement);
        }
コード例 #12
0
 public Task Insert(IStatement statement)
 {
     _queriesWaitingInLineSemaphore.Wait(); // Since the dataset does not fit in memory, we limit the pending queries count
     var taskCompletionSource = new TaskCompletionSource<RowSet>();
     _insertionQueue.Post(new PendingInsert { Statement = statement, Completion = taskCompletionSource });
     return taskCompletionSource.Task;
 }
 /// <summary>Handles the specified statement.</summary>
 /// <param name="statement">The statement.</param>
 /// <param name="scope">The scope.</param>
 /// <returns>Returns the string.</returns>
 public override StatementDescriptor Handle(IStatement statement, AutoTemplateScope scope)
 {
   return new StatementDescriptor(scope)
   {
     Template = "continue;"
   };
 }
コード例 #14
0
ファイル: ProcedureSql.cs プロジェクト: hejiquan/iBATIS_2010
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="statement">The statement.</param>
        /// <param name="sqlStatement"></param>
        /// <param name="scope"></param>
        public ProcedureSql(IScope scope, string sqlStatement, IStatement statement)
        {
            _sqlStatement = sqlStatement;
            _statement = statement;

            _dataExchangeFactory = scope.DataExchangeFactory;
        }
    /// <summary>Handles the specified statement.</summary>
    /// <param name="statement">The statement.</param>
    /// <param name="scope">The scope.</param>
    /// <returns>Returns the string.</returns>
    public override StatementDescriptor Handle(IStatement statement, AutoTemplateScope scope)
    {
      var ifStatement = statement as IIfStatement;
      if (ifStatement == null)
      {
        return null;
      }

      var condition = ifStatement.Condition;
      if (condition == null)
      {
        return null;
      }

      var expressionDescriptor = ExpressionTemplateBuilder.Handle(condition, scope.ScopeParameters);
      if (expressionDescriptor != null)
      {
        return new StatementDescriptor(scope, string.Format("if ({0}) {{ $END$ }}", expressionDescriptor.Template), expressionDescriptor.TemplateVariables);
      }

      var result = new StatementDescriptor(scope)
      {
        Template = string.Format("if ({0}) {{ $END$ }}", condition.GetText())
      };

      string variableName;
      if (scope.ScopeParameters.TryGetValue("VariableName", out variableName))
      {
        result.Template = result.Template.Replace(variableName, "$VariableName$");
      }

      return result;
    }
コード例 #16
0
 public bool TryCombineStatement(IStatement statement, ICodeOptimizationService optimize)
 {
     var otherRtn = statement as StatementReturn;
     if (otherRtn == null)
         return false;
     return otherRtn._rtnValue.RawValue == _rtnValue.RawValue;
 }
コード例 #17
0
        /// <summary>
        /// Try to combine two assign statements. Since this will be for totally
        /// trivial cases, this should be "easy" - only when they are the same.
        /// </summary>
        /// <param name="statement"></param>
        /// <returns></returns>
        public bool TryCombineStatement(IStatement statement, ICodeOptimizationService opt)
        {
            if (statement == null)
                throw new ArgumentNullException("statement");

            if (opt == null)
                throw new ArgumentNullException("opt");

            var otherAssign = statement as StatementAssign;
            if (otherAssign == null)
                return false;

            if (Expression.RawValue != otherAssign.Expression.RawValue)
                return false;

            // If the statements are identical, then we can combine by default without having to do any
            // further work.

            if (otherAssign.ResultVariable.RawValue == ResultVariable.RawValue)
                return true;

            // If we have declared, then we are sole owner - so we can force the change. Otherwise, we
            // need to let the infrastructure figure out where the declared is and change it from there.

            return opt.TryRenameVarialbeOneLevelUp(otherAssign.ResultVariable.RawValue, ResultVariable);
        }
コード例 #18
0
        public NegationStatement(IStatement statementToNegate)
        {
            if (statementToNegate == null)
                throw new ArgumentNullException("statementToNegate");

            _NegatedStatement = statementToNegate;
        }
    /// <summary>Handles the specified statement.</summary>
    /// <param name="statement">The statement.</param>
    /// <param name="scope">The scope.</param>
    /// <returns>Returns the string.</returns>
    public override StatementDescriptor Handle(IStatement statement, AutoTemplateScope scope)
    {
      var returnStatement = statement as IReturnStatement;
      if (returnStatement == null)
      {
        return null;
      }

      var value = returnStatement.Value;
      if (value == null)
      {
        return new StatementDescriptor(scope)
        {
          Template = "return;"
        };
      }

      var expressionDescriptor = ExpressionTemplateBuilder.Handle(value, scope.ScopeParameters);
      if (expressionDescriptor == null)
      {
        return null;
      }

      return new StatementDescriptor(scope, string.Format("return {0}", expressionDescriptor.Template), expressionDescriptor.TemplateVariables);
    }
コード例 #20
0
ファイル: SqlGenerator.cs プロジェクト: wangsying/SpiderJobs
        /// <summary>
        /// Creates an delete SQL command text for a specified statement
        /// </summary>
        /// <param name="statement">The statement to build the SQL command text.</param>
        /// <returns>The SQL command text for the statement.</returns>
        private static string BuildDeleteQuery(IStatement statement)
        {
            StringBuilder output = new StringBuilder();
            Delete delete = (Delete) statement;
            string[] keysList = delete.Generate.By.Split(',');

            output.Append("DELETE FROM");
            output.Append("\t" + delete.Generate.Table + "");
            output.Append(" WHERE ");

            // Create the where clause
            int length = keysList.Length;
            for (int i = 0; i < keysList.Length; i++)
            {
                string columnName = keysList[i].Trim();

                if (i > 0)
                {
                    output.Append("\tAND " + columnName + " = ?");
                }
                else
                {
                    output.Append("\t " + columnName + " = ?");
                }
            }

            return output.ToString();
        }
コード例 #21
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="session"></param>
		/// <param name="statement"></param>
		/// <param name="commandText"></param>
		/// <param name="request"></param>
		public PreparedStatementFactory(ISqlMapSession session, RequestScope request, IStatement statement, string commandText)
		{
			_session = session;
			_request = request;
			_statement = statement;
			_commandText = commandText;
		}
コード例 #22
0
        /// <summary>
        /// Can exchange the orders these statements are?
        /// </summary>
        /// <param name="s"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public static bool StatementCommutes(IStatement s1, IStatement s2)
        {
            if (!(s1 is ICMStatementInfo))
                return false;
            if (!(s2 is ICMStatementInfo))
                return false;

            var c1Info = s1 as ICMStatementInfo;
            var c2Info = s2 as ICMStatementInfo;

            // If the results of 1 will alter 2 or vice versa
            var c1DependsOnC2 = c1Info.DependentVariables.Intersect(c2Info.ResultVariables);
            if (c1DependsOnC2.Count() > 0)
                return false;

            var c2DependsOnC1 = c2Info.DependentVariables.Intersect(c1Info.ResultVariables);
            if (c2DependsOnC1.Count() > 0)
                return false;

            // If they both change the same variables, then we have an ordering problem.
            var resultsDependent = c1Info.ResultVariables.Intersect(c2Info.ResultVariables);
            if (resultsDependent.Count() > 0)
                return false;

            return true;
        }
コード例 #23
0
 public MemberCompletionProvider(ICompletionDataGenerator cdg, ISyntaxRegion sr, IBlockNode b, IStatement stmt)
     : base(cdg)
 {
     AccessExpression = sr;
     ScopedBlock = b;
     ScopedStatement = stmt;
 }
コード例 #24
0
ファイル: DynamicSql.cs プロジェクト: hejiquan/iBATIS_2010
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicSql"/> class.
        /// </summary>
        /// <param name="configScope">The config scope.</param>
        /// <param name="statement">The statement.</param>
        internal DynamicSql(ConfigurationScope configScope, IStatement statement)
        {
            _statement = statement;

            _usePositionalParameters = configScope.DataSource.DbProvider.UsePositionalParameters;
            _dataExchangeFactory = configScope.DataExchangeFactory;
        }
コード例 #25
0
ファイル: ContextFrame.cs プロジェクト: DinrusGroup/DRC
        public ContextFrame(ResolutionContext ctxt, IBlockNode b, IStatement stmt = null)
        {
            this.ctxt = ctxt;
            declarationCondititons = new ConditionalCompilation.ConditionSet(ctxt.CompilationEnvironment);

            Set(b,stmt);
        }
コード例 #26
0
 public CtrlSpaceCompletionProvider(ICompletionDataGenerator cdg, IBlockNode b, IStatement stmt, MemberFilter vis = MemberFilter.All)
     : base(cdg)
 {
     this.curBlock = b;
     this.curStmt = stmt;
     visibleMembers = vis;
 }
コード例 #27
0
        public void ApplyFrom(ResolverContext other)
        {
            if (other == null)
                return;

            ScopedBlock = other.ScopedBlock;
            ScopedStatement = other.ScopedStatement;
        }
コード例 #28
0
 public IfStatement(IExpression booleanExp, IStatement thenBranch,
     IStatement elseBranch, int row, int col)
     : base(row, col)
 {
     Condition = booleanExp;
     ThenBranch = WrapInBlock(thenBranch);
     ElseBranch = WrapInBlock(elseBranch);
 }
コード例 #29
0
ファイル: SqlGenerator.cs プロジェクト: techvenky/mybatisnet
		/// <summary>
		/// Creates an select SQL command text for a specified statement
		/// </summary>
		/// <param name="statement">The statement to build the SQL command text.</param>
		/// <returns>The SQL command text for the statement.</returns>
		private static string BuildSelectQuery(IStatement statement)
		{
			StringBuilder output = new StringBuilder();
			Select select = (Select) statement;
			int columnCount = statement.ParameterMap.PropertiesList.Count;

			output.Append("SELECT ");

			// Create the list of columns
			for (int i = 0; i < columnCount; i++) 
			{
				ParameterProperty property = (ParameterProperty) statement.ParameterMap.PropertiesList[i];
						
				if (i < (columnCount - 1)) 
				{
					output.Append("\t" + property.ColumnName + " as "+property.PropertyName+",");
				} 
				else 
				{
					output.Append("\t" + property.ColumnName + " as "+property.PropertyName);
				}
			}

			output.Append(" FROM ");
			output.Append("\t" + select.Generate.Table + "");

			// Create the where clause

			string [] compositeKeyList = select.Generate.By.Split(new Char [] {','});
			if (compositeKeyList.Length > 0 && select.Generate.By.Length>0)
			{
				output.Append(" WHERE ");
				int length = compositeKeyList.Length;
				for (int i = 0; i < length; i++) 
				{
					string columnName = compositeKeyList[i];
						
					if (i > 0) 
					{
						output.Append("\tAND " + columnName + " = ?" );
					} 
					else 
					{
						output.Append("\t" + columnName + " = ?" );
					}
				}
			}

			// 'Select All' case
			if (statement.ParameterClass == null)
			{
				// The ParameterMap is just used to build the query
				// to avoid problems later, we set it to null
				statement.ParameterMap = null;
			}

			return output.ToString();
		}
コード例 #30
0
		public MultiTableUpdateExecutor(IStatement statement) : base(statement, log)
		{
			if (!Factory.Dialect.SupportsTemporaryTables)
			{
				throw new HibernateException("cannot perform multi-table updates using dialect not supporting temp tables");
			}
			var updateStatement = (UpdateStatement) statement;

			FromElement fromElement = updateStatement.FromClause.GetFromElement();
			string bulkTargetAlias = fromElement.TableAlias;
			persister = fromElement.Queryable;

			idInsertSelect = GenerateIdInsertSelect(persister, bulkTargetAlias, updateStatement.WhereClause);
			log.Debug("Generated ID-INSERT-SELECT SQL (multi-table update) : " + idInsertSelect);

			string[] tableNames = persister.ConstraintOrderedTableNameClosure;
			string[][] columnNames = persister.ConstraintOrderedTableKeyColumnClosure;

			string idSubselect = GenerateIdSubselect(persister);
			IList<AssignmentSpecification> assignmentSpecifications = Walker.AssignmentSpecifications;

			updates = new SqlString[tableNames.Length];
			hqlParameters = new IParameterSpecification[tableNames.Length][];
			for (int tableIndex = 0; tableIndex < tableNames.Length; tableIndex++)
			{
				bool affected = false;
				var parameterList = new List<IParameterSpecification>();
				SqlUpdateBuilder update =
					new SqlUpdateBuilder(Factory.Dialect, Factory).SetTableName(tableNames[tableIndex])
					.SetWhere(
						string.Format("({0}) IN ({1})", StringHelper.Join(", ", columnNames[tableIndex]), idSubselect));

				if (Factory.Settings.IsCommentsEnabled)
				{
					update.SetComment("bulk update");
				}
				foreach (var specification in assignmentSpecifications)
				{
					if (specification.AffectsTable(tableNames[tableIndex]))
					{
						affected = true;
						update.AppendAssignmentFragment(specification.SqlAssignmentFragment);
						if (specification.Parameters != null)
						{
							for (int paramIndex = 0; paramIndex < specification.Parameters.Length; paramIndex++)
							{
								parameterList.Add(specification.Parameters[paramIndex]);
							}
						}
					}
				}
				if (affected)
				{
					updates[tableIndex] = update.ToSqlString();
					hqlParameters[tableIndex] = parameterList.ToArray();
				}
			}
		}
コード例 #31
0
 public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved,
                                    int nbRetry)
 {
     Interlocked.Increment(ref ReadTimeoutCounter);
     return(RetryDecision.Rethrow());
 }
コード例 #32
0
 public virtual void OpenStatement(IStatement istmt)
 {
     Open(istmt);
     OpenOutput();
 }
コード例 #33
0
 private void AddStatement(IStatement ist)
 {
     blockStack.Peek().Add(ist);
 }
コード例 #34
0
        /// <summary>
        /// Update the dependency information of all statements, assuming that the original statements have been permuted and duplicated, but not transformed.
        /// </summary>
        /// <param name="outputs"></param>
        private void PostProcessDependencies(ICollection <IStatement> outputs)
        {
            Dictionary <IStatement, int> indexOfStatement = new Dictionary <IStatement, NodeIndex>(new IdentityComparer <IStatement>());

            if (clonesOfStatement.Count == 0)
            {
                return;
            }
            DeadCodeTransform.ForEachStatement(outputs,
                                               _ => { },
                                               _ => { },
                                               _ => { },
                                               _ => { },
                                               ist =>
            {
                DependencyInformation di = context.InputAttributes.Get <DependencyInformation>(ist);
                if (di != null)
                {
                    // must make a clone since this statement may appear in multiple contexts
                    DependencyInformation di2 = (DependencyInformation)di.Clone();
                    di2.AddClones(clonesOfStatement);
                    IStatement originalStatement;
                    originalStatementOfClone.TryGetValue(ist, out originalStatement);
                    // originalStatement is non-null iff ist is a clone
                    IEnumerable <IStatement> clones;
                    if (clonesOfStatement.TryGetValue(originalStatement ?? ist, out clones))
                    {
                        // clones become Overwrites
                        foreach (var clone in clones)
                        {
                            di2.Add(DependencyType.Overwrite, clone);
                        }
                        if (originalStatement != null)
                        {
                            di2.Add(DependencyType.Overwrite, originalStatement);
                        }
                    }
                    // keep only the most recent overwrite that is not an allocation, and all overwrites that are allocations.
                    IStatement mostRecentWriter   = null;
                    int mostRecentWriterIndex     = 0;
                    List <IStatement> allocations = new List <IStatement>();
                    foreach (var writer in di2.Overwrites)
                    {
                        int index;
                        indexOfStatement.TryGetValue(writer, out index);
                        if (index > mostRecentWriterIndex)
                        {
                            mostRecentWriterIndex = index;
                            mostRecentWriter      = writer;
                        }
                        if (di2.HasDependency(DependencyType.Declaration, writer))
                        {
                            allocations.Add(writer);
                        }
                    }
                    di2.Remove(DependencyType.Overwrite);
                    // all allocations must remain as Overwrites
                    foreach (var dep in allocations)
                    {
                        di2.Add(DependencyType.Overwrite, dep);
                    }
                    if (mostRecentWriter != null)
                    {
                        di2.Add(DependencyType.Overwrite, mostRecentWriter);
                    }
                    context.OutputAttributes.Remove <DependencyInformation>(ist);
                    context.OutputAttributes.Set(ist, di2);
                }
                indexOfStatement[ist] = indexOfStatement.Count + 1;
            });
        }
コード例 #35
0
        public DependencyGraph2(BasicTransformContext context,
                                IEnumerable <IStatement> inputs,
                                BackEdgeHandling backEdgeHandling,
                                Action <IWhileStatement> beginWhile,
                                Action <IWhileStatement> endWhile,
                                Action <IConditionStatement> beginFirstIterPost,
                                Action <IConditionStatement> endFirstIterPost,
                                Action <IStatement, NodeIndex> action)
        {
            Set <NodeIndex> nodesInCurrentWhile = new Set <EdgeIndex>();
            int             whileDepth          = 0;

            // create a dependency graph where while loops are flattened (the while loops themselves are not nodes)
            // the graph will only contain read-after-write and write-after-alloc dependencies for now
            // add write-after-read dependencies
            isWriteAfterRead = dependencyGraph.CreateEdgeData(false);
            DeadCodeTransform.ForEachStatement(inputs,
                                               delegate(IWhileStatement iws)
            {
                beginWhile(iws);
                nodesInCurrentWhile.Clear();
                whileDepth++;
            },
                                               delegate(IWhileStatement iws)
            {
                // all duplicates in a while loop should share all targets
                foreach (KeyValuePair <IStatement, Set <NodeIndex> > entry in duplicates)
                {
                    IStatement ist          = entry.Key;
                    Set <NodeIndex> set     = entry.Value;
                    Set <NodeIndex> targets = new Set <EdgeIndex>();
                    // collect all targets in the while loop
                    foreach (NodeIndex node in set)
                    {
                        foreach (NodeIndex target in dependencyGraph.TargetsOf(node))
                        {
                            if (nodesInCurrentWhile.Contains(target))
                            {
                                targets.Add(target);
                            }
                        }
                    }
                    Set <NodeIndex> backEdgeTargets = null;
                    if (!backEdges.TryGetValue(ist, out backEdgeTargets))
                    {
                        backEdgeTargets = new Set <EdgeIndex>();
                        backEdges[ist]  = backEdgeTargets;
                    }
                    // add all targets to all duplicates in the loop
                    foreach (NodeIndex node in set)
                    {
                        if (!nodesInCurrentWhile.Contains(node))
                        {
                            continue;
                        }
                        foreach (NodeIndex target in targets)
                        {
                            if (!dependencyGraph.ContainsEdge(node, target))
                            {
                                if (backEdgeHandling == BackEdgeHandling.Include)
                                {
                                    dependencyGraph.AddEdge(node, target);
                                }
                                else if (backEdgeHandling == BackEdgeHandling.Reverse)
                                {
                                    if (!dependencyGraph.ContainsEdge(target, node))
                                    {
                                        dependencyGraph.AddEdge(target, node);
                                    }
                                }
                                if (target < node)
                                {
                                    if (backEdgeTargets == null && !backEdges.TryGetValue(ist, out backEdgeTargets))
                                    {
                                        backEdgeTargets = new Set <EdgeIndex>();
                                        backEdges[ist]  = backEdgeTargets;
                                    }
                                    backEdgeTargets.Add(target);
                                }
                            }
                        }
                    }
                }
                endWhile(iws);
                whileDepth--;
            },
                                               beginFirstIterPost,
                                               endFirstIterPost,
                                               delegate(IStatement ist)
            {
                DependencyInformation di = context.InputAttributes.Get <DependencyInformation>(ist);
                if (di == null)
                {
                    context.Error("Dependency information not found for statement: " + ist);
                    di = new DependencyInformation();
                }
                NodeIndex targetIndex = dependencyGraph.AddNode();
                Set <NodeIndex> backEdgeTargets;
                Set <NodeIndex> sources = new Set <NodeIndex>();                                  // for fast checking of duplicate sources
                foreach (IStatement source in
                         di.GetDependenciesOfType(DependencyType.Dependency | DependencyType.Declaration))
                {
                    int sourceIndex;
                    // we assume that the statements are already ordered properly to respect dependencies.
                    // if the source is not in indexOfNode, then it must be a cyclic dependency in this while loop.
                    if (indexOfNode.TryGetValue(source, out sourceIndex))
                    {
                        if (!sources.Contains(sourceIndex))
                        {
                            sources.Add(sourceIndex);
                            EdgeIndex edge = dependencyGraph.AddEdge(sourceIndex, targetIndex);
                        }
                    }
                    else
                    {
                        sourceIndex = -1;
                    }
                    if (sourceIndex == -1)
                    {
                        // add a back edge
                        if (!backEdges.TryGetValue(source, out backEdgeTargets))
                        {
                            backEdgeTargets   = new Set <EdgeIndex>();
                            backEdges[source] = backEdgeTargets;
                        }
                        backEdgeTargets.Add(targetIndex);
                        // add a dependency on the initializers of source
                        Stack <IStatement> todo = new Stack <IStatement>();
                        todo.Push(source);
                        while (todo.Count > 0)
                        {
                            IStatement source2        = todo.Pop();
                            DependencyInformation di2 = context.InputAttributes.Get <DependencyInformation>(source2);
                            if (di2 == null)
                            {
                                context.Error("Dependency information not found for statement: " + source2);
                                continue;
                            }
                            foreach (IStatement init in di2.Overwrites)
                            {
                                int initIndex;
                                if (indexOfNode.TryGetValue(init, out initIndex))
                                {
                                    if (!sources.Contains(initIndex))
                                    {
                                        sources.Add(initIndex);
                                        EdgeIndex edge = dependencyGraph.AddEdge(initIndex, targetIndex);
                                    }
                                }
                                else
                                {
                                    todo.Push(init);
                                }
                            }
                        }
                    }
                }
                if (indexOfNode.ContainsKey(ist))
                {
                    Set <int> set;
                    if (!duplicates.TryGetValue(ist, out set))
                    {
                        set             = new Set <int>();
                        duplicates[ist] = set;
                        set.Add(indexOfNode[ist]);
                    }
                    set.Add(targetIndex);
                }
                // the same statement may appear multiple times.  when looking up indexOfNode, we want to use the last occurrence of the statement.
                indexOfNode[ist] = targetIndex;                                    // must do this at the end, in case the stmt depends on a previous occurrence of itself
                nodesInCurrentWhile.Add(targetIndex);
                nodes.Add(ist);
                if (backEdgeHandling != BackEdgeHandling.Ignore && backEdges.TryGetValue(ist, out backEdgeTargets))
                {
                    // now that ist has an index, we can fill in the back edges
                    foreach (NodeIndex node in backEdgeTargets)
                    {
                        if (backEdgeHandling == BackEdgeHandling.Include)
                        {
                            if (dependencyGraph.ContainsEdge(targetIndex, node))
                            {
                                throw new Exception("Internal: back edge already present");
                            }
                            dependencyGraph.AddEdge(targetIndex, node);
                        }
                        else if (backEdgeHandling == BackEdgeHandling.Reverse)
                        {
                            // make a new edge, even if one exists.
                            EdgeIndex edge         = dependencyGraph.AddEdge(node, targetIndex);
                            isWriteAfterRead[edge] = true;
                        }
                        else
                        {
                            throw new NotSupportedException($"backEdgeHandling == {backEdgeHandling}");
                        }
                    }
                }
                action(ist, targetIndex);
            });
            bool includeWriteAfterRead = false;

            if (includeWriteAfterRead)
            {
                // loop statements in their original order
                foreach (NodeIndex target in dependencyGraph.Nodes)
                {
                    IStatement ist = nodes[target];
                    if (ist is IWhileStatement)
                    {
                        continue;
                    }
                    foreach (NodeIndex source in GetPreviousReaders(context, dependencyGraph, target, nodes, indexOfNode).ToReadOnlyList())
                    {
                        if (source > target)
                        {
                            throw new Exception("Internal: source statement follows target");
                        }
                        // make a new edge, even if one exists.
                        EdgeIndex edge = dependencyGraph.AddEdge(source, target);
                        isWriteAfterRead[edge] = true;
                    }
                }
            }
            isWriteAfterWrite = dependencyGraph.CreateEdgeData(false);
            // loop statements in their original order
            foreach (NodeIndex target in dependencyGraph.Nodes)
            {
                IStatement ist = nodes[target];
                if (ist is IWhileStatement)
                {
                    continue;
                }

                foreach (NodeIndex source in GetOverwrites(context, dependencyGraph, target, nodes, indexOfNode).ToReadOnlyList())
                {
                    if (source > target)
                    {
                        throw new Exception("Internal: source statement follows target");
                    }
                    if (dependencyGraph.ContainsEdge(source, target))
                    {
                        foreach (EdgeIndex edge in dependencyGraph.EdgesLinking(source, target))
                        {
                            isWriteAfterWrite[edge] = true;
                        }
                    }
                    else
                    {
                        EdgeIndex edge = dependencyGraph.AddEdge(source, target);
                        isWriteAfterWrite[edge] = true;
                    }
                }
            }

            dependencyGraph.NodeCountIsConstant = true;
            dependencyGraph.IsReadOnly          = true;
            for (int targetIndex = 0; targetIndex < dependencyGraph.Nodes.Count; targetIndex++)
            {
                IStatement            ist = nodes[targetIndex];
                DependencyInformation di  = context.InputAttributes.Get <DependencyInformation>(ist);
                if (di == null)
                {
                    continue;
                }
                if (di.IsOutput)
                {
                    outputNodes.Add(targetIndex);
                }
            }
        }
コード例 #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UpdateMappedStatement"/> class.
 /// </summary>
 /// <param name="modelStore">The model store.</param>
 /// <param name="statement">The statement.</param>
 public UpdateMappedStatement(IModelStore modelStore, IStatement statement)
     : base(modelStore, statement)
 {
 }
コード例 #37
0
        private static IMethodBody /*?*/ FirstStatementIsIteratorCreation(IMetadataHost host, ISourceMethodBody possibleIterator, INameTable nameTable, IStatement statement)
        {
            ICreateObjectInstance createObjectInstance = GetICreateObjectInstance(statement);

            if (createObjectInstance == null)
            {
                // If the first statement in the method body is not the creation of iterator closure, return a dummy.
                // Possible corner case not handled: a local is used to hold the constant value for the initial state of the closure.
                return(null);
            }
            ITypeReference closureType /*?*/        = createObjectInstance.MethodToCall.ContainingType;
            ITypeReference unspecializedClosureType = ContractHelper.Unspecialized(closureType);

            if (!AttributeHelper.Contains(unspecializedClosureType.Attributes, host.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute))
            {
                return(null);
            }
            INestedTypeReference closureTypeAsNestedTypeReference = unspecializedClosureType as INestedTypeReference;

            if (closureTypeAsNestedTypeReference == null)
            {
                return(null);
            }
            ITypeReference unspecializedClosureContainingType = ContractHelper.Unspecialized(closureTypeAsNestedTypeReference.ContainingType);

            if (closureType != null && TypeHelper.TypesAreEquivalent(possibleIterator.MethodDefinition.ContainingTypeDefinition, unspecializedClosureContainingType))
            {
                IName MoveNextName = nameTable.GetNameFor("MoveNext");
                foreach (ITypeDefinitionMember member in closureType.ResolvedType.GetMembersNamed(MoveNextName, false))
                {
                    IMethodDefinition moveNext = member as IMethodDefinition;
                    if (moveNext != null)
                    {
                        ISpecializedMethodDefinition moveNextGeneric = moveNext as ISpecializedMethodDefinition;
                        if (moveNextGeneric != null)
                        {
                            moveNext = moveNextGeneric.UnspecializedVersion.ResolvedMethod;
                        }
                        return(moveNext.Body);
                    }
                }
            }
            return(null);
        }
コード例 #38
0
 public IEnumerable <Host> NewQueryPlan(string keyspace, IStatement query)
 {
     return(_childPolicy.NewQueryPlan(keyspace, query));
 }
コード例 #39
0
 internal SelectMappedStatement(ISqlMapper sqlMap, IStatement statement) : base(sqlMap, statement)
 {
 }
コード例 #40
0
ファイル: Parser.cs プロジェクト: Pandawan/min
        /// <summary>
        /// Get a for statement and compile it to a while (under the hood).
        /// </summary>
        private IStatement ForStatement()
        {
            /**
             *  Desugaring for loop into a while loop:
             *
             *  initializer;
             *  while (condition) {
             *      body;
             *      increment;
             *  }
             */

            Consume(TokenType.LEFT_PAREN, "Expect '(' after 'for'.");

            // First part of for loop, an expression/declaration that runs once
            IStatement initializer;

            if (Match(TokenType.SEMICOLON))
            {
                initializer = null;
            }
            else if (Match(TokenType.LET))
            {
                initializer = LetDeclaration();
            }
            else
            {
                initializer = ExpressionStatement();
            }

            // Second part of for loop, a condition that is checked on every iteration
            IExpression condition = null;

            if (Check(TokenType.SEMICOLON) == false)
            {
                condition = Expression();
            }

            Consume(TokenType.SEMICOLON, "Expect ';' after loop condition.");

            // Third part of for loop, an incrementer that runs every iteration
            IExpression increment = null;

            if (Check(TokenType.RIGHT_PAREN) == false)
            {
                increment = Expression();
            }

            Consume(TokenType.RIGHT_PAREN, "Expect ')' after for clauses.");

            IStatement body = Statement();

            // If there is an increment
            if (increment != null)
            {
                // Add the increment to the body of the while loop
                body = new BlockStatement(new List <IStatement>()
                {
                    body, new ExpressionStatement(increment)
                });
            }

            // Create a while loop with condition + body (which also has increment)
            if (condition == null)
            {
                condition = new LiteralExpression(true);
            }
            body = new WhileStatement(condition, body);

            // Lastly, add an initializer before the while loop
            if (initializer != null)
            {
                body = new BlockStatement(new List <IStatement>()
                {
                    initializer,
                    body
                });
            }

            return(body);
        }
コード例 #41
0
 public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry)
 {
     return(RetryDecision.Rethrow());
 }
コード例 #42
0
 public RetryDecision OnRequestError(IStatement statement, Configuration config, Exception ex, int nbRetry)
 {
     Interlocked.Increment(ref RequestErrorConter);
     return(RetryDecision.Rethrow());
 }
コード例 #43
0
 public ISpeculativeExecutionPlan NewPlan(string keyspace, IStatement statement)
 {
     Interlocked.Increment(ref Count);
     return(new ConstantSpeculativeExecutionPolicy(10, 1).NewPlan(keyspace, statement));
 }
コード例 #44
0
 public override void VisitYieldBreakStatement(IStatement operation)
 {
 }
コード例 #45
0
        private RequestHandlerMockResult BuildRequestHandler(
            IStatement statement,
            Action <TestConfigurationBuilder> configBuilderAct,
            IExecutionProfile profile)
        {
            var cts        = new CancellationTokenSource();
            var connection = Mock.Of <IConnection>();

            // create config
            var configBuilder = new TestConfigurationBuilder
            {
                ConnectionFactory = new FakeConnectionFactory(() => connection),
                Policies          = new Policies(new RoundRobinPolicy(), new ConstantReconnectionPolicy(100), new DefaultRetryPolicy())
            };

            configBuilderAct(configBuilder);
            var config          = configBuilder.Build();
            var initializerMock = Mock.Of <IInitializer>();

            Mock.Get(initializerMock).Setup(i => i.ContactPoints).Returns(new List <IPEndPoint>
            {
                new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042),
                new IPEndPoint(IPAddress.Parse("127.0.0.2"), 9042)
            });
            Mock.Get(initializerMock).Setup(i => i.GetConfiguration()).Returns(config);

            // create cluster
            var cluster = Cluster.BuildFrom(initializerMock, new List <string>());

            config.Policies.LoadBalancingPolicy.Initialize(cluster);

            // create session
            var session = new Session(cluster, config, null, Serializer.Default);

            // create request handler
            var options = profile != null
                ? new RequestOptions(profile, null, config.Policies, config.SocketOptions, config.QueryOptions, config.ClientOptions)
                : config.DefaultRequestOptions;
            var requestHandler = new RequestHandler(
                session,
                new Serializer(ProtocolVersion.V3),
                statement,
                options);

            // create mock result object
            var mockResult = new RequestHandlerMockResult(requestHandler);

            // mock connection send
            Mock.Get(connection)
            .Setup(c => c.Send(It.IsAny <IRequest>(), It.IsAny <Action <Exception, Response> >(), It.IsAny <int>()))
            .Returns <IRequest, Action <Exception, Response>, int>((req, act, timeout) =>
            {
                mockResult.SendResults.Enqueue(new ConnectionSendResult {
                    Request = req, TimeoutMillis = timeout
                });
                Task.Run(async() =>
                {
                    var rp  = (FakeRetryPolicy)(statement.RetryPolicy ?? options.RetryPolicy);
                    var sep = (FakeSpeculativeExecutionPolicy)options.SpeculativeExecutionPolicy;
                    if (Interlocked.Read(ref rp.Count) > 0 && Interlocked.Read(ref sep.Count) > 0)
                    {
                        await Task.Delay(1, cts.Token).ConfigureAwait(false);
                        act(null, new ProxyResultResponse(ResultResponse.ResultResponseKind.Void));
                        cts.Cancel();
                    }
                    else
                    {
                        try
                        {
                            await Task.Delay(10, cts.Token).ConfigureAwait(false);
                        }
                        finally
                        {
                            act(new OverloadedException(string.Empty), null);
                        }
                    }
                });
                return(new OperationState(act)
                {
                    Request = req,
                    TimeoutMillis = timeout
                });
            });
            Mock.Get(connection)
            .SetupGet(c => c.EndPoint)
            .Returns(new ConnectionEndPoint(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042), null));

            return(mockResult);
        }
コード例 #46
0
 public override void VisitEndStatement(IStatement operation)
 {
 }
コード例 #47
0
 public IEnumerable <Host> NewQueryPlan(string keyspace, IStatement query)
 {
     return(_cluster.AllHosts());
 }
コード例 #48
0
 public override void VisitInvalidStatement(IStatement operation)
 {
 }
コード例 #49
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="statement">The statement.</param>
        /// <param name="scope"></param>
        public StaticSql(IScope scope, IStatement statement)
        {
            _statement = statement;

            _dataExchangeFactory = scope.DataExchangeFactory;
        }
コード例 #50
0
        /// <summary>
        /// Parse Inline ParameterMap
        /// </summary>
        /// <param name="statement"></param>
        /// <param name="sqlStatement"></param>
        /// <returns>A new sql command text.</returns>
        /// <param name="scope"></param>
        public SqlText ParseInlineParameterMap(IScope scope, IStatement statement, string sqlStatement)
        {
            string    newSql             = sqlStatement;
            ArrayList mappingList        = new ArrayList();
            Type      parameterClassType = null;

            if (statement != null)
            {
                parameterClassType = statement.ParameterClass;
            }

            StringTokenizer parser       = new StringTokenizer(sqlStatement, PARAMETER_TOKEN, true);
            StringBuilder   newSqlBuffer = new StringBuilder();

            string token     = null;
            string lastToken = null;

            IEnumerator enumerator = parser.GetEnumerator();

            while (enumerator.MoveNext())
            {
                token = (string)enumerator.Current;

                if (PARAMETER_TOKEN.Equals(lastToken))
                {
                    if (PARAMETER_TOKEN.Equals(token))
                    {
                        newSqlBuffer.Append(PARAMETER_TOKEN);
                        token = null;
                    }
                    else
                    {
                        ParameterProperty mapping = null;
                        if (token.IndexOf(PARAM_DELIM) > -1)
                        {
                            mapping = OldParseMapping(token, parameterClassType, scope);
                        }
                        else
                        {
                            mapping = NewParseMapping(token, parameterClassType, scope);
                        }

                        mappingList.Add(mapping);
                        newSqlBuffer.Append("? ");

                        enumerator.MoveNext();
                        token = (string)enumerator.Current;
                        if (!PARAMETER_TOKEN.Equals(token))
                        {
                            throw new DataMapperException("Unterminated inline parameter in mapped statement (" + statement.Id + ").");
                        }
                        token = null;
                    }
                }
                else
                {
                    if (!PARAMETER_TOKEN.Equals(token))
                    {
                        newSqlBuffer.Append(token);
                    }
                }

                lastToken = token;
            }

            newSql = newSqlBuffer.ToString();

            ParameterProperty[] mappingArray = (ParameterProperty[])mappingList.ToArray(typeof(ParameterProperty));

            SqlText sqlText = new SqlText();

            sqlText.Text       = newSql;
            sqlText.Parameters = mappingArray;

            return(sqlText);
        }
コード例 #51
0
        /// <summary>
        /// Add a statement of the form x = f(...) to the MSL.
        /// </summary>
        /// <param name="method">Stores the method to call, the argument variables, and target variable.</param>
        /// <remarks>
        /// If any variable in the statement is an item variable, then we surround the statement with a loop over its range.
        /// Since there may be multiple item variables, and each item may depend on multiple ranges, we may end up with multiple loops.
        /// </remarks>
        private void BuildMethodInvoke(MethodInvoke method)
        {
            if (method.ReturnValue is Variable variable && variable.Inline)
            {
                return;
            }
            // Open containing blocks
            List <IStatementBlock> stBlocks    = method.Containers;
            List <Range>           localRanges = new List <Range>();
            // each argument of method puts a partial order on the ranges.
            // e.g.  array[i,j][k]  requires i < k, j < k  but says nothing about i and j
            // we assemble these constraints into a total order.
            Dictionary <Range, int> indexOfRange = new Dictionary <Range, int>();
            Dictionary <IModelExpression, List <List <Range> > > dict = MethodInvoke.GetRangeBrackets(method.ReturnValueAndArgs());

            foreach (IModelExpression arg in method.ReturnValueAndArgs())
            {
                MethodInvoke.ForEachRange(arg,
                                          delegate(Range r) { if (!localRanges.Contains(r))
                                                              {
                                                                  localRanges.Add(r);
                                                              }
                                          });
            }
            ParameterInfo[] pis = method.method.GetParameters();
            for (int i = 0; i < pis.Length; i++)
            {
                IModelExpression arg = method.Arguments[i];
                ParameterInfo    pi  = pis[i];
                if (pi.IsOut &&
                    arg is HasObservedValue argHasObservedValue &&
                    argHasObservedValue.IsObserved)
                {
                    throw new NotImplementedException(string.Format("Out parameter '{0}' of {1} cannot be observed.  Use ConstrainEqual or observe a copy of the variable.", pi.Name, method));
                }
            }
            foreach (IStatementBlock b in method.Containers)
            {
                if (b is HasRange br)
                {
                    localRanges.Remove(br.Range);
                }
            }
            localRanges.Sort(delegate(Range a, Range b) { return(MethodInvoke.CompareRanges(dict, a, b)); });
            // convert from List<Range> to List<IStatementBlock>
            List <IStatementBlock> localRangeBlocks = new List <IStatementBlock>(localRanges.Select(r => r));

            BuildStatementBlocks(stBlocks, true);
            BuildStatementBlocks(localRangeBlocks, true);

            // Invoke method
            IExpression methodExpr = method.GetExpression();

            foreach (ICompilerAttribute attr in method.attributes)
            {
                Attributes.Add(methodExpr, attr);
            }
            IStatement st = Builder.ExprStatement(methodExpr);

            if (methodExpr is IAssignExpression &&
                method.ReturnValue is HasObservedValue hasObservedValue &&
                hasObservedValue.IsObserved)
            {
                Attributes.Set(st, new Constraint());
            }
            AddStatement(st);

            BuildStatementBlocks(localRangeBlocks, false);
            BuildStatementBlocks(stBlocks, false);
        }
コード例 #52
0
        /// <summary>
        /// Item1 - True, if isExpression returns true
        /// Item2 - If Item1 is true, it contains the type of the alias that is defined in the isExpression
        /// </summary>
        private Tuple <bool, AbstractType> evalIsExpression_EvalSpecToken(IsExpression isExpression, AbstractType typeToCheck, bool DoAliasHandling = false)
        {
            bool         r   = false;
            AbstractType res = null;

            switch (isExpression.TypeSpecializationToken)
            {
            /*
             * To handle semantic tokens like "return" or "super" it's just needed to
             * look into the current resolver context -
             * then, we'll be able to gather either the parent method or the currently scoped class definition.
             */
            case DTokens.Struct:
            case DTokens.Union:
            case DTokens.Class:
            case DTokens.Interface:
                if (r = typeToCheck is UserDefinedType &&
                        ((TemplateIntermediateType)typeToCheck).Definition.ClassType == isExpression.TypeSpecializationToken)
                {
                    res = typeToCheck;
                }
                break;

            case DTokens.Enum:
                if (!(typeToCheck is EnumType))
                {
                    break;
                }
                {
                    var tr = (UserDefinedType)typeToCheck;
                    r   = true;
                    res = tr.Base;
                }
                break;

            case DTokens.Function:
            case DTokens.Delegate:
                if (typeToCheck is DelegateType)
                {
                    var isFun = false;
                    var dgr   = (DelegateType)typeToCheck;
                    if (!dgr.IsFunctionLiteral)
                    {
                        r = isExpression.TypeSpecializationToken == (
                            (isFun = ((DelegateDeclaration)dgr.DeclarationOrExpressionBase).IsFunction) ? DTokens.Function : DTokens.Delegate);
                    }
                    // Must be a delegate otherwise
                    else
                    {
                        isFun = !(r = isExpression.TypeSpecializationToken == DTokens.Delegate);
                    }

                    if (r)
                    {
                        //TODO
                        if (isFun)
                        {
                            // TypeTuple of the function parameter types. For C- and D-style variadic functions, only the non-variadic parameters are included.
                            // For typesafe variadic functions, the ... is ignored.
                        }
                        else
                        {
                            // the function type of the delegate
                        }
                    }
                }
                else                         // Normal functions are also accepted as delegates
                {
                    r = isExpression.TypeSpecializationToken == DTokens.Delegate &&
                        typeToCheck is MemberSymbol &&
                        ((DSymbol)typeToCheck).Definition is DMethod;

                    //TODO: Alias handling, same as couple of lines above
                }
                break;

            case DTokens.Super:                     //TODO: Test this
                var dc = DResolver.SearchClassLikeAt(ctxt.ScopedBlock, isExpression.Location) as DClassLike;

                if (dc != null)
                {
                    var udt = DResolver.ResolveBaseClasses(new ClassType(dc, dc, null), ctxt, true) as ClassType;

                    if (r = udt.Base != null && ResultComparer.IsEqual(typeToCheck, udt.Base))
                    {
                        var l = new List <AbstractType>();
                        if (udt.Base != null)
                        {
                            l.Add(udt.Base);
                        }
                        if (udt.BaseInterfaces != null && udt.BaseInterfaces.Length != 0)
                        {
                            l.AddRange(udt.BaseInterfaces);
                        }

                        res = new DTuple(isExpression, l);
                    }
                }
                break;

            case DTokens.Const:
            case DTokens.Immutable:
            case DTokens.InOut:                     // TODO?
            case DTokens.Shared:
                if (r = typeToCheck.Modifier == isExpression.TypeSpecializationToken)
                {
                    res = typeToCheck;
                }
                break;

            case DTokens.Return:                     // TODO: Test
                IStatement _u = null;
                var        dm = DResolver.SearchBlockAt(ctxt.ScopedBlock, isExpression.Location, out _u) as DMethod;

                if (dm != null)
                {
                    var retType_ = TypeDeclarationResolver.GetMethodReturnType(dm, ctxt);

                    if (r = retType_ != null && ResultComparer.IsEqual(typeToCheck, retType_))
                    {
                        res = retType_;
                    }
                }
                break;
            }

            return(new Tuple <bool, AbstractType>(r, res));
        }
コード例 #53
0
 /// <summary>
 /// Method for comparing this IStatement object to another (using ID)
 /// </summary>
 /// <param name="other">The other IStatement object to compare against.</param>
 /// <returns>The result of the comparison</returns>
 public int CompareTo(IStatement other)
 {
     return(this.ID.CompareTo(other.ID));
 }
コード例 #54
0
        private void UpdatePath(object sender, Mono.TextEditor.DocumentLocationEventArgs e)
        {
            var ast = Document.ParsedDocument as ParsedDModule;

            if (ast == null)
            {
                return;
            }

            var SyntaxTree = ast.DDom;

            if (SyntaxTree == null)
            {
                return;
            }

            // Resolve the hovered piece of code
            var        loc          = new CodeLocation(Document.Editor.Caret.Location.Column, Document.Editor.Caret.Location.Line);
            IStatement stmt         = null;
            var        currentblock = DResolver.SearchBlockAt(SyntaxTree, loc, out stmt) as IBlockNode;

            //could be an enum value, which is not IBlockNode
            if (currentblock is DEnum)
            {
                foreach (INode nd in (currentblock as DEnum).Children)
                {
                    if ((nd is DEnumValue) &&
                        ((nd.Location <= loc) && (nd.EndLocation >= loc)))
                    {
                        currentblock = nd as IBlockNode;
                        break;
                    }
                }
            }

            List <PathEntry> result = new List <PathEntry>();
            INode            node   = currentblock;

            while ((node != null) && ((node is IBlockNode) || (node is DEnumValue)))
            {
                PathEntry entry;

                var icon = DCompletionData.GetNodeIcon(node as DNode);

                entry          = new PathEntry(icon.IsNull?null: ImageService.GetPixbuf(icon.Name, IconSize.Menu), node.Name + DParameterDataProvider.GetNodeParamString(node));
                entry.Position = EntryPosition.Left;
                entry.Tag      = node;
                //do not include the module in the path bar
                if ((node.Parent != null) && !((node is DNode) && (node as DNode).IsAnonymous))
                {
                    result.Insert(0, entry);
                }
                node = node.Parent;
            }

            if (!((currentblock is DMethod) || (currentblock is DEnumValue)))
            {
                PathEntry noSelection = new PathEntry(GettextCatalog.GetString("No Selection"))
                {
                    Tag = new NoSelectionCustomNode(currentblock)
                };
                result.Add(noSelection);
            }

            var prev = CurrentPath;

            CurrentPath = result.ToArray();
            OnPathChanged(new DocumentPathChangedEventArgs(prev));
        }
コード例 #55
0
 public virtual void CloseStatement(IStatement istmt)
 {
     Close(istmt);
     CloseOutput(istmt);
 }
コード例 #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SelectMappedStatement"/> class.
 /// </summary>
 /// <param name="modelStore">The model store.</param>
 /// <param name="statement">The statement.</param>
 public SelectMappedStatement(IModelStore modelStore, IStatement statement)
     : base(modelStore, statement)
 {
 }
コード例 #57
0
 public RetryDecision OnUnavailable(IStatement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry)
 {
     return(RetryDecision.Rethrow());
 }
コード例 #58
0
 public RetryDecision OnWriteTimeout(IStatement query, ConsistencyLevel cl, string writeType, int requiredAcks, int receivedAcks,
                                     int nbRetry)
 {
     Interlocked.Increment(ref WriteTimeoutCounter);
     return(RetryDecision.Rethrow());
 }
コード例 #59
0
 public RetryDecision OnUnavailable(IStatement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry)
 {
     Interlocked.Increment(ref UnavailableCounter);
     return(RetryDecision.Rethrow());
 }
コード例 #60
0
 public RetryDecision OnWriteTimeout(IStatement query, ConsistencyLevel cl, string writeType, int requiredAcks, int receivedAcks, int nbRetry)
 {
     return(RetryDecision.Rethrow());
 }