Example #1
0
        public override void Translate(MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            MemberExpression member   = (m.Object ?? m.Arguments[0]) as MemberExpression;
            IDbObject        dbBinary = null;

            if (member.Type == typeof(string))
            {
                var dbConstants = (IDbConstant)state.ResultStack.Pop();
                dbConstants.Val = $"%{dbConstants.Val}%";

                var dbExpression = (IDbSelectable)state.ResultStack.Pop();
                dbBinary = _dbFactory.BuildBinary(dbExpression, DbOperator.Like, dbConstants);
            }
            else if (member.Type.IsArray)
            {
                var dbConstants = (IDbConstant)state.ResultStack.Pop();

                var dbExpression = (IDbSelectable)state.ResultStack.Pop();
                var dbFunc       = _dbFactory.BuildFunc(SqlTranslationHelper.GetSqlOperator(DbOperator.Any), false, m.Method.ReturnType, dbExpression);
                dbBinary = _dbFactory.BuildBinary(dbConstants, DbOperator.Equal, dbFunc);
            }
            else
            {
                throw new NotSupportedException($"Type {member.Type} is not supported");
            }

            state.ResultStack.Push(dbBinary);
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Segment"/> class.
        /// </summary>
        /// <param name="id">The Id of the segment.</param>
        /// <param name="state">The translation state of the segment.</param>
        public Segment(string id, TranslationState state)
            : base(id)
        {
            this.RegisterElementInformation(ElementInformationFromReflection.Create(this));

            this.State = state;
        }
        protected void CreateAggregation(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator,
            IDbSelect childSelect, IDbFunc dbFunc)
        {
            var dbSelect = (IDbSelect)state.ResultStack.Peek();

            if (childSelect == null)
            {
                state.ResultStack.Push(dbFunc);
                return;
            }

            var alias = nameGenerator.GenerateAlias(dbSelect, dbFunc.Name, true);

            dbFunc.Alias = alias;
            childSelect.Selection.Add(dbFunc);

            var cRef   = dbSelect.Joins.Single(j => ReferenceEquals(j.To.Referee, childSelect)).To;
            var column = _dbFactory.BuildColumn(cRef, alias, m.Method.ReturnType);

            var dbDefaultVal = _dbFactory.BuildConstant(Activator.CreateInstance(m.Method.ReturnType));
            var dbIsNullFunc = _dbFactory.BuildNullCheckFunc(column, dbDefaultVal);

            state.ResultStack.Push(dbIsNullFunc);
        }
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var dbSelect = state.ResultStack.Peek() as IDbSelect;

            if (dbSelect != null)
            {
                dbSelect.Selection.IsDistinct = true;
            }

            var caller     = m.GetCaller();
            var entityInfo = caller.NodeType == ExpressionType.MemberAccess
                ? this._infoProvider.FindEntityInfo(caller.Type)
                : null;

            // if the caller of the Distinct function is a Entity
            // We need to add its primary keys into the query so that the result
            // of distinct is correct. Otherwise, it will only distinct on join keys
            if (entityInfo != null)
            {
                foreach (var pk in entityInfo.Keys)
                {
                    var pkColumn = _dbFactory.BuildColumn(dbSelect.GetReturnEntityRef(), pk.DbName, pk.ValType);
                    dbSelect.Selection.Add(pkColumn);
                }
            }
        }
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var arguments = state.ResultStack.Pop();
            var dbSelect  = (IDbSelect)state.ResultStack.Pop();

            var selections = SqlTranslationHelper.ProcessSelection(arguments, _dbFactory);

            foreach (var selectable in selections)
            {
                SqlTranslationHelper.UpdateJoinType(selectable.Ref);
                dbSelect.Selection.Add(selectable);
            }

            var newSelectRef = _dbFactory.BuildRef(dbSelect);
            var newSelect    = _dbFactory.BuildSelect(newSelectRef);

            newSelectRef.Alias = nameGenerator.GenerateAlias(dbSelect, TranslationConstants.SubSelectPrefix, true);

            selections = selections.Concat(dbSelect.Selection.Where(s => s.IsJoinKey)).ToArray();
            foreach (var selectable in selections)
            {
                var newSelectable = CreateNewSelectableForWrappingSelect(selectable, newSelectRef, _dbFactory);

                newSelect.Selection.Add(newSelectable);
            }

            state.ResultStack.Push(newSelect);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Segment"/> class.
        /// </summary>
        /// <param name="id">The Id of the segment.</param>
        /// <param name="state">The translation state of the segment.</param>
        public Segment(string id, TranslationState state)
            : base(id)
        {
            this.RegisterElementInformation(ElementInformationFromReflection.Create(this));

            this.State = state;
        }
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            // there may not be a preidcate in any method call
            IDbObject condition = null;

            if (m.GetArguments().Any())
            {
                condition = state.ResultStack.Pop();
            }

            var childSelect = (IDbSelect)state.ResultStack.Pop();
            var dbSelect    = (IDbSelect)state.ResultStack.Peek();

            childSelect.Where = condition.ToBinary(_dbFactory);

            var dbJoin = dbSelect.Joins.Single(j => ReferenceEquals(j.To.Referee, childSelect));

            IDbBinary whereClause = null;

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var joinKey in dbJoin.Condition.GetOperands().OfType <IDbColumn>().Where(c => ReferenceEquals(c.Ref, dbJoin.To)))
            {
                var pkColumn = _dbFactory.BuildColumn(dbJoin.To, joinKey.Name, joinKey.ValType.DotNetType, joinKey.Alias);
                var binary   = _dbFactory.BuildBinary(pkColumn, DbOperator.IsNot, _dbFactory.BuildConstant(null));

                whereClause = whereClause.UpdateBinary(binary, _dbFactory);
            }

            state.ResultStack.Push(whereClause);
        }
