示例#1
0
        public string Translate(string cql, params object[] arguments)
        {
            if(arguments != null)
                cql = string.Format(cql, arguments);

            var parser =  new CodeQL.parsers.cql.Parser();
            if(!parser.Parse(cql))
                throw new ApplicationException("Parsing error");

            using(TranslationContext ctx = new TranslationContext(parser.Batch))
            {
                if(BeforeTransformStart != null)
                    BeforeTransformStart();

                // resolve aliases first
                new AliasBinder().Run();

                // run transforms
                new ClassHandler().Run();

                if(AfterTransformComplete != null)
                    AfterTransformComplete();
            }

            return new SqlWriter().Write(parser.Batch);
        }
示例#2
0
            protected TranslationContext(TranslationContext parent, int start)
            {
                Parent = parent;
                Start = start;

                ResultType = parent.ResultType;
                Instructions = parent.Instructions;
                OffsetToIndex = parent.OffsetToIndex;
                TryOffsets = parent.TryOffsets;
                IndexToHandler = parent.IndexToHandler;
                IndexToFilter = parent.IndexToFilter;
                Handlers = parent.Handlers;
            }
示例#3
0
            public TranslationContext(TypeRef resultType, PE.Instruction[] instructions, IImSeq<PE.ExceptionHandlingClause> handlers)
            {
                Parent = null;
                Start = 0;

                ResultType = resultType;
                Instructions = instructions;
                Handlers = handlers;

                var offsetToIndex = new Map<int, int>();
                for (var i = 0; i < instructions.Length; i++)
                {
                    if (offsetToIndex.ContainsKey(instructions[i].Offset))
                        throw new InvalidOperationException("instructions share same offset");
                    offsetToIndex.Add(instructions[i].Offset, i);
                }
                OffsetToIndex = offsetToIndex;

                var tryOffsets = new Set<int>();
                var indexToHandler = new Map<int, PE.ExceptionHandlingClause>();
                var indexToFilter = new Map<int, PE.ExceptionHandlingClause>();
                foreach (var ehc in handlers)
                {
                    if (!tryOffsets.Contains(ehc.TryOffset))
                        tryOffsets.Add(ehc.TryOffset);
                    var i = OffsetToIndex[ehc.HandlerOffset];
                    indexToHandler.Add(i, ehc);
                    if (ehc.Flags == PE.CorILExceptionClause.Filter)
                    {
                        var j = OffsetToIndex[ehc.FilterOffset];
                        indexToHandler.Add(j, ehc);
                    }
                }
                TryOffsets = tryOffsets;
                IndexToHandler = indexToHandler;
                IndexToFilter = indexToFilter;
            }
示例#4
0
 public FilterTranslationContext(TranslationContext parent, int start, PE.ExceptionHandlingClause clause)
     : base(parent, start)
 {
     Clause = clause;
 }
示例#5
0
        /// <summary>
        /// Gets the translated code for the grammar structure.
        /// </summary>
        /// <returns>The translated code for the grammar structure.</returns>
        public Stage Translate(TranslationContext context)
        {
            // Create blank stage instance
            Stage stage = new Stage();

            // Create new translation context
            TranslationContext newContext = new TranslationContext(this, context);

            // Translate superglobal variables
            foreach (GlobalVarDeclaration globalVarDeclaration in Variables)
            {
                stage.Variables.Add(globalVarDeclaration.Translate(newContext));
            }

            // Translate superglobal lists
            foreach (GlobalListDeclaration globalListDeclaration in Lists)
            {
                stage.Lists.Add(globalListDeclaration.Translate(newContext));
            }

            // Translate sprites and get statistics
            int spriteCount = 0;
            int scriptCount = 0;

            foreach (Sprite translated in Sprites.Select(x => x.Translate(newContext)))
            {
                stage.Children.Add(translated);

                // Update statistics
                scriptCount += translated.Scripts.Count;
                spriteCount++;
            }

            // Get pen layer md5
            using (MemoryStream ms = new MemoryStream())
            {
                Settings.PenLayerImage.Save(ms, ImageFormat.Png);
                stage.PenLayerMd5 = ms.ToArray().GetMd5Checksum() + Helpers.Settings.PngExtension;
            }

            // Backdrops
            foreach (Asset backdrop in Settings.Backdrops)
            {
                // Find backdrop file
                if (!context.ProjectAssets.CostumeFiles.TryGetValue(backdrop.Path, out LoadedAsset backdropData))
                {
                    context.ErrorList.Add(new CompilerError($"Backdrop '{backdrop.Path}' could not be found",
                                                            ErrorType.FileNotFound, null, Helpers.Settings.ProjectSettingsFile));
                    return(null);
                }

                // Create backdrop
                // TODO bitmap resolution
                dynamic rotationCenter = backdrop.Attributes.rotationCenter;
                stage.Costumes.Add(new Costume
                {
                    Name             = backdrop.Name,
                    Id               = backdropData.Id,
                    BitmapResolution = 1,
                    Md5              = backdropData.Contents.GetMd5Checksum() + backdropData.Extension,
                    RotationCenter   = new Point((int)rotationCenter.x.Value, (int)rotationCenter.y.Value)
                });
            }

            // Store project info / stats
            stage.Info = new ProjectInfo
            {
                SpriteCount = spriteCount,
                ScriptCount = scriptCount
            };

            // Insert Choop notice
            stage.Comments.Add(new Comment
            {
                Text     = Resources.ChoopNotice,
                Location = new Point(20, 20),
                Size     = new Size(500, 200),
                Open     = true,
                BlockId  = -1
            });

            return(stage);
        }
示例#6
0
 public UnitOfWork()
 {
     this._context = new TranslationContext();
 }
示例#7
0
        /// <summary>
        /// Gets the translated code for the grammar structure.
        /// </summary>
        /// <returns>The translated code for the grammar structure.</returns>
        public Sprite Translate(TranslationContext context)
        {
            // Find definition file
            if (!context.ProjectAssets.SpriteDefinitionFiles.TryGetValue(DefinitionFile,
                                                                         out SpriteSettings definitionFile))
            {
                context.ErrorList.Add(new CompilerError($"Definition file '{DefinitionFile}' could not be found",
                                                        ErrorType.FileNotFound, ErrorToken, FileName));
                return(null);
            }

            // Create new sprite instance
            Sprite sprite = new Sprite
            {
                Name           = Name,
                CurrentCostume = definitionFile.CostumeIndex,
                Direction      = definitionFile.Direction,
                Draggable      = definitionFile.Draggable,
                LibraryIndex   = context.Project.Sprites.Count,
                Location       = definitionFile.Location,
                RotationStyle  = definitionFile.RotationStyle,
                Scale          = definitionFile.Scale,
                Visible        = definitionFile.Visible
            };

            // Create translation context
            TranslationContext newContext = new TranslationContext(this, context);

            // Variables
            foreach (GlobalVarDeclaration globalVarDeclaration in Variables)
            {
                sprite.Variables.Add(globalVarDeclaration.Translate(newContext));
            }

            // Lists
            foreach (GlobalListDeclaration globalListDeclaration in Lists)
            {
                sprite.Lists.Add(globalListDeclaration.Translate(newContext));
            }

            // Events
            foreach (ScriptTuple[] translated in EventHandlers.Select(x => x.Translate(newContext)))
            {
                sprite.Scripts.Add(translated[0]);
                sprite.Scripts.Add(translated[1]);
            }

            // Methods
            foreach (MethodDeclaration methodDeclaration in Methods)
            {
                sprite.Scripts.Add(methodDeclaration.Translate(newContext));
            }

            // Costumes
            foreach (Asset costume in definitionFile.Costumes)
            {
                // Find costume file
                if (!context.ProjectAssets.CostumeFiles.TryGetValue(costume.Path, out LoadedAsset costumeData))
                {
                    context.ErrorList.Add(new CompilerError($"Costume '{costume.Path}' could not be found",
                                                            ErrorType.FileNotFound, null, DefinitionFile));
                    break;
                }

                // Create costume

                // TODO resolution
                dynamic rotationCenter = costume.Attributes.rotationCenter;
                sprite.Costumes.Add(new Costume
                {
                    Name             = costume.Name,
                    Id               = costumeData.Id,
                    BitmapResolution = 1,
                    Md5              = costumeData.Contents.GetMd5Checksum() + costumeData.Extension,
                    RotationCenter   = new Point((int)rotationCenter.x.Value, (int)rotationCenter.y.Value)
                });
            }

            // Sounds
            foreach (Asset sound in definitionFile.Sounds)
            {
                // Find sound file
                if (!context.ProjectAssets.SoundFiles.TryGetValue(sound.Path, out LoadedAsset soundData))
                {
                    context.ErrorList.Add(new CompilerError($"Sound '{sound.Path}' could not be found",
                                                            ErrorType.FileNotFound, null, DefinitionFile));
                    break;
                }

                // Create sound
                int sampleRate     = BitConverter.ToInt32(soundData.Contents, 24);
                int bytesPerSample = BitConverter.ToInt16(soundData.Contents, 34) / 8;
                int sampleCount    = BitConverter.ToInt32(soundData.Contents, 40) / bytesPerSample;

                sprite.Sounds.Add(new Sound
                {
                    Name        = sound.Name,
                    Id          = soundData.Id,
                    Md5         = soundData.Contents.GetMd5Checksum() + soundData.Extension,
                    Rate        = sampleRate,
                    SampleCount = sampleCount
                });
            }

            return(sprite);
        }
        private static string GetDefaultCase(Expression defaultBody, TranslationContext context)
        {
            var defaultCaseBody = context.TranslateCodeBlock(defaultBody);

            return(GetCase(defaultCaseBody, "default:"));
        }
 private static string GetTest(ConditionalExpression conditional, TranslationContext context)
 => new FormattedCondition(conditional.Test, context);
        private static AggregationExpression TranslateStringEqualsMethod(TranslationContext context, MethodCallExpression expression)
        {
            var method    = expression.Method;
            var arguments = expression.Arguments;

            Expression lhsExpression;
            Expression rhsExpression;
            Expression comparisonTypeExpression = null;

            if (method.IsStatic)
            {
                lhsExpression = arguments[0];
                rhsExpression = arguments[1];
                if (arguments.Count == 3)
                {
                    comparisonTypeExpression = arguments[2];
                }
            }
            else
            {
                lhsExpression = expression.Object;
                rhsExpression = arguments[0];
                if (arguments.Count == 2)
                {
                    comparisonTypeExpression = arguments[1];
                }
            }

            StringComparison comparisonType = StringComparison.Ordinal;

            if (comparisonTypeExpression != null)
            {
                comparisonType = comparisonTypeExpression.GetConstantValue <StringComparison>(containingExpression: expression);
            }

            var lhsTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, lhsExpression);
            var rhsTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, rhsExpression);

            AstExpression ast;

            switch (comparisonType)
            {
            case StringComparison.CurrentCulture:
            case StringComparison.Ordinal:
                ast = AstExpression.Eq(lhsTranslation.Ast, rhsTranslation.Ast);
                break;

            case StringComparison.CurrentCultureIgnoreCase:
            case StringComparison.OrdinalIgnoreCase:
                ast = AstExpression.Eq(AstExpression.StrCaseCmp(lhsTranslation.Ast, rhsTranslation.Ast), 0);
                break;

            default:
                goto notSupported;
            }

            return(new AggregationExpression(expression, ast, new BooleanSerializer()));

