Пример #1
0
        public static IStatementFormatter GetFormatter(IIndentable indentable, StringBuilder outSql, IStatement statement)
        {
            Type formatterType;

            if (!_formatters.TryGetValue(statement.GetType(), out formatterType))
            {
                throw new FormatterNotImplementedException(
                          "Formatter not implemented for statement: " + statement.GetType().Name
                          );
            }

            var formatter = Activator.CreateInstance(
                formatterType,
                indentable,
                outSql,
                statement
                ) as IStatementFormatter;

            if (formatter == null)
            {
                throw new ArgumentNullException("Formatter not instantiated: " + formatterType.Name);
            }

            return(formatter);
        }
Пример #2
0
 private static void ThrowUnknownStatement(IStatement state)
 {
     System.Text.StringBuilder build = new System.Text.StringBuilder();
     build.Append("未知の Statement です。\r\n");
     build.Append("----------------------------\r\n型\r\n");
     build.Append(state.GetType());
     build.Append("\r\n----------------------------\r\nインターフェイス\r\n");
     foreach (System.Type t in state.GetType().GetInterfaces())
     {
         build.Append(t);
     }
     throw new System.Exception(build.ToString());
 }
        public static void WriteStatement(Context context, IStatement statement)
        {
            if (statement is IExpression)
            {
                WriteExpression(context, (IExpression)statement);
            }
            else if (statement is ReturnStatement)
            {
                WriteReturnStatement(context, (ReturnStatement)statement);
            }
            else if (statement is IfStatement)
            {
                WriteIfStatement(context, (IfStatement)statement);
            }
            else if (statement is VariableDeclaration)
            {
                WriteVariableDeclaration(context, (VariableDeclaration)statement);
            }
            else
            {
                throw new NotImplementedException($"Unknown statement type: {statement.GetType().Name}");
            }

            Write(context, ';');
        }
Пример #4
0
 public virtual StatementViewModel CreateStatementByInstance(IStatement statement, ILanguage language)
 {
     if (statement is Set.Statements.HasPartStatement)
     {
         return(new HasPartStatement(statement as Set.Statements.HasPartStatement, language));
     }
     else if (statement is Set.Statements.GroupStatement)
     {
         return(new GroupStatement(statement as Set.Statements.GroupStatement, language));
     }
     else if (statement is Set.Statements.HasSignStatement)
     {
         return(new HasSignStatement(statement as Set.Statements.HasSignStatement, language));
     }
     else if (statement is Modules.Classification.Statements.IsStatement)
     {
         return(new IsStatement(statement as Modules.Classification.Statements.IsStatement, language));
     }
     else if (statement is Set.Statements.SignValueStatement)
     {
         return(new SignValueStatement(statement as Set.Statements.SignValueStatement, language));
     }
     else if (statement is Mathematics.Statements.ComparisonStatement)
     {
         return(new ComparisonStatement(statement as Mathematics.Statements.ComparisonStatement, language));
     }
     else if (statement is Processes.Statements.ProcessesStatement)
     {
         return(new ProcessesStatement(statement as Processes.Statements.ProcessesStatement, language));
     }
     else
     {
         throw new NotSupportedException(statement.GetType().FullName);
     }
 }
        /// <summary>
        /// Can we combine? Yes, if and only if the same guy and same variables!
        /// </summary>
        /// <param name="statement"></param>
        /// <param name="optimize"></param>
        /// <returns></returns>
        public bool TryCombineStatement(IStatement statement, ICodeOptimizationService optimize)
        {
            if (statement.GetType() != typeof(StatementRecordPairValues))
            {
                return(false);
            }
            var other = statement as StatementRecordPairValues;

            if (other._index.RawValue != _index.RawValue)
            {
                return(false);
            }

            var isTheSame = _savers.Zip(other._savers, (f, s) => f.indexValue.RawValue == s.indexValue.RawValue && f.mapRecord.Type == s.mapRecord.Type).All(b => b);

            if (!isTheSame)
            {
                return(false);
            }

            // Now we can do them all.
            foreach (var saver in _savers.Zip(other._savers, (f, s) => Tuple.Create(f, s)))
            {
                optimize.TryRenameVarialbeOneLevelUp(saver.Item2.mapRecord.RawValue, saver.Item1.mapRecord);
            }

            return(true);
        }
Пример #6
0
        /// <summary>
        /// Gets the Request to send to a cassandra node based on the statement type
        /// </summary>
        internal IRequest GetRequest(IStatement statement)
        {
            var defaultConsistency = Configuration.QueryOptions.GetConsistencyLevel();

            if (statement is RegularStatement)
            {
                var s       = (RegularStatement)statement;
                var options = QueryProtocolOptions.CreateFromQuery(s, defaultConsistency);
                options.ValueNames = s.QueryValueNames;
                return(new QueryRequest(BinaryProtocolVersion, s.QueryString, s.IsTracing, options));
            }
            if (statement is BoundStatement)
            {
                var s       = (BoundStatement)statement;
                var options = QueryProtocolOptions.CreateFromQuery(s, defaultConsistency);
                return(new ExecuteRequest(BinaryProtocolVersion, s.PreparedStatement.Id, null, s.IsTracing, options));
            }
            if (statement is BatchStatement)
            {
                var s           = (BatchStatement)statement;
                var consistency = defaultConsistency;
                if (s.ConsistencyLevel != null)
                {
                    consistency = s.ConsistencyLevel.Value;
                }
                return(new BatchRequest(BinaryProtocolVersion, s, consistency));
            }
            throw new NotSupportedException("Statement of type " + statement.GetType().FullName + " not supported");
        }