Example #8
0
        public async void TranslateFile()
        {
            TranslationState = TranslationState.started;

            int    counter = 0;
            string line    = string.Empty;

            StreamReader reader = new StreamReader(Path);

            while ((line = reader.ReadLine()) != null)
            {
                TranslationJob job = new TranslationJob
                {
                    Id           = this.Id,
                    OriginalWord = line
                };
                job.LineNumber = counter++;

                job = await TranslateJob(job);

                //TODO: do as Task?
                Handler.ProcessTranslationJob(job);
            }

            reader.Close();
            reader.Dispose();

            TranslationState = TranslationState.done;

            //===== Notify the parent that we have completed our translation file =====
            Handler.TranslationObjectCompleted();
        }
Example #9
0
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var dbConstants  = (IDbConstant)state.ResultStack.Pop();
            var dbExpression = (IDbSelectable)state.ResultStack.Pop();
            var dbBinary     = _dbFactory.BuildFunc("MyFunc", false, dbExpression, dbConstants);

            state.ResultStack.Push(dbBinary);
        }
Example #10
0
        public override void Translate(MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var dbElement   = state.ResultStack.Pop();
            var whereClause = dbElement.ToBinary(_dbFactory);

            var dbSelect = (IDbSelect)state.ResultStack.Peek();

            dbSelect.UpdateWhereClause(whereClause, _dbFactory);
        }
Example #11
0
        protected static IDbSelectable GetAggregationTarget(MethodCallExpression m, TranslationState state)
        {
            if (!m.GetArguments().Any())
            {
                return(null);
            }

            var dbObj = state.ResultStack.Pop();

            return((IDbSelectable)dbObj);
        }
