public ScopeBase(ScopeInfo scopeInfo, object[] values)
 {
     Info = scopeInfo;
     Values = values;
     if (Values == null)
         Values = new object[scopeInfo.ValuesCount];
 }
Beispiel #2
0
 public SlotBinding(SlotInfo slot, AstNode fromNode, ScopeInfo fromScope) : base(slot.Name, BindingTargetType.Slot) {
   Slot = slot;
   FromNode = fromNode;
   FromScope = fromScope;
   SlotIndex = slot.Index;
   StaticScopeIndex = Slot.ScopeInfo.StaticIndex;
   SetupAccessorMethods();
 }
Beispiel #3
0
 public AppDataMap(bool languageCaseSensitive, AstNode programRoot = null) {
   LanguageCaseSensitive = languageCaseSensitive;
   ProgramRoot = programRoot?? new AstNode(); 
   var mainScopeInfo = new ScopeInfo(ProgramRoot, LanguageCaseSensitive); 
   StaticScopeInfos.Add(mainScopeInfo);
   mainScopeInfo.StaticIndex = 0;
   MainModule = new ModuleInfo("main", "main", mainScopeInfo);
   Modules.Add(MainModule);
 }
Beispiel #4
0
 public BindingRequest(ScriptThread thread, AstNode fromNode, string symbol, BindingRequestFlags flags) {
   Thread = thread;
   FromNode = fromNode;
   FromModule = thread.App.DataMap.GetModule(fromNode.ModuleNode);
   Symbol = symbol;
   Flags = flags;
   FromScopeInfo = thread.CurrentScope.Info;
   IgnoreCase = !thread.Runtime.Language.Grammar.CaseSensitive;
 }
Beispiel #5
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   lock (LockObject) {
     if (DependentScopeInfo == null) {
       var langCaseSensitive = thread.App.Language.Grammar.CaseSensitive;
       DependentScopeInfo = new ScopeInfo(this, langCaseSensitive);
     }
     // In the first evaluation the parameter list will add parameter's SlotInfo objects to Scope.ScopeInfo
     thread.PushScope(DependentScopeInfo, null);
     Parameters.Evaluate(thread);
     thread.PopScope();
     //Set Evaluate method and invoke it later
     this.Evaluate = EvaluateAfter;
   }
   var result = Evaluate(thread);
   thread.CurrentNode = Parent; //standard epilog
   return result;
 }
Beispiel #6
0
		public object Call(ScriptThread thread, object[] parameters)
		{
			var astNode = new AstNode(); // TODO: figure it out
			var newScopeInfo = new ScopeInfo(astNode, thread.App.Language.Grammar.CaseSensitive);
			thread.PushScope(newScopeInfo, parameters);

			try
			{
				var expression =
					parameters != null && parameters.Length > 0 ?
						parameters[0] as PassiveExpression : null;

				return Function(expression);
			}
			finally
			{
				thread.PopScope();
			}
		}
Beispiel #7
0
    public override void Init(AstContext context, ParseTreeNode parseNode)
		{
			base.Init(context, parseNode);

			foreach (var node in parseNode.ChildNodes)
			{
				if (node.AstNode is IdentifierNode)
				{
					Name = (node.AstNode as IdentifierNode).Symbol;
				}
				else if (node.AstNode is Block)
				{
					Block = (node.AstNode as Block);
					Block.Parent = this;
				}
				else if (node.Term is KeyTerm && node.Term.Name == "$ENTRY")
				{
					IsPublic = true;
				}
			}

			ScopeInfo = new ScopeInfo(this, context.Language.Grammar.CaseSensitive);
			AsString = (IsPublic ? "public " : "private ") + Name;
		}
Beispiel #8
0
        public override bool CheckInvocation(TexlBinding binding, TexlNode[] args, DType[] argTypes, IErrorContainer errors, out DType returnType, out Dictionary <TexlNode, DType> nodeToCoercedTypeMap)
        {
            Contracts.AssertValue(args);
            Contracts.AssertValue(argTypes);
            Contracts.Assert(args.Length == argTypes.Length);
            Contracts.AssertValue(errors);
            nodeToCoercedTypeMap = null;
            int viewCount = 0;

            bool fArgsValid = base.CheckInvocation(args, argTypes, errors, out returnType, out nodeToCoercedTypeMap);

            var dataSourceVisitor = new ViewFilterDataSourceVisitor(binding);

            // Ensure that all the args starting at index 1 are booleans or view
            for (int i = 1; i < args.Length; i++)
            {
                if (argTypes[i].Kind == DKind.ViewValue)
                {
                    if (++viewCount > 1)
                    {
                        // Only one view expected
                        errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrOnlyOneViewExpected);
                        fArgsValid = false;
                        continue;
                    }

                    // Use the visitor to get the datasource info and if a view was already used anywhere in the node tree.
                    args[0].Accept(dataSourceVisitor);
                    var dataSourceInfo = dataSourceVisitor.cdsDataSourceInfo;

                    if (dataSourceVisitor.ContainsViewFilter)
                    {
                        // Only one view expected
                        errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrOnlyOneViewExpected);
                        fArgsValid = false;
                        continue;
                    }

                    if (dataSourceInfo != null)
                    {
                        // Verify the view belongs to the same datasource
                        var viewInfo = argTypes[i].ViewInfo.VerifyValue();
                        if (viewInfo.RelatedEntityName != dataSourceInfo.Name)
                        {
                            errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrViewFromCurrentTableExpected, dataSourceInfo.Name);
                            fArgsValid = false;
                        }
                    }
                    else
                    {
                        errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrBooleanExpected);
                        fArgsValid = false;
                    }

                    continue;
                }
                else if (DType.Boolean.Accepts(argTypes[i]))
                {
                    continue;
                }
                else if (!argTypes[i].CoercesTo(DType.Boolean))
                {
                    errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrBooleanExpected);
                    fArgsValid = false;
                    continue;
                }
            }

            // The first Texl function arg determines the cursor type, the scope type for the lambda params, and the return type.
            DType typeScope;

            fArgsValid &= ScopeInfo.CheckInput(args[0], argTypes[0], errors, out typeScope);

            Contracts.Assert(typeScope.IsRecord);
            returnType = typeScope.ToTable();

            return(fArgsValid);
        }
Beispiel #9
0
 public ScopeInfo(ITypeSymbol type)
 {
     this.Type = type;
     this.usedTypeArguments = new HashSet <string>(ScopeInfo.AllTypeArguments(type).Select(i => i.Name));
 }
        public ScopeInfo InsertOrUpdateScopeInfo(ScopeInfo scopeInfo)
        {
            bool alreadyOpened = connection.State == ConnectionState.Open;
            bool exist;

            try
            {
                using (var command = connection.CreateCommand())
                {
                    if (transaction != null)
                    {
                        command.Transaction = transaction;
                    }


                    if (!alreadyOpened)
                    {
                        connection.Open();
                    }

                    command.CommandText = $@"Select count(*) from {scopeTableName.Quoted().ToString()} where sync_scope_id = @sync_scope_id";

                    var p = command.CreateParameter();
                    p.ParameterName = "@sync_scope_id";
                    p.Value         = scopeInfo.Id.ToString();
                    p.DbType        = DbType.String;
                    command.Parameters.Add(p);

                    exist = (long)command.ExecuteScalar() > 0;
                }

                string stmtText = exist
                    ? $"Update {scopeTableName.Quoted().ToString()} set sync_scope_name=@sync_scope_name, scope_timestamp={MySqlObjectNames.TimestampValue}, scope_is_local=@scope_is_local, scope_last_sync=@scope_last_sync, scope_last_sync_timestamp=@scope_last_sync_timestamp, scope_last_sync_duration=@scope_last_sync_duration  where sync_scope_id=@sync_scope_id"
                    : $"Insert into {scopeTableName.Quoted().ToString()} (sync_scope_name, scope_timestamp, scope_is_local, scope_last_sync, sync_scope_id, scope_last_sync_timestamp, scope_last_sync_duration) values (@sync_scope_name, {MySqlObjectNames.TimestampValue}, @scope_is_local, @scope_last_sync, @sync_scope_id, @scope_last_sync_timestamp, @scope_last_sync_duration)";

                using (var command = connection.CreateCommand())
                {
                    if (transaction != null)
                    {
                        command.Transaction = transaction;
                    }

                    command.CommandText = stmtText;

                    var p = command.CreateParameter();
                    p.ParameterName = "@sync_scope_name";
                    p.Value         = scopeInfo.Name;
                    p.DbType        = DbType.String;
                    command.Parameters.Add(p);

                    p = command.CreateParameter();
                    p.ParameterName = "@scope_is_local";
                    p.Value         = scopeInfo.IsLocal;
                    p.DbType        = DbType.Boolean;
                    command.Parameters.Add(p);

                    p = command.CreateParameter();
                    p.ParameterName = "@scope_last_sync";
                    p.Value         = scopeInfo.LastSync.HasValue ? (object)scopeInfo.LastSync.Value : DBNull.Value;
                    p.DbType        = DbType.DateTime;
                    command.Parameters.Add(p);

                    p = command.CreateParameter();
                    p.ParameterName = "@scope_last_sync_timestamp";
                    p.Value         = scopeInfo.LastSyncTimestamp;
                    p.DbType        = DbType.Int64;
                    command.Parameters.Add(p);

                    p = command.CreateParameter();
                    p.ParameterName = "@scope_last_sync_duration";
                    p.Value         = scopeInfo.LastSyncDuration;
                    p.DbType        = DbType.Int64;
                    command.Parameters.Add(p);

                    p = command.CreateParameter();
                    p.ParameterName = "@sync_scope_id";
                    p.Value         = scopeInfo.Id.ToString();
                    p.DbType        = DbType.String;
                    command.Parameters.Add(p);

                    using (DbDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            scopeInfo.Name              = reader["sync_scope_name"] as String;
                            scopeInfo.Id                = new Guid((string)reader["sync_scope_id"]);
                            scopeInfo.Timestamp         = MySqlManager.ParseTimestamp(reader["scope_timestamp"]);
                            scopeInfo.IsLocal           = (bool)reader["scope_is_local"];
                            scopeInfo.LastSyncDuration  = reader["scope_last_sync_duration"] != DBNull.Value ? (long)reader["scope_last_sync_duration"] : 0L;
                            scopeInfo.LastSyncTimestamp = reader["scope_last_sync_timestamp"] != DBNull.Value ? (long)reader["scope_last_sync_timestamp"] : 0L;
                            scopeInfo.LastSync          = reader["scope_last_sync"] != DBNull.Value ? (DateTime?)reader["scope_last_sync"] : null;
                        }
                    }

                    return(scopeInfo);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during CreateTableScope : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }
            }
        }