Пример #7
0
        private static bool TestLetStatement(IStatement statement, string name)
        {
            if (statement.TokenLiteral() != "let")
            {
                Console.WriteLine("Expected 'len', but got {0}", statement.TokenLiteral());
                return false;
            }

            var letStatement = statement.GetType();

            if (letStatement != typeof(LetStatement))
            {
                Console.WriteLine("Expected 'LetStatement', but got {0}", letStatement);
                return false;
            }

            if (statement.Name.StringValue != name)
            {
                Console.WriteLine("Expected {0}, but got {1}", statement.Name.StringValue, name);
                return false;
            }

            if (statement.Name.TokenLiteral() != name)
            {
                Console.WriteLine("Expected {0}, but got {1}", statement.Name, name);
                return false;
            }

            return true;
        }
Пример #8
0
        protected virtual void VisitStatement(IStatement statement)
        {
            if (!StatementVisitors.ContainsKey(statement.GetType()))
            {
                throw new NotImplementedException("Statement " + statement.GetType().Name + " is not implemented");
            }

            StatementVisitors[statement.GetType()](this, statement);

            if (statement is Token)
            {
                var token = (Token)statement;
                State.Parameters.AddRange(token.Parameters);
                State.ParameterValues.AddRange(token.ParameterValues);
            }
        }
Пример #9
0
 private void WriteUnsupported(IStatement value)
 {
     _formatter.WriteLiteral("# Unsupported statement " + value.GetType().Name + ":");
     _formatter.WriteLine();
     _formatter.WriteLiteral("#" + value.ToString());
     _formatter.WriteLine();
 }
Пример #10
0
 protected override IStatement DoConvertStatement(IStatement ist)
 {
     if ((ist is IForStatement) || (ist is IExpressionStatement) || (ist is IBlockStatement) || (ist is IConditionStatement))
     {
         return(base.DoConvertStatement(ist));
     }
     Error("Unsupported statement type: " + ist.GetType().Name);
     return(ist);
 }
Пример #11
0
        public static IStatementFormatter GetFormatter( IIndentable indentable, StringBuilder outSql, IStatement statement )
        {
            Type formatterType;
            if ( !_formatters.TryGetValue( statement.GetType(), out formatterType ) )
                throw new FormatterNotImplementedException(
                    "Formatter not implemented for statement: " + statement.GetType().Name
                );

            var formatter = Activator.CreateInstance(
                formatterType,
                indentable,
                outSql,
                statement
            ) as IStatementFormatter;

            if ( formatter == null )
                throw new ArgumentNullException( "Formatter not instantiated: " + formatterType.Name );

            return formatter;
        }
Пример #12
0
        private void TestLetStatement(IStatement s, string name)
        {
            Assert.AreEqual("let", s.TokenLiteral, $"s.TokenLiteral is not 'let'. got={s.TokenLiteral}");

            var letStmnt = s as LetStatement;

            Assert.IsNotNull(letStmnt, $"s is not LetStatement. got={s.GetType().Name}");

            Assert.AreEqual(name, letStmnt.Name.Value, $"letStmt.Name.Value not '{name}'. got={letStmnt.Name.Value}");

            Assert.AreEqual(name, letStmnt.Name.TokenLiteral, $"s.Name not '{name}'. got={letStmnt.Name}");
        }
Пример #13
0
        /// <summary>
        /// Gets the Request to send to a cassandra node based on the statement type
        /// </summary>
        internal static IRequest GetRequest(IStatement statement, ISerializer serializer, IRequestOptions requestOptions)
        {
            ICqlRequest request = null;

            if (statement.IsIdempotent == null)
            {
                statement.SetIdempotence(requestOptions.DefaultIdempotence);
            }

            if (statement is RegularStatement s1)
            {
                s1.Serializer = serializer;
                var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s1, requestOptions, null);
                options.ValueNames = s1.QueryValueNames;
                request            = new QueryRequest(serializer, s1.QueryString, options, s1.IsTracing, s1.OutgoingPayload);
            }

            if (statement is BoundStatement s2)
            {
                // set skip metadata only when result metadata id is supported because of CASSANDRA-10786
                var skipMetadata =
                    serializer.ProtocolVersion.SupportsResultMetadataId() &&
                    s2.PreparedStatement.ResultMetadata.ContainsColumnDefinitions();

                var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s2, requestOptions, skipMetadata);
                request = new ExecuteRequest(
                    serializer,
                    s2.PreparedStatement.Id,
                    null,
                    s2.PreparedStatement.ResultMetadata,
                    options,
                    s2.IsTracing,
                    s2.OutgoingPayload);
            }

            if (statement is BatchStatement s)
            {
                s.Serializer = serializer;
                var consistency = requestOptions.ConsistencyLevel;
                if (s.ConsistencyLevel.HasValue)
                {
                    consistency = s.ConsistencyLevel.Value;
                }
                request = new BatchRequest(serializer, s.OutgoingPayload, s, consistency, requestOptions);
            }

            if (request == null)
            {
                throw new NotSupportedException("Statement of type " + statement.GetType().FullName + " not supported");
            }
            return(request);
        }
Пример #14
0
        private static StatementType GetExpressionType(IStatement statement)
        {
            System.Type   t = statement.GetType();
            StatementType ret;

            if (state_types.TryGetValue(statement.GetType(), out ret))
            {
                return(ret);
            }

            System.Type[] interfaces = t.GetInterfaces();
            for (int i = 0, iM = interfaces.Length; i < iM; i++)
            {
                if (state_types.TryGetValue(interfaces[i], out ret))
                {
                    state_types[t] = ret;                   // 覚えて置く
                    return(ret);
                }
            }

            return(StatementType.Unknown);
        }