Example #12
0
        private void TranslateAndCreatePhpFiles(TranslationInfo translationInfo, string outDir)
        {
            if (_verboseToConsole)
            {
                Console.WriteLine("Translate C# -> Php");
            }

            translationInfo.CurrentAssembly = CompiledAssembly;
            var assemblyTi = translationInfo.GetOrMakeTranslationInfo(CompiledAssembly);
            var ecBaseDir  = Path.Combine(outDir, assemblyTi.RootPath.Replace("/", "\\"));

            Console.WriteLine("Output root {0}", ecBaseDir);

            if (!string.IsNullOrEmpty(assemblyTi.PhpPackageSourceUri))
            {
                DownloadAndUnzip(assemblyTi.PhpPackageSourceUri, ecBaseDir, assemblyTi.PhpPackagePathStrip);
                return; //??? czy return?
            }

            var translationState = new TranslationState(translationInfo);
            var translator       = new Translator.Translator(translationState);

            translator.Translate(Sandbox);

            var libName = assemblyTi.LibraryName;

            if (_verboseToConsole)
            {
                Console.WriteLine("Create Php output files");
            }

            #region Tworzenie plików php

            {
                // var emitContext = new EmitContext();
                var emitStyle = new PhpEmitStyle();

                translationInfo.CurrentAssembly = CompiledAssembly; // dla pewności
                foreach (var module in translator.Modules.Where(i => i.Name.Library == libName && !i.IsEmpty))
                {
                    var fileName = module.Name.MakeEmitPath(ecBaseDir, 1);
                    foreach (var modProcessor in translationInfo.ModuleProcessors)
                    {
                        modProcessor.BeforeEmit(module, translationInfo);
                    }
                    var emiter = new PhpSourceCodeEmiter();
                    module.Emit(emiter, emitStyle, fileName);
                }
            }

            #endregion
        }
Example #13
0
        public override void Translate(MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var dbContants = (IDbConstant)state.ResultStack.Pop();

            dbContants.Val = m.Method.Name == "StartsWith"
                    ? $"{dbContants.Val}%"
                    : $"%{dbContants.Val}";

            var dbExpression = (IDbSelectable)state.ResultStack.Pop();
            var dbBinary     = _dbFactory.BuildBinary(dbExpression, DbOperator.Like, dbContants);

            state.ResultStack.Push(dbBinary);
        }
Example #14
0
        protected static CompilationTestInfo ParseCs(string code, bool translate, Info info = null)
        {
            var project = CreateOneFileProject(code, info?.Ref);
            var c       = new Cs2PyCompiler
            {
                CSharpProject = project
            };

            c.TranslationAssemblies.Add(typeof(AssemblySandbox).Assembly);

            c.ReferencedAssemblies.Add(typeof(Tensorflow.TensorShape).Assembly);
            c.ReferencedAssemblies.Add(typeof(System.Linq.Enumerable).Assembly);
            c.ReferencedAssemblies.Add(typeof(System.Data.Linq.Binary).Assembly);
            var filename = Path.GetTempFileName().Replace(".tmp", ".dll");
            var er       = c.CompileCSharpProject(c.Sandbox, filename);

            if (!er.Success && er.Diagnostics.Any())
            {
                throw new Exception(er.Diagnostics[0].GetMessage());
            }
            Assert.True(er.Success);
            var translationInfo = c.ParseCsSource();

            if (!translate)
            {
                return(new CompilationTestInfo(c, translationInfo, null));
            }
            var translationState = new TranslationState(translationInfo);
            var translator       = new Translator(translationState);

            translator.Info.CurrentAssembly = c.CompiledAssembly;
            translator.Translate(c.Sandbox);
            var compare = info?.Compare;

            if (compare != null)
            {
                compare = compare.Trim();
                if (!compare.StartsWith("'''"))
                {
                    compare = "'''\r\nGenerated with cs2py\r\n'''\r\n" + compare;
                }
                var emiter = new PySourceCodeEmiter();
                var writer = new PySourceCodeWriter();
                translator.Modules[0].Emit(emiter, writer, new PyEmitStyle());
                var pyCode = writer.GetCode();
                Assert.Equal(compare.Trim(), pyCode.Trim());
            }

            return(new CompilationTestInfo(c, translationInfo, translator));
        }