notSupported:
            throw new ExpressionNotSupportedException(expression);
        }
示例#11
0
        public static String Serialize(object obj, TranslationContext translationContext, StringFormat format)
        {
            StringSerializer stringSerializer = FormatSerializer.GetStringSerializer(format);

            return(stringSerializer.Serialize(obj, translationContext));
        }
示例#12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="stream"></param>
        /// <param name="translationContext"></param>
        /// <param name="format"></param>
        public static void Serialize(object obj, Stream stream, TranslationContext translationContext, Format format)
        {
            FormatSerializer serializer = FormatSerializer.GetSerializer(format);

            serializer.Serialize(obj, stream, translationContext);
        }
示例#13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="file"></param>
        /// <param name="translationContext"></param>
        /// <param name="format"></param>
        public async static Task Serialize(object obj, object file, TranslationContext translationContext, Format format)
        {
            Stream writeStream = await FundamentalPlatformSpecifics.Get().OpenFileWriteStream(file);

            Serialize(obj, writeStream, translationContext, format);
        }
示例#14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="stringBuilder"></param>
        /// <param name="translationContext"></param>
        /// <param name="format"></param>
        public static void Serialize(object obj, StringBuilder stringBuilder, TranslationContext translationContext, StringFormat format)
        {
            StringSerializer stringSerializer = FormatSerializer.GetStringSerializer(format);

            stringSerializer.Serialize(obj, stringBuilder, translationContext);
        }
示例#15
0
        public async Task <object> DeserializeUri(ParsedUri uri, Format format = Format.Xml, TranslationContext context = null, IDeserializationHookStrategy deserializationHookStrategy = null)
        {
            object result = null;

            var request = WebRequest.Create(uri);

            if (request != null)
            {
                WebResponse response = await request.GetResponseAsync();

                result = Deserialize(response.GetResponseStream(), context, deserializationHookStrategy, format);
            }

            return(result);
        }
示例#16
0
 public override string Marshall(object instance, TranslationContext context = null)
 {
     return(((Rect)instance).ToString());
 }
        public override List <string> CodeGen(TranslationContext context)
        {
            var csContext  = (CSTranslationContext)context;
            var csClass    = csContext.CurrentClass;
            var codeResult = new List <string>();
            var operand    = GetOperand <VMSetToNextOperand>();

            if (operand.SearchType == VMSetToNextSearchType.ClosestHouse)
            {
                return(Line($"_bResult = false; //set to next closest house not yet impl"));
            }

            codeResult.Add($"{{ //set to next ({operand.SearchType.ToString()})");
            codeResult.Add($"var targetValue = {CSScopeMemory.GetExpression(csContext, operand.TargetOwner, operand.TargetData, false)};");

            //re-evaluation of what this actually does:
            //tries to find the next object id (from the previous) that meets a specific condition.
            //the previous object id is supplied via the target variable
            //
            //we should take the first result with object id > targetValue.

            if (operand.SearchType == VMSetToNextSearchType.PartOfAMultipartTile)
            {
                codeResult.Add($"var objPointer = context.VM.GetObjectById(targetValue);");
                codeResult.Add($"var result = VMSetToNext.MultitilePart(context, objPointer, targetValue);");
                codeResult.Add($"_bResult = result != 0;");
                codeResult.Add($"if (_bResult) {CSScopeMemory.SetStatement(csContext, operand.TargetOwner, operand.TargetData, "=", "result", false)}");
                codeResult.Add($"}}");
            }
            else if (operand.SearchType == VMSetToNextSearchType.ObjectAdjacentToObjectInLocal)
            {
                codeResult.Add($"var objPointer = context.VM.GetObjectById(targetValue);");
                codeResult.Add($"var result = VMSetToNext.AdjToLocal(context, objPointer, {operand.Local});");
                codeResult.Add($"_bResult = result != null;");
                codeResult.Add($"if (_bResult) {CSScopeMemory.SetStatement(csContext, operand.TargetOwner, operand.TargetData, "=", "result.ObjectID", false)}");
                codeResult.Add($"}}");
            }
            else if (operand.SearchType == VMSetToNextSearchType.Career)
            {
                codeResult.Add($"var result = Content.Content.Get().Jobs.SetToNext(targetValue);");
                codeResult.Add($"_bResult = result >= 0;");
                codeResult.Add($"if (_bResult) {CSScopeMemory.SetStatement(csContext, operand.TargetOwner, operand.TargetData, "=", "result", false)}");
                codeResult.Add($"}}");
            }
            else if (operand.SearchType == VMSetToNextSearchType.NeighborId)
            {
                codeResult.Add($"var result = Content.Content.Get().Neighborhood.SetToNext(targetValue);");
                codeResult.Add($"_bResult = result >= 0;");
                codeResult.Add($"if (_bResult) {CSScopeMemory.SetStatement(csContext, operand.TargetOwner, operand.TargetData, "=", "result", false)};");
                codeResult.Add($"}}");
            }
            else if (operand.SearchType == VMSetToNextSearchType.NeighborOfType)
            {
                codeResult.Add($"var result = Content.Content.Get().Neighborhood.SetToNext(targetValue, {operand.GUID});");
                codeResult.Add($"_bResult = result >= 0;");
                codeResult.Add($"if (_bResult) {CSScopeMemory.SetStatement(csContext, operand.TargetOwner, operand.TargetData, "=", "result", false)};");
                codeResult.Add($"}}");
            }
            else
            {
                //if we've cached the search type, use that instead of all objects
                switch (operand.SearchType)
                {
                case VMSetToNextSearchType.ObjectOnSameTile:
                    codeResult.Add($"var objPointer = context.VM.GetObjectById(targetValue) ?? context.Caller;");
                    codeResult.Add($"var entities = context.VM.Context.ObjectQueries.GetObjectsAt(objPointer.Position);");
                    break;

                case VMSetToNextSearchType.Person:
                case VMSetToNextSearchType.FamilyMember:
                    codeResult.Add($"var entities = context.VM.Context.ObjectQueries.Avatars;");
                    break;

                case VMSetToNextSearchType.ObjectOfType:
                    codeResult.Add($"var entities = context.VM.Context.ObjectQueries.GetObjectsByGUID({operand.GUID});");
                    break;

                case VMSetToNextSearchType.ObjectWithCategoryEqualToSP0:
                    csClass.UseParams = true;
                    codeResult.Add($"var entities = context.VM.Context.ObjectQueries.GetObjectsByCategory(args[0]);");
                    break;

                default:
                    codeResult.Add($"var entities = context.VM.Entities;");
                    break;
                }
                codeResult.Add($"_bResult = false;");
                codeResult.Add($"if (entities != null) {{");

                bool loop = (operand.SearchType == VMSetToNextSearchType.ObjectOnSameTile);

                codeResult.Add($"var ind = (entities.Count < 4)?0:VM.FindNextIndexInObjList(entities, targetValue);");
                codeResult.Add($"for (int i = ind; i < entities.Count; i++) {{");
                codeResult.Add($"var tempObj = entities[i];");

                string found = null;
                switch (operand.SearchType)
                { //manual search types
                case VMSetToNextSearchType.NonPerson:
                    found = "tempObj is VMGameObject";
                    break;

                case VMSetToNextSearchType.FamilyMember:
                    found = "(context.VM.TS1State.CurrentFamily?.FamilyGUIDs?.Contains(((VMAvatar)tempObj).Object.OBJ.GUID) ?? false)";
                    break;

                default:
                    //set to next object, or cached search.
                    break;
                }

                if (found != null)
                {
                    codeResult.Add($"if (tempObj.ObjectID > targetValue && {found}) {{");
                }
                else
                {
                    codeResult.Add($"if (tempObj.ObjectID > targetValue) {{");
                }
                codeResult.Add($"{CSScopeMemory.SetStatement(csContext, operand.TargetOwner, operand.TargetData, "=", "tempObj.ObjectID", false)}");
                codeResult.Add($"_bResult = true; break;");
                codeResult.Add($"}}"); //end if

                codeResult.Add($"}}"); //end loop

                if (loop)
                {
                    codeResult.Add($"if (!_bResult) {{");
                    codeResult.Add($"VMEntity first = entities.FirstOrDefault();");
                    codeResult.Add($"_bResult = first != null && entities.Contains(objPointer);");
                    codeResult.Add($"if (_bResult) {CSScopeMemory.SetStatement(csContext, operand.TargetOwner, operand.TargetData, "=", "first.ObjectID", false)}");
                    codeResult.Add($"}}");
                    //loop around
                }

                codeResult.Add($"}}");                   //end "entities != null"

                codeResult.Add($"}} //end set to next"); //end primitive scope
            }

            return(codeResult);
        }