Пример #15
0
 protected string StatementLabel(IStatement ist)
 {
     if (ist is IExpressionStatement)
     {
         IExpressionStatement ies = (IExpressionStatement)ist;
         string s;
         if (ies.Expression is IAssignExpression)
         {
             s = ExpressionToString(((IAssignExpression)ies.Expression).Target);
         }
         else
         {
             s = ExpressionToString(ies.Expression);
         }
         if (s.StartsWith("this."))
         {
             s = s.Substring(5);
         }
         //if (s.EndsWith("[0]")) s = s.Substring(0, s.Length - 3);
         return(s);
     }
     if (ist is IForStatement)
     {
         return(StatementLabel(((IForStatement)ist).Body.Statements[0]));
     }
     if (ist is IConditionStatement)
     {
         return(String.Format("if ({0}) {1}", ((IConditionStatement)ist).Condition.ToString(),
                              StatementLabel(((IConditionStatement)ist).Then)));
     }
     if (ist is IBlockStatement)
     {
         int    blockSize = ((IBlockStatement)ist).Statements.Count;
         string s;
         if (blockSize > 0)
         {
             s = StatementLabel(((IBlockStatement)ist).Statements[0]);
         }
         else
         {
             s = "EmptyBlock";
         }
         if (blockSize > 1)
         {
             s += " ...";
         }
         return(s);
     }
     return(ist.GetType().Name);
 }
        public override void TraverseChildren(IStatement statement)
        {
            log.WriteTrace("Traversing {0} statement.", statement.GetType().Name);

            var statementVisitor = new NewObjStatementVisitor(statement, log, registry);
            statementVisitor.Traverse(statement);

            var fieldReferenceVisitor = new FieldReferenceVisitor(statement, log, registry);
            fieldReferenceVisitor.Traverse(statement);

            var fieldAssignmentVisitor = new FieldAssignmentVisitor(statement, log, registry);
            fieldAssignmentVisitor.Traverse(statement);

            base.TraverseChildren(statement);
        }
Пример #17
0
        public IPhpStatement[] TranslateStatement(IStatement x)
        {
            if (!(x is CSharpBase))
            {
                throw new Exception("Błąd translacji " + x.GetType().FullName);
            }
            var op = new OptimizeOptions();

            var s      = new PhpStatementSimplifier(op);
            var a      = new PhpStatementTranslatorVisitor(_state);
            var tmp    = a.Visit(x as CSharpBase);
            var result = new List <IPhpStatement>(tmp.Length);

            result.AddRange(tmp.Select(i => s.Visit(i as PhpSourceBase)));
            return(result.ToArray());
        }
        public void TestTryCombine([PexAssumeUnderTest]StatementForLoop target, IStatement s)
        {
            /// We should never be able to combine any filter statements currently!

            var val = new Variables.ValSimple("true", typeof(bool));
            var result = target.TryCombineStatement(s, null);

            if (s.GetType() != typeof(StatementForLoop))
            {
                Assert.IsFalse(result, "Types not right");
            }
            else
            {
                var other = s as StatementForLoop;
                Assert.AreEqual(other.ArrayLength == target.ArrayLength, result, "for loops not conssitent");
            }
        }
Пример #19
0
        public void TestTryCombine([PexAssumeUnderTest] StatementForLoop target, IStatement s)
        {
            /// We should never be able to combine any filter statements currently!

            var val    = new Variables.ValSimple("true", typeof(bool));
            var result = target.TryCombineStatement(s, null);

            if (s.GetType() != typeof(StatementForLoop))
            {
                Assert.IsFalse(result, "Types not right");
            }
            else
            {
                var other = s as StatementForLoop;
                Assert.AreEqual(other.ArrayLength == target.ArrayLength, result, "for loops not conssitent");
            }
        }
Пример #20
0
        public void GenerateStatement(IStatement statement, ILGenerator ilGenerator)
        {
            switch (statement)
            {
            case VariableAssignment variableAssignment:
                GenerateVarAssignment(variableAssignment, ilGenerator);
                break;

            case ArrayElementAssignment arrayElementAssignment:
                GenerateArrayElementAssignment(arrayElementAssignment, ilGenerator);
                break;

            case VariableDeclaration declaration:
                GenerateDeclaration(declaration, ilGenerator);
                break;

            case FunctionCall functionCall:
                GenerateFuncCall(functionCall, ilGenerator);
                break;

            case ReturnStatement returnStatement:
                GenerateReturnStatement(returnStatement, ilGenerator);
                break;

            case WhileStatement whileStatement:
                GenerateWhileStatement(whileStatement, ilGenerator);
                break;

            case IfStatement ifStatement:
                GenerateIfStatement(ifStatement, ilGenerator);
                break;

            case ForStatement forStatement:
                GenerateForStatement(forStatement, ilGenerator);
                break;

            case BlockStatement blockStatement:
                GenerateBlockStatement(blockStatement, ilGenerator);
                break;

            default:
                throw new NotImplementedException($"Cannot Generate statement: {statement.GetType()}");
            }
        }
Пример #21
0
        private static void Process(this IStatement statement)
        {
            switch (statement)
            {
            case VariableAssignment variableAssignment:
                variableAssignment.Process();
                break;

            case ArrayElementAssignment arrayElementAssignment:
                arrayElementAssignment.Process();
                break;

            case VariableDeclaration declaration:
                declaration.Process();
                break;

            case FunctionCall functionCall:
                functionCall.Process();
                break;

            case ReturnStatement returnStatement:
                returnStatement.Process();
                break;

            case WhileStatement whileStatement:
                whileStatement.Process();
                break;

            case IfStatement ifStatement:
                ifStatement.Process();
                break;

            case ForStatement forStatement:
                forStatement.Process();
                break;

            case BlockStatement blockStatement:
                blockStatement.Process();
                break;

            default:
                throw new NotImplementedException($"Statements process: {statement.GetType()}");
            }
        }