Example #15
0
 private RequiresTranslationState ConvertToRequiresTranslationState(TranslationState translationState)
 {
     return(translationState switch
     {
         TranslationState.DoNotTranslate => RequiresTranslationState.DoNotTranslate,
         TranslationState.New => RequiresTranslationState.New,
         TranslationState.Unassigned => RequiresTranslationState.Unassigned,
         TranslationState.Unchanged => RequiresTranslationState.Unchanged,
         TranslationState.Updated => RequiresTranslationState.Updated,
         _ => throw new Exception(string.Format(
                                      "Unknown or unsupported TranslationState: {0}",
                                      translationState.ToString()
                                      )),
     });
Example #16
0
        /// <summary> Translate to SQL </summary>
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var dbExpression = GetAggregationTarget(m, state);

            IDbSelect childSelect = null;

            if (!m.GetCaller().Type.IsGrouping())
            {
                childSelect = state.ResultStack.Pop() as IDbSelect;
            }

            // if the aggregation does not have expression, it means
            // the caller of the aggregation method must be a Select method call
            // In this case, the actual expression that we need to aggregate on,
            // will be inside the child select statement
            if (dbExpression == null && childSelect != null)
            {
                // to get the actual expression, we need to first unwrap the child select
                // because the translation of Select call always wrap the actual select
                childSelect = (IDbSelect)childSelect.From.Referee;

                dbExpression = childSelect.Selection.Last(
                    s => string.IsNullOrEmpty(s.Alias) ||
                    !s.Alias.EndsWith(TranslationConstants.JoinKeySuffix));

                childSelect.Selection.Remove(dbExpression);
                childSelect.GroupBys.Remove(dbExpression);
            }

            if (dbExpression == null)
            {
                throw new NotSupportedException("Can not aggregate.");
            }

            if (!(dbExpression is IDistinctable))
            {
                throw new NotSupportedException("Expression must be Distinctable");
            }

            var distinctable = (IDistinctable)dbExpression;

            distinctable.IsDistinct = true;

            var dbFunc = _dbFactory.BuildFunc("count", true, m.Method.ReturnType, dbExpression);

            CreateAggregation(m, state, nameGenerator, childSelect, dbFunc);
        }
Example #17
0
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var predicate = BuildCondition(m, state);

            IDbSelect childSelect = null;

            if (!m.GetCaller().Type.IsGrouping())
            {
                childSelect = state.ResultStack.Pop() as IDbSelect;
            }

            var dbCountFunc = _dbFactory.BuildFunc(m.Method.Name.ToLower(), true, m.Method.ReturnType, predicate);

            CreateAggregation(m, state, nameGenerator, childSelect, dbCountFunc);
        }
Example #18
0
        private IDbObject BuildCondition(MethodCallExpression m, TranslationState state)
        {
            var countOne = _dbFactory.BuildConstant(1);

            if (!m.GetArguments().Any())
            {
                return(countOne);
            }

            var dbElement = state.ResultStack.Pop();
            var dbBinary  = dbElement.ToBinary(_dbFactory);

            var tuple = Tuple.Create <IDbBinary, IDbObject>(dbBinary, countOne);

            return(_dbFactory.BuildCondition(new [] { tuple }, _dbFactory.BuildConstant(null)));
        }
Example #19
0
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            // group by can be a column, a expression, or a list of columns / expressions
            var arguments = state.ResultStack.Pop();
            var dbSelect  = (IDbSelect)state.ResultStack.Pop();

            var groupBys = dbSelect.GroupBys;

            groupBys.IsSingleKey = !(arguments is IDbList <DbKeyValue>);

            var selections = SqlTranslationHelper.ProcessSelection(arguments, _dbFactory);

            foreach (var selectable in selections)
            {
                SqlTranslationHelper.UpdateJoinType(selectable.Ref);

                var refCol = selectable as IDbRefColumn;
                // if we group on a ref column, we are actaully group by on the primary key
                // of the entity that ref column referring to. In the refering entity is actually
                // another ref column, then we will need to get the primay key recursive from RefTo
                if (refCol?.RefTo != null)
                {
                    foreach (var pk in refCol.GetPrimaryKeys())
                    {
                        refCol.RefTo.AddToReferedSelect(_dbFactory, pk.Name, pk.ValType);
                    }
                }

                dbSelect.GroupBys.Add(selectable);
            }

            // if the group by is a single expression like groupby(x => x.Children.Count())
            // it will be translated into a expression and will not have alias
            // in this case, we will need to give it an alias which will be used later
            if (groupBys.IsSingleKey)
            {
                var column = groupBys.Single();
                if (column.Alias == null)
                {
                    column.Alias = "Key";
                }
            }

            state.ResultStack.Push(dbSelect);
        }