示例#18
0
        public static AstFilter Translate(TranslationContext context, BinaryExpression expression, BinaryExpression moduloExpression, Expression remainderExpression)
        {
            var fieldExpression = moduloExpression.Left;
            var field           = ExpressionToFilterFieldTranslator.Translate(context, fieldExpression);

            var       divisorExpression = moduloExpression.Right;
            BsonValue divisor;
            BsonValue remainder;

            if (divisorExpression.Type == typeof(decimal) && remainderExpression.Type == typeof(decimal))
            {
                divisor   = divisorExpression.GetConstantValue <decimal>(containingExpression: moduloExpression);
                remainder = remainderExpression.GetConstantValue <decimal>(containingExpression: expression);
            }
            else if (divisorExpression.Type == typeof(double) && remainderExpression.Type == typeof(double))
            {
                divisor   = divisorExpression.GetConstantValue <double>(containingExpression: moduloExpression);
                remainder = remainderExpression.GetConstantValue <double>(containingExpression: expression);
            }
            else if (divisorExpression.Type == typeof(float) && remainderExpression.Type == typeof(float))
            {
                divisor   = divisorExpression.GetConstantValue <float>(containingExpression: moduloExpression);
                remainder = remainderExpression.GetConstantValue <float>(containingExpression: expression);
            }
            else if (divisorExpression.Type == typeof(int) && remainderExpression.Type == typeof(int))
            {
                divisor   = divisorExpression.GetConstantValue <int>(containingExpression: moduloExpression);
                remainder = remainderExpression.GetConstantValue <int>(containingExpression: expression);
            }
            else if (divisorExpression.Type == typeof(long) && remainderExpression.Type == typeof(long))
            {
                divisor   = divisorExpression.GetConstantValue <long>(containingExpression: moduloExpression);
                remainder = remainderExpression.GetConstantValue <long>(containingExpression: expression);
            }
            else if (divisorExpression.Type == typeof(uint) && remainderExpression.Type == typeof(uint))
            {
                divisor   = divisorExpression.GetConstantValue <uint>(containingExpression: moduloExpression);
                remainder = remainderExpression.GetConstantValue <uint>(containingExpression: expression);
            }
            else if (divisorExpression.Type == typeof(ulong) && remainderExpression.Type == typeof(ulong))
            {
                divisor   = (long)divisorExpression.GetConstantValue <ulong>(containingExpression: moduloExpression);
                remainder = (long)remainderExpression.GetConstantValue <ulong>(containingExpression: expression);
            }
            else
            {
                throw new ExpressionNotSupportedException(expression);
            }

            var moduloComparisonAst = AstFilter.Mod(field, divisor, remainder);

            switch (expression.NodeType)
            {
            case ExpressionType.Equal:
                return(moduloComparisonAst);

            case ExpressionType.NotEqual:
                return(AstFilter.Not(moduloComparisonAst));
            }

            throw new ExpressionNotSupportedException(expression);
        }
示例#19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="textWriter"></param>
        /// <param name="translationContext"></param>
        /// <param name="format"></param>
        public static void Serialize(object obj, TextWriter textWriter, TranslationContext translationContext, StringFormat format)
        {
            StringSerializer serializer = FormatSerializer.GetStringSerializer(format);

            serializer.Serialize(obj, textWriter, translationContext);
        }