Пример #22
0
        public IPlatformStatementTranspiler GetTranspilerForStatement(IStatement statement)
        {
            var sttType = statement.GetType();

            if (_typeTranspilers.TryGetValue(sttType, out var value))
            {
                return(value);
            }

            if (_fallbackType.TryGetValue(sttType, out sttType))
            {
                if (_typeTranspilers.TryGetValue(sttType, out value))
                {
                    return(value);
                }
            }

            throw new InvalidOperationException();
        }
Пример #23
0
 private static IExpression GetContainerExpression(IStatement container)
 {
     if (container is IForStatement ifs)
     {
         return(Recognizer.LoopSizeExpression(ifs));
     }
     else if (container is IConditionStatement ics)
     {
         return(ics.Condition);
     }
     else if (container is IRepeatStatement irs)
     {
         return(irs.Count);
     }
     else
     {
         throw new ArgumentException($"unrecognized container type: {container.GetType()}");
     }
 }
Пример #24
0
        public Task ExecuteStatement(IStatement stat, LuaState state, CancellationToken token = default)
        {
            if (state.FunctionState.DidReturn || token.IsCancellationRequested)
            {
                return(Task.CompletedTask);
            }

            switch (stat)
            {
            case Assignment assignment:
                return(_statementInterpreter.ExecuteAssignment(assignment, state, token));

            case LocalAssignment localAssignment:
                return(_statementInterpreter.ExecuteLocalAssignment(localAssignment, state, token));

            case FunctionCall call:
                return(_statementInterpreter.ExecuteFunctionCall(call, state, token));

            case Block block:
                return(_statementInterpreter.ExecuteBlock(block, state, token));

            case IfStat ifStat:
                return(_statementInterpreter.ExecuteIfStat(ifStat, state, token));

            case ReturnStat returnStat:
                return(_statementInterpreter.ExecuteReturnStat(returnStat, state, token));

            case WhileStat whileStat:
                return(_statementInterpreter.ExecuteWhileStat(whileStat, state, token));

            case RepeatStat repeatStat:
                return(_statementInterpreter.ExecuteRepeatStat(repeatStat, state, token));

            case GenericFor genericFor:
                return(_statementInterpreter.ExecuteGenericFor(genericFor, state, token));

            case NumericFor numericFor:
                return(_statementInterpreter.ExecuteNumericFor(numericFor, state, token));

            default:
                throw new NotImplementedException(stat.GetType().Name);
            }
        }
Пример #25
0
        public IPyStatement[] TranslateStatement([NotNull] IStatement x)
        {
            if (x == null)
            {
                throw new ArgumentNullException(nameof(x));
            }
            if (!(x is CSharpBase))
            {
                throw new Exception($"Translation error: {x.GetType().FullName} is not CSharpBase instance");
            }
            var op = new OptimizeOptions();

            var s      = new PyStatementSimplifier(op);
            var a      = new PyStatementTranslatorVisitor(_state);
            var tmp    = a.Visit(x as CSharpBase);
            var result = new List <IPyStatement>(tmp.Length);

            result.AddRange(tmp.Select(i => s.Visit(i as PySourceBase)));
            return(result.ToArray());
        }
        /// <summary>
        /// Gets the Request to send to a cassandra node based on the statement type
        /// </summary>
        internal static IRequest GetRequest(IStatement statement, Serializer serializer, Configuration config)
        {
            ICqlRequest request = null;

            if (statement.IsIdempotent == null)
            {
                statement.SetIdempotence(config.QueryOptions.GetDefaultIdempotence());
            }
            if (statement is RegularStatement)
            {
                var s = (RegularStatement)statement;
                s.Serializer = serializer;
                var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s, config.QueryOptions, config.Policies);
                options.ValueNames = s.QueryValueNames;
                request            = new QueryRequest(serializer.ProtocolVersion, s.QueryString, s.IsTracing, options);
            }
            if (statement is BoundStatement)
            {
                var s       = (BoundStatement)statement;
                var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s, config.QueryOptions, config.Policies);
                request = new ExecuteRequest(serializer.ProtocolVersion, s.PreparedStatement.Id, null, s.IsTracing, options);
            }
            if (statement is BatchStatement)
            {
                var s = (BatchStatement)statement;
                s.Serializer = serializer;
                var consistency = config.QueryOptions.GetConsistencyLevel();
                if (s.ConsistencyLevel != null)
                {
                    consistency = s.ConsistencyLevel.Value;
                }
                request = new BatchRequest(serializer.ProtocolVersion, s, consistency);
            }
            if (request == null)
            {
                throw new NotSupportedException("Statement of type " + statement.GetType().FullName + " not supported");
            }
            //Set the outgoing payload for the request
            request.Payload = statement.OutgoingPayload;
            return(request);
        }
Пример #27
0
		public virtual string GetSql (IStatement statement)
		{
			if (statement == null)
				throw new ArgumentNullException ("statement");
			
			Type type = statement.GetType ();
			if (type == typeof (SelectStatement))
				return GetStatementSql (statement as SelectStatement);
			else if (type == typeof (InsertStatement))
				return GetStatementSql (statement as InsertStatement);	
			else if (type == typeof (UpdateStatement))
				return GetStatementSql (statement as UpdateStatement);
			else if (type == typeof (DeleteStatement))
				return GetStatementSql (statement as DeleteStatement);
			else if (type == typeof (DropStatement))
				return GetStatementSql (statement as DropStatement);		
			else if (type == typeof (TruncateStatement))
				return GetStatementSql (statement as TruncateStatement);
			else
				throw new NotImplementedException (type.FullName);
		}