Beispiel #11
0
        public List <ScopeInfo> GetAllScopes(string scopeName)
        {
            var command = connection.CreateCommand();

            if (transaction != null)
            {
                command.Transaction = transaction;
            }

            bool alreadyOpened = connection.State == ConnectionState.Open;

            List <ScopeInfo> scopes = new List <ScopeInfo>();

            try
            {
                if (!alreadyOpened)
                {
                    connection.Open();
                }

                command.CommandText =
                    @"SELECT sync_scope_id
                           , sync_scope_name
                           , scope_timestamp
                           , scope_is_local
                           , scope_last_sync
                    FROM  scope_info
                    WHERE sync_scope_name = @sync_scope_name";

                var p = command.CreateParameter();
                p.ParameterName = "@sync_scope_name";
                p.Value         = scopeName;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                using (DbDataReader reader = command.ExecuteReader())
                {
                    // read only the first one
                    while (reader.Read())
                    {
                        ScopeInfo scopeInfo = new ScopeInfo();
                        scopeInfo.Name          = reader["sync_scope_name"] as String;
                        scopeInfo.Id            = (Guid)reader["sync_scope_id"];
                        scopeInfo.LastTimestamp = DbManager.ParseTimestamp(reader["scope_timestamp"]);
                        scopeInfo.LastSync      = reader["scope_last_sync"] != DBNull.Value ? (DateTime?)reader["scope_last_sync"] : null;
                        scopeInfo.IsLocal       = reader.GetBoolean(reader.GetOrdinal("scope_is_local"));
                        scopes.Add(scopeInfo);
                    }
                }

                return(scopes);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during GetAllScopes : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }

                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
 public ScopeBase(ScopeInfo scopeInfo) : this(scopeInfo, null) { }
        protected override object DoEvaluate(Irony.Interpreter.ScriptThread thread)
        {
            object retval = null;
            thread.CurrentNode = this;  //standard prolog
            IEnumerable<object> o = null;

            string functionName = function.ChildNodes[0].FindTokenAndGetText();
            switch (functionName.ToLowerInvariant())
            {
                case "count":
                    o = Left as IEnumerable<object>;
                    if (o != null)
                        retval = o.Count();
                    else
                        retval = -1;
                    break;
                case "range":
                    o = Left as IEnumerable<object>;
                    if (o != null)
                    {
                        // by default return the first
                        int iFrom = GetIndex(thread, Arguments[0], o, 0);
                        int iTo = GetIndex(thread, Arguments[1], o, iFrom);

                        if (iFrom < 0)
                            iFrom = 0;
                        if (iTo >= o.Count())
                            iTo = o.Count();

                        List<object> tretval = new List<object>();
                        for (int i = iFrom; i <= iTo; i++)
                        {
                            tretval.Add(o.ElementAt(i));
                        }
                        retval = tretval;
                    }
                    else
                        retval = null;
                    break;
                case "where":

                    o = Left as IEnumerable<object>;
                    if (o != null)
                    {

                        List<object> tretvalWhere = new List<object>();
                        foreach (var item in o)
                        {
                            // todo: bonghi: needs to check the context is set here.
                            var scpInfo = new ScopeInfo(this, false);
                            object[] oIfc = new object[] { item };
                            thread.PushScope(scpInfo, oIfc);

                            try
                            {
                                object oCondition = Arguments[0].Evaluate(thread);
                                if ((bool)oCondition)
                                {
                                    tretvalWhere.Add(item);
                                }
                            }
                            catch (Exception)
                            {
                                // if problems just ignore so that statements that don't compute (say for missing properties) are still ok.
                            }
                            thread.PopScope();
                        }

                        retval = tretvalWhere;
                    }
                    else
                        retval = null;
                    break;
                default:
                    throw new Exception("Not implemented: " + functionName);
            }

            thread.CurrentNode = Parent; //standard epilog
            return retval;
        }
        protected override void OnTranslate(ShaderTranslationContext sc, VariableDeclarationSyntax syntax, ScopeInfo scope)
        {
            string     typeName = syntax.Type.ToString();
            ShaderType type     = ShaderType.TranslateType(sc, typeName);

            ScopeInfo tScope = sc.Source.OpenScope(ScopeType.Typed, type);

            tScope.TypeInfo = type;
            tScope.IsLocal  = syntax.Parent is LocalDeclarationStatementSyntax;
            tScope.Items    = syntax.Variables;

            if (syntax.Parent is FieldDeclarationSyntax fieldSyntax)
            {
                tScope.TranslatedModifiers = sc.Language.TranslateModifiers(fieldSyntax.Modifiers);
            }

            sc.Complete(syntax.Type);
        }
Beispiel #15
0
        public async Task <ScopeInfo> InsertOrUpdateClientScopeInfoAsync(ScopeInfo scopeInfo)
        {
            var command = connection.CreateCommand();

            if (transaction != null)
            {
                command.Transaction = transaction;
            }
            bool alreadyOpened = connection.State == ConnectionState.Open;

            try
            {
                if (!alreadyOpened)
                {
                    await connection.OpenAsync().ConfigureAwait(false);
                }

                command.CommandText = $@"Select count(*) from {scopeTableName.Unquoted().ToString()} where sync_scope_id = @sync_scope_id";

                var p = command.CreateParameter();
                p.ParameterName = "@sync_scope_id";
                p.Value         = scopeInfo.Id.ToString();
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                var exist = ((long)await command.ExecuteScalarAsync().ConfigureAwait(false)) > 0;

                string stmtText = exist
                    ? $"Update {scopeTableName.Unquoted().ToString()} set sync_scope_name=@sync_scope_name, sync_scope_schema=@sync_scope_schema, sync_scope_setup=@sync_scope_setup, sync_scope_version=@sync_scope_version, scope_last_sync=@scope_last_sync, scope_last_server_sync_timestamp=@scope_last_server_sync_timestamp,  scope_last_sync_timestamp=@scope_last_sync_timestamp, scope_last_sync_duration=@scope_last_sync_duration where sync_scope_id=@sync_scope_id"
                    : $"Insert into {scopeTableName.Unquoted().ToString()} (sync_scope_name, sync_scope_schema, sync_scope_setup, sync_scope_version, scope_last_sync, scope_last_sync_duration, scope_last_server_sync_timestamp, scope_last_sync_timestamp, sync_scope_id) values (@sync_scope_name, @sync_scope_schema, @sync_scope_setup, @sync_scope_version, @scope_last_sync, @scope_last_sync_duration, @scope_last_server_sync_timestamp, @scope_last_sync_timestamp, @sync_scope_id)";

                command             = connection.CreateCommand();
                command.CommandText = stmtText;

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_name";
                p.Value         = scopeInfo.Name;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_schema";
                p.Value         = scopeInfo.Schema == null ? DBNull.Value : (object)JsonConvert.SerializeObject(scopeInfo.Schema);
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_setup";
                p.Value         = scopeInfo.Setup == null ? DBNull.Value : (object)JsonConvert.SerializeObject(scopeInfo.Setup);
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_version";
                p.Value         = string.IsNullOrEmpty(scopeInfo.Version) ? DBNull.Value : (object)scopeInfo.Version;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync";
                p.Value         = scopeInfo.LastSync.HasValue ? (object)scopeInfo.LastSync.Value : DBNull.Value;
                p.DbType        = DbType.DateTime;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_server_sync_timestamp";
                p.Value         = scopeInfo.LastServerSyncTimestamp;
                p.DbType        = DbType.Int64;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync_timestamp";
                p.Value         = scopeInfo.LastSyncTimestamp;
                p.DbType        = DbType.Int64;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync_duration";
                p.Value         = scopeInfo.LastSyncDuration;
                p.DbType        = DbType.Int64;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_id";
                p.Value         = scopeInfo.Id.ToString();
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                using (DbDataReader reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            scopeInfo.Name     = reader["sync_scope_name"] as string;
                            scopeInfo.Schema   = reader["sync_scope_schema"] == DBNull.Value ? null : JsonConvert.DeserializeObject <SyncSet>((string)reader["sync_scope_schema"]);
                            scopeInfo.Setup    = reader["sync_scope_setup"] == DBNull.Value ? null : JsonConvert.DeserializeObject <SyncSetup>((string)reader["sync_scope_setup"]);
                            scopeInfo.Version  = reader["sync_scope_version"] as string;
                            scopeInfo.Id       = reader.GetGuid(reader.GetOrdinal("sync_scope_id"));
                            scopeInfo.LastSync = reader["scope_last_sync"] != DBNull.Value
                                        ? (DateTime?)reader.GetDateTime(reader.GetOrdinal("scope_last_sync"))
                                        : null;
                            scopeInfo.LastSyncTimestamp       = reader["scope_last_sync_timestamp"] != DBNull.Value ? reader.GetInt64(reader.GetOrdinal("scope_last_sync_timestamp")) : 0L;
                            scopeInfo.LastServerSyncTimestamp = reader["scope_last_server_sync_timestamp"] != DBNull.Value ? reader.GetInt64(reader.GetOrdinal("scope_last_server_sync_timestamp")) : 0L;
                            scopeInfo.LastSyncDuration        = reader["scope_last_sync_duration"] != DBNull.Value ? reader.GetInt64(reader.GetOrdinal("scope_last_sync_duration")) : 0L;
                        }
                    }
                }

                return(scopeInfo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during InsertOrUpdateClientScopeInfoAsync : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }

                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
 public async Task <(SyncContext, BatchInfo, ChangesStatistics)> GetChangeBatchAsync(SyncContext ctx, ScopeInfo scopeInfo)
 => await this.LocalProvider.GetChangeBatchAsync(ctx, scopeInfo);
 public async Task <SyncContext> EnsureDatabaseAsync(SyncContext ctx, ScopeInfo scopeInfo)
 => await this.LocalProvider.EnsureDatabaseAsync(ctx, scopeInfo);
 public async Task <(SyncContext, ChangesStatistics)> ApplyChangesAsync(SyncContext ctx, ScopeInfo fromScope, BatchInfo changes)
 => await this.LocalProvider.ApplyChangesAsync(ctx, fromScope, changes);
Beispiel #19
0
 private static ScopeViewModel ToModel(ScopeInfo info)
 {
     return(SimpleMapper.From <ScopeInfo, ScopeViewModel>(info));
 }
        protected override void OnTranslate(ShaderTranslationContext sc, AssignmentExpressionSyntax syntax, ScopeInfo scope)
        {
            if (scope.Type == ScopeType.ExpandedInitializer)
            {
                sc.Source.Append($"{scope.Identifier}.");
                sc.Source.OpenScope(ScopeType.Variable);
            }

            // TODO check if the assignment uses a valid operator. Does the language support operand assignments (e.g *= += or /=)
            sc.Runner.Translate(sc, syntax.Left);
            if (sc.IsCompleted(syntax.Right)) // Property translation may have replaced the assignment with a set-method call.
            {
                return;
            }

            sc.Source.Append($" {syntax.OperatorToken} ");
            sc.Runner.Translate(sc, syntax.Right);
        }
Beispiel #21
0
        public override void ExecuteBatchCommand(DbCommand cmd, DmView applyTable, DmTable failedRows, ScopeInfo scope)
        {
            if (applyTable.Count <= 0)
            {
                return;
            }

            // Insert data in bulk table
            BulkInsertTemporyTable(BulkInsertTemporyTableText(applyTable));

            ((OracleParameterCollection)cmd.Parameters)["sync_scope_id"].Value      = scope.Id;
            ((OracleParameterCollection)cmd.Parameters)["sync_min_timestamp"].Value = scope.LastTimestamp;

            bool alreadyOpened = this._connection.State == ConnectionState.Open;

            try
            {
                if (!alreadyOpened)
                {
                    this._connection.Open();
                }

                if (this._transaction != null)
                {
                    cmd.Transaction = this._transaction;
                }

                using (DbDataReader dataReader = cmd.ExecuteReader())
                {
                    failedRows.Fill(dataReader);
                }
            }
            catch (DbException ex)
            {
                Debug.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                if (!alreadyOpened && this._connection.State != ConnectionState.Closed)
                {
                    this._connection.Close();
                }
            }
        }
Beispiel #22
0
        public List <ScopeInfo> GetAllScopes(string scopeName)
        {
            var command = connection.CreateCommand();

            if (transaction != null)
            {
                command.Transaction = transaction;
            }

            bool alreadyOpened = connection.State == ConnectionState.Open;

            List <ScopeInfo> scopes = new List <ScopeInfo>();

            try
            {
                if (!alreadyOpened)
                {
                    connection.Open();
                }

                command.CommandText =
                    $@"SELECT [sync_scope_id]
                           , [sync_scope_name]
                           , [scope_timestamp]
                           , [scope_is_local]
                           , [scope_last_sync]
                           , [scope_last_sync_timestamp]
                           , [scope_last_sync_duration]
                    FROM  {scopeTableName.QuotedObjectName}
                    WHERE [sync_scope_name] = @sync_scope_name";

                var p = command.CreateParameter();
                p.ParameterName = "@sync_scope_name";
                p.Value         = scopeName;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                using (DbDataReader reader = command.ExecuteReader())
                {
                    // read only the first one
                    while (reader.Read())
                    {
                        ScopeInfo scopeInfo = new ScopeInfo();
                        scopeInfo.Name              = reader["sync_scope_name"] as String;
                        scopeInfo.Id                = (Guid)reader["sync_scope_id"];
                        scopeInfo.Timestamp         = SqlManager.ParseTimestamp(reader["scope_timestamp"]);
                        scopeInfo.LastSync          = reader["scope_last_sync"] != DBNull.Value ? (DateTime?)reader["scope_last_sync"] : null;
                        scopeInfo.LastSyncTimestamp = reader["scope_last_sync_timestamp"] != DBNull.Value ? (long)reader["scope_last_sync_timestamp"] : 0;
                        scopeInfo.LastSyncDuration  = reader["scope_last_sync_duration"] != DBNull.Value ? (long)reader["scope_last_sync_duration"] : 0;
                        scopeInfo.IsLocal           = (bool)reader["scope_is_local"];
                        scopes.Add(scopeInfo);
                    }
                }

                return(scopes);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during GetAllScopes : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }

                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
        protected override void OnTranslate(ShaderTranslationContext sc, PropertyDeclarationSyntax syntax, ScopeInfo scope)
        {
            ScopeInfo classScope = scope.FindOfType(ScopeType.Class);
            ScopeInfo pScope     = sc.Source.OpenScope(ScopeType.Property);

            pScope.Identifier = syntax.Identifier.ValueText;

            sc.Complete(syntax.Type);

            pScope.TypeInfo = ShaderType.TranslateType(sc, syntax.Type.ToString());
        }
        protected override void OnTranslate(ShaderTranslationContext sc, MemberAccessExpressionSyntax syntax, ScopeInfo scope)
        {
            switch (syntax.Expression)
            {
            case IdentifierNameSyntax idSyntax:
                // Is this a static class identifier?
                // Static classes are abstract and sealed at IL level.
                Type targetType = ShaderType.Resolve(sc, idSyntax.Identifier.ValueText);
                if (targetType != null && targetType.IsClass && targetType.IsAbstract && targetType.IsSealed)
                {
                    // Is the member a constant value? If so, we can take it's value directly.
                    FieldInfo fInfo = targetType.GetField(syntax.Name.Identifier.ValueText);
                    if (fInfo != null && (fInfo.Attributes & FieldAttributes.Literal) == FieldAttributes.Literal)
                    {
                        object val = fInfo.GetValue(null);
                        if (val != null)
                        {
                            sc.Source.Append(val.ToString());
                            sc.CompleteChildren(syntax);
                            return;
                        }
                    }
                }
                else
                {
                    ScopeInfo cScope = scope.FindOfType(ScopeType.Class);
                    if (cScope == sc.Source.RootScope)
                    {
                        FieldInfo fInfo = cScope.TypeInfo.OriginalType.GetField(idSyntax.Identifier.ValueText);
                        if (fInfo != null && sc.ConstantBuffers.Values.Any(x => x.TypeInfo == fInfo.FieldType))
                        {
                            if (!sc.Language.InstancedConstantBuffers)
                            {
                                sc.CompleteSelfAndChildren(syntax.Expression);
                                sc.Runner.Translate(sc, syntax.Name);
                                return;
                            }
                        }
                    }
                }
                break;

            case ThisExpressionSyntax thisSyntax:
            case BaseExpressionSyntax baseSyntax:
                ScopeInfo pScope = scope.FindOfType(ScopeType.Class);
                if (pScope.TypeInfo.OriginalType == sc.ShaderType)
                {
                    sc.Complete(syntax.Expression);

                    // Are we translating a shader intrinsic method/function?
                    if (syntax.Name is IdentifierNameSyntax idSyntax && syntax.Parent is InvocationExpressionSyntax)
                    {
                        string translatedIntrinsic = ShaderType.GetIntrinsicTranslation(sc, idSyntax.Identifier.ValueText);
                        sc.Source.Append(translatedIntrinsic);
                        sc.Complete(syntax.Name);
                    }
                    return;
                }
                break;
            }

            sc.Runner.Translate(sc, syntax.Expression);
            sc.Source.Append(syntax.OperatorToken);
            sc.Runner.Translate(sc, syntax.Name);
        }
        /// <summary>
        /// Executing a batch command
        /// </summary>
        /// <param name="cmd">the DbCommand already prepared</param>
        /// <param name="applyTable">the table rows to apply</param>
        /// <param name="failedRows">the failed rows dmTable to store failed rows</param>
        /// <param name="scope">the current scope</param>
        public override void ExecuteBatchCommand(DbCommand cmd, DmTable applyTable, DmTable failedRows, ScopeInfo scope)
        {
            if (applyTable.Rows.Count <= 0)
            {
                return;
            }

            var lstMutableColumns = applyTable.Columns.Where(c => !c.ReadOnly).ToList();

            List <SqlDataRecord> records = new List <SqlDataRecord>(applyTable.Rows.Count);

            SqlMetaData[] metadatas = new SqlMetaData[lstMutableColumns.Count];

            for (int i = 0; i < lstMutableColumns.Count; i++)
            {
                var column = lstMutableColumns[i];

                SqlMetaData metadata = GetSqlMetadaFromType(column);
                metadatas[i] = metadata;
            }
            try
            {
                foreach (var dmRow in applyTable.Rows)
                {
                    SqlDataRecord record = new SqlDataRecord(metadatas);

                    int sqlMetadataIndex = 0;
                    for (int i = 0; i < dmRow.ItemArray.Length; i++)
                    {
                        // check if it's readonly
                        if (applyTable.Columns[i].ReadOnly)
                        {
                            continue;
                        }

                        // Get the default value
                        // Since we have the readonly values in ItemArray, get the value from original column
                        dynamic defaultValue = applyTable.Columns[i].DefaultValue;
                        dynamic rowValue     = dmRow[i];
                        var     columnType   = applyTable.Columns[i].DataType;

                        // metadatas don't have readonly values, so get from sqlMetadataIndex
                        var sqlMetadataType = metadatas[sqlMetadataIndex].SqlDbType;
                        if (rowValue != null)
                        {
                            switch (sqlMetadataType)
                            {
                            case SqlDbType.BigInt:
                                if (columnType != typeof(long))
                                {
                                    if (Int64.TryParse(rowValue.ToString(), out Int64 v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Int64", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Bit:
                                if (columnType != typeof(bool))
                                {
                                    if (Boolean.TryParse(rowValue.ToString(), out Boolean v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Boolean", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Date:
                            case SqlDbType.DateTime:
                            case SqlDbType.DateTime2:
                            case SqlDbType.SmallDateTime:
                                if (columnType != typeof(DateTime))
                                {
                                    if (DateTime.TryParse(rowValue.ToString(), out DateTime v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to DateTime", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.DateTimeOffset:
                                if (columnType != typeof(DateTimeOffset))
                                {
                                    if (DateTimeOffset.TryParse(rowValue.ToString(), out DateTimeOffset dt))
                                    {
                                        rowValue = dt;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to DateTimeOffset", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Decimal:
                                if (columnType != typeof(Decimal))
                                {
                                    if (Decimal.TryParse(rowValue.ToString(), out decimal v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Decimal", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Float:
                                if (columnType != typeof(Double))
                                {
                                    if (Double.TryParse(rowValue.ToString(), out Double v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Double", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Real:
                                if (columnType != typeof(float))
                                {
                                    if (float.TryParse(rowValue.ToString(), out float v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Double", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Image:
                            case SqlDbType.Binary:
                            case SqlDbType.VarBinary:
                                if (columnType != typeof(Byte[]))
                                {
                                    rowValue = BitConverter.GetBytes(rowValue);
                                }
                                break;

                            case SqlDbType.Variant:
                                break;

                            case SqlDbType.Int:
                                if (columnType != typeof(Int32))
                                {
                                    if (Int32.TryParse(rowValue.ToString(), out int v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Int32", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Money:
                            case SqlDbType.SmallMoney:
                                if (columnType != typeof(Decimal))
                                {
                                    if (Decimal.TryParse(rowValue.ToString(), out Decimal v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Decimal", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.NChar:
                            case SqlDbType.NText:
                            case SqlDbType.VarChar:
                            case SqlDbType.Xml:
                            case SqlDbType.NVarChar:
                            case SqlDbType.Text:
                            case SqlDbType.Char:
                                if (columnType != typeof(string))
                                {
                                    rowValue = rowValue.ToString();
                                }
                                break;

                            case SqlDbType.SmallInt:
                                if (columnType != typeof(Int16))
                                {
                                    if (Int16.TryParse(rowValue.ToString(), out Int16 v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Int16", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Time:
                                if (columnType != typeof(TimeSpan))
                                {
                                    if (TimeSpan.TryParse(rowValue.ToString(), out TimeSpan v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to TimeSpan", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Timestamp:
                                break;

                            case SqlDbType.TinyInt:
                                if (columnType != typeof(Byte))
                                {
                                    if (Byte.TryParse(rowValue.ToString(), out byte v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Byte", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;

                            case SqlDbType.Udt:
                                throw new SyncException($"Can't use UDT as SQL Type", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);

                            case SqlDbType.UniqueIdentifier:
                                if (columnType != typeof(Guid))
                                {
                                    if (Guid.TryParse(rowValue.ToString(), out Guid v))
                                    {
                                        rowValue = v;
                                    }
                                    else
                                    {
                                        throw new SyncException($"Can't convert value {rowValue} to Guid", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
                                    }
                                }
                                break;
                            }
                        }

                        if (applyTable.Columns[i].AllowDBNull && rowValue == null)
                        {
                            rowValue = DBNull.Value;
                        }
                        else if (rowValue == null)
                        {
                            rowValue = defaultValue;
                        }

                        record.SetValue(sqlMetadataIndex, rowValue);
                        sqlMetadataIndex++;
                    }
                    records.Add(record);
                }
            }
            catch (Exception ex)
            {
                throw new SyncException($"Can't create a SqlRecord based on the rows we have: {ex.Message}", Enumerations.SyncStage.ApplyingChanges, SyncExceptionType.NotSupported);
            }


            ((SqlParameterCollection)cmd.Parameters)["@changeTable"].TypeName     = string.Empty;
            ((SqlParameterCollection)cmd.Parameters)["@changeTable"].Value        = records;
            ((SqlParameterCollection)cmd.Parameters)["@sync_scope_id"].Value      = scope.Id;
            ((SqlParameterCollection)cmd.Parameters)["@sync_min_timestamp"].Value = scope.LastTimestamp;

            bool alreadyOpened = this.connection.State == ConnectionState.Open;

            try
            {
                if (!alreadyOpened)
                {
                    this.connection.Open();
                }

                if (this.transaction != null)
                {
                    cmd.Transaction = this.transaction;
                }


                using (DbDataReader dataReader = cmd.ExecuteReader())
                {
                    failedRows.Fill(dataReader);
                }
            }
            catch (DbException ex)
            {
                Debug.WriteLine(ex.Message);
                //DbException dbException = dbException1;
                //Error = CheckZombieTransaction(tvpCommandNameForApplyType, Adapter.TableName, dbException);
                //this.AddFailedRowsAfterRIFailure(applyTable, failedRows);
                throw;
            }
            finally
            {
                if (!alreadyOpened && this.connection.State != ConnectionState.Closed)
                {
                    this.connection.Close();
                }
            }
        }
Beispiel #26
0
 protected override void OnTranslate(ShaderTranslationContext sc, InitializerExpressionSyntax syntax, ScopeInfo scope)
 {
     if (syntax.Parent is ArrayCreationExpressionSyntax arrayCreationSyntax || syntax.Parent is EqualsValueClauseSyntax equalsAssignmentSyntax)
     {
         ScopeInfo iScope = sc.Source.OpenScope(ScopeType.ArrayInitializer);
         iScope.Items = syntax.Expressions;
     }
 }
        public ScopeInfo InsertOrUpdateScopeInfo(ScopeInfo scopeInfo)
        {
            var command = connection.CreateCommand();

            if (transaction != null)
            {
                command.Transaction = transaction;
            }
            bool alreadyOpened = connection.State == ConnectionState.Open;

            try
            {
                if (!alreadyOpened)
                {
                    connection.Open();
                }

                command.CommandText = @"
                    MERGE INTO scope_info base
                    USING (
                               SELECT  :sync_scope_id AS sync_scope_id,  
	                                   :sync_scope_name AS sync_scope_name,  
                                       :scope_is_local as scope_is_local,
                                       to_date(:scope_last_sync, 'DD/MM/YYYY HH24:MI:SS') AS scope_last_sync,
                                       to_number(to_char(systimestamp, 'YYYYMMDDHH24MISSFF3')) as scope_timestamp
                                FROM dual
                           ) changes
                    ON (base.sync_scope_id = changes.sync_scope_id)
                    WHEN NOT MATCHED THEN
	                    INSERT (sync_scope_name, sync_scope_id, scope_is_local, scope_last_sync, scope_timestamp)
	                    VALUES (changes.sync_scope_name, changes.sync_scope_id, changes.scope_is_local, changes.scope_last_sync, changes.scope_timestamp)
                    WHEN MATCHED THEN
	                    UPDATE SET sync_scope_name = changes.sync_scope_name, 
                                   scope_is_local = changes.scope_is_local, 
                                   scope_last_sync = changes.scope_last_sync,
                                   scope_timestamp = changes.scope_timestamp
                ";

                var p = command.CreateParameter();
                p.ParameterName = "sync_scope_name";
                p.Value         = scopeInfo.Name;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "sync_scope_id";
                p.Value         = scopeInfo.Id.ToString();
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "scope_is_local";
                p.Value         = scopeInfo.IsLocal ? 1 : 0;
                p.DbType        = DbType.Int32;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "scope_last_sync";
                if (scopeInfo.LastSync.HasValue)
                {
                    p.Value = $"{scopeInfo.LastSync.Value.ToShortDateString()} {scopeInfo.LastSync.Value.ToLongTimeString()}";
                }
                else
                {
                    p.Value = DBNull.Value;
                }
                p.DbType = DbType.String;
                command.Parameters.Add(p);

                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during CreateTableScope : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }

                if (command != null)
                {
                    command.Dispose();
                }
            }

            command = connection.CreateCommand();
            if (transaction != null)
            {
                command.Transaction = transaction;
            }
            alreadyOpened = connection.State == ConnectionState.Open;

            try
            {
                if (!alreadyOpened)
                {
                    connection.Open();
                }

                command.CommandText = @"
                    SELECT sync_scope_name, sync_scope_id, scope_timestamp, scope_is_local, scope_last_sync
                    FROM SCOPE_INFO
                    WHERE sync_scope_id = :sync_scope_id";

                var p = command.CreateParameter();
                p.ParameterName = "sync_scope_id";
                p.Value         = scopeInfo.Id.ToString();
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                using (DbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        scopeInfo.Name          = reader["sync_scope_name"] as String;
                        scopeInfo.Id            = Guid.Parse(reader["sync_scope_id"].ToString());
                        scopeInfo.LastTimestamp = OracleManager.ParseTimestamp(reader["scope_timestamp"]);
                        scopeInfo.IsLocal       = Convert.ToInt32(reader["scope_is_local"]) == 1;
                        scopeInfo.LastSync      = reader["scope_last_sync"] != DBNull.Value ? (DateTime?)reader["scope_last_sync"] : null;
                    }
                }

                return(scopeInfo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during SelectTableScope : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }

                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
        public virtual async Task <List <ScopeInfo> > GetAllClientScopesAsync(string scopeName)
        {
            var command = connection.CreateCommand();

            if (transaction != null)
            {
                command.Transaction = transaction;
            }

            bool alreadyOpened = connection.State == ConnectionState.Open;

            var scopes = new List <ScopeInfo>();

            try
            {
                if (!alreadyOpened)
                {
                    await connection.OpenAsync().ConfigureAwait(false);
                }

                command.CommandText =
                    $@"SELECT [sync_scope_id]
                           , [sync_scope_name]
                           , [sync_scope_schema]
                           , [sync_scope_setup]
                           , [sync_scope_version]
                           , [scope_last_sync]
                           , [scope_last_server_sync_timestamp]
                           , [scope_last_sync_timestamp]
                           , [scope_last_sync_duration]
                    FROM  {scopeTableName.Quoted().ToString()}
                    WHERE [sync_scope_name] = @sync_scope_name";

                var p = command.CreateParameter();
                p.ParameterName = "@sync_scope_name";
                p.Value         = scopeName;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
                {
                    if (reader.HasRows)
                    {
                        // read only the first one
                        while (reader.Read())
                        {
                            var scopeInfo = new ScopeInfo();
                            scopeInfo.Name     = reader["sync_scope_name"] as string;
                            scopeInfo.Schema   = reader["sync_scope_schema"] == DBNull.Value ? null : JsonConvert.DeserializeObject <SyncSet>((string)reader["sync_scope_schema"]);
                            scopeInfo.Setup    = reader["sync_scope_setup"] == DBNull.Value ? null : JsonConvert.DeserializeObject <SyncSetup>((string)reader["sync_scope_setup"]);
                            scopeInfo.Version  = reader["sync_scope_version"] as string;
                            scopeInfo.Id       = (Guid)reader["sync_scope_id"];
                            scopeInfo.LastSync = reader["scope_last_sync"] != DBNull.Value ? (DateTime?)reader["scope_last_sync"] : null;
                            scopeInfo.LastServerSyncTimestamp = reader["scope_last_server_sync_timestamp"] != DBNull.Value ? (long)reader["scope_last_server_sync_timestamp"] : 0;
                            scopeInfo.LastSyncTimestamp       = reader["scope_last_sync_timestamp"] != DBNull.Value ? (long)reader["scope_last_sync_timestamp"] : 0;
                            scopeInfo.LastSyncDuration        = reader["scope_last_sync_duration"] != DBNull.Value ? (long)reader["scope_last_sync_duration"] : 0;
                            scopes.Add(scopeInfo);
                        }
                    }
                }

                return(scopes);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during GetAllScopes : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }

                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
        protected override void OnTranslate(ShaderTranslationContext sc, ArrowExpressionClauseSyntax syntax, ScopeInfo scope)
        {
            if (scope.Type == ScopeType.Method)
            {
                sc.Source.OpenScope(ScopeType.Block);
                if (scope.Method.ReturnType != typeof(void))
                {
                    sc.Source.Append("return ");
                }

                sc.Source.OpenScope(ScopeType.Variable);
            }
        }
        public virtual async Task <ScopeInfo> InsertOrUpdateClientScopeInfoAsync(ScopeInfo scopeInfo)
        {
            var command = connection.CreateCommand();

            if (transaction != null)
            {
                command.Transaction = transaction;
            }
            bool alreadyOpened = connection.State == ConnectionState.Open;

            try
            {
                if (!alreadyOpened)
                {
                    await connection.OpenAsync().ConfigureAwait(false);
                }

                command.CommandText = $@"
                    MERGE {scopeTableName.Quoted().ToString()} AS [base] 
                    USING (
                               SELECT  @sync_scope_id AS sync_scope_id,  
	                                   @sync_scope_name AS sync_scope_name,  
	                                   @sync_scope_schema AS sync_scope_schema,  
	                                   @sync_scope_setup AS sync_scope_setup,  
	                                   @sync_scope_version AS sync_scope_version,  
                                       @scope_last_sync AS scope_last_sync,
                                       @scope_last_sync_timestamp AS scope_last_sync_timestamp,
                                       @scope_last_server_sync_timestamp AS scope_last_server_sync_timestamp,
                                       @scope_last_sync_duration AS scope_last_sync_duration
                           ) AS [changes] 
                    ON [base].[sync_scope_id] = [changes].[sync_scope_id]
                    WHEN NOT MATCHED THEN
	                    INSERT ([sync_scope_name], [sync_scope_schema], [sync_scope_setup], [sync_scope_version], [sync_scope_id], [scope_last_sync], [scope_last_sync_timestamp],           [scope_last_server_sync_timestamp],           [scope_last_sync_duration])
	                    VALUES ([changes].[sync_scope_name], [changes].[sync_scope_schema], [changes].[sync_scope_setup], [changes].[sync_scope_version], [changes].[sync_scope_id], [changes].[scope_last_sync],  [changes].[scope_last_sync_timestamp], [changes].[scope_last_server_sync_timestamp], [changes].[scope_last_sync_duration])
                    WHEN MATCHED THEN
	                    UPDATE SET [sync_scope_name] = [changes].[sync_scope_name], 
                                   [sync_scope_schema] = [changes].[sync_scope_schema], 
                                   [sync_scope_setup] = [changes].[sync_scope_setup], 
                                   [sync_scope_version] = [changes].[sync_scope_version], 
                                   [scope_last_sync] = [changes].[scope_last_sync],
                                   [scope_last_sync_timestamp] = [changes].[scope_last_sync_timestamp],
                                   [scope_last_server_sync_timestamp] = [changes].[scope_last_server_sync_timestamp],
                                   [scope_last_sync_duration] = [changes].[scope_last_sync_duration]
                    OUTPUT  INSERTED.[sync_scope_name], 
                            INSERTED.[sync_scope_schema], 
                            INSERTED.[sync_scope_setup], 
                            INSERTED.[sync_scope_version], 
                            INSERTED.[sync_scope_id], 
                            INSERTED.[scope_last_sync],
                            INSERTED.[scope_last_sync_timestamp],
                            INSERTED.[scope_last_server_sync_timestamp],
                            INSERTED.[scope_last_sync_duration];
                ";

                var p = command.CreateParameter();
                p.ParameterName = "@sync_scope_name";
                p.Value         = scopeInfo.Name;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_schema";
                p.Value         = scopeInfo.Schema == null ? DBNull.Value : (object)JsonConvert.SerializeObject(scopeInfo.Schema);
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_setup";
                p.Value         = scopeInfo.Setup == null  ? DBNull.Value : (object)JsonConvert.SerializeObject(scopeInfo.Setup);
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_version";
                p.Value         = string.IsNullOrEmpty(scopeInfo.Version) ? DBNull.Value : (object)scopeInfo.Version;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_id";
                p.Value         = scopeInfo.Id;
                p.DbType        = DbType.Guid;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync";
                p.Value         = scopeInfo.LastSync.HasValue ? (object)scopeInfo.LastSync.Value : DBNull.Value;
                p.DbType        = DbType.DateTime;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync_timestamp";
                p.Value         = scopeInfo.LastSyncTimestamp;
                p.DbType        = DbType.Int64;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_server_sync_timestamp";
                p.Value         = scopeInfo.LastServerSyncTimestamp;
                p.DbType        = DbType.Int64;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync_duration";
                p.Value         = scopeInfo.LastSyncDuration;
                p.DbType        = DbType.Int64;
                command.Parameters.Add(p);


                using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            scopeInfo.Name                    = reader["sync_scope_name"] as string;
                            scopeInfo.Schema                  = reader["sync_scope_schema"] == DBNull.Value ? null : JsonConvert.DeserializeObject <SyncSet>((string)reader["sync_scope_schema"]);
                            scopeInfo.Setup                   = reader["sync_scope_setup"] == DBNull.Value ? null : JsonConvert.DeserializeObject <SyncSetup>((string)reader["sync_scope_setup"]);
                            scopeInfo.Version                 = reader["sync_scope_Version"] as string;
                            scopeInfo.Id                      = (Guid)reader["sync_scope_id"];
                            scopeInfo.LastSync                = reader["scope_last_sync"] != DBNull.Value ? (DateTime?)reader["scope_last_sync"] : null;
                            scopeInfo.LastSyncTimestamp       = reader["scope_last_sync_timestamp"] != DBNull.Value ? (long)reader["scope_last_sync_timestamp"] : 0;
                            scopeInfo.LastServerSyncTimestamp = reader["scope_last_server_sync_timestamp"] != DBNull.Value ? (long)reader["scope_last_server_sync_timestamp"] : 0;
                            scopeInfo.LastSyncDuration        = reader["scope_last_sync_duration"] != DBNull.Value ? (long)reader["scope_last_sync_duration"] : 0;
                        }
                    }
                }

                return(scopeInfo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during CreateTableScope : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }

                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
 public Task <ScopeInfo> InsertOrUpdateClientScopeInfoAsync(ScopeInfo scopeInfo) => Task.FromResult(scopeInfo);
        internal List<CompletionItem> GetCompletionList(CodePoint location, string idents)
        {
            ScopeInfo scopeIdentifier = new ScopeInfo();
            if (!GetScopeIdentifier(location, ref scopeIdentifier))
                return null; // Unknown scope.

            bool isStatic = false;
            int identifierType = GetIdentifierType(scopeIdentifier, location, idents, true, ref isStatic);
            if (ProtoCore.DSASM.Constants.kInvalidIndex == identifierType)
                return null; // No identifier of given name found in scope.

            return (GetClassMembers(identifierType, isStatic, scopeIdentifier));
        }
Beispiel #33
0
 public ScopeInfo(ScopeInfo parentScope)
 {
     this.Type = parentScope.Type;
     this.usedTypeArguments = new HashSet <string>(parentScope.usedTypeArguments);
 }
        internal List<MethodSignature> GetMethodSignatures(CodePoint location, string idents)
        {
            ScopeInfo scopeIdentifier = new ScopeInfo();
            if (!GetScopeIdentifier(location, ref scopeIdentifier))
                return null; // Unknown scope.

            // This identifier list traversal is slightly different from the one for
            // 'GetCompletionList'. For example, "a.b.c.d.e.foo" where the "foo"
            // identifier is expected to be a method name, so the logic needs only to
            // traverse up to "e" to resolve its type, disregarding "foo".
            //
            bool isStatic = false;
            int identifierType = GetIdentifierType(scopeIdentifier, location, idents, false, ref isStatic);

            // If the "search site" is not within any class body/method.
            if (ProtoCore.DSASM.Constants.kInvalidIndex == scopeIdentifier.ClassScope)
            {
                // If the "search target" is in global scope...
                if (ProtoCore.DSASM.Constants.kInvalidIndex == identifierType)
                {
                    // Only get those global methods that belong to the same
                    // block as the search site (methods residing in another
                    // block cannot be accessed within the current block).
                    //
                    // GetMethodSignatures(scopeIdentifier)
                }

                // If the "search target" is in a class...
                else
                {
                    // While looking up methods of a class in a global scope,
                    // it can at most access methods that are made public.
                    //
                    // GetClassMethods(identifierType, false, AccessSpecifier.kPublic, results);
                }
            }

            // If the "search site" is within a class body/method.
            else
            {
                // If user only types "foo" (instead of "a.b.foo") within a class
                // body/method, then look for "foo" within the current class, or
                // in any base classes if it can be accessed from the search site.
                //
                if (ProtoCore.DSASM.Constants.kInvalidIndex == identifierType)
                {
                }

                // If user types "a.b.foo", then at most public methods can be
                // accessed. But if user types "this.foo", then a traversal is
                // required up the class hierarchy to obtain methods with name "foo".
                else
                {
                }
            }

            return null;
        }
        protected override void OnTranslate(ShaderTranslationContext sc, PredefinedTypeSyntax syntax, ScopeInfo scope)
        {
            string     typeName = syntax.Keyword.ToString();
            ShaderType type     = ShaderType.TranslateType(sc, typeName);

            sc.Source.Append(type.Translation);
        }
        private int GetBlockMemberType(ScopeInfo scopeIdentifier, string identifier)
        {
            int currentBlock = scopeIdentifier.BlockId;
            while (currentBlock != ProtoCore.DSASM.Constants.kInvalidIndex)
            {
                string[] conditions =
                {
                    "Name = " + GetDatabaseType(identifier),
                    "CodeBlock = " + currentBlock.ToString(),
                    "ClassScope = " + scopeIdentifier.ClassScope.ToString(),
                    "Procedure = " + scopeIdentifier.FunctionIndex.ToString()
                };

                try
                {
                    string statement = SelectFromStatement(TableNames.Symbols, conditions);
                    SQLiteCommand command = new SQLiteCommand(statement, connection);
                    SQLiteDataReader reader = command.ExecuteReader();
                    if (null != reader && (false != reader.HasRows))
                    {
                        if (reader.Read()) // Read in the only record.
                        {
                            int dataType = reader.GetInt32(5); // "DataType" field.
                            int staticType = reader.GetInt32(6); // "StaticType" field.
                            return GetSymbolType(staticType, dataType);
                        }
                    }
                }
                catch (Exception exception)
                {
                    HandleException(exception);
                }

                // Nothing found, go up to the parent block.
                currentBlock = GetParentBlock(currentBlock);
            }

            return ProtoCore.DSASM.Constants.kInvalidIndex; // Invalid type.
        }
Beispiel #37
0
 public override void ExecuteBatchCommand(DbCommand cmd, DmTable applyTable, DmTable failedRows, ScopeInfo scope)
 {
     throw new NotImplementedException();
 }
        private List<CompletionItem> GetClassMembers(int classScope, bool isStatic, ScopeInfo scopeIdentifier)
        {
            if (ProtoCore.DSASM.Constants.kInvalidIndex == classScope)
            {
                string mesg = "'GetClassMembers' called for invalid class scope!";
                throw new InvalidOperationException(mesg);
            }

            List<int> classesToSearch = GetAllBaseClasses(classScope);

            bool withinClassHierarchy = false;
            if (ProtoCore.DSASM.Constants.kInvalidIndex != scopeIdentifier.ClassScope)
            {
                // "scopeIdentifier" represents the scope in which AutoComplete list
                // has been requested, this is referred to as "search site". This line
                // checks to see if the search site is falling within the class
                // hierarchy leading up from 'classScope' (i.e. the class out of which
                // members are to be retrieved).
                //
                withinClassHierarchy = classesToSearch.Contains(scopeIdentifier.ClassScope);
            }

            // The resulting completion list.
            List<CompletionItem> results = new List<CompletionItem>();

            while (classesToSearch.Count > 0)
            {
                int currentClass = classesToSearch[0];
                classesToSearch.RemoveAt(0);

                // If the site is within a class body or class method, then the
                // result of searching the same class should include even the
                // private class properties/methods. As the search goes up to
                // the parent class, then search results should exclude private
                // properties/methods. If the search site is outside of a class
                // body, then only public properties/methods should be returned.
                //
                AccessSpecifier maxAllowedAccess = AccessSpecifier.kPublic;
                if (currentClass == classScope)
                {
                    // Within the current class, allow private access.
                    maxAllowedAccess = AccessSpecifier.kPrivate;
                }
                else if (false != withinClassHierarchy)
                {
                    // Not within the 'classScope', but somewhere along
                    // the class hierarchy, allow access to protected members.
                    maxAllowedAccess = AccessSpecifier.kProtected;
                }

                GetClassProperties(currentClass, isStatic, maxAllowedAccess, results);
                GetClassMethods(currentClass, isStatic, maxAllowedAccess, results);
            }

            return results;
        }
Beispiel #39
0
        public ScopeInfo InsertOrUpdateScopeInfo(ScopeInfo scopeInfo)
        {
            var command = connection.CreateCommand();

            if (transaction != null)
            {
                command.Transaction = transaction;
            }
            bool alreadyOpened = connection.State == ConnectionState.Open;

            try
            {
                if (!alreadyOpened)
                {
                    connection.Open();
                }

                command.CommandText = $@"
                    MERGE {scopeTableName.QuotedObjectName} AS [base] 
                    USING (
                               SELECT  @sync_scope_id AS sync_scope_id,  
	                                   @sync_scope_name AS sync_scope_name,  
                                       @scope_is_local as scope_is_local,
                                       @scope_last_sync AS scope_last_sync,
                                       @scope_last_sync_timestamp AS scope_last_sync_timestamp,
                                       @scope_last_sync_duration AS scope_last_sync_duration
                           ) AS [changes] 
                    ON [base].[sync_scope_id] = [changes].[sync_scope_id]
                    WHEN NOT MATCHED THEN
	                    INSERT ([sync_scope_name], [sync_scope_id], [scope_is_local], [scope_last_sync], [scope_last_sync_timestamp], [scope_last_sync_duration])
	                    VALUES ([changes].[sync_scope_name], [changes].[sync_scope_id], [changes].[scope_is_local], [changes].[scope_last_sync],  [changes].[scope_last_sync_timestamp], [changes].[scope_last_sync_duration])
                    WHEN MATCHED THEN
	                    UPDATE SET [sync_scope_name] = [changes].[sync_scope_name], 
                                   [scope_is_local] = [changes].[scope_is_local], 
                                   [scope_last_sync] = [changes].[scope_last_sync],
                                   [scope_last_sync_timestamp] = [changes].[scope_last_sync_timestamp],
                                   [scope_last_sync_duration] = [changes].[scope_last_sync_duration]
                    OUTPUT  INSERTED.[sync_scope_name], 
                            INSERTED.[sync_scope_id], 
                            INSERTED.[scope_timestamp], 
                            INSERTED.[scope_is_local],
                            INSERTED.[scope_last_sync],
                            INSERTED.[scope_last_sync_timestamp],
                            INSERTED.[scope_last_sync_duration];
                ";

                var p = command.CreateParameter();
                p.ParameterName = "@sync_scope_name";
                p.Value         = scopeInfo.Name;
                p.DbType        = DbType.String;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@sync_scope_id";
                p.Value         = scopeInfo.Id;
                p.DbType        = DbType.Guid;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_is_local";
                p.Value         = scopeInfo.IsLocal;
                p.DbType        = DbType.Boolean;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync";
                p.Value         = scopeInfo.LastSync.HasValue ? (object)scopeInfo.LastSync.Value : DBNull.Value;
                p.DbType        = DbType.DateTime;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync_timestamp";
                p.Value         = scopeInfo.LastSyncTimestamp;
                p.DbType        = DbType.Int64;
                command.Parameters.Add(p);

                p = command.CreateParameter();
                p.ParameterName = "@scope_last_sync_duration";
                p.Value         = scopeInfo.LastSyncDuration;
                p.DbType        = DbType.Int64;
                command.Parameters.Add(p);


                using (DbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        scopeInfo.Name              = reader["sync_scope_name"] as String;
                        scopeInfo.Id                = (Guid)reader["sync_scope_id"];
                        scopeInfo.Timestamp         = SqlManager.ParseTimestamp(reader["scope_timestamp"]);
                        scopeInfo.IsLocal           = (bool)reader["scope_is_local"];
                        scopeInfo.LastSync          = reader["scope_last_sync"] != DBNull.Value ? (DateTime?)reader["scope_last_sync"] : null;
                        scopeInfo.LastSyncTimestamp = reader["scope_last_sync_timestamp"] != DBNull.Value ? (long)reader["scope_last_sync_timestamp"] : 0;
                        scopeInfo.LastSyncDuration  = reader["scope_last_sync_duration"] != DBNull.Value ? (long)reader["scope_last_sync_duration"] : 0;
                    }
                }

                return(scopeInfo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during CreateTableScope : {ex}");
                throw;
            }
            finally
            {
                if (!alreadyOpened && connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }

                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
Beispiel #40
0
        internal int GetArrayElementType(ScopeInfo scopeInfo, string[] identList)
        {
            if (null == arrayTypeTable)
                return ((int)PrimitiveType.kInvalidType);

            string arrayName = identList[0];
            foreach (KeyValuePair<ScopedArray, ArrayElementType> arrayType in arrayTypeTable)
            {
                if (arrayType.Key.ScopeInfo == scopeInfo)
                {
                    if (arrayType.Key.ArrayName == arrayName)
                    {
                        ArrayElementType arrayRoot = arrayType.Value;
                        ArrayElementType element = arrayRoot.GetElementFromIndices(identList);
                        if (null != element)
                            return element.Type.UID;
                    }
                }
            }

            return ((int)PrimitiveType.kInvalidType);
        }
        protected override void OnTranslate(ShaderTranslationContext sc, AccessorDeclarationSyntax syntax, ScopeInfo scope)
        {
            if (scope.Type == ScopeType.Property)
            {
                switch (syntax.Keyword.ValueText)
                {
                case "get":
                    sc.Source.Append($"{scope.TypeInfo.Translation} get{scope.Identifier}()");
                    break;

                case "set":
                    sc.Source.Append($"void set{scope.Identifier}({scope.TypeInfo.Translation} value)");
                    break;
                }

                ScopeInfo mScope     = sc.Source.OpenScope(ScopeType.Method);
                ScopeInfo classScope = scope.FindOfType(ScopeType.Class);
                mScope.Method = classScope.TypeInfo.OriginalType.GetMethod($"{syntax.Keyword.ValueText}_{scope.Identifier}");
            }
        }
Beispiel #42
0
    private Scope _parent; //computed on demand

    public Scope(ScopeInfo scopeInfo, Scope caller, Scope creator, object[] parameters) : base(scopeInfo) {
      Caller = caller;
      Creator = creator; 
      Parameters = parameters;
    }
        protected override void OnTranslate(ShaderTranslationContext sc, VariableDeclaratorSyntax syntax, ScopeInfo scope)
        {
            if (scope.Type == ScopeType.Typed)
            {
                FieldInfo            fInfo      = null;
                MappedField          mField     = null;
                MappedConstantBuffer cBufferMap = null;

                if (scope.Parent.Type == ScopeType.Struct)
                {
                    fInfo = scope.Parent.TypeInfo.OriginalType.GetField(syntax.Identifier.ValueText);
                    sc.ConstantBuffers.TryGetValue(scope.Parent.TypeInfo.OriginalType.Name, out cBufferMap);
                }

                if (fInfo == null)
                {
                    sc.Fields.TryGetValue(syntax.Identifier.ValueText, out fInfo);
                }


                if (fInfo != null)
                {
                    int fieldIndex = scope.Items.IndexOf(syntax);
                    mField = Pooling.MappedFields.Get();
                    mField.Initialize(scope.TypeInfo, fInfo);
                    cBufferMap?.AddField(mField);

                    sc.Language.TranslateFieldPrefix(sc, syntax, mField, fieldIndex, cBufferMap);
                    sc.Source.Append($"{scope.TranslatedModifiers} ");
                    sc.Source.Append(scope.TypeInfo.Translation);
                    sc.Source.Append($" {syntax.Identifier.ValueText}");
                    sc.Language.TranslateFieldPostfix(sc, syntax, mField, fieldIndex, cBufferMap);
                }
                else
                {
                    sc.Source.Append($"{scope.TranslatedModifiers} ");
                    sc.Source.Append(scope.TypeInfo.Translation);
                    sc.Source.Append($" {syntax.Identifier.ValueText}");
                }

                // Handle corner-cases for array initializers.
                if (scope.TypeInfo != null && syntax.Initializer != null)
                {
                    if (scope.TypeInfo.WasArrayType)
                    {
                        switch (syntax.Initializer.Value)
                        {
                        case InitializerExpressionSyntax initSyntax:
                            IEnumerable <SyntaxNode> initChildren = initSyntax.ChildNodes();
                            int arraySize = initChildren.Count();
                            sc.Source.Append($"[{arraySize}]");

                            if (mField != null)
                            {
                                mField.ArrayDimensions.Add(arraySize);
                            }

                            // TODO multi-dimensional array support (e.g. [4][2]).
                            //     - For multi-dimensional arrays, we can simply take the dimensions directly.
                            //     - For jagged arrays, we need to find the largest sub-array and use that as the size for it's respective dimension.
                            break;

                        case ArrayCreationExpressionSyntax arraySyntax:
                            sc.Runner.Translate(sc, arraySyntax.Type);
                            break;
                        }
                    }
                }

                bool isForInitializer = (syntax.Parent is VariableDeclarationSyntax varDecSyntax && varDecSyntax.Parent is ForStatementSyntax forSyntax);
                if (!isForInitializer)
                {
                    if (syntax.Initializer != null && syntax.Initializer.Value is ObjectCreationExpressionSyntax objSyntax && objSyntax.Initializer != null)
                    {
                        ScopeInfo si = sc.Source.OpenScope(ScopeType.ExpandedInitializer);
                        si.Identifier = syntax.Identifier.ValueText;
                        sc.Source.Append(" = ");

                        // Are we instantiating a new struct value with no args?
                        if (objSyntax.ArgumentList.Arguments.Count == 0 && scope.TypeInfo.OriginalType.IsValueType)
                        {
                            sc.Source.Append($"({scope.TypeInfo.Translation})0;"); // TODO does GLSL allow this? Do we abstract or add a language property to check against?
                            sc.Source.AppendLineBreak();
                            sc.Complete(objSyntax.ArgumentList);
                            sc.Complete(objSyntax.Type);
                        }
                        else
                        {
                            sc.Source.Append(scope.TypeInfo.Translation);
                            sc.Runner.Translate(sc, objSyntax.ArgumentList);
                            sc.Source.Append(";");
                            sc.Source.AppendLineBreak();
                            sc.Runner.Translate(sc, objSyntax.Initializer);
                            sc.Complete(objSyntax.ArgumentList);
                            sc.Complete(objSyntax.Type);
                        }

                        // We no longer need to translate the object creation syntax, but we still want it's initializer.
                        sc.Complete(syntax.Initializer);
                        sc.Runner.Translate(sc, objSyntax.Initializer);
                    }
                    else
                    {
                        ScopeInfo si = sc.Source.OpenScope(ScopeType.Variable);
                        si.Identifier = syntax.Identifier.ValueText;
                    }
                }
            }
 public void PushClosureScope(ScopeInfo scopeInfo, Scope closureParent, object[] parameters) {
   CurrentScope = new Scope(scopeInfo, CurrentScope, closureParent, parameters);
 }
Beispiel #45
0
        public override bool CheckInvocation(TexlBinding binding, TexlNode[] args, DType[] argTypes, IErrorContainer errors, out DType returnType, out Dictionary <TexlNode, DType> nodeToCoercedTypeMap)
        {
            Contracts.AssertValue(args);
            Contracts.AssertValue(argTypes);
            Contracts.Assert(args.Length == argTypes.Length);
            Contracts.AssertValue(errors);
            Contracts.Assert(MinArity <= args.Length && args.Length <= MaxArity);

            bool fArgsValid = base.CheckInvocation(args, argTypes, errors, out returnType, out nodeToCoercedTypeMap);

            // The first arg determines the scope type for the lambda params, and the return type.
            DType typeScope;

            fArgsValid &= ScopeInfo.CheckInput(args[0], argTypes[0], errors, out typeScope);
            Contracts.Assert(typeScope.IsRecord);

            // The result type has N additional columns, as specified by (args[1],args[2]), (args[3],args[4]), ... etc.
            returnType = typeScope.ToTable();

            int count = args.Length;

            if ((count & 1) == 0)
            {
                errors.EnsureError(DocumentErrorSeverity.Severe, args[0].Parent.CastList().Parent.CastCall(), TexlStrings.ErrBadArityOdd, count);
            }

            for (var i = 1; i < count; i += 2)
            {
                TexlNode nameArg     = args[i];
                DType    nameArgType = argTypes[i];

                // Verify we have a string literal for the column name. Accd to spec, we don't support
                // arbitrary expressions that evaluate to string values, because these values contribute to
                // type analysis, so they need to be known upfront (before AddColumns executes).
                StrLitNode nameNode;
                if (nameArgType.Kind != DKind.String ||
                    (nameNode = nameArg.AsStrLit()) == null)
                {
                    fArgsValid = false;
                    errors.EnsureError(DocumentErrorSeverity.Severe, nameArg, TexlStrings.ErrExpectedStringLiteralArg_Name, nameArg.ToString());
                    continue;
                }

                // Verify that the name is valid.
                if (!DName.IsValidDName(nameNode.Value))
                {
                    fArgsValid = false;
                    errors.EnsureError(DocumentErrorSeverity.Severe, nameArg, TexlStrings.ErrArgNotAValidIdentifier_Name, nameNode.Value);
                    continue;
                }

                DName  columnName = new DName(nameNode.Value);
                string colName;
                if (DType.TryGetDisplayNameForColumn(typeScope, columnName, out colName))
                {
                    columnName = new DName(colName);
                }

                // Verify that the name doesn't already exist as either a logical or display name
                DType  columnType;
                string unused;
                if (typeScope.TryGetType(columnName, out columnType) || DType.TryGetLogicalNameForColumn(typeScope, columnName, out unused))
                {
                    fArgsValid = false;
                    errors.EnsureError(DocumentErrorSeverity.Moderate, nameArg, TexlStrings.ErrColExists_Name, columnName);
                    continue;
                }

                if (i + 1 >= count)
                {
                    break;
                }

                columnType = argTypes[i + 1];

                // Augment the result type to include the specified column, and verify that it
                // hasn't been specified already within the same invocation.
                bool fError = false;
                returnType = returnType.Add(ref fError, DPath.Root, columnName, columnType);
                if (fError)
                {
                    fArgsValid = false;
                    errors.EnsureError(DocumentErrorSeverity.Moderate, nameArg, TexlStrings.ErrColConflict_Name, columnName);
                    continue;
                }
            }

            return(fArgsValid);
        }
        protected override void DfsTraverse(ProtoCore.AST.Node pNode, ref ProtoCore.Type inferedType, bool isBooleanOp = false, ProtoCore.AssociativeGraph.GraphNode graphNode = null, ProtoCore.DSASM.AssociativeSubCompilePass subPass = ProtoCore.DSASM.AssociativeSubCompilePass.kNone)
        {
            AssociativeNode node = pNode as AssociativeNode;
            if ((null == node) || node.skipMe)
                return;

            if (node is IdentifierNode)
            {
                EmitIdentifierNode(node, ref inferedType, isBooleanOp, graphNode, subPass);
            }
            else if (node is IntNode)
            {
                EmitIntNode(node, ref inferedType, isBooleanOp, subPass);
            }
            else if (node is DoubleNode)
            {
                EmitDoubleNode(node, ref inferedType, isBooleanOp, subPass);
            }
            else if (node is BooleanNode)
            {
                EmitBooleanNode(node, ref inferedType, subPass);
            }
            else if (node is CharNode)
            {
                EmitCharNode(node, ref inferedType, isBooleanOp, subPass);
            }
            else if (node is StringNode)
            {
                EmitStringNode(node, ref inferedType, subPass);
            }
            else if (node is NullNode)
            {
                EmitNullNode(node, ref inferedType, isBooleanOp, subPass);
            }
            #if ENABLE_INC_DEC_FIX
            else if (node is PostFixNode)
            {
                EmitPostFixNode(node, ref inferedType);
            }
            #endif
            else if (node is ReturnNode)
            {
                EmitReturnNode(node);
            }
            else if (node is RangeExprNode)
            {
                EmitRangeExprNode(node, ref inferedType, subPass);
            }
            else if (node is ForLoopNode)
            {
                EmitForLoopNode(node);
            }
            else if (node is LanguageBlockNode)
            {
                EmitLanguageBlockNode(node, ref inferedType, subPass);
            }
            else if (node is ClassDeclNode)
            {
                EmitClassDeclNode(node, ref inferedType, subPass);
            }
            else if (node is ConstructorDefinitionNode)
            {
                EmitConstructorDefinitionNode(node, ref inferedType, subPass);
            }
            else if (node is FunctionDefinitionNode)
            {
                EmitFunctionDefinitionNode(node, ref inferedType, subPass);
            }
            else if (node is FunctionCallNode)
            {
                EmitFunctionCallNode(node, ref inferedType, isBooleanOp, graphNode, subPass);
            }
            else if (node is ModifierStackNode)
            {
                EmitModifierStackNode(node, ref inferedType);
            }
            else if (node is ExprListNode)
            {
                ScopedArray scopedArray = null;
                ArrayElementType parentElementType = this.arrayElementType;

                // The same code is parsed in multiple passes, don't populate array element type table all
                // the times, we should only do it when all things are parsed.
                bool generateArrayElementTypes = subPass == ProtoCore.DSASM.AssociativeSubCompilePass.kNone;

                if (generateArrayElementTypes && (null != CoreCodeGen.arrayTypeTable))
                {
                    ScopeInfo scopeInfo = new ScopeInfo()
                    {
                        // For global scope, "localProcedure" will be of null value.
                        BlockId = ((null == localProcedure) ? 0 : localProcedure.runtimeIndex),
                        ClassScope = ((null == localProcedure) ? -1 : localProcedure.classScope),
                        FunctionIndex = ((null == localProcedure) ? -1 : localProcedure.procId)
                    };

                    node.Name = node.Name == null ? string.Empty : node.Name;
                    if (null != parentElementType || (!string.IsNullOrEmpty(node.Name)))
                    {
                        scopedArray = new ScopedArray(scopeInfo, node.Name);
                        this.arrayElementType = new ArrayElementType();
                    }
                }

                EmitExprListNode(node, ref inferedType, graphNode, subPass);

                if (generateArrayElementTypes && (null != CoreCodeGen.arrayTypeTable))
                {
                    if (null == parentElementType)
                    {
                        CoreCodeGen.arrayTypeTable.InsertRootElementType(
                            scopedArray, this.arrayElementType);

                        this.arrayElementType = null;
                    }
                    else
                    {
                        parentElementType.AppendChild(this.arrayElementType);
                        this.arrayElementType = parentElementType;
                    }
                }
            }
            else if (node is IdentifierListNode)
            {
                EmitIdentifierListNode(node, ref inferedType, isBooleanOp, graphNode, subPass);
            }
            else if (node is IfStatementNode)
            {
                EmitIfStatementNode(node, ref inferedType);
            }
            else if (node is InlineConditionalNode)
            {
                EmitInlineConditionalNode(node, ref inferedType, graphNode, subPass);
            }
            else if (node is UnaryExpressionNode)
            {
                EmitUnaryExpressionNode(node, ref inferedType, graphNode);
            }
            else if (node is BinaryExpressionNode)
            {
                EmitBinaryExpressionNode(node, ref inferedType, isBooleanOp, graphNode, subPass);
            }
            else if (node is ImportNode)
            {
                EmitImportNode(node, ref inferedType, subPass);
            }
            else if (node is ExceptionHandlingNode)
            {
                EmitExceptionHandlingNode(node, graphNode, subPass);
            }
            else if (node is ThrowNode)
            {
            }
        }
        private int GetClassMemberType(ScopeInfo scopeIdentifier, string identifier, bool isStatic)
        {
            // The identifier is within a class body, having a name
            // "this" would have made its type the same as the class.
            if (identifier == "this")
                return scopeIdentifier.ClassScope;

            List<int> classesToSearch = GetAllBaseClasses(scopeIdentifier.ClassScope);
            while (classesToSearch.Count > 0)
            {
                int currentClass = classesToSearch[0];
                classesToSearch.RemoveAt(0);

                string[] conditions =
                {
                    "Name = " + GetDatabaseType(identifier),
                    "CodeBlock = " + scopeIdentifier.BlockId.ToString(),
                    "ClassScope = " + currentClass.ToString(),
                    "Procedure = " + scopeIdentifier.FunctionIndex.ToString(),
                    "IsStatic = " + GetDatabaseType(isStatic)
                };

                try
                {
                    string statement = SelectFromStatement(TableNames.Symbols, conditions);
                    SQLiteCommand command = new SQLiteCommand(statement, connection);
                    SQLiteDataReader reader = command.ExecuteReader();
                    if (null != reader && (false != reader.HasRows))
                    {
                        if (reader.Read()) // Read in the only record.
                        {
                            int dataType = reader.GetInt32(5); // "DataType" field.
                            int staticType = reader.GetInt32(6); // "StaticType" field.
                            return GetSymbolType(staticType, dataType);
                        }
                    }
                }
                catch (Exception exception)
                {
                    HandleException(exception);
                }

                // The procedure ID is only applicable to the current class, as we
                // proceed to check in base classes, we will not need the procedure
                // ID as it won't be applicable there (even if another procedure with
                // the same ID exists in that parent class). So we'll just set it to
                // an invalid value. The same rule applies to a block (it is possible
                // to have a block embedded within a class member function, in which
                // case the block will not be zero).
                //
                scopeIdentifier.BlockId = 0;
                scopeIdentifier.FunctionIndex = ProtoCore.DSASM.Constants.kInvalidIndex;
            }

            return ProtoCore.DSASM.Constants.kInvalidIndex; // Invalid type.
        }
 protected override void OnTranslate(ShaderTranslationContext sc, FieldDeclarationSyntax syntax, ScopeInfo scope)
 {
     // Does the language allow instanced constant buffers and does the field use a constant buffer struct type?
     if (sc.ConstantBuffers.ContainsKey(syntax.Declaration.Type.ToString()))
     {
         if (!sc.Language.InstancedConstantBuffers)
         {
             sc.CompleteSelfAndChildren(syntax);
         }
     }
     else
     {
         sc.CompleteSelfAndChildren(syntax.AttributeLists);
     }
 }
Beispiel #49
0
 internal ScopedArray(ScopeInfo scopeInfo, string name)
 {
     this.arrayName = name;
     this.scopeInfo = scopeInfo;
 }
        private int GetIdentifierType(ScopeInfo scopeIdentifier, CodePoint location,
            string identifier, bool includeLastIdent, ref bool isStatic)
        {
            isStatic = false;
            if (string.IsNullOrEmpty(identifier))
                return ProtoCore.DSASM.Constants.kInvalidIndex;

            // Split the identifier list (e.g. "a.b.c" -> { "a", "b", "c" })
            char[] seperator = { '.' };
            string[] idents = identifier.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
            if (null == idents || (idents.Length <= 0))
                return ProtoCore.DSASM.Constants.kInvalidIndex;

            // The caller may choose to drop the last identifier in the list, if
            // it represents a method name. For example, "a.b.foo", the search
            // only goes up to determine the type of "b" while disregarding "foo".
            if (false == includeLastIdent)
            {
                List<string> intermediate = idents.ToList();
                intermediate.RemoveAt(intermediate.Count - 1);
                if (intermediate.Count <= 0)
                    return ProtoCore.DSASM.Constants.kInvalidIndex;

                idents = idents.ToArray();
            }

            // First we need to find out the type of the "root
            // variable". For example, "a" in the case of "a.b.c".
            //
            string rootIdentifier = idents[0];
            int rootType = ProtoCore.DSASM.Constants.kInvalidIndex;

            if (ProtoCore.DSASM.Constants.kInvalidIndex != scopeIdentifier.ClassScope)
            {
                // If this symbol is in a language block within a class definition...
                if (scopeIdentifier.BlockId != 0)
                    rootType = GetBlockMemberType(scopeIdentifier, rootIdentifier);

                // This identifier is found within a class definition region.
                if (ProtoCore.DSASM.Constants.kInvalidIndex == rootType)
                    rootType = GetClassMemberType(scopeIdentifier, rootIdentifier, isStatic);
            }
            else
            {
                // For identifiers found outside of the class definition region...
                rootType = GetBlockMemberType(scopeIdentifier, rootIdentifier);
            }

            // It seems like the identifier does not correspond to a valid variable
            // name given the scope it resides in. Check to see if it represents the
            // name of an existing class.
            if (ProtoCore.DSASM.Constants.kInvalidIndex == rootType)
            {
                bool isImported = false;
                rootType = GetClassScopeFromName(rootIdentifier, ref isImported);
                if (ProtoCore.DSASM.Constants.kInvalidIndex == rootType)
                    return ProtoCore.DSASM.Constants.kInvalidIndex;

                // We have found a class with name matching "rootIdentifier",
                // which means the subsequent identifier(s) is a static member.
                isStatic = true;
            }

            int finalType = ProtoCore.DSASM.Constants.kInvalidIndex;
            for (int index = 1; index < idents.Length; ++index)
            {
                string ident = idents[index];
                finalType = GetClassMemberType(scopeIdentifier, ident, isStatic);
                if (ProtoCore.DSASM.Constants.kInvalidIndex == finalType)
                    return ProtoCore.DSASM.Constants.kInvalidIndex;

                isStatic = false; // Can't be static after the root level.
            }

            return finalType;
        }
 public void PushScope(ScopeInfo scopeInfo, object[] parameters) {
   CurrentScope = new Scope(scopeInfo, CurrentScope, CurrentScope, parameters);
 }
        private MethodSignature GetMethodSignature(ScopeInfo methodScope, string methodName)
        {
            // @TODO(Ben): Remove these comments.
            //
            // 0  "CodeBlock      INTEGER",
            // 1  "ClassScope     INTEGER",
            // 2  "Procedure      INTEGER",
            // 3  "Name           NCHAR(255)",
            // 4  "AccessSpec     INTEGER",
            // 5  "DataType       INTEGER",
            // 6  "StaticType     INTEGER",
            // 7  "IsArgument     BOOLEAN",
            // 8  "IsArray        BOOLEAN",
            // 9  "IsStatic       BOOLEAN",
            // 10 "IsTemporary    BOOLEAN"
            //
            // 11 "Id             INTEGER PRIMARY KEY",
            // 12 "IsIndexable    BOOLEAN",
            // 13 "Name           NCHAR(255)",
            // 14 "Rank           INTEGER"

            string[] conditions =
            {
                "CodeBlock = " + methodScope.BlockId.ToString(),
                "ClassScope = " + methodScope.ClassScope.ToString(),
                "Procedure = " + methodScope.FunctionIndex.ToString()
            };

            string[] joints =
            {
                "s.StaticType = t.Id"
            };

            MethodSignature signature = new MethodSignature(methodName);

            try
            {
                string leftTable = TableNames.Symbols + " s";
                string rightTable = TableNames.DataTypes + " t";
                string statement = SelectJoinStatement(leftTable, rightTable, joints, conditions);
                SQLiteCommand command = new SQLiteCommand(statement, connection);
                SQLiteDataReader reader = command.ExecuteReader();
                if (null != reader && (false != reader.HasRows))
                {
                    while (reader.Read())
                    {
                        // "s.Name", "t.Name" and no default argument.
                        signature.AddArgument(reader.GetString(3), reader.GetString(13), null);
                    }
                }
            }
            catch (Exception exception)
            {
                HandleException(exception);
            }

            return null;
        }
        /// <summary>
        /// Returns all of the script IDs for the class
        /// </summary>
        /// <param name="javascriptClass">The text handler that has the class's javascript</param>
        /// <param name="subProcess">The process that must have the given script loaded</param>
        /// <returns></returns>
        public ScopeInfo GetScopeInfoForClass(ITextHandler javascriptClass, SubProcess subProcess)
        {
            DateTime javascriptLastModified = javascriptClass.FileContainer.LastModified;

            ScopeInfo toReturn = null;
            using (TimedLock.Lock(ScopeInfoCache))
                ScopeInfoCache.TryGetValue(javascriptClass.FileContainer.FileId, out toReturn);

            if (null != toReturn)
                if (toReturn.JavascriptLastModified == javascriptLastModified)
                {
                    using (TimedLock.Lock(PrecompiledScriptDataByID))
                        foreach (int scriptID in toReturn.ScriptsAndIDsToBuildScope)
                            subProcess.LoadCompiled(
                                Thread.CurrentThread.ManagedThreadId,
                                PrecompiledScriptDataByID[scriptID],
                                scriptID);

                    return toReturn;
                }

            string javascript = javascriptClass.ReadAll();
            string fileType = null;
            List<int> scriptIDsToBuildScope = new List<int>();

            ISession ownerSession = FileHandlerFactoryLocator.SessionManagerHandler.CreateSession();

            try
            {
                ownerSession.Login(javascriptClass.FileContainer.Owner);

                IWebConnection ownerWebConnection = new BlockingShellWebConnection(
                    FileHandlerFactoryLocator.WebServer,
                    ownerSession,
                    javascriptClass.FileContainer.FullPath,
                    null,
                    null,
                    new CookiesFromBrowser(),
                    CallingFrom.Web,
                    WebMethod.GET);

                IEnumerable<ScriptAndMD5> dependantScriptsAndMD5s = FileHandlerFactoryLocator.WebServer.WebComponentResolver.DetermineDependantScripts(
                    GetRequiredScriptURLs(javascriptClass, out fileType),
                    ownerWebConnection);

                // Load static methods that are passed into the Javascript environment as-is
                Dictionary<string, MethodInfo> functionsInScope = SubProcessFactory.GetFunctionsForFileType(fileType);

                // Load all dependant scripts
                foreach (ScriptAndMD5 dependantScript in dependantScriptsAndMD5s)
                {
                    int scriptID = GetScriptID(
                        dependantScript.ScriptName + "___" + ownerSession.User.Identity,
                        dependantScript.MD5,
                        dependantScript.Script,
                        subProcess);

                    scriptIDsToBuildScope.Add(scriptID);
                }

                // Construct Javascript to shell to the "base" webHandler
                Set<Type> webHandlerTypes = new Set<Type>(FileHandlerFactoryLocator.WebHandlerPlugins);
                if (null != fileType)
                    webHandlerTypes.Add(FileHandlerFactoryLocator.WebHandlerClasses[fileType]);

                string baseWrapper = GetJavascriptWrapperForBase("base", webHandlerTypes);
                scriptIDsToBuildScope.Add(
                    GetScriptID(
                        javascriptClass.FileContainer.FullPath + "___" + "serversideBaseWrapper",
                        StringParser.GenerateMD5String(baseWrapper),
                        baseWrapper,
                        subProcess));

                // Get the ID for the actual javascript
                scriptIDsToBuildScope.Add(
                    GetScriptID(
                        javascriptClass.FileContainer.FullPath,
                        StringParser.GenerateMD5String(javascript),
                        javascript,
                        subProcess));

                // Add a little shunt to return information about the options
                scriptIDsToBuildScope.Add(
                    GetScriptID(
                        "____scopeshunt",
                        "xxx",
                        "\nif (this.options) options; else null;",
                        subProcess));

                toReturn = new ScopeInfo(
                    javascriptLastModified,
                    functionsInScope,
                    scriptIDsToBuildScope);

                using (TimedLock.Lock(ScopeInfoCache))
                    ScopeInfoCache[javascriptClass.FileContainer.FileId] = toReturn;

                return toReturn;
            }
            finally
            {
                FileHandlerFactoryLocator.SessionManagerHandler.EndSession(ownerSession.SessionId);
            }
        }
        private void GetMethodSignatures(ScopeInfo scopeIdentifier, bool isStatic,
            string name, AccessSpecifier maxAllowedAccess, List<MethodSignature> results)
        {
            // Searching for a named method(s) in a given class (goes way up in hierarchy).
            if (ProtoCore.DSASM.Constants.kInvalidIndex != scopeIdentifier.ClassScope)
            {
                List<int> classesToSearch = GetAllBaseClasses(scopeIdentifier.ClassScope);
                while (classesToSearch.Count > 0)
                {
                    int currentClass = classesToSearch[0];
                    classesToSearch.RemoveAt(0);

                    // 0  "CodeBlock      INTEGER",
                    // 1  "ClassScope     INTEGER",
                    // 2  "Procedure      INTEGER",
                    // 3  "Name           NCHAR(255)",
                    // 4  "AccessSpec     INTEGER",
                    // 5  "ReturnType     INTEGER",
                    // 6  "IsExternal     BOOLEAN",
                    // 7  "IsStatic       BOOLEAN",
                    // 8  "IsConstructor  BOOLEAN"
                    //
                    // 9  "Id             INTEGER PRIMARY KEY",
                    // 10 "IsIndexable    BOOLEAN",
                    // 11 "Name           NCHAR(255)",
                    // 12 "Rank           INTEGER"

                    string[] conditions =
                    {
                        "CodeBlock = 0",
                        "ClassScope = " + currentClass.ToString(),
                        "Name = " + GetDatabaseType(name),
                        "AccessSpec <= " + ((int)maxAllowedAccess).ToString(),
                        "IsStatic = " + GetDatabaseType(isStatic)
                    };

                    string[] joints =
                    {
                        "p.ReturnType = t.Id"
                    };

                    try
                    {
                        string leftTable = TableNames.Procedures + " p";
                        string rightTable = TableNames.DataTypes + " t";

                        string statement = SelectJoinStatement(
                            leftTable, rightTable, joints, conditions);

                        SQLiteCommand command = new SQLiteCommand(statement, connection);
                        SQLiteDataReader reader = command.ExecuteReader();
                        if (null != reader && (false != reader.HasRows))
                        {
                            while (reader.Read())
                            {
                                ScopeInfo methodScope = new ScopeInfo()
                                {
                                    BlockId = 0,
                                    ClassScope = currentClass,
                                    FunctionIndex = reader.GetInt32(2) // "p.Procedure" field.
                                };

                                MethodSignature signature = GetMethodSignature(methodScope, name);
                                if (null == signature)
                                    continue;

                                signature.ReturnType = reader.GetString(11); // "t.Name" field.
                                signature.IsProperty = false;
                                signature.IsExternal = reader.GetBoolean(6); // "IsExternal" field.
                                signature.IsStatic = reader.GetBoolean(7); // "IsStatic" field.
                                signature.Access = ((AccessSpecifier)reader.GetInt32(4)); // "AccessSpec" field.

                                if (reader.GetBoolean(8)) // "IsConstructor" field.
                                    signature.IsConstructor = true;
                                else
                                    signature.IsMethod = true;

                                results.Add(signature);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        HandleException(exception);
                    }

                    // While the search moves up the class hierarchy, access will
                    // turn from "private" to "protected". If the 'maxAllowedAccess'
                    // was "public" to begin with, then it stays as "public".
                    //
                    if (maxAllowedAccess == AccessSpecifier.kPrivate)
                        maxAllowedAccess = AccessSpecifier.kProtected;
                }
            }
            else
            {
                // Looking for a global method in scope with the given name.
            }
        }
        private bool GetScopeIdentifier(CodePoint location, ref ScopeInfo scopeIdentifier)
        {
            string[] conditions =
            {
                "StartLine <= " + location.LineNo.ToString(),
                "EndLine >= " + location.LineNo.ToString()
            };

            Dictionary<ScopeInfo, CodeRange> scopeIdentifiers = null;

            try
            {
                string statement = SelectFromStatement(TableNames.ScopeRanges, conditions);
                SQLiteCommand command = new SQLiteCommand(statement, connection);
                SQLiteDataReader reader = command.ExecuteReader();
                if (null == reader || (false == reader.HasRows))
                    return false; // No record was found matching.

                while (reader.Read())
                {
                    int startLine = reader.GetInt32(1);
                    int startColumn = reader.GetInt32(2);
                    int endLine = reader.GetInt32(3);
                    int endColumn = reader.GetInt32(4);

                    bool withinRange = true;
                    if (location.LineNo == startLine && (location.CharNo < startColumn))
                        withinRange = false;
                    else if (location.LineNo == endLine && (location.CharNo >= endColumn))
                        withinRange = false;

                    if (false == withinRange)
                        continue;

                    if (null == scopeIdentifiers)
                        scopeIdentifiers = new Dictionary<ScopeInfo, CodeRange>();

                    string path = GetScriptPath(reader.GetInt32(0));
                    ScopeInfo scope = new ScopeInfo()
                    {
                        BlockId = reader.GetInt32(5),
                        ClassScope = reader.GetInt32(6),
                        FunctionIndex = reader.GetInt32(7)
                    };

                    CodeRange range = MakeCodeRange(startLine, startColumn, endLine, endColumn, path);
                    scopeIdentifiers.Add(scope, range);
                }
            }
            catch (Exception exception)
            {
                HandleException(exception);
                return false;
            }

            if (null == scopeIdentifiers || (scopeIdentifiers.Count <= 0))
                return false;

            // Attempt to find the inner-most scope by seeing
            // if one scope completely contains another scope.
            //
            bool foundInnerMostScope = false;
            CodeRange innerMostScope = new CodeRange();
            foreach (var identifier in scopeIdentifiers)
            {
                if (false == foundInnerMostScope)
                {
                    innerMostScope = identifier.Value;
                    scopeIdentifier = identifier.Key;
                    foundInnerMostScope = true;
                    continue;
                }

                if (innerMostScope.InsideRange(identifier.Value))
                {
                    innerMostScope = identifier.Value;
                    scopeIdentifier = identifier.Key;
                }
            }

            return foundInnerMostScope;
        }
        internal void AddScopeIdentifier(int blockId, int classId, int procId,
            int startLine, int startColumn, int endLine, int endColumn, string scriptPath)
        {
            // Generated methods, built-in functions, class getters/setters
            // have no valid source location information, skip processing them.
            if (startLine < 0 || (startColumn < 0) || endLine < 0 || (endColumn < 0))
                return;

            if (null == scopeIdentifiers)
                scopeIdentifiers = new Dictionary<ScopeInfo, CodeRange>();

            ScopeInfo scope = new ScopeInfo()
            {
                BlockId = blockId,
                ClassScope = classId,
                FunctionIndex = procId
            };

            if (scopeIdentifiers.ContainsKey(scope))
                throw new InvalidOperationException("No two scopes should be identical!");

            scopeIdentifiers[scope] = SymbolDatabaseProxy.MakeCodeRange(
                startLine, startColumn, endLine, endColumn, scriptPath);
        }