示例#20
0
 public override string Marshall(object instance, TranslationContext context = null)
 {
     byte[] bytes = ((MemoryStream)instance).ToArray();
     return(System.Convert.ToBase64String(bytes));
 }
 private static string GetSubject(MemberExpression memberExpression, TranslationContext context)
 {
     return((memberExpression.Expression != null)
         ? GetInstanceMemberSubject(memberExpression, context)
         : memberExpression.Member.DeclaringType.GetFriendlyName());
 }
        public static AggregationExpression Translate(TranslationContext context, MethodCallExpression expression)
        {
            switch (expression.Method.Name)
            {
            case "Abs": return(AbsMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Add": return(AddMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Aggregate": return(AggregateMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "All": return(AllMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Any": return(AnyMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Average": return(AverageMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Ceiling": return(CeilingMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "CompareTo": return(CompareToMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Concat": return(ConcatMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Contains": return(ContainsMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "DefaultIfEmpty": return(DefaultIfEmptyMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Distinct": return(DistinctMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "ElementAt": return(ElementAtMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Equals": return(EqualsMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Except": return(ExceptMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Exp": return(ExpMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Floor": return(FloorMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "get_Item": return(GetItemMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Intersect": return(IntersectMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "IsNullOrEmpty": return(IsNullOrEmptyMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "IsSubsetOf": return(IsSubsetOfMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Parse": return(ParseMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Pow": return(PowMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Range": return(RangeMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Reverse": return(ReverseMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Select": return(SelectMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "SetEquals": return(SetEqualsMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Split": return(SplitMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Sqrt": return(SqrtMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "StrLenBytes": return(StrLenBytesMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Subtract": return(SubtractMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Sum": return(SumMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Take": return(TakeMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "ToArray": return(ToArrayMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "ToList": return(ToListMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "ToString": return(ToStringMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Truncate": return(TruncateMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Where": return(WhereMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Union": return(UnionMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Zip": return(ZipMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "AddDays":
            case "AddHours":
            case "AddMilliseconds":
            case "AddMinutes":
            case "AddMonths":
            case "AddQuarters":
            case "AddSeconds":
            case "AddTicks":
            case "AddWeeks":
            case "AddYears":
                return(DateTimeAddOrSubtractMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Count":
            case "LongCount":
                return(CountMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "First":
            case "Last":
                return(FirstOrLastMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "IndexOf":
            case "IndexOfBytes":
                return(IndexOfMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "IndexOfAny":
                return(IndexOfAnyMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Log":
            case "Log10":
                return(LogMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Max":
            case "Min":
                return(MaxOrMinMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "StandardDeviationPopulation":
            case "StandardDeviationSample":
                return(StandardDeviationMethodsToAggregationExpressionTranslator.Translate(context, expression));

            case "StartsWith":
            case "EndsWith":
                return(StartsWithContainsOrEndsWithMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Substring":
            case "SubstrBytes":
                return(SubstringMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "ToLower":
            case "ToLowerInvariant":
            case "ToUpper":
            case "ToUpperInvariant":
                return(ToLowerOrToUpperMethodToAggregationExpressionTranslator.Translate(context, expression));

            case "Trim":
            case "TrimEnd":
            case "TrimStart":
                return(TrimMethodToAggregationExpressionTranslator.Translate(context, expression));
            }

            throw new ExpressionNotSupportedException(expression);
        }
 private static string GetInstanceMemberSubject(MemberExpression memberExpression, TranslationContext context)
 {
     return(SubjectIsCapturedInstance(memberExpression)
         ? null
         : context.Translate(memberExpression.Expression));
 }
示例#24
0
        public override void Run(List <ExpressionSharpnode> arguments, SyntaxNode originalNode, TranslationContext context)
        {
            // Error checking
            int numArguments = arguments.Count;

            if (numArguments != 1)
            {
                this.Errors.Add(new Error(Diagnostics.SSIL301_InternalLocalizedError,
                                          originalNode,
                                          "incorrect number of arguments for a quantifier expression"));
                this.Silvernode = new ErrorSilvernode(originalNode);
                return;
            }
            if (!(arguments[0] is LambdaSharpnode))
            {
                this.Errors.Add(new Error(Diagnostics.SSIL124_QuantifierMustGetLambda,
                                          originalNode));
                this.Silvernode = new ErrorSilvernode(originalNode);
                return;
            }

            // Use the lambda expression to create the Viper code
            LambdaSharpnode lambda = (LambdaSharpnode)arguments[0];

            if (lambda.PrepareForInsertionIntoQuantifier(context))
            {
                this.Silvernode = new SimpleSequenceSilvernode(originalNode, this.kind == QuantifierKind.ForAll ? "forall " : "exists ",
                                                               new IdentifierSilvernode(lambda.VariableIdentifier),
                                                               " : ",
                                                               new TypeSilvernode(null, lambda.VariableSilverType),
                                                               " :: ",
                                                               lambda.BodySilvernode
                                                               );
            }
            else
            {
                var res = lambda.GetErrorTranslationResult();
                this.Silvernode = res.Silvernode;
                this.Errors.AddRange(res.Errors);
            }
        }
示例#25
0
 public ObjectType TransformModel(TranslationContext context, ObjectType sourceType)
 {
     // TODO: The result type is actually String, not an object type..., this should be okay because it's never going to be the result of a ClinicalRequest...
     throw new NotImplementedException();
 }
示例#26
0
        private CREFModel.ClinicalAssertion TranslateClinicalAssertion(TranslationContext context, Node node)
        {
            // node is expected to be an ActionGroup
            // Action types determine the assertion to be created
            // CreateAction - MissingDataAssertion
            // UpdateAction - MissingDataAssertion
            // MessageAction - OutOfRangeAssertion
            // CollectInformationAction - MissingDataAssertion
            // Any other action cannot be represented

            var assertions = new List <CREFModel.ClinicalAssertion>();

            var subElements = node.Children.FirstOrDefault(c => c.Name == "subElements");

            if (subElements != null)
            {
                foreach (var element in subElements.Children)
                {
                    if (element.Name == "simpleAction")
                    {
                        switch (element.NodeType.GetLocalName())
                        {
                        case "CreateAction": assertions.Add(TranslateCreateAction(context, element)); break;

                        case "UpdateAction": assertions.Add(TranslateUpdateAction(context, element)); break;

                        case "MessageAction": assertions.Add(TranslateMessageAction(context, element)); break;

                        case "CollectInformationAction": assertions.Add(TranslateCollectInformationAction(context, element)); break;

                        default: throw new NotSupportedException(String.Format("Translation of {0} actions is not supported.", element.NodeType.GetLocalName()));
                        }
                    }
                    else if (element.Name == "actionGroup")
                    {
                        assertions.Add(TranslateClinicalAssertion(context, element));
                    }
                    else if (element.Name == "actionGroupReference")
                    {
                        throw new NotSupportedException("Translation of action group references is not supported.");
                    }
                }
            }

            if (assertions.Count > 1)
            {
                var compositeAssertion = new CREFModel.CompositeAssertion();

                compositeAssertion.CompositionType = GetCompositionType(GetGroupSelectionBehavior(node));

                var descriptionNode = node.Children.FirstOrDefault(c => c.Name == "Description");
                if (descriptionNode != null)
                {
                    compositeAssertion.Description = descriptionNode.GetAttribute <string>("value");
                }

                compositeAssertion.CompositeAssertionAssertions.AddRange(assertions);

                return(compositeAssertion);
            }

            return(assertions[0]);
        }
示例#27
0
        public object TransformModelPath(TranslationContext context, ObjectType sourceType, ASTNode node, string path)
        {
            // This translation expects the ADXP (Address Part) to be accessed through an HeD expression of:
            // First(Filter(Property(, 'part'), Equal(Property(, 'type'), <vMR Address Type Code>)))
            // This would translate to direct property access of the relevant value in the StructuredAddress type of the Allscripts Model
            var firstNode = node.Children.FirstOrDefault(c => c.Name == "source" && c.NodeType.GetLocalName() == "First");

            if (firstNode != null)
            {
                var filterNode = firstNode.Children.FirstOrDefault(c => c.Name == "source" && c.NodeType.GetLocalName() == "Filter");
                if (filterNode != null)
                {
                    var propertyNode = filterNode.Children.FirstOrDefault(c => c.Name == "source" && c.NodeType.GetLocalName() == "Property" && c.GetAttribute <string>("path") == "part");
                    if (propertyNode != null)
                    {
                        var equalNode = filterNode.Children.FirstOrDefault(c => c.Name == "condition" && c.NodeType.GetLocalName() == "Equal");
                        if (equalNode != null)
                        {
                            var propertyTypeNode = equalNode.Children.FirstOrDefault(c => c.Name == "operand" && c.NodeType.GetLocalName() == "Property" && c.GetAttribute <string>("path") == "type");
                            if (propertyTypeNode != null)
                            {
                                var partTypeNode = equalNode.Children.FirstOrDefault(c => c.NodeType.GetLocalName() == "StringLiteral" || c.NodeType.GetLocalName() == "Literal");
                                if (partTypeNode != null)
                                {
                                    var partType = partTypeNode.GetAttribute <string>("value");
                                    switch (partType)
                                    {
                                    // AddressLine
                                    case "AL": return(GetPropertyExpression(context, propertyNode, "AddressLine1"));

                                    // Additional Locator
                                    case "ADL": break;

                                    // Unit Identifier
                                    case "UNID": break;

                                    // Unit Designator
                                    case "UNIT": break;

                                    // Delivery Address Line
                                    case "DAL": return(GetPropertyExpression(context, propertyNode, "AddressLine1"));

                                    // Delivery Installation Type
                                    case "DINST": break;

                                    // Delivery Installation Area
                                    case "DINSTA": break;

                                    // Delivery Installation Qualifier
                                    case "DINSTQ": break;

                                    // Delivery Mode
                                    case "DMOD": break;

                                    // Delivery Mode Identifier
                                    case "DMODID": break;

                                    // Street Address Line
                                    case "SAL": return(GetPropertyExpression(context, propertyNode, "AddressLine1"));

                                    // Building Number
                                    case "BNR": break;

                                    // Building Number Suffix
                                    case "BNS": break;

                                    // Street Name
                                    case "STR": break;

                                    // Street Name Base
                                    case "STB": break;

                                    // Street Type
                                    case "STTYP": break;

                                    // Direction
                                    case "DIR": break;

                                    // Intersection
                                    case "INT": break;

                                    // Care of
                                    case "CAR": break;

                                    // Census Tract
                                    case "CEN": break;

                                    // Country
                                    case "CNT": return(GetPropertyExpression(context, propertyNode, "Country"));

                                    // County or Parish
                                    case "CPA": return(GetPropertyExpression(context, propertyNode, "CountyCode"));

                                    // Municipality or City
                                    case "CTY": return(GetPropertyExpression(context, propertyNode, "City"));

                                    // Delimiter
                                    case "DEL": break;

                                    // Post Office Box
                                    case "POB": break;

                                    // Precinct
                                    case "PRE": break;

                                    // State
                                    case "STA": return(GetPropertyExpression(context, propertyNode, "StateOrProvince"));

                                    // Zip
                                    case "ZIP": return(GetPropertyExpression(context, propertyNode, "PostalCode"));

                                    // Delivery Point Identifier
                                    case "DPID": break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // If we make it here, translation failed because the pattern was not what was expected.
            throw new InvalidOperationException("Could not translated Adress Part reference to a representation within CREF.");
        }
        // public static methods
        public static ExecutableQuery <TDocument, TOutput> Translate <TDocument>(MongoQueryProvider <TDocument> provider, TranslationContext context, MethodCallExpression expression)
        {
            var method    = expression.Method;
            var arguments = expression.Arguments;

            if (method.IsOneOf(__averageMethods))
            {
                var sourceExpression = arguments[0];
                var pipeline         = ExpressionToPipelineTranslator.Translate(context, sourceExpression);
                var sourceSerializer = pipeline.OutputSerializer;

                AstExpression valueExpression;
                if (method.IsOneOf(__averageWithSelectorMethods))
                {
                    var selectorLambda      = ExpressionHelper.UnquoteLambda(arguments[1]);
                    var selectorTranslation = ExpressionToAggregationExpressionTranslator.TranslateLambdaBody(context, selectorLambda, sourceSerializer, asRoot: true);
                    valueExpression = selectorTranslation.Ast;
                }
                else
                {
                    Ensure.That(sourceSerializer is IWrappedValueSerializer, "Expected sourceSerializer to be an IWrappedValueSerializer.", nameof(sourceSerializer));
                    var root = AstExpression.Var("ROOT", isCurrent: true);
                    valueExpression = AstExpression.GetField(root, "_v");
                }

                IBsonSerializer outputValueSerializer = expression.GetResultType() switch
                {
                    Type t when t == typeof(int) => new Int32Serializer(),
                    Type t when t == typeof(long) => new Int64Serializer(),
                    Type t when t == typeof(float) => new SingleSerializer(),
                    Type t when t == typeof(double) => new DoubleSerializer(),
                    Type t when t == typeof(decimal) => new DecimalSerializer(),
                    Type {
                        IsConstructedGenericType : true
                    } t when t.GetGenericTypeDefinition() == typeof(Nullable <>) => (IBsonSerializer)Activator.CreateInstance(typeof(NullableSerializer <>).MakeGenericType(t.GenericTypeArguments[0])),
                    _ => throw new ExpressionNotSupportedException(expression)
                };
                var outputWrappedValueSerializer = WrappedValueSerializer.Create("_v", outputValueSerializer);

                pipeline = pipeline.AddStages(
                    outputWrappedValueSerializer,
                    AstStage.Group(
                        id: BsonNull.Value,
                        fields: AstExpression.AccumulatorField("_v", AstAccumulatorOperator.Avg, valueExpression)),
                    AstStage.Project(AstProject.ExcludeId()));

                return(ExecutableQuery.Create(
                           provider.Collection,
                           provider.Options,
                           pipeline,
                           __finalizer));
            }

            throw new ExpressionNotSupportedException(expression);
        }
    }
示例#29
0
 public ObjectType TransformModel(TranslationContext context, ObjectType sourceType)
 {
     // There is no CREF equivalent for this class, should be okay though because it should never be the result type of a ClinicalRequest.
     throw new NotImplementedException();
 }
示例#30
0
 protected string GenerateMethod(TypeDefinition type, string methodName, bool followDependencies)
 {
     var method = type.GetMethods(methodName).First();
     TextWriter writer = new StringWriter();
     var generator = new JsCodeGenerator(this.typeSystem, writer, false);
     var context = new TranslationContext(this.typeSystem, generator);
     var asmDependencies = new List<AssemblyDefinition>();
     context.GenerateMethod(method, followDependencies, asmDependencies);
     return writer.ToString();
 }
示例#31
0
 public Instructions InstructionsFromMethodBody(TypeRef returnType, PE.MethodBody methodBody)
 {
     var ctxt = new TranslationContext(returnType, methodBody.Instructions, methodBody.ExceptionHandlingClauses);
     return InstructionsFromContext(ctxt);
 }
示例#32
0
 public TryTranslationContext(TranslationContext parent, int start, IImSeq<PE.ExceptionHandlingClause> clauses)
     : base(parent, start)
 {
     Clauses = clauses;
 }
示例#33
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="textWriter"></param>
 /// <param name="translationContext"></param>
 public abstract void Serialize(object obj, BinaryWriter textWriter, TranslationContext translationContext);
示例#34
0
        private Instructions InstructionsFromContext(TranslationContext ctxt)
        {
            var instructions = new Seq<Instruction>();
            var i = ctxt.Start;
            while (!ctxt.AtEnd(i))
            {
                var j = i > ctxt.Start ? ctxt.JumpOverHandlers(i) : i;
                if (j > i)
                    i = j;
                else
                {
                    var ehcs = ctxt.OutermostTryBlocks(i);
                    if (ehcs != null)
                    {
                        // A try instruction begins here with given handlers
                        var offset = ctxt.Instructions[i].Offset;
                        var tryCtxt = new TryTranslationContext(ctxt, i, ehcs);
                        var tryBlock = InstructionsFromContext(tryCtxt);

                        var handlers = new Seq<TryInstructionHandler>();
                        foreach (var ehc in ehcs)
                        {
                            var handlerCtxt = new HandlerTranslationContext
                                (tryCtxt, ctxt.OffsetToIndex[ehc.HandlerOffset], ehc);
                            var handlerBlock = InstructionsFromContext(handlerCtxt);
                            switch (ehc.Flags)
                            {
                            case PE.CorILExceptionClause.Exception:
                                handlers.Add(new CatchTryInstructionHandler((TypeRef)ehc.Class, handlerBlock));
                                break;
                            case PE.CorILExceptionClause.Filter:
                                {
                                    var filterCtxt = new FilterTranslationContext
                                        (tryCtxt, ctxt.OffsetToIndex[ehc.FilterOffset], ehc);
                                    var filterBlock = InstructionsFromContext(filterCtxt);
                                    handlers.Add(new FilterTryInstructionHandler(filterBlock, handlerBlock));
                                    break;
                                }
                            case PE.CorILExceptionClause.Finally:
                                handlers.Add(new FinallyTryInstructionHandler(handlerBlock));
                                break;
                            case PE.CorILExceptionClause.Fault:
                                handlers.Add(new FaultTryInstructionHandler(handlerBlock));
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                        }
                        instructions.Add(new TryInstruction(offset, tryBlock, handlers));

                        // Jump over try block
                        var nextOffset = ehcs[0].TryOffset + ehcs[0].TryLength;
                        if (!ctxt.OffsetToIndex.TryGetValue(nextOffset, out i))
                            i = ctxt.Instructions.Length;
                    }
                    else
                    {
                        var instruction = ctxt.Instructions[i++];
                        var offset = instruction.Offset;

                        while (instruction.OpCode == PE.OpCode.Unaligned || instruction.OpCode == PE.OpCode.Volatile ||
                               instruction.OpCode == PE.OpCode.Tailcall)
                        {
                            // Skip over any ignored prefixes, but remember instruction begins at original offset
                            // NOTE: What ever happened to the "no." prefix mentioned in the spec?
                            if (i >= ctxt.Instructions.Length)
                                throw new InvalidOperationException("invalid instructions");
                            instruction = ctxt.Instructions[i++];
                        }
                        switch (instruction.OpCode)
                        {
                        case PE.OpCode.Cpblk:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Cpblk));
                            break;
                        case PE.OpCode.Initblk:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Initblk));
                            break;
                        case PE.OpCode.Arglist:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Arglist));
                            break;
                        case PE.OpCode.Localloc:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Localloc));
                            break;
                        case PE.OpCode.Jmp:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Jmp));
                            break;
                        case PE.OpCode.Calli:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Calli));
                            break;
                        case PE.OpCode.Sizeof:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Sizeof));
                            break;
                        case PE.OpCode.Mkrefany:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Mkrefany));
                            break;
                        case PE.OpCode.Refanytype:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Refanytype));
                            break;
                        case PE.OpCode.Refanyval:
                            instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Refanyval));
                            break;
                        case PE.OpCode.Nop:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Nop));
                            break;
                        case PE.OpCode.Break:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Break));
                            break;
                        case PE.OpCode.Dup:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Dup));
                            break;
                        case PE.OpCode.Pop:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Pop));
                            break;
                        case PE.OpCode.Ldnull:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Ldnull));
                            break;
                        case PE.OpCode.Ckfinite:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Ckfinite));
                            break;
                        case PE.OpCode.Throw:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Throw));
                            break;
                        case PE.OpCode.Rethrow:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Rethrow));
                            break;
                        case PE.OpCode.Ldind_ref:
                            instructions.Add(new MiscInstruction(offset, MiscOp.LdindRef));
                            break;
                        case PE.OpCode.Stind_ref:
                            instructions.Add(new MiscInstruction(offset, MiscOp.StindRef));
                            break;
                        case PE.OpCode.Ldelem_ref:
                            instructions.Add(new MiscInstruction(offset, MiscOp.LdelemRef));
                            break;
                        case PE.OpCode.Stelem_ref:
                            instructions.Add(new MiscInstruction(offset, MiscOp.StelemRef));
                            break;
                        case PE.OpCode.Ldlen:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Ldlen));
                            break;
                        case PE.OpCode.Ret:
                            if (ctxt.ResultType == null)
                                instructions.Add(new MiscInstruction(offset, MiscOp.Ret));
                            else
                                instructions.Add(new MiscInstruction(offset, MiscOp.RetVal));
                            break;
                        case PE.OpCode.Endfilter:
                            instructions.Add(new MiscInstruction(offset, MiscOp.Endfilter));
                            break;
                        case PE.OpCode.Endfinally: // aka EndFault
                            instructions.Add(new MiscInstruction(offset, MiscOp.Endfinally));
                            break;
                        case PE.OpCode.Br_s:
                        case PE.OpCode.Br:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.Br, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Brtrue_s: // aka brinst.s
                        case PE.OpCode.Brtrue: // aka brinst
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.Brtrue, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Brfalse_s: // aka brzero.s, brnull.s
                        case PE.OpCode.Brfalse: // aka brzero, brnull
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.Brfalse, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Beq:
                        case PE.OpCode.Beq_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.Breq, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Bne_un:
                        case PE.OpCode.Bne_un_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.Brne, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Leave:
                        case PE.OpCode.Leave_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.Leave, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Blt:
                        case PE.OpCode.Blt_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.BrLt, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Blt_un:
                        case PE.OpCode.Blt_un_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.BrLt, true, (int)instruction.Value));
                            break;
                        case PE.OpCode.Ble:
                        case PE.OpCode.Ble_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.BrLe, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Ble_un:
                        case PE.OpCode.Ble_un_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.BrLe, true, (int)instruction.Value));
                            break;
                        case PE.OpCode.Bgt:
                        case PE.OpCode.Bgt_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.BrGt, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Bgt_un:
                        case PE.OpCode.Bgt_un_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.BrGt, true, (int)instruction.Value));
                            break;
                        case PE.OpCode.Bge:
                        case PE.OpCode.Bge_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.BrGe, false, (int)instruction.Value));
                            break;
                        case PE.OpCode.Bge_un:
                        case PE.OpCode.Bge_un_s:
                            instructions.Add
                                (new BranchInstruction(offset, BranchOp.BrGe, true, (int)instruction.Value));
                            break;
                        case PE.OpCode.Switch:
                            instructions.Add(new SwitchInstruction(offset, (Seq<int>)instruction.Value));
                            break;
                        case PE.OpCode.Ceq:
                            instructions.Add(new CompareInstruction(offset, CompareOp.Ceq, false));
                            break;
                        case PE.OpCode.Clt:
                            instructions.Add(new CompareInstruction(offset, CompareOp.Clt, false));
                            break;
                        case PE.OpCode.Clt_un:
                            instructions.Add(new CompareInstruction(offset, CompareOp.Clt, true));
                            break;
                        case PE.OpCode.Cgt:
                            instructions.Add(new CompareInstruction(offset, CompareOp.Cgt, false));
                            break;
                        case PE.OpCode.Cgt_un:
                            instructions.Add(new CompareInstruction(offset, CompareOp.Cgt, true));
                            break;
                        case PE.OpCode.Ldarg_0:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, 0));
                            break;
                        case PE.OpCode.Ldarg_1:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, 1));
                            break;
                        case PE.OpCode.Ldarg_2:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, 2));
                            break;
                        case PE.OpCode.Ldarg_3:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, 3));
                            break;
                        case PE.OpCode.Ldarg:
                        case PE.OpCode.Ldarg_s:
                            instructions.Add
                                (new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, (int)instruction.Value));
                            break;
                        case PE.OpCode.Ldarga:
                        case PE.OpCode.Ldarga_s:
                            instructions.Add
                                (new ArgLocalInstruction(offset, ArgLocalOp.Lda, ArgLocal.Arg, (int)instruction.Value));
                            break;
                        case PE.OpCode.Starg:
                        case PE.OpCode.Starg_s:
                            instructions.Add
                                (new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Arg, (int)instruction.Value));
                            break;
                        case PE.OpCode.Ldloc_0:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Local, 0));
                            break;
                        case PE.OpCode.Ldloc_1:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Local, 1));
                            break;
                        case PE.OpCode.Ldloc_2:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Local, 2));
                            break;
                        case PE.OpCode.Ldloc_3:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Local, 3));
                            break;
                        case PE.OpCode.Ldloc:
                        case PE.OpCode.Ldloc_s:
                            instructions.Add
                                (new ArgLocalInstruction
                                     (offset, ArgLocalOp.Ld, ArgLocal.Local, (int)instruction.Value));
                            break;
                        case PE.OpCode.Ldloca:
                        case PE.OpCode.Ldloca_s:
                            instructions.Add
                                (new ArgLocalInstruction
                                     (offset, ArgLocalOp.Lda, ArgLocal.Local, (int)instruction.Value));
                            break;
                        case PE.OpCode.Stloc_0:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Local, 0));
                            break;
                        case PE.OpCode.Stloc_1:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Local, 1));
                            break;
                        case PE.OpCode.Stloc_2:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Local, 2));
                            break;
                        case PE.OpCode.Stloc_3:
                            instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Local, 3));
                            break;
                        case PE.OpCode.Stloc:
                        case PE.OpCode.Stloc_s:
                            instructions.Add
                                (new ArgLocalInstruction
                                     (offset, ArgLocalOp.St, ArgLocal.Local, (int)instruction.Value));
                            break;
                        case PE.OpCode.Ldfld:
                            instructions.Add
                                (new FieldInstruction(offset, FieldOp.Ldfld, (FieldRef)instruction.Value, false));
                            break;
                        case PE.OpCode.Ldsfld:
                            instructions.Add
                                (new FieldInstruction(offset, FieldOp.Ldfld, (FieldRef)instruction.Value, true));
                            break;
                        case PE.OpCode.Ldflda:
                            instructions.Add
                                (new FieldInstruction(offset, FieldOp.Ldflda, (FieldRef)instruction.Value, false));
                            break;
                        case PE.OpCode.Ldsflda:
                            instructions.Add
                                (new FieldInstruction(offset, FieldOp.Ldflda, (FieldRef)instruction.Value, true));
                            break;
                        case PE.OpCode.Stfld:
                            instructions.Add
                                (new FieldInstruction(offset, FieldOp.Stfld, (FieldRef)instruction.Value, false));
                            break;
                        case PE.OpCode.Stsfld:
                            instructions.Add
                                (new FieldInstruction(offset, FieldOp.Stfld, (FieldRef)instruction.Value, true));
                            break;
                        case PE.OpCode.Ldtoken:
                            {
                                if (instruction.Value is FieldRef)
                                    instructions.Add
                                        (new FieldInstruction
                                             (offset, FieldOp.Ldtoken, (FieldRef)instruction.Value, default(bool)));
                                else if (instruction.Value is MethodRef)
                                    instructions.Add
                                        (new MethodInstruction
                                             (offset, MethodOp.Ldtoken, null, false, (MethodRef)instruction.Value));
                                else if (instruction.Value is TypeRef)
                                    // NOTE: May be a higher-kinded type
                                    instructions.Add
                                        (new TypeInstruction(offset, TypeOp.Ldtoken, (TypeRef)instruction.Value));
                                else
                                    throw new InvalidOperationException("unexpected ldtoken instruction value");
                                break;
                            }
                        case PE.OpCode.Constrained:
                            {
                                var constrained = (TypeRef)instruction.Value;
                                if (i >= ctxt.Instructions.Length)
                                    throw new InvalidOperationException("invalid instructions");
                                instruction = ctxt.Instructions[i++];
                                if (instruction.OpCode != PE.OpCode.Callvirt)
                                    throw new InvalidOperationException("invalid instruction");
                                instructions.Add
                                    (new MethodInstruction
                                         (offset, MethodOp.Call, constrained, true, (MethodRef)instruction.Value));
                                break;
                            }
                        case PE.OpCode.Call:
                            instructions.Add
                                (new MethodInstruction
                                     (offset, MethodOp.Call, null, false, (MethodRef)instruction.Value));
                            break;
                        case PE.OpCode.Callvirt:
                            instructions.Add
                                (new MethodInstruction
                                     (offset, MethodOp.Call, null, true, (MethodRef)instruction.Value));
                            break;
                        case PE.OpCode.Ldftn:
                            instructions.Add
                                (new MethodInstruction
                                     (offset, MethodOp.Ldftn, null, false, (MethodRef)instruction.Value));
                            break;
                        case PE.OpCode.Ldvirtftn:
                            instructions.Add
                                (new MethodInstruction
                                     (offset, MethodOp.Ldftn, null, true, (MethodRef)instruction.Value));
                            break;
                        case PE.OpCode.Newobj:
                            instructions.Add
                                (new MethodInstruction
                                     (offset, MethodOp.Newobj, null, false, (MethodRef)instruction.Value));
                            break;
                        case PE.OpCode.Ldind_i1:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.Int8Ref));
                            break;
                        case PE.OpCode.Ldind_u1:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.UInt8Ref));
                            break;
                        case PE.OpCode.Ldind_i2:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.Int16Ref));
                            break;
                        case PE.OpCode.Ldind_u2:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.UInt16Ref));
                            break;
                        case PE.OpCode.Ldind_i4:
                        case PE.OpCode.Ldind_u4:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.Int32Ref));
                            break;
                        case PE.OpCode.Ldind_i8:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.Int64Ref));
                            break;
                        case PE.OpCode.Ldind_i:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.IntNativeRef));
                            break;
                        case PE.OpCode.Ldind_r4:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.SingleRef));
                            break;
                        case PE.OpCode.Ldind_r8:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.DoubleRef));
                            break;
                        case PE.OpCode.Ldobj:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Stind_i1:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.Int8Ref));
                            break;
                        case PE.OpCode.Stind_i2:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.Int16Ref));
                            break;
                        case PE.OpCode.Stind_i4:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.Int32Ref));
                            break;
                        case PE.OpCode.Stind_i8:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.Int64Ref));
                            break;
                        case PE.OpCode.Stind_i:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.IntNativeRef));
                            break;
                        case PE.OpCode.Stind_r4:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.SingleRef));
                            break;
                        case PE.OpCode.Stind_r8:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.DoubleRef));
                            break;
                        case PE.OpCode.Stobj:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Cpobj:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Cpobj, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Newarr:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Newarr, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Initobj:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Initobj, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Castclass:
                            instructions.Add
                                (new TypeInstruction(offset, TypeOp.Castclass, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Isinst:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Isinst, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Box:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Box, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Unbox:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Unbox, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Unbox_any:
                            instructions.Add(new TypeInstruction(offset, TypeOp.UnboxAny, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Ldelem_i1:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.Int8Ref));
                            break;
                        case PE.OpCode.Ldelem_u1:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.UInt8Ref));
                            break;
                        case PE.OpCode.Ldelem_i2:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.Int16Ref));
                            break;
                        case PE.OpCode.Ldelem_u2:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.UInt16Ref));
                            break;
                        case PE.OpCode.Ldelem_i4:
                        case PE.OpCode.Ldelem_u4:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.Int32Ref));
                            break;
                        case PE.OpCode.Ldelem_i:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.IntNativeRef));
                            break;
                        case PE.OpCode.Ldelem_i8: // aka ldelem.u8
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.Int64Ref));
                            break;
                        case PE.OpCode.Ldelem_r4:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.SingleRef));
                            break;
                        case PE.OpCode.Ldelem_r8:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.DoubleRef));
                            break;
                        case PE.OpCode.Ldelem: // aka ldelem.any
                            instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Stelem_i1:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.Int8Ref));
                            break;
                        case PE.OpCode.Stelem_i2:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.Int16Ref));
                            break;
                        case PE.OpCode.Stelem_i4:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.Int32Ref));
                            break;
                        case PE.OpCode.Stelem_i8:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.Int64Ref));
                            break;
                        case PE.OpCode.Stelem_i:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.IntNativeRef));
                            break;
                        case PE.OpCode.Stelem_r4:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.SingleRef));
                            break;
                        case PE.OpCode.Stelem_r8:
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.DoubleRef));
                            break;
                        case PE.OpCode.Stelem: // aka stelem.any
                            instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Readonly:
                            if (i >= ctxt.Instructions.Length)
                                throw new InvalidOperationException("invalid instruction");
                            instruction = ctxt.Instructions[i++];
                            if (instruction.OpCode != PE.OpCode.Ldelema)
                                throw new InvalidOperationException("invalid instruction");
                            instructions.Add(new LdElemAddrInstruction(offset, true, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Ldelema:
                            instructions.Add(new LdElemAddrInstruction(offset, false, (TypeRef)instruction.Value));
                            break;
                        case PE.OpCode.Ldc_i4_0:
                            instructions.Add(new LdInt32Instruction(offset, 0));
                            break;
                        case PE.OpCode.Ldc_i4_1:
                            instructions.Add(new LdInt32Instruction(offset, 1));
                            break;
                        case PE.OpCode.Ldc_i4_2:
                            instructions.Add(new LdInt32Instruction(offset, 2));
                            break;
                        case PE.OpCode.Ldc_i4_3:
                            instructions.Add(new LdInt32Instruction(offset, 3));
                            break;
                        case PE.OpCode.Ldc_i4_4:
                            instructions.Add(new LdInt32Instruction(offset, 4));
                            break;
                        case PE.OpCode.Ldc_i4_5:
                            instructions.Add(new LdInt32Instruction(offset, 5));
                            break;
                        case PE.OpCode.Ldc_i4_6:
                            instructions.Add(new LdInt32Instruction(offset, 6));
                            break;
                        case PE.OpCode.Ldc_i4_7:
                            instructions.Add(new LdInt32Instruction(offset, 7));
                            break;
                        case PE.OpCode.Ldc_i4_8:
                            instructions.Add(new LdInt32Instruction(offset, 8));
                            break;
                        case PE.OpCode.Ldc_i4_m1:
                            instructions.Add(new LdInt32Instruction(offset, -1));
                            break;
                        case PE.OpCode.Ldc_i4:
                        case PE.OpCode.Ldc_i4_s:
                            instructions.Add(new LdInt32Instruction(offset, (int)instruction.Value));
                            break;
                        case PE.OpCode.Ldc_i8:
                            instructions.Add(new LdInt64Instruction(offset, (long)instruction.Value));
                            break;
                        case PE.OpCode.Ldc_r4:
                            instructions.Add(new LdSingleInstruction(offset, (float)instruction.Value));
                            break;
                        case PE.OpCode.Ldc_r8:
                            instructions.Add(new LdDoubleInstruction(offset, (double)instruction.Value));
                            break;
                        case PE.OpCode.Ldstr:
                            instructions.Add(new LdStringInstruction(offset, (string)instruction.Value));
                            break;
                        case PE.OpCode.Add:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Add, false, false));
                            break;
                        case PE.OpCode.Add_ovf:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Add, true, false));
                            break;
                        case PE.OpCode.Add_ovf_un:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Add, true, true));
                            break;
                        case PE.OpCode.Sub:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Sub, false, false));
                            break;
                        case PE.OpCode.Sub_ovf:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Sub, true, false));
                            break;
                        case PE.OpCode.Sub_ovf_un:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Sub, true, true));
                            break;
                        case PE.OpCode.Mul:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Mul, false, false));
                            break;
                        case PE.OpCode.Mul_ovf:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Mul, true, false));
                            break;
                        case PE.OpCode.Mul_ovf_un:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Mul, true, true));
                            break;
                        case PE.OpCode.Div:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Div, false, false));
                            break;
                        case PE.OpCode.Div_un:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Div, false, true));
                            break;
                        case PE.OpCode.Rem:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Rem, false, false));
                            break;
                        case PE.OpCode.Rem_un:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Rem, false, true));
                            break;
                        case PE.OpCode.Neg:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Neg, false, false));
                            break;
                        case PE.OpCode.And:
                            instructions.Add(new ArithInstruction(offset, ArithOp.BitAnd, false, false));
                            break;
                        case PE.OpCode.Or:
                            instructions.Add(new ArithInstruction(offset, ArithOp.BitOr, false, false));
                            break;
                        case PE.OpCode.Xor:
                            instructions.Add(new ArithInstruction(offset, ArithOp.BitXor, false, false));
                            break;
                        case PE.OpCode.Not:
                            instructions.Add(new ArithInstruction(offset, ArithOp.BitNot, false, false));
                            break;
                        case PE.OpCode.Shl:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Shl, false, false));
                            break;
                        case PE.OpCode.Shr:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Shr, false, false));
                            break;
                        case PE.OpCode.Shr_un:
                            instructions.Add(new ArithInstruction(offset, ArithOp.Shr, false, true));
                            break;
                        case PE.OpCode.Conv_i1:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int8, false, false));
                            break;
                        case PE.OpCode.Conv_u1:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt8, false, false));
                            break;
                        case PE.OpCode.Conv_i2:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int16, false, false));
                            break;
                        case PE.OpCode.Conv_u2:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt16, false, false));
                            break;
                        case PE.OpCode.Conv_i4:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int32, false, false));
                            break;
                        case PE.OpCode.Conv_u4:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt32, false, false));
                            break;
                        case PE.OpCode.Conv_i8:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int64, false, false));
                            break;
                        case PE.OpCode.Conv_u8:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt64, false, false));
                            break;
                        case PE.OpCode.Conv_i:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.IntNative, false, false));
                            break;
                        case PE.OpCode.Conv_u:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UIntNative, false, false));
                            break;
                        case PE.OpCode.Conv_r4:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Single, false, false));
                            break;
                        case PE.OpCode.Conv_r8:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Double, false, false));
                            break;
                        case PE.OpCode.Conv_r_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Double, false, true));
                            break;
                        case PE.OpCode.Conv_ovf_i1:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int8, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_u1:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt8, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_i2:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int16, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_u2:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt16, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_i4:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int32, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_u4:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt32, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_i8:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int64, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_u8:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt64, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_i:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.IntNative, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_u:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UIntNative, true, false));
                            break;
                        case PE.OpCode.Conv_ovf_i1_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int8, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_u1_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt8, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_i2_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int16, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_u2_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt16, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_i4_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int32, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_u4_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt32, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_i8_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.Int64, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_u8_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt64, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_i_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.IntNative, true, true));
                            break;
                        case PE.OpCode.Conv_ovf_u_un:
                            instructions.Add(new ConvInstruction(offset, NumberFlavor.UIntNative, true, true));
                            break;
                        default:
                            throw new InvalidOperationException("invalid instruction");

                        }
                    }
                }
            }

            // Must always contain at least one instruction, otherwise control would have fallen through
            if (instructions.Count == 0)
                throw new InvalidOperationException("empty instructions");

            return new Instructions(null, instructions);
        }