Пример #28
0
        /// <summary>
        /// Gets the Request to send to a cassandra node based on the statement type
        /// </summary>
        internal static IRequest GetRequest(IStatement statement, ISerializer serializer, IRequestOptions requestOptions)
        {
            ICqlRequest request = null;

            if (statement.IsIdempotent == null)
            {
                statement.SetIdempotence(requestOptions.DefaultIdempotence);
            }
            if (statement is RegularStatement s1)
            {
                s1.Serializer = serializer;
                var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s1, requestOptions);
                options.ValueNames = s1.QueryValueNames;
                request            = new QueryRequest(serializer.ProtocolVersion, s1.QueryString, s1.IsTracing, options);
            }
            if (statement is BoundStatement s2)
            {
                var options = QueryProtocolOptions.CreateFromQuery(serializer.ProtocolVersion, s2, requestOptions);
                request = new ExecuteRequest(serializer.ProtocolVersion, s2.PreparedStatement.Id, null,
                                             s2.PreparedStatement.ResultMetadataId, s2.IsTracing, options);
            }
            if (statement is BatchStatement s)
            {
                s.Serializer = serializer;
                var consistency = requestOptions.ConsistencyLevel;
                if (s.ConsistencyLevel.HasValue)
                {
                    consistency = s.ConsistencyLevel.Value;
                }
                request = new BatchRequest(serializer.ProtocolVersion, s, consistency, requestOptions);
            }
            if (request == null)
            {
                throw new NotSupportedException("Statement of type " + statement.GetType().FullName + " not supported");
            }
            //Set the outgoing payload for the request
            request.Payload = statement.OutgoingPayload;
            return(request);
        }
Пример #29
0
        public virtual string GetSql(IStatement statement)
        {
            if (statement == null)
            {
                throw new ArgumentNullException("statement");
            }

            Type type = statement.GetType();

            if (type == typeof(SelectStatement))
            {
                return(GetStatementSql(statement as SelectStatement));
            }
            else if (type == typeof(InsertStatement))
            {
                return(GetStatementSql(statement as InsertStatement));
            }
            else if (type == typeof(UpdateStatement))
            {
                return(GetStatementSql(statement as UpdateStatement));
            }
            else if (type == typeof(DeleteStatement))
            {
                return(GetStatementSql(statement as DeleteStatement));
            }
            else if (type == typeof(DropStatement))
            {
                return(GetStatementSql(statement as DropStatement));
            }
            else if (type == typeof(TruncateStatement))
            {
                return(GetStatementSql(statement as TruncateStatement));
            }
            else
            {
                throw new NotImplementedException(type.FullName);
            }
        }
Пример #30
0
        /// <inheritdoc />
        public IAsyncResult BeginExecute(IStatement statement, object tag, AsyncCallback callback, object state)
        {
            if (statement == null)
            {
                throw new ArgumentNullException("statement");
            }
            var options     = Cluster.Configuration.QueryOptions;
            var consistency = statement.ConsistencyLevel ?? options.GetConsistencyLevel();

            if (statement is RegularStatement)
            {
                return(BeginQuery((RegularStatement)statement, callback, state, tag));
            }
            if (statement is BoundStatement)
            {
                return(BeginExecuteQuery((BoundStatement)statement, callback, state, tag));
            }
            if (statement is BatchStatement)
            {
                return(BeginBatch((BatchStatement)statement, callback, state, tag));
            }
            throw new NotSupportedException("Statement of type " + statement.GetType().FullName + " not supported");
        }
Пример #31
0
        void WriteStatement(IStatement stmt)
        {
            switch (stmt)
            {
            case IInsertStatement insertStmt:
                WriteInsertStatement(insertStmt);
                break;

            case IInsertSelectStatement insertSelectStmt:
                WriteInsertSelectStatement(insertSelectStmt);
                break;

            case ISelectStatement selectStmt:
                WriteSelectStatement(selectStmt);
                break;

            case IUpdateStatement updateStmt:
                WriteUpdateStatement(updateStmt);
                break;

            case IDeleteStatement deleteStmt:
                WriteDeleteStatement(deleteStmt);
                break;

            case IDeclareVariableStatement declareStmt:
                WriteDeclareSqlVariable(declareStmt);
                break;

            case ISetVariableStatement setStmt:
                WriteSetSqlVariable(setStmt);
                break;

            default:
                throw new Exception("Unsupported statement " + stmt.GetType().Name);
            }
        }
Пример #32
0
 // Modifies affectingVariables.
 internal static bool ContainerAffectsVariables(IStatement container, Set <IVariableDeclaration> affectingVariables)
 {
     if (container is IForStatement)
     {
         IForStatement ifs2 = (IForStatement)container;
         if (affectingVariables.Contains(Recognizer.LoopVariable(ifs2)))
         {
             // all variables in the loop bounds become affecting variables.
             affectingVariables.AddRange(
                 Recognizer.GetVariables(Recognizer.LoopStartExpression(ifs2)).Concat(
                     Recognizer.GetVariables(ifs2.Condition)
                     ));
             return(true);
         }
         return(false);
     }
     else if (container is IConditionStatement)
     {
         IConditionStatement ics = (IConditionStatement)container;
         // if the condition refers to an affecting variable, then it is a parent.
         bool isParent = Recognizer.GetVariables(ics.Condition).Any(affectingVariables.Contains);
         if (isParent)
         {
             // all variables in the condition become affecting variables,
             // since they change the outcome of the condition and therefore the bounds of ifs.
             affectingVariables.AddRange(Recognizer.GetVariables(ics.Condition));
             return(true);
         }
         return(false);
     }
     else
     {
         throw new NotImplementedException($"Unrecognized container type: {StringUtil.TypeToString(container.GetType())}");
     }
 }