Example #20
0
        public static void SetTargetState(this XElement transUnitElement, TranslationState state)
        {
            if (GetTargetState(transUnitElement) == state)
            {
                return;
            }

#pragma warning disable IDE0072 // Add missing cases
            var value = state switch
#pragma warning restore IDE0072 // Add missing cases
            {
                TranslationState.NeedsReview => NeedsReviewStates.First(),
                TranslationState.Approved => ApprovedStates.First(),
                _ => NewState
            };

            SetTargetState(transUnitElement, value);
        }
Example #21
0
        protected void CreateAggregation(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator,
            IDbSelect childSelect, IDbFunc dbFunc)
        {
            var dbSelect = (IDbSelect)state.ResultStack.Peek();

            if (childSelect == null)
            {
                state.ResultStack.Push(dbFunc);
                return;
            }

            var alias = nameGenerator.GenerateAlias(dbSelect, dbFunc.Name, true);

            dbFunc.Alias = alias;
            childSelect.Selection.Add(dbFunc);

            /**
             * Aggregation can happen after a method that generate new select.
             * In this case, join from the main select to the child select will not be
             * updated yet at this stage, so we need to correct the join to on the
             * correct child select statment.
             * For example:
             * var query = db.Blogs
             *     .Where(b => b.BlogId > 0)
             *     .Select(b => new
             *      {
             *          b.BlogId,
             *          Cnt = b.Posts.Select(p => p.Title).Distinct().Count()
             *      });
             * `b.Posts.Select(p => p.Title).Distinct()` will create a new child select and
             * it will not be the one that the main select is currently targeting, so we
             * need to correct the join target.
             */
            ReLinkToChildSelect(dbSelect, childSelect);

            var cRef   = dbSelect.Joins.Single(j => ReferenceEquals(j.To.Referee, childSelect)).To;
            var column = _dbFactory.BuildColumn(cRef, alias, m.Method.ReturnType);

            var dbDefaultVal = _dbFactory.BuildConstant(Activator.CreateInstance(m.Method.ReturnType));
            var dbIsNullFunc = _dbFactory.BuildNullCheckFunc(m.Method.ReturnType, column, dbDefaultVal);

            state.ResultStack.Push(dbIsNullFunc);
        }
Example #22
0
        public List <TextInfomationDto> GetTextInformation(int resourceVersionId, ParentResource parentResource)
        {
            var resourceInformationList = new List <TextInfomationDto>();

            var resourceString = m_procedureService.GetStringDataForResourceVersionIDs(resourceVersionId);
            var lineOrder      = 1;

            foreach (var item in resourceString.stringDataForResourceVersionID)
            {
                TextInfomationDto textInfomationDto = new TextInfomationDto
                {
                    Description           = GetDescription(item),
                    CurrentText           = item.Text,
                    IsTranslationEligible = item.IsTranslationEligible,
                    FriendlyStringId      = item.FriendlyStringId,
                    StringId           = item.StringId,
                    LocalizedVersionId = item.LocalizedVersionId,
                    MaxCharacterLength = item.MaxCharacterLength,
                    RecordingTypeName  = item.RecordingTypeName,
                    TimingRestriction  = ConvertStringTimeConstraintToDocumentTimingRestriction(item.TimingRestriction),
                    WordCount          = item.WordCount,
                    LineOrder          = lineOrder++,
                };
                GetStringTypeInformation(item, textInfomationDto);
                bool             previouslyExported = SetPreviousText(resourceString, item, textInfomationDto);
                TranslationState translationState   = previouslyExported ? TranslationState.Unchanged : TranslationState.DoNotTranslate;
                textInfomationDto.RequiresTranslationState = ConvertToRequiresTranslationState(translationState);
                GetSetGrammarInformation(resourceString, item, textInfomationDto);

                Links link = new Links();
                link.Parent.AddRange(m_functionService.Udf_GetConversationLineParent(resourceVersionId, textInfomationDto.StringId));
                link.Children.AddRange(GetChildLinkInfo(resourceVersionId, textInfomationDto));
                textInfomationDto.Links.Add(link);

                textInfomationDto.ParentResource.Add(parentResource);

                textInfomationDto.Speakers.Add(m_functionService.Udf_GetResourceVersionStringListener(resourceVersionId, item.StringId));

                GetSetEnglishStrings(textInfomationDto);
                resourceInformationList.Add(textInfomationDto);
            }
            return(resourceInformationList);
        }