示例#35
0
        public object TransformModelPath(TranslationContext context, ObjectType sourceType, ASTNode node, string path)
        {
            switch (path)
            {
            // ClinicalStatement
            // templateId : List<CodedIdentifier>

            // id : II
            case "id": return(TranslateIdReference(context, sourceType, node, path));

            // dataSourceType : CD
            // evaluatedPersonId : II
            // extension : List<CodedNameValuePair>

            // SubstanceAdministrationBase
            // substanceAdministrationGeneralPurpose : CD
            // doseType : CD
            // substance : AdministrableSubstance
            // substance.substanceCode : CD
            case "substance.substanceCode": return(TranslateCodeReference(context, sourceType, node, path));

            // substance.strength : RTO_PQ
            case "substance.strength": return(GetPropertyExpression(context, node, "ProductConcentration"));                     // TODO: Translate RTO_PQ

            // substance.form : CD
            case "substance.form": return(GetPropertyExpression(context, node, "ProductForm"));                     // TODO: translate form?

            // substance.substanceBrandCode : CD
            case "substance.substanceBrandCode": return(GetPropertyExpression(context, node, "BrandName"));                     // TODO: Translate brand code?

            // substance.substanceGenericCode : CD
            // substance.manufacturer: CD
            case "substance.manufacturer": return(GetPropertyExpression(context, node, "DrugManufacturer"));                     // TODO: Translate code

            // substance.lotNo : ST

            // doseQuantity : IVL_PQ
            case "doseQuantity": return(GetPropertyExpression(context, node, "Dose"));                     // TODO: Translate PQ with DoseUnits?

            // deliveryRoute : CD
            case "deliveryRoute": return(GetPropertyExpression(context, node, "Route"));                     // TODO: Route mapping?

            // deliveryRate : IVL_PQ // Frequency?
            // dosingPeriod : IVL_PQ // Interval?
            // dosingPeriodIntevrvalIsImportant : BL
            // deliveryMethod : CD
            // approachBodySite : BodySite
            // targetBodySite : BodySite

            // SubstanceAdministrationEvent
            // doseNumber : INT
            // administrationTimeInterval : IVL_TS
            case "administrationTimeInterval": return(GetPropertyExpression(context, node, "StartDateTime"));                     // TODO: StopDateTime? Duration?

            // documentationTime : IVL_TS
            // informationAttestationType : CD
            // isValid : BL
            // relatedEntity : List<RelatedEntity>
            // relatedClinicalStatement : List<RelatedClinicalStatement>

            // SubstanceAdministrationOrder
            // criticality : CD
            // doseRestriction : DoseRestriction
            // administrationTimeInterval : IVL_TS
            // dosingSig : List<CD>
            // numberFillsAllowed : INT
            // orderEventTime : IVL_TS
            // relatedEntity : List<RelatedEntity>
            // relatedClinicalStatement : List<RelatedClinicalStatement>

            // SubstanceAdministrationProposal
            // criticality : CD
            // doseRestriction : DoseRestriction
            // proposedAdministrationTimeInterval : IVL_TS
            // validAdministrationTime : IVL_TS
            // numberFillsAllowed : INT
            // originationMode : CD
            // comment : List<Documentation>
            // prnReason : List<object>
            // infuseOver : IVL_PQ
            // timing : CD
            // relatedEntity : List<RelatedEntity>
            // relatedClinicalStatement : List<RelatedClinicalStatement>

            // UndeliveredSubstanceAdministration
            // reason : CD
            // subjectEffectiveTime : IVL_TS
            // documentationTime : IVL_TS
            // relatedEntity : List<RelatedEntity>
            // relatedClinicalStatement : List<RelatedClinicalStatement>

            default: throw new NotSupportedException(String.Format("Referenced property ({0}.{1}) does not have an equivalent CREF representation.", sourceType.Name, path));
            }
        }