Пример #33
0
        public IPhpStatement[] TranslateStatement(IStatement x)
        {
            if (!(x is CSharpBase)) throw new Exception("Błąd translacji " + x.GetType().FullName);
            var op = new OptimizeOptions();

            var s = new StatementSimplifier(op);
            var a = new StatementTranslatorVisitor(_state);
            var tmp = a.Visit(x as CSharpBase);
            var result = new List<IPhpStatement>(tmp.Length);
            result.AddRange(tmp.Select(i => s.Visit(i as PhpSourceBase)));
            return result.ToArray();
        }
Пример #34
0
//
//        public InvalidStatementStructureCompilerException(string message)
//            : base(message)
//        {
//        }
//
//        public InvalidStatementStructureCompilerException(string message, Exception innerException) : base(message, innerException)
//        {
//        }
//
//        public InvalidStatementStructureCompilerException(Exception innerException) : base(innerException)
//        {
//        }

        public static string CreateMessage(IStatement statement, StatementInfo info)
        {
            return
                ($"Invalid statement of type '{statement?.GetType().Name}' was found {info}");
        }
            private void WriteStatement(IStatement value, IFormatter formatter, bool lastStatement)
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                if (value is IBlockStatement)
                {
                    this.WriteBlockStatement(value as IBlockStatement, formatter);
                    return;
                }

                if (value is IExpressionStatement)
                {
                    this.WriteExpressionStatement(value as IExpressionStatement, formatter);
                    return;
                }

                if (value is IGotoStatement)
                {
                    this.WriteGotoStatement(value as IGotoStatement, formatter);
                    return;
                }

                if (value is ILabeledStatement)
                {
                    this.WriteLabeledStatement(value as ILabeledStatement, formatter);
                    return;
                }

                if (value is IConditionStatement)
                {
                    this.WriteConditionStatement(value as IConditionStatement, formatter);
                    return;
                }

                if (value is IMethodReturnStatement)
                {
                    this.WriteMethodReturnStatement(value as IMethodReturnStatement, formatter, lastStatement);
                    return;
                }

                if (value is IForStatement)
                {
                    this.WriteForStatement(value as IForStatement, formatter);
                    return;
                }

                if (value is IForEachStatement)
                {
                    this.WriteForEachStatement(value as IForEachStatement, formatter);
                    return;
                }

                if (value is IUsingStatement)
                {
                    this.WriteUsingStatement(value as IUsingStatement, formatter);
                    return;
                }

                if (value is IFixedStatement)
                {
                    this.WriteFixedStatement(value as IFixedStatement, formatter);
                    return;
                }

                if (value is IWhileStatement)
                {
                    this.WriteWhileStatement(value as IWhileStatement, formatter);
                    return;
                }

                if (value is IDoStatement)
                {
                    this.WriteDoStatement(value as IDoStatement, formatter);
                    return;
                }

                if (value is ITryCatchFinallyStatement)
                {
                    this.WriteTryCatchFinallyStatement(value as ITryCatchFinallyStatement, formatter);
                    return;
                }

                if (value is IThrowExceptionStatement)
                {
                    this.WriteThrowExceptionStatement(value as IThrowExceptionStatement, formatter);
                    return;
                }

                if (value is IAttachEventStatement)
                {
                    this.WriteAttachEventStatement(value as IAttachEventStatement, formatter);
                    return;
                }

                if (value is IRemoveEventStatement)
                {
                    this.WriteRemoveEventStatement(value as IRemoveEventStatement, formatter);
                    return;
                }

                if (value is ISwitchStatement)
                {
                    this.WriteSwitchStatement(value as ISwitchStatement, formatter);
                    return;
                }

                if (value is IBreakStatement)
                {
                    this.WriteBreakStatement(value as IBreakStatement, formatter);
                    return;
                }

                if (value is IContinueStatement)
                {
                    this.WriteContinueStatement(value as IContinueStatement, formatter);
                    return;
                }

                if (value is IMemoryCopyStatement)
                {
                    this.WriteMemoryCopyStatement(value as IMemoryCopyStatement, formatter);
                    return;
                }

                if (value is IMemoryInitializeStatement)
                {
                    this.WriteMemoryInitializeStatement(value as IMemoryInitializeStatement, formatter);
                    return;
                }

                if (value is IDebugBreakStatement)
                {
                    this.WriteDebugBreakStatement(value as IDebugBreakStatement, formatter);
                    return;
                }

                if (value is ILockStatement)
                {
                    this.WriteLockStatement(value as ILockStatement, formatter);
                    return;
                }

                if (value is ICommentStatement)
                {
                    this.WriteCommentStatement(value as ICommentStatement, formatter);
                    return;
                }

                throw new ArgumentException("Invalid statement type `" + value.GetType() + "`.", "value");
            }