Example #23
0
        public override void Translate(MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            // group by can be a column, a expression, or a list of columns / expressions
            var arguments = state.ResultStack.Pop();
            var dbSelect  = (IDbSelect)state.ResultStack.Pop();

            var direction = m.Method.Name.EndsWith("Descending") ? DbOrderDirection.Desc : DbOrderDirection.Asc;

            var selections = SqlTranslationHelper.ProcessSelection(arguments, _dbFactory);

            foreach (var selectable in selections)
            {
                SqlTranslationHelper.UpdateJoinType(selectable.Ref);
                var orderByCol = _dbFactory.BuildOrderByColumn(selectable, direction);
                dbSelect.OrderBys.Add(orderByCol);
            }

            state.ResultStack.Push(dbSelect);
        }
Example #24
0
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var joinType      = (IDbConstant)state.ResultStack.Pop();
            var selection     = state.ResultStack.Pop();
            var joinCondition = (IDbBinary)state.ResultStack.Pop();

            var toSelect   = (IDbSelect)state.ResultStack.Pop();
            var fromSelect = (IDbSelect)state.ResultStack.Pop();

            var toSelectRef = _dbFactory.BuildRef(toSelect, nameGenerator.GenerateAlias(fromSelect, "sq", true));

            // todo: review how join condition is translated
            // create result selection for final select
            UpdateSelection(fromSelect, selection, toSelectRef);

            // create join to inner select
            var joinKeys = joinCondition.GetOperands().OfType <IDbColumn>().Where(c => c.Ref.OwnerSelect == toSelect);

            foreach (var joinKey in joinKeys)
            {
                toSelect.Selection.Remove(joinKey);

                var alias    = nameGenerator.GenerateAlias(toSelect, joinKey.Name + "_jk", true);
                var innerCol = _dbFactory.BuildColumn(joinKey);
                innerCol.Alias = alias;
                toSelect.Selection.Add(innerCol);

                joinKey.Ref   = toSelectRef;
                joinKey.Name  = alias;
                joinKey.Alias = string.Empty;
            }

            var dbJoin = _dbFactory.BuildJoin(toSelectRef, fromSelect, joinCondition, (DbJoinType)joinType.Val);

            fromSelect.Joins.Add(dbJoin);

            var finalSelectRef = _dbFactory.BuildRef(fromSelect, nameGenerator.GenerateAlias(null, "sq", true));
            var finalSelect    = _dbFactory.BuildSelect(finalSelectRef);

            state.ResultStack.Push(finalSelect);
        }
Example #25
0
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            var vals = new List <object>();

            while (state.ResultStack.Peek() is IDbConstant)
            {
                var dbConstants = (IDbConstant)state.ResultStack.Pop();
                if (dbConstants.Val is IEnumerable val)
                {
                    vals = val.Cast <object>().ToList();
                    break;
                }
                vals.Insert(0, dbConstants.Val);
            }

            var dbExpression = (IDbSelectable)state.ResultStack.Pop();
            var dbBinary     = vals.Count == 0
                ? _dbFactory.BuildBinary(_dbFactory.BuildConstant(0), DbOperator.Equal, _dbFactory.BuildConstant(1))
                : _dbFactory.BuildBinary(dbExpression, DbOperator.In, _dbFactory.BuildConstant(vals, true));

            state.ResultStack.Push(dbBinary);
        }