示例#36
0
        public object TransformModelPath(TranslationContext context, ObjectType sourceType, ASTNode node, string path)
        {
            switch (path)
            {
            // ClinicalStatement
            // templateId : List<CodedIdentifier>

            // id : II
            case "id": return(TranslateIdReference(context, sourceType, node, path));

            // dataSourceType : CD
            // evaluatedPersonId : II
            // extension : List<CodedNameValuePair>

            // ObservationBase
            // observationFocus : CD
            case "observationFocus": return(TranslateCodeReference(context, sourceType, node, path));

            // observationMethod : CD
            // targetBodySite : BodySite

            // ObservationOrder
            // criticality : CD
            // orderEventTime : IVL_TS
            // observationTime : IVL_TS
            // repeatNumber : INT
            // relatedEntity : List<RelatedEntity>
            // relatedClinicalStatement : List<RelatedClinicalStatement>

            // ObservationProposal
            // criticality : CD
            // proposedObservationTime : IVL_TS
            // repeatNumber : INT
            // relatedEntity : List<RelatedEntity>
            // relatedClinicalStatement : List<RelatedClinicalStatement>

            // ObservationResult

            // observationEventTime : IVL_TS
            case "observationEventTime": return(GetPropertyExpression(context, node, "ResultDateTime"));                     // with Interval selector?

            // observationValue : ANY
            case "observationValue": return(GetPropertyExpression(context, node, "Value"));

            // interpretation : List<CD>
            case "interpretation":
            {
                var list = new CREFModel.ListExpression();
                list.Items.Add(GetPropertyExpression(context, node, "Interpretation"));     // TODO: Interpretation mapping?
                return(list);
            }

            // relatedEntity : List<RelatedEntity>
            // relatedClinicalStatement : List<RelatedClinicalStatement>

            // UnconductedObservation
            // reason : CD
            // subjectEffectiveTime : IVL_TS
            // documentationTime : IVL_TS
            // relatedEntity : List<RelatedEntity>
            // relatedClinicalStatement : List<RelatedClinicalStatement>

            default: throw new NotSupportedException(String.Format("Referenced property ({0}.{1}) does not have an equivalent CREF representation.", sourceType.Name, path));
            }
        }