Пример #36
0
 /// <summary>
 /// Gets the Request to send to a cassandra node based on the statement type
 /// </summary>
 internal IRequest GetRequest(IStatement statement)
 {
     var defaultConsistency = Configuration.QueryOptions.GetConsistencyLevel();
     if (statement is RegularStatement)
     {
         var s = (RegularStatement)statement;
         var options = QueryProtocolOptions.CreateFromQuery(s, defaultConsistency);
         options.ValueNames = s.QueryValueNames;
         return new QueryRequest(BinaryProtocolVersion, s.QueryString, s.IsTracing, options);
     }
     if (statement is BoundStatement)
     {
         var s = (BoundStatement)statement;
         var options = QueryProtocolOptions.CreateFromQuery(s, defaultConsistency);
         return new ExecuteRequest(BinaryProtocolVersion, s.PreparedStatement.Id, null, s.IsTracing, options);
     }
     if (statement is BatchStatement)
     {
         var s = (BatchStatement)statement;
         var consistency = defaultConsistency;
         if (s.ConsistencyLevel != null)
         {
             consistency = s.ConsistencyLevel.Value;
         }
         return new BatchRequest(BinaryProtocolVersion, s, consistency);
     }
     throw new NotSupportedException("Statement of type " + statement.GetType().FullName + " not supported");
 }
Пример #37
0
        public virtual void VisitStatement(IStatement value)
        {
            if (value == null)
            {
                return;
            }

            // Performance: This method gets called often and needs to run fast.
            // 216988 ExpressionStatement
            // 123584 BlockStatement
            //  41587 ConditionStatement
            //  25567 MethodReturnStatement
            //  15264 LabeledStatement
            //  13260 GotoStatement

            if (value is IExpressionStatement)
            {
                this.VisitExpressionStatement(value as IExpressionStatement);
                return;
            }

            if (value is IBlockStatement)
            {
                this.VisitBlockStatement(value as IBlockStatement);
                return;
            }

            if (value is IConditionStatement)
            {
                this.VisitConditionStatement(value as IConditionStatement);
                return;
            }

            if (value is IMethodReturnStatement)
            {
                this.VisitMethodReturnStatement(value as IMethodReturnStatement);
                return;
            }

            if (value is ILabeledStatement)
            {
                this.VisitLabeledStatement(value as ILabeledStatement);
                return;
            }

            if (value is IGotoStatement)
            {
                this.VisitGotoStatement(value as IGotoStatement);
                return;
            }

            if (value is IForStatement)
            {
                this.VisitForStatement(value as IForStatement);
                return;
            }

            if (value is IForEachStatement)
            {
                this.VisitForEachStatement(value as IForEachStatement);
                return;
            }

            if (value is IWhileStatement)
            {
                this.VisitWhileStatement(value as IWhileStatement);
                return;
            }

            if (value is IDoStatement)
            {
                this.VisitDoStatement(value as IDoStatement);
                return;
            }

            if (value is ITryCatchFinallyStatement)
            {
                this.VisitTryCatchFinallyStatement(value as ITryCatchFinallyStatement);
                return;
            }

            if (value is IThrowExceptionStatement)
            {
                this.VisitThrowExceptionStatement(value as IThrowExceptionStatement);
                return;
            }

            if (value is IAttachEventStatement)
            {
                this.VisitAttachEventStatement(value as IAttachEventStatement);
                return;
            }

            if (value is IRemoveEventStatement)
            {
                this.VisitRemoveEventStatement(value as IRemoveEventStatement);
                return;
            }

            if (value is ISwitchStatement)
            {
                this.VisitSwitchStatement(value as ISwitchStatement);
                return;
            }

            if (value is IBreakStatement)
            {
                this.VisitBreakStatement(value as IBreakStatement);
                return;
            }

            if (value is IContinueStatement)
            {
                this.VisitContinueStatement(value as IContinueStatement);
                return;
            }

            if (value is ICommentStatement)
            {
                this.VisitCommentStatement(value as ICommentStatement);
                return;
            }

            if (value is IUsingStatement)
            {
                this.VisitUsingStatement(value as IUsingStatement);
                return;
            }

            if (value is IFixedStatement)
            {
                this.VisitFixedStatement(value as IFixedStatement);
                return;
            }

            if (value is ILockStatement)
            {
                this.VisitLockStatement(value as ILockStatement);
                return;
            }

            if (value is IMemoryCopyStatement)
            {
                this.VisitMemoryCopyStatement(value as IMemoryCopyStatement);
                return;
            }

            if (value is IMemoryInitializeStatement)
            {
                this.VisitMemoryInitializeStatement(value as IMemoryInitializeStatement);
                return;
            }

            if (value is IDebugBreakStatement)
            {
                this.VisitDebugBreakStatement(value as IDebugBreakStatement);
                return;
            }

            throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Invalid statement type '{0}'.", value.GetType().Name));
        }
Пример #38
0
 /// <summary>
 /// Gets the Request to send to a cassandra node based on the statement type
 /// </summary>
 internal IRequest GetRequest(IStatement statement)
 {
     ICqlRequest request = null;
     if (statement is RegularStatement)
     {
         var s = (RegularStatement)statement;
         s.ProtocolVersion = BinaryProtocolVersion;
         var options = QueryProtocolOptions.CreateFromQuery(s, Configuration.QueryOptions);
         options.ValueNames = s.QueryValueNames;
         request = new QueryRequest(BinaryProtocolVersion, s.QueryString, s.IsTracing, options);
     }
     if (statement is BoundStatement)
     {
         var s = (BoundStatement)statement;
         var options = QueryProtocolOptions.CreateFromQuery(s, Configuration.QueryOptions);
         request = new ExecuteRequest(BinaryProtocolVersion, s.PreparedStatement.Id, null, s.IsTracing, options);
     }
     if (statement is BatchStatement)
     {
         var s = (BatchStatement)statement;
         s.ProtocolVersion = BinaryProtocolVersion;
         var consistency = Configuration.QueryOptions.GetConsistencyLevel();
         if (s.ConsistencyLevel != null)
         {
             consistency = s.ConsistencyLevel.Value;
         }
         request = new BatchRequest(BinaryProtocolVersion, s, consistency);
     }
     if (request == null)
     {
         throw new NotSupportedException("Statement of type " + statement.GetType().FullName + " not supported");   
     }
     //Set the outgoing payload for the request
     request.Payload = statement.OutgoingPayload;
     return request;
 }