Example #26
0
 public abstract void Translate(
     MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator);
Example #27
0
 public TranslatorItem(StringItem translated, StringItem original, TranslationState state)
 {
     this.translated = translated;
     this.original   = original;
     this.state      = state;
 }
Example #28
0
 public TranslatorItem(StringItem translated, StringItem original, TranslationState state)
 {
     this.translated=translated;
     this.original=original;
     this.state=state;
 }
Example #29
0
 /// <summary>
 /// 以倒叙比较两个状态的大小
 /// </summary>
 /// <param name="x">第一个要比较的对象</param>
 /// <param name="y">第二个要比较的对象</param>
 /// <returns>小于 0 则 y 小于 x, 等于 0 则 y 等于 x, 大于 0 则 y 大于 x。</returns>
 public static int CompareDesc(TranslationState x, TranslationState y)
 {
     return(_stateSort.IndexOf(y) - _stateSort.IndexOf(x));
 }
Example #30
0
        // Internal Methods 

        internal static Translator PrepareTranslator()
        {
            if (_translator != null)
            {
                return(_translator);
            }
            var csProject = LangPhpTestCsProj;

            using (var comp = new Cs2PhpCompiler {
                VerboseToConsole = true, ThrowExceptions = true
            })
            {
                Console.WriteLine("Try to load " + csProject);

#if DEBUG
                comp.LoadProject(csProject, "DEBUG");
#else
                comp.LoadProject(csProject, "RELEASE");
#endif

                /*
                 * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Compiler\bin\Debug\Lang.Php.Compiler.dll
                 * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Framework\bin\Debug\Lang.Php.Framework.dll
                 * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Test\bin\Debug\Lang.Php.dll
                 */


                Console.WriteLine("Preparing before compilation");
                string[] removeL = "Lang.Php.Compiler,Lang.Php.Framework,Lang.Php".Split(',');

                #region Remove Lang.Php reference

                {
                    foreach (var r in removeL)
                    {
                        // ... will be replaced by reference to dll from compiler base dir
                        // I know - compilation libraries should be loaded into separate application domain
                        var remove =
                            comp.CSharpProject.MetadataReferences.FirstOrDefault(i => i.Display.EndsWith(r + ".dll"));
                        if (remove != null)
                        {
                            comp.RemoveMetadataReferences(remove);
                        }
                    }
                }

                #endregion

                string[] filenames;

                #region We have to remove and add again references - strange

                {
                    // in other cases some referenced libraries are ignored
                    var refToRemove = comp.CSharpProject.MetadataReferences.OfType <MetadataFileReference>().ToList();
                    foreach (var i in refToRemove)
                    {
                        comp.RemoveMetadataReferences(i);
                    }
                    var ref1 = refToRemove.Select(i => i.FilePath).ToList();
                    // foreach (var r in removeL)
                    //     ref1.Add(Path.Combine(Directory.GetCurrentDirectory(), r + ".dll"));
                    ref1.Add(typeof(DirectCallAttribute).Assembly.Location);
                    ref1.Add(typeof(EmitContext).Assembly.Location);
                    ref1.Add(typeof(Extension).Assembly.Location);
                    filenames = ref1.Distinct().ToArray();
                }

                #endregion

                #region Translation assemblies

                {
                    comp.TranslationAssemblies.Add(typeof(Extension).Assembly);
                    comp.TranslationAssemblies.Add(typeof(Translator).Assembly);
                }

                #endregion

                foreach (var fileName in filenames)
                {
                    var g = new MetadataFileReference(fileName, MetadataReferenceProperties.Assembly);
                    comp.AddMetadataReferences(g);
                    Console.WriteLine("  Add reference     {0}", g.Display);
                }

                //                using (var sandbox = new AssemblySandbox())
                //                {
                //                //
                //                Console.WriteLine("Start compile");
                //                var result = comp.CompileCSharpProject(sandbox, comp.DllFileName);
                //                if (!result.Success)
                //                {
                //                    foreach (var i in result.Diagnostics)
                //                        Console.WriteLine(i);
                //                }
                //                Assert.True(result.Success, "Compilation failed");
                //                }
                TranslationInfo translationInfo = comp.ParseCsSource();


                translationInfo.CurrentAssembly = comp.CompiledAssembly;
                var assemblyTi = translationInfo.GetOrMakeTranslationInfo(comp.CompiledAssembly);
                var ecBaseDir  = Path.Combine(Directory.GetCurrentDirectory(), assemblyTi.RootPath.Replace("/", "\\"));
                Console.WriteLine("Output root {0}", ecBaseDir);

                var translationState = new TranslationState(translationInfo);
                _translator = new Translator(translationState);

                _translator.Translate(comp.Sandbox);
                return(_translator);
            }
        }
 public override void Translate(MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
 {
     throw new System.NotImplementedException();
 }
Example #32
0
        public void Compile()
        {
            using (new AppConfigManipulator())
            {
                CompilerEngine.ExecuteInSeparateAppDomain(
                    ce =>
                {
#if DEBUG
                    ce.Configuration = "DEBUG";
#else
                    ce.Configuration = "RELEASE";
#endif
                    ce.CsProject = LangPhpTestCsProj;
                    ce.OutDir    = ce.BinaryOutputDir = Path.GetTempPath();
                    ce.Referenced.Clear();

                    var types = new[]
                    {
                        typeof(Func <,>),
                        typeof(EmitContext),
                        typeof(ThisExpression),
                        typeof(CompilerEngine)
                    };
                    {
                        var tmp =
                            Assembly.Load(
                                "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                        ce.Referenced.Add(tmp.GetCodeLocation().FullName);
                    }
                    ce.Referenced.AddRange(types.Select(type => type.Assembly.GetCodeLocation().FullName));


                    ce.TranlationHelpers.Clear();
                    ce.ReferencedPhpLibsLocations.Clear();
                    ce.Check();

                    using (var comp = ce.PreparePhpCompiler())
                    {
                        Console.WriteLine("Compilation");
                        var emitResult = comp.CompileCSharpProject(comp.Sandbox, ce.DllFilename);
                        if (!emitResult.Success)
                        {
                            foreach (var i in emitResult.Diagnostics.Where(a => a.Severity == DiagnosticSeverity.Error))
                            {
                                throw new Exception("Compilation error: " + i.GetMessage());
                            }
                        }


                        var translationInfo = comp.ParseCsSource();


                        translationInfo.CurrentAssembly = comp.CompiledAssembly;
                        var assemblyTi = translationInfo.GetOrMakeTranslationInfo(comp.CompiledAssembly);
                        var ecBaseDir  = Path.Combine(Directory.GetCurrentDirectory(),
                                                      assemblyTi.RootPath.Replace("/", "\\"));
                        Console.WriteLine("Output root {0}", ecBaseDir);

                        var translationState = new TranslationState(translationInfo);
                        var translator       = new Translator(translationState);

                        translator.Translate(comp.Sandbox);

                        // =============
                        var m =
                            string.Join(", ", translator.Modules.Select(i => i.Name.Name).OrderBy(i => i)).ToArray();

                        //Assert.True(m == "Lang_Php_Test_Code_MyCode, Lang_Php_Test_Code_SampleEmptyClass", m);

                        MethodTranslation(ModuleMycode, ClassMycode, "BasicMath1", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "Collections", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "CostantsAndVariables", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "Filters", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "StringConcats", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "PregTest", translator);

//                            ModuleTranslation("Lang_Php_Test_Code_SampleEmptyClass", translator);
//                            ModuleTranslation("Lang_Php_Test_Code_BusinessClass", translator);
//                            ModuleTranslation("Lang_Php_Test_Code_BusinessClassDefinedConst", translator);

                        foreach (var moduleName in translator.Modules.Select(i => i.Name.Name))
                        {
                            ModuleTranslation(moduleName, translator);
                        }
                    }
                    ;
                }, AppDomain.CurrentDomain);
            }
        }