示例#37
0
        // public static methods
        public static ExecutableQuery <TDocument, long> Translate <TDocument>(MongoQueryProvider <TDocument> provider, TranslationContext context, MethodCallExpression expression)
        {
            var method    = expression.Method;
            var arguments = expression.Arguments;

            if (method.IsOneOf(__longCountMethods))
            {
                var sourceExpression = arguments[0];
                var pipeline         = ExpressionToPipelineTranslator.Translate(context, sourceExpression);

                if (method.IsOneOf(__longCountWithPredicateMethods))
                {
                    var predicateLambda = ExpressionHelper.UnquoteLambda(arguments[1]);
                    var predicateFilter = ExpressionToFilterTranslator.TranslateLambda(context, predicateLambda, parameterSerializer: pipeline.OutputSerializer);

                    pipeline = pipeline.AddStages(
                        pipeline.OutputSerializer,
                        AstStage.Match(predicateFilter));
                }

                pipeline = pipeline.AddStages(
                    __wrappedInt64Serializer,
                    AstStage.Count("_v"));

                return(ExecutableQuery.Create(
                           provider.Collection,
                           provider.Options,
                           pipeline,
                           _finalizer));
            }

            throw new ExpressionNotSupportedException(expression);
        }
示例#38
0
 public ObjectType TransformModel(TranslationContext context, ObjectType sourceType)
 {
     return((ObjectType)CREFModel.DataTypes.ResolveType(typeof(AllscriptsModel.Medication)));
 }
示例#39
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="stream"></param>
 /// <param name="translationContext"></param>
 public override void Serialize(object obj, Stream stream, TranslationContext translationContext)
 {
     Serialize(obj, new BinaryWriter(stream), translationContext);
 }