Пример #39
0
        public static string GetRefUrlFor(IStatement s, CodeLocation caret)
        {
            if (s is IExpressionContainingStatement) {
                var exprs = (s as IExpressionContainingStatement).SubExpressions;
                IExpression targetExpr = null;

                if (exprs != null)
                    foreach (var ex in exprs)
                        if (caret >= ex.Location &&
                            caret <= ex.EndLocation &&
                            (targetExpr = ExpressionHelper.SearchExpressionDeeply (ex, caret))
                            != ex)
                            break;

                if (targetExpr != null)
                    return GetRefUrlFor (targetExpr);
            }

            if (s is DeclarationStatement) {
                var ds = s as DeclarationStatement;

                foreach (var decl in ds.Declarations) {
                    if (caret >= decl.Location && caret <= decl.EndLocation) {
                        if (decl is DVariable) {
                            var dv = decl as DVariable;

                            if (dv.Initializer != null &&
                                caret >= dv.Location &&
                                caret <= dv.EndLocation)
                                return GetRefUrlFor (dv.Initializer);
                        }
                    }
                }
            }

            if (s is StatementContainingStatement) {
                var stmts = (s as StatementContainingStatement).SubStatements;

                if (stmts != null)
                    foreach (var stmt in stmts) {
                        if (caret >= stmt.Location && caret <= stmt.EndLocation) {
                            var r = GetRefUrlFor (stmt, caret);

                            if (r != null)
                                return r;
                        }
                    }
            }

            var url = "statement.html#";

            if (s is ForeachStatement && (s as ForeachStatement).IsRangeStatement)
                url += "ForeachRangeStatement";
            else if (s is StatementCondition)
            {
                var sc = (StatementCondition) s;
                if(sc.Condition is DebugCondition)
                    url = "version.html#DebugCondition";
                else if (sc.Condition is VersionCondition)
                    url = "version.html#VersionCondition";
                else if (sc.Condition is StaticIfCondition)
                    url = "version.html#StaticIfCondition";
            }
            else
                url += s.GetType ().Name;

            return url;
        }
Пример #40
0
        public static string GetRefUrlFor(IStatement s, CodeLocation caret)
        {
            if (s is IExpressionContainingStatement)
            {
                var         exprs      = (s as IExpressionContainingStatement).SubExpressions;
                IExpression targetExpr = null;

                if (exprs != null)
                {
                    foreach (var ex in exprs)
                    {
                        if (caret >= ex.Location &&
                            caret <= ex.EndLocation &&
                            (targetExpr = ExpressionHelper.SearchExpressionDeeply(ex, caret))
                            != ex)
                        {
                            break;
                        }
                    }
                }

                if (targetExpr != null)
                {
                    return(GetRefUrlFor(targetExpr));
                }
            }

            if (s is DeclarationStatement)
            {
                var ds = s as DeclarationStatement;

                foreach (var decl in ds.Declarations)
                {
                    if (caret >= decl.Location && caret <= decl.EndLocation)
                    {
                        if (decl is DVariable)
                        {
                            var dv = decl as DVariable;

                            if (dv.Initializer != null &&
                                caret >= dv.Location &&
                                caret <= dv.EndLocation)
                            {
                                return(GetRefUrlFor(dv.Initializer));
                            }
                        }
                    }
                }
            }

            if (s is StatementContainingStatement)
            {
                var stmts = (s as StatementContainingStatement).SubStatements;

                if (stmts != null)
                {
                    foreach (var stmt in stmts)
                    {
                        if (caret >= stmt.Location && caret <= stmt.EndLocation)
                        {
                            var r = GetRefUrlFor(stmt, caret);

                            if (r != null)
                            {
                                return(r);
                            }
                        }
                    }
                }
            }


            var url = "statement.html#";

            if (s is ForeachStatement && (s as ForeachStatement).IsRangeStatement)
            {
                url += "ForeachRangeStatement";
            }
            else if (s is StatementCondition)
            {
                var sc = (StatementCondition)s;
                if (sc.Condition is DebugCondition)
                {
                    url = "version.html#DebugCondition";
                }
                else if (sc.Condition is VersionCondition)
                {
                    url = "version.html#VersionCondition";
                }
                else if (sc.Condition is StaticIfCondition)
                {
                    url = "version.html#StaticIfCondition";
                }
            }
            else
            {
                url += s.GetType().Name;
            }

            return(url);
        }
        /// <summary>
        /// Can we combine? Yes, if and only if the same guy and same variables!
        /// </summary>
        /// <param name="statement"></param>
        /// <param name="optimize"></param>
        /// <returns></returns>
        public bool TryCombineStatement(IStatement statement, ICodeOptimizationService optimize)
        {
            if (statement.GetType() != typeof(StatementRecordPairValues))
                return false;
            var other = statement as StatementRecordPairValues;
            if (other._index.RawValue != _index.RawValue)
                return false;

            var isTheSame = _savers.Zip(other._savers, (f, s) => f.indexValue.RawValue == s.indexValue.RawValue && f.mapRecord.Type == s.mapRecord.Type).All(b => b);
            if (!isTheSame)
            {
                return false;
            }

            // Now we can do them all.
            foreach (var saver in _savers.Zip(other._savers, (f, s) => Tuple.Create(f, s)))
            {
                optimize.TryRenameVarialbeOneLevelUp(saver.Item2.mapRecord.RawValue, saver.Item1.mapRecord);
            }

            return true;
        }