Beispiel #1
0
        private void LoadStation(string file)
        {
            Playlist playlist = new Playlist();

            playlist.Load(file);

            MetaEntry helix_meta = playlist.FindMetaEntry("/BansheeXSPF:helix_required");

            if (!helix_meta.Equals(MetaEntry.Zero) && !AlwaysShowHelixStationsSchema.Get())
            {
                bool have_helix = false;
                foreach (Banshee.MediaEngine.PlayerEngine engine in PlayerEngineCore.Engines)
                {
                    if (engine.Id == "helix-remote")
                    {
                        have_helix = true;
                        break;
                    }
                }

                if (!have_helix)
                {
                    return;
                }
            }

            total_stations += playlist.Tracks.Count;
            station_groups.Add(playlist);
        }
Beispiel #2
0
        public void AppendMeta(MetaEntry meta, string contentSeparator)
        {
            if (meta == null)
            {
                return;
            }

            var index = meta.Name ?? meta.HttpEquiv;

            if (String.IsNullOrEmpty(index))
            {
                return;
            }

            if (_metas == null)
            {
                _metas = new Dictionary <string, MetaEntry>();
            }

            MetaEntry existingMeta;

            if (_metas.TryGetValue(index, out existingMeta))
            {
                meta = MetaEntry.Combine(existingMeta, meta, contentSeparator);
            }

            _metas[index] = meta;
        }
Beispiel #3
0
        public void SetMeta(string name = null, string content = null, string httpEquiv = null, string charset = null)
        {
            var metaEntry = new MetaEntry();

            if (!String.IsNullOrEmpty(name))
            {
                metaEntry.Name = name;
            }

            if (!String.IsNullOrEmpty(content))
            {
                metaEntry.Content = content;
            }

            if (!String.IsNullOrEmpty(httpEquiv))
            {
                metaEntry.HttpEquiv = httpEquiv;
            }

            if (!String.IsNullOrEmpty(charset))
            {
                metaEntry.Charset = charset;
            }

            SetMeta(metaEntry);
        }
        public async Task AppendMeta()
        {
            var resourceManager = new ResourceManager(
                Enumerable.Empty <IResourceManifestProvider>(),
                new ResourceManifestState(),
                new OptionsWrapper <ResourceManagementOptions>(new ResourceManagementOptions()),
                StubFileVersionProvider.Instance
                );

            var first = new MetaEntry(name: "keywords", content: "bar")
                        .AddAttribute("attr1", "val1");
            var second = new MetaEntry(name: "keywords", content: "baz")
                         .AddAttribute("attr2", "val2");

            resourceManager.AppendMeta(first, ",");
            resourceManager.AppendMeta(second, ",");

            var keywordsMeta = resourceManager.GetRegisteredMetas()
                               .FirstOrDefault(entry => entry.Name == "keywords");

            var document = await ParseHtmlAsync(keywordsMeta.GetTag());

            var meta = document
                       .QuerySelector <IHtmlMetaElement>("meta[name=keywords]");

            Assert.Equal("bar,baz", meta.Content);
            Assert.Contains(meta.Attributes, attr => attr.Name == "attr1" && attr.Value == "val1");
            Assert.Contains(meta.Attributes, attr => attr.Name == "attr2" && attr.Value == "val2");
        }
Beispiel #5
0
        public static MetaEntry BuildPropertyMetaTag(string metaKey, string propertyType, string value)
        {
            var metaEntry = new MetaEntry {
                Name = metaKey
            };

            metaEntry.SetAttribute("property", propertyType);
            metaEntry.SetAttribute("content", value);
            return(metaEntry);
        }
Beispiel #6
0
    public MetaEntry GetMeta(string metaName, string nodeName)
    {
        if (metas.Count > 0)
        {
            MetaEntry query = metas.Find(entry => (CompareString(entry.metaName, metaName) && CompareString(entry.nodeName, nodeName)));
            return(query);
        }

        return(null);
    }
Beispiel #7
0
    public MetaEntry GetMeta(string metaName)
    {
        if (metas.Count > 0)
        {
            MetaEntry query = metas.Find(entry => entry.metaName == metaName);
            return(query);
        }

        return(null);
    }
Beispiel #8
0
        /// <summary>
        ///     Converts the supplied CIL hint to a meta entry (including the CIL hint key).
        /// </summary>
        /// <param name = "hint">The CIL hint to serialize</param>
        /// <returns>The serialized cil hint.</returns>
        public static MetaEntry ToMetaEntry(this ICilHint hint)
        {
            var key = hint.CilKey;
            var fields = hint.GetFields();

            var entry = new MetaEntry[fields.Length + 1];
            entry[0] = key;
            Array.Copy(fields, 0, entry, 1, fields.Length);

            return (MetaEntry) entry;
        }
Beispiel #9
0
        void ExtractEntry(MetaEntry entry, bool decrypt = false)
        {
            if (decrypt && entry.Encrypted && passcode == null)
            {
                var gotPasscode = false;
                while (gotPasscode == false)
                {
                    gotPasscode = RequestPasscode();
                    if (gotPasscode)
                    {
                        break;
                    }
                    var result = MessageBox.Show(
                        "Sorry, that passcode was incorrect." + Environment.NewLine
                        + "Abort to cancel extraction, ignore to extract in encrypted form, retry to try a new passcode.",
                        "Invalid Passcode",
                        MessageBoxButtons.AbortRetryIgnore,
                        MessageBoxIcon.Warning);
                    if (result == DialogResult.Abort)
                    {
                        return;
                    }
                    if (result == DialogResult.Ignore)
                    {
                        break;
                    }
                }
            }
            var name = entry.NameTableOffset != 0 ? pkg.EntryNames.GetName(entry.NameTableOffset) : entry.id.ToString();

            if (new SaveFileDialog()
            {
                FileName = name
            } is SaveFileDialog s && s.ShowDialog() == DialogResult.OK)
            {
                using (var f = File.OpenWrite(s.FileName))
                    using (var entryStream = pkgFile.CreateViewStream(entry.DataOffset, entry.DataSize))
                    {
                        if (entry.Encrypted && decrypt && passcode != null)
                        {
                            var tmp = new byte[(entry.DataSize + 15) & ~15];
                            entryStream.Read(tmp, 0, tmp.Length);
                            tmp = Entry.Decrypt(tmp, pkg.Header.content_id, passcode, entry);
                            f.Write(tmp, 0, (int)entry.DataSize);
                        }
                        else
                        {
                            entryStream.CopyTo(f);
                        }
                    }
            }
        }
Beispiel #10
0
 public ForeachHint(MetaEntry[] hint)
 {
     if (hint == null)
         throw new ArgumentNullException("hint");
     if (hint.Length < EntryLength)
         throw new ArgumentException(string.Format("Hint must have at least {0} entries.",
             EntryLength));
     _enumVar = hint[EnumVarIndex + 1].Text;
     _castAddress = int.Parse(hint[CastAddressIndex + 1].Text);
     _getCurrentAddress = int.Parse(hint[GetCurrentAddressIndex + 1].Text);
     _moveNextAddress = int.Parse(hint[MoveNextAddressIndex + 1].Text);
     _disposeAddress = int.Parse(hint[DisposeAddressIndex + 1].Text);
 }
Beispiel #11
0
    public string GetMetaValue(string metaName, string nodeName)
    {
        if (metas.Count > 0)
        {
            MetaEntry query = metas.Find(entry => (CompareString(entry.metaName, metaName) && CompareString(entry.nodeName, nodeName)));
            if (query != null)
            {
                return(query.metaValue);
            }
        }

        return(null);
    }
        public void RegisterMeta()
        {
            var resourceManager = new ResourceManager(
                new OptionsWrapper <ResourceManagementOptions>(new ResourceManagementOptions()),
                StubFileVersionProvider.Instance
                );

            var metaEntry = new MetaEntry(name: "foo", content: "bar");

            resourceManager.RegisterMeta(metaEntry);

            var registeredMetas = resourceManager.GetRegisteredMetas();

            Assert.Contains(metaEntry, registeredMetas);
        }
Beispiel #13
0
        public void RegisterMeta(MetaEntry meta)
        {
            if (meta == null)
            {
                return;
            }

            if (_metas == null)
            {
                _metas = new Dictionary <string, MetaEntry>();
            }

            var index = meta.Name ?? meta.HttpEquiv ?? "charset";

            _metas[index] = meta;
        }
Beispiel #14
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var metaEntry = new MetaEntry(Name, Content, HttpEquiv, Charset);

            foreach (var attribute in output.Attributes)
            {
                if (String.Equals(attribute.Name, "name", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                metaEntry.SetAttribute(attribute.Name, attribute.Value.ToString());
            }

            _resourceManager.AppendMeta(metaEntry, Separator ?? ", ");

            output.TagName = null;
        }
Beispiel #15
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var metaEntry = new MetaEntry(Name, Content, HttpEquiv, Charset);

            foreach (var attribute in output.Attributes)
            {
                if (String.Equals(attribute.Name, "name", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                metaEntry.SetAttribute(attribute.Name, attribute.Value.ToString());
            }

            _resourceManager.AppendMeta(metaEntry, Separator ?? ", ");

            output.TagName = null;
        }
Beispiel #16
0
        private void CheckForUpdates(bool force)
        {
            if (!force && LastUpdateCheck - (DateTime.Now - check_timeout) > TimeSpan.Zero)
            {
                return;
            }

            Playlist playlist = new Playlist();

            playlist.Load(CreateXspfWebStream(master_xspf_uri));

            DateTime master_last_modified = DateTime.MinValue;

            MetaEntry meta = playlist.FindMetaEntry("/BansheeXSPF:last_modified");

            if (!meta.Equals(MetaEntry.Zero))
            {
                master_last_modified = W3CDateTime.Parse(meta.Value).LocalTime;
            }

            if (!force && master_last_modified <= LastUpdated)
            {
                return;
            }

            try {
                Directory.CreateDirectory(stations_path);

                foreach (string xspf_file in Directory.GetFiles(stations_path, "*.xspf"))
                {
                    File.Delete(xspf_file);
                }
            } catch {
            }

            foreach (Track station in playlist.Tracks)
            {
                DownloadStation(station.Locations[0]);
            }

            LastUpdated     = master_last_modified;
            LastUpdateCheck = DateTime.Now;
        }
Beispiel #17
0
        protected override DriverResult Display(OgMetaPart part, string displayType, dynamic shapeHelper)
        {
            if (displayType != "Detail")
            {
                return(null);
            }
            var resourceManager = _waContextAccessor.GetContext().Resolve <IResourceManager>();

            if (!String.IsNullOrWhiteSpace(part.Title))
            {
                var ogTitle = new MetaEntry {
                    Name = "ogtitle"
                };
                ogTitle.AddAttribute("property", "og:title");
                ogTitle.AddAttribute("content", part.Title);
                resourceManager.SetMeta(ogTitle);
            }
            if (!String.IsNullOrWhiteSpace(part.Type))
            {
                var ogType = new MetaEntry {
                    Name = "ogtype"
                };
                ogType.AddAttribute("property", "og:type");
                ogType.AddAttribute("content", part.Type);
                resourceManager.SetMeta(ogType);
            }
            if (!String.IsNullOrWhiteSpace(part.Url))
            {
                var ogUrl = new MetaEntry {
                    Name = "ogurl"
                };
                ogUrl.AddAttribute("property", "og:url");
                ogUrl.AddAttribute("content", part.Url);
                resourceManager.SetMeta(ogUrl);
            }
            if (!String.IsNullOrWhiteSpace(part.ImgUrl))
            {
                var ogImgUrl = new MetaEntry {
                    Name = "ogimg"
                };
                ogImgUrl.AddAttribute("property", "og:image");
                ogImgUrl.AddAttribute("content", part.ImgUrl);
                resourceManager.SetMeta(ogImgUrl);
            }
            if (!String.IsNullOrWhiteSpace(part.Description))
            {
                var ogDesc = new MetaEntry {
                    Name = "ogdesc"
                };
                ogDesc.AddAttribute("property", "og:description");
                ogDesc.AddAttribute("content", part.Description);
                resourceManager.SetMeta(ogDesc);
            }
            if (!String.IsNullOrWhiteSpace(part.SiteName))
            {
                var ogSiteName = new MetaEntry {
                    Name = "ogsitename"
                };
                ogSiteName.AddAttribute("property", "og:site_name");
                ogSiteName.AddAttribute("content", part.SiteName);
                resourceManager.SetMeta(ogSiteName);
            }
            return(null);
        }
Beispiel #18
0
 internal void _DetermineSharedNames()
 {
     var outerVars = new MetaEntry[_outerVariables.Count];
     var i = 0;
     foreach (var outerVar in _outerVariables)
         outerVars[i++] = outerVar;
     if (i > 0)
         Function.Meta[PFunction.SharedNamesKey] = (MetaEntry) outerVars;
 }
 public void AddMeta(MetaEntry newEntry)
 {
   metas.Add(newEntry);
 }
Beispiel #20
0
        /// <summary>
        ///     Parses CIL extension hint from a meta entry.
        /// </summary>
        /// <param name = "hint"></param>
        /// <returns></returns>
        public static CilExtensionHint FromMetaEntry(MetaEntry[] hint)
        {
            var offsets = new List<int>(hint.Length);
            foreach (var metaEntry in hint.Skip(1))
            {
                if (metaEntry == null)
                    continue;
                int offset;
                if (Int32.TryParse(metaEntry.Text, out offset))
                    offsets.Add(offset);
            }

            return new CilExtensionHint(offsets);
        }
Beispiel #21
0
        /// <summary>
        ///     Safely remoes a range of instructions without invalidating jumps or try-blocks. Notifies <see
        ///      cref = "AddressChangeHooks" />.
        /// </summary>
        /// <param name = "index">The address of the first instruction to remove.</param>
        /// <param name = "count">The number of instructions to remove.</param>
        public void RemoveInstructionRange(int index, int count)
        {
            var code = Code;
            if (index < 0 || index >= code.Count)
                throw new ArgumentOutOfRangeException("index");
            if (count < 0 || index + count > code.Count)
                throw new ArgumentOutOfRangeException("count");
            if (count == 0)
                return;

            //Remove the instruction
            code.RemoveRange(index, count);

            //Adapt source mapping
            SourceMapping.RemoveRange(index, count);

            //Correct jump targets by...);
            int i;
            for (i = 0; i < code.Count; i++)
            {
                var ins = code[i];
                if ((ins.IsJump || ins.OpCode == OpCode.leave)
                    && ins.Arguments > index) //decrementing target addresses pointing 
                    //behind the removed instruction
                    code[i] = ins.With(arguments: ins.Arguments - count);
            }

            //Correct try-catch-finally blocks
            var modifiedBlocks = new MetaEntry[_function.TryCatchFinallyBlocks.Count];
            i = 0;
            foreach (var block in _function.TryCatchFinallyBlocks)
            {
                if (block.BeginTry > index)
                    block.BeginTry -= count;
                if (block.BeginFinally > index)
                    block.BeginFinally -= count;
                if (block.BeginCatch > index)
                    block.BeginCatch -= count;
                if (block.EndTry > index)
                    block.EndTry -= count;

                if (!block.IsValid)
                    throw new PrexoniteException
                        (
                        "The try-catch-finally block (" + block +
                            ") is not valid after optimization.");

                modifiedBlocks[i++] = block;
            }
            _function.Meta[TryCatchFinallyBlock.MetaKey] = (MetaEntry) modifiedBlocks;

            //Change custom addresses into this code (e.g., cil compiler hints)
            foreach (var hook in _addressChangeHooks)
                if (hook.InstructionIndex > index)
                    hook.React(hook.InstructionIndex - count);
        }
Beispiel #22
0
        public static void SetCilHint(IHasMetaTable target, ICilHint newHint)
        {
            MetaEntry cilHints;
            if (target.Meta.TryGetValue(Loader.CilHintsKey, out cilHints))
            {
                var hints = cilHints.List;
                var replaced = false;
                var excessHints = 0;
                for (var i = 0; i < hints.Length; i++)
                {
                    var cilHint = hints[i].List;

                    //We're only interested in CIL hints that conflict with the new one.
                    if (!Engine.StringsAreEqual(cilHint[0].Text, newHint.CilKey))
                        continue;


                    if (replaced)
                    {
                        hints[i] = null;
                        excessHints++;
                    }
                    else
                    {
                        hints[i] = newHint.ToMetaEntry();
                        replaced = true;
                    }
                }

                if (excessHints == 0)
                {
                    if (!replaced)
                        target.Meta.AddTo(Loader.CilHintsKey, newHint.ToMetaEntry());
                    //otherwise the array has already been modified by ref.
                }
                else
                {
                    //need to resize array (and possibly add new CIL hint)
                    var newHints = new MetaEntry[hints.Length - excessHints + (replaced ? 0 : 1)];
                    int idxNew;
                    int idxOld;
                    for (idxNew = idxOld = 0; idxOld < hints.Length; idxOld++)
                    {
                        var oldHint = hints[idxOld];
                        if (oldHint == null)
                            continue;

                        newHints[idxNew++] = oldHint;
                    }
                    if (!replaced)
                        newHints[idxNew] = newHint.ToMetaEntry();

                    target.Meta[Loader.CilHintsKey] = (MetaEntry) newHints;
                }
            }
            else
            {
                target.Meta[Loader.CilHintsKey] = (MetaEntry) new[] {newHint.ToMetaEntry()};
            }
        }
Beispiel #23
0
        private static void _emitInstructions(CompilerState state)
        {
            //Tables of foreach call hint hooks
            var foreachCasts = new Dictionary<int, ForeachHint>();
            var foreachGetCurrents = new Dictionary<int, ForeachHint>();
            var foreachMoveNexts = new Dictionary<int, ForeachHint>();
            var foreachDisposes = new Dictionary<int, ForeachHint>();

            foreach (var hint in state._ForeachHints)
            {
                foreachCasts.Add(hint.CastAddress, hint);
                foreachGetCurrents.Add(hint.GetCurrentAddress, hint);
                foreachMoveNexts.Add(hint.MoveNextAddress, hint);
                foreachDisposes.Add(hint.DisposeAddress, hint);
            }

            var sourceCode = state.Source.Code;

            //CIL Extension
            var cilExtensionMode = false;
            List<CompileTimeValue> staticArgv = null;

            for (var instructionIndex = 0; instructionIndex < sourceCode.Count; instructionIndex++)
            {
                #region Handling for try-finally-catch blocks

                //Handle try-finally-catch blocks
                //Push new blocks
                foreach (var block in state.Seh.GetOpeningTryBlocks(instructionIndex))
                {
                    state.TryBlocks.Push(block);
                    if (block.HasFinally)
                        state.Il.BeginExceptionBlock();
                    if (block.HasCatch)
                        state.Il.BeginExceptionBlock();
                }

                //Handle active blocks
                if (state.TryBlocks.Count > 0)
                {
                    CompiledTryCatchFinallyBlock block;
                    do
                    {
                        block = state.TryBlocks.Peek();
                        if (instructionIndex == block.BeginFinally)
                        {
                            if (block.SkipTry == instructionIndex)
                            {
                                //state.Il.MarkLabel(block.SkipTryLabel);
                                state.Il.Emit(OpCodes.Nop);
                            }
                            state.Il.BeginFinallyBlock();
                        }
                        else if (instructionIndex == block.BeginCatch)
                        {
                            if (block.HasFinally)
                                state.Il.EndExceptionBlock(); //end finally here
                            state.Il.BeginCatchBlock(typeof (Exception));
                            //parse the exception
                            state.EmitLoadLocal(state.SctxLocal);
                            state.Il.EmitCall(OpCodes.Call, Runtime.ParseExceptionMethod, null);
                            //user code will store it in a local variable
                        }
                        else if (instructionIndex == block.EndTry)
                        {
                            if (block.HasFinally || block.HasCatch)
                                state.Il.EndExceptionBlock();
                            if (block.SkipTry == instructionIndex)
                            {
                                //state.Il.MarkLabel(block.SkipTryLabel);
                                state.Il.Emit(OpCodes.Nop);
                            }
                            state.TryBlocks.Pop();
                            block = null; //signal another loop iteration
                        }
                    } while (block == null && state.TryBlocks.Count > 0);
                }

                #endregion

                state.MarkInstruction(instructionIndex);

                var ins = sourceCode[instructionIndex];

                #region CIL hints

                // **** CIL hints ****
                //  * CIL Extension *
                {
                    if (state._CilExtensionOffsets.Count > 0 &&
                        state._CilExtensionOffsets.Peek() == instructionIndex)
                    {
                        state._CilExtensionOffsets.Dequeue();
                        if (staticArgv == null)
                            staticArgv = new List<CompileTimeValue>(8);
                        else
                            staticArgv.Clear();
                        cilExtensionMode = true;
                    }
                    if (cilExtensionMode)
                    {
                        CompileTimeValue compileTimeValue;
                        if (CompileTimeValue.TryParse(ins, state.IndexMap, state.Cache, state.Source.ParentApplication.Module.Name, out compileTimeValue))
                        {
                            staticArgv.Add(compileTimeValue);
                        }
                        else
                        {
                            //found the actual invocation of the CIL extension
                            cilExtensionMode = false;

                            switch (ins.OpCode)
                            {
                                case OpCode.cmd:
                                    PCommand command;
                                    ICilExtension extension;
                                    if (
                                        !state.TargetEngine.Commands.TryGetValue(ins.Id, out command) ||
                                            (extension = command as ICilExtension) == null)
                                        goto default;

                                    extension.Implement(state, ins, staticArgv.ToArray(),
                                        ins.Arguments - staticArgv.Count);
                                    break;
                                default:
                                    throw new PrexoniteException(
                                        "The CIL compiler does not support CIL extensions for this opcode: " +
                                            ins);
                            }
                        }
                        continue;
                    }
                }
                //  * Foreach *
                {
                    ForeachHint hint;
                    if (foreachCasts.TryGetValue(instructionIndex, out hint))
                    {
                        //result of (expr).GetEnumerator on the stack
                        //cast IEnumerator
                        state.EmitLoadLocal(state.SctxLocal);
                        state.Il.EmitCall(OpCodes.Call, Runtime.ExtractEnumeratorMethod, null);
                        instructionIndex++;
                        //stloc enum
                        state.EmitStoreLocal(state.Symbols[hint.EnumVar].Local);
                        continue;
                    }
                    else if (foreachGetCurrents.TryGetValue(instructionIndex, out hint))
                    {
                        //ldloc enum
                        state.EmitLoadLocal(state.Symbols[hint.EnumVar].Local);
                        instructionIndex++;
                        //get.0 Current
                        state.Il.EmitCall(OpCodes.Callvirt, ForeachHint.GetCurrentMethod, null);
                        //result will be stored by user code
                        continue;
                    }
                    else if (foreachMoveNexts.TryGetValue(instructionIndex, out hint))
                    {
                        //ldloc enum
                        state.EmitLoadLocal(state.Symbols[hint.EnumVar].Local);
                        instructionIndex++;
                        //get.0 MoveNext
                        state.Il.EmitCall(OpCodes.Callvirt, ForeachHint.MoveNextMethod, null);
                        instructionIndex++;
                        //jump.t begin
                        var target = sourceCode[instructionIndex].Arguments; //read from user code
                        state.Il.Emit(OpCodes.Brtrue, state.InstructionLabels[target]);
                        continue;
                    }
                    else if (foreachDisposes.TryGetValue(instructionIndex, out hint))
                    {
                        //ldloc enum
                        state.EmitLoadLocal(state.Symbols[hint.EnumVar].Local);
                        instructionIndex++;
                        //@cmd.1 dispose
                        state.Il.EmitCall(OpCodes.Callvirt, ForeachHint.DisposeMethod, null);
                        continue;
                    }
                }

                #endregion

                //  * Normal code generation *
                //Decode instruction
                var argc = ins.Arguments;
                var justEffect = ins.JustEffect;
                var id = ins.Id;
                int idx;
                string methodId;
                string typeExpr;
                var moduleName = ins.ModuleName;

                //Emit code for the instruction
                switch (ins.OpCode)
                {
                        #region NOP

                        //NOP
                    case OpCode.nop:
                        //Do nothing
                        state.Il.Emit(OpCodes.Nop);
                        break;

                        #endregion

                        #region LOAD

                        #region LOAD CONSTANT

                        //LOAD CONSTANT
                    case OpCode.ldc_int:
                        state.EmitLoadIntAsPValue(argc);
                        break;
                    case OpCode.ldc_real:
                        state.EmitLoadRealAsPValue(ins);
                        break;
                    case OpCode.ldc_bool:
                        state.EmitLoadBoolAsPValue(argc != 0);
                        break;
                    case OpCode.ldc_string:
                        state.EmitLoadStringAsPValue(id);
                        break;

                    case OpCode.ldc_null:
                        state.EmitLoadNullAsPValue();
                        break;

                        #endregion LOAD CONSTANT

                        #region LOAD REFERENCE

                        //LOAD REFERENCE
                    case OpCode.ldr_loc:
                        state.EmitLoadLocalRefAsPValue(id);
                        break;
                    case OpCode.ldr_loci:
                        id = state.IndexMap[argc];
                        goto case OpCode.ldr_loc;
                    case OpCode.ldr_glob:
                        state.EmitLoadGlobalRefAsPValue(id, moduleName);
                        break;
                    case OpCode.ldr_func:
                        state.EmitLoadFuncRefAsPValue(id, moduleName);
                        break;
                    case OpCode.ldr_cmd:
                        state.EmitLoadCmdRefAsPValue(id);
                        break;
                    case OpCode.ldr_app:
                        CompilerState.EmitLoadAppRefAsPValue(state);
                        break;
                    case OpCode.ldr_eng:
                        state.EmitLoadEngRefAsPValue();
                        break;
                    case OpCode.ldr_type:
                        state.EmitPTypeAsPValue(id);
                        break;
                    case OpCode.ldr_mod:
                        state.EmitModuleNameAsPValue(moduleName);
                        break;

                        #endregion //LOAD REFERENCE

                        #endregion //LOAD

                        #region VARIABLES

                        #region LOCAL

                        //LOAD LOCAL VARIABLE
                    case OpCode.ldloc:
                        state.EmitLoadPValue(state.Symbols[id]);
                        break;
                    case OpCode.stloc:
                        //Don't use EmitStorePValue here, because this is a more efficient solution
                        var sym = state.Symbols[id];
                        if (sym.Kind == SymbolKind.Local)
                        {
                            state.EmitStoreLocal(sym.Local.LocalIndex);
                        }
                        else if (sym.Kind == SymbolKind.LocalRef)
                        {
                            state.EmitStoreLocal(state.PrimaryTempLocal.LocalIndex);
                            state.EmitLoadLocal(sym.Local.LocalIndex);
                            state.EmitLoadLocal(state.PrimaryTempLocal.LocalIndex);
                            state.Il.EmitCall(OpCodes.Call, SetValueMethod, null);
                        }
                        break;

                    case OpCode.ldloci:
                        id = state.IndexMap[argc];
                        goto case OpCode.ldloc;

                    case OpCode.stloci:
                        id = state.IndexMap[argc];
                        goto case OpCode.stloc;

                        #endregion

                        #region GLOBAL

                        //LOAD GLOBAL VARIABLE
                    case OpCode.ldglob:
                        state.EmitLoadGlobalValue(id, moduleName);
                        break;
                    case OpCode.stglob:
                        state.EmitStoreLocal(state.PrimaryTempLocal);
                        state.EmitLoadGlobalReference(id,moduleName);
                        state.EmitLoadLocal(state.PrimaryTempLocal);
                        state.Il.EmitCall(OpCodes.Call, SetValueMethod, null);
                        break;

                        #endregion

                        #endregion

                        #region CONSTRUCTION

                        //CONSTRUCTION
                    case OpCode.newobj:
                        state.EmitNewObj(id, argc);
                        break;
                    case OpCode.newtype:
                        state.FillArgv(argc);
                        state.EmitLoadLocal(state.SctxLocal);
                        state.ReadArgv(argc);
                        state.Il.Emit(OpCodes.Ldstr, id);
                        state.Il.EmitCall(OpCodes.Call, Runtime.NewTypeMethod, null);
                        break;

                    case OpCode.newclo:
                        //Collect shared variables
                        MetaEntry[] entries;
                        var func = state.Source.ParentApplication.Functions[id];
                        if (func.Meta.ContainsKey(PFunction.SharedNamesKey))
                            entries = func.Meta[PFunction.SharedNamesKey].List;
                        else
                            entries = new MetaEntry[] {};
                        var hasSharedVariables = entries.Length > 0;
                        if (hasSharedVariables)
                        {
                            state.EmitLdcI4(entries.Length);
                            state.Il.Emit(OpCodes.Newarr, typeof (PVariable));
                            state.EmitStoreLocal(state.SharedLocal);
                            for (var i = 0; i < entries.Length; i++)
                            {
                                state.EmitLoadLocal(state.SharedLocal);
                                state.EmitLdcI4(i);
                                state.EmitLoadLocal(state.Symbols[entries[i].Text].Local);
                                state.Il.Emit(OpCodes.Stelem_Ref);
                            }
                        }
                        state.EmitLoadLocal(state.SctxLocal);
                        if (hasSharedVariables)
                            state.EmitLoadLocal(state.SharedLocal);
                        else
                            state.Il.Emit(OpCodes.Ldnull);

                        state.EmitNewClo(id,moduleName);
                        break;

                    case OpCode.newcor:
                        state.FillArgv(argc);
                        state.EmitLoadLocal(state.SctxLocal);
                        state.ReadArgv(argc);
                        state.Il.EmitCall(OpCodes.Call, Runtime.NewCoroutineMethod, null);
                        break;

                        #endregion

                        #region OPERATORS

                        #region UNARY

                        //UNARY OPERATORS
                    case OpCode.incloc:
                        sym = state.Symbols[id];
                        if (sym.Kind == SymbolKind.Local)
                        {
                            state.EmitLoadLocal(sym.Local);
                            state.EmitLoadLocal(state.SctxLocal);
                            state.Il.EmitCall(OpCodes.Call, PVIncrementMethod, null);
                            state.EmitStoreLocal(sym.Local);
                        }
                        else if (sym.Kind == SymbolKind.LocalRef)
                        {
                            state.EmitLoadLocal(sym.Local);
                            state.Il.Emit(OpCodes.Dup);
                            state.Il.EmitCall(OpCodes.Call, GetValueMethod, null);
                            state.EmitLoadLocal(state.SctxLocal);
                            state.Il.EmitCall(OpCodes.Call, PVIncrementMethod, null);
                            state.Il.EmitCall(OpCodes.Call, SetValueMethod, null);
                        }
                        break;

                    case OpCode.incloci:
                        id = state.IndexMap[argc];
                        goto case OpCode.incloc;

                    case OpCode.incglob:
                        state.EmitLoadGlobalReference(id,moduleName);
                        state.Il.Emit(OpCodes.Dup);
                        state.Il.EmitCall(OpCodes.Call, GetValueMethod, null);
                        state.EmitLoadLocal(state.SctxLocal);
                        state.Il.EmitCall(OpCodes.Call, PVIncrementMethod, null);
                        state.Il.EmitCall(OpCodes.Call, SetValueMethod, null);
                        break;

                    case OpCode.decloc:
                        sym = state.Symbols[id];
                        if (sym.Kind == SymbolKind.Local)
                        {
                            state.EmitLoadLocal(sym.Local);
                            state.EmitLoadLocal(state.SctxLocal);
                            state.Il.EmitCall(OpCodes.Call, PVDecrementMethod, null);
                            state.EmitStoreLocal(sym.Local);
                        }
                        else if (sym.Kind == SymbolKind.LocalRef)
                        {
                            state.EmitLoadLocal(sym.Local);
                            state.Il.Emit(OpCodes.Dup);
                            state.Il.EmitCall(OpCodes.Call, GetValueMethod, null);
                            state.EmitLoadLocal(state.SctxLocal);
                            state.Il.EmitCall(OpCodes.Call, PVDecrementMethod, null);
                            state.Il.EmitCall(OpCodes.Call, SetValueMethod, null);
                        }
                        break;
                    case OpCode.decloci:
                        id = state.IndexMap[argc];
                        goto case OpCode.decloc;

                    case OpCode.decglob:
                        state.EmitLoadGlobalReference(id,moduleName);
                        state.Il.Emit(OpCodes.Dup);
                        state.Il.EmitCall(OpCodes.Call, GetValueMethod, null);
                        state.EmitLoadLocal(state.SctxLocal);
                        state.Il.EmitCall(OpCodes.Call, PVDecrementMethod, null);
                        state.Il.EmitCall(OpCodes.Call, SetValueMethod, null);
                        break;

                        #endregion

                        #region BINARY

                        // all binary operators are implemented as CIL extensions in
                        //  Prexonite.Commands.Core.Operators

                        #endregion //OPERATORS

                        #endregion

                        #region TYPE OPERATIONS

                        #region TYPE CHECK

                        //TYPE CHECK
                    case OpCode.check_const:
                        //Stack:
                        //  Obj
                        state.EmitLoadType(id);
                        //Stack:
                        //  Obj
                        //  Type
                        state.EmitCall(Runtime.CheckTypeConstMethod);
                        break;
                    case OpCode.check_arg:
                        //Stack: 
                        //  Obj
                        //  Type
                        state.Il.EmitCall(OpCodes.Call, Runtime.CheckTypeMethod, null);
                        break;

                    case OpCode.check_null:
                        state.Il.EmitCall(OpCodes.Call, PVIsNullMethod, null);
                        state.Il.Emit(OpCodes.Box, typeof (bool));
                        state.Il.EmitCall(OpCodes.Call, GetBoolPType, null);
                        state.Il.Emit(OpCodes.Newobj, NewPValue);
                        break;

                        #endregion

                        #region TYPE CAST

                    case OpCode.cast_const:
                        //Stack:
                        //  Obj
                        state.EmitLoadType(id);
                        //Stack:
                        //  Obj
                        //  Type
                        state.EmitLoadLocal(state.SctxLocal);
                        state.EmitCall(Runtime.CastConstMethod);

                        break;
                    case OpCode.cast_arg:
                        //Stack
                        //  Obj
                        //  Type
                        state.EmitLoadLocal(state.SctxLocal);
                        state.Il.EmitCall(OpCodes.Call, Runtime.CastMethod, null);
                        break;

                        #endregion

                        #endregion

                        #region OBJECT CALLS

                        #region DYNAMIC

                    case OpCode.get:
                        state.FillArgv(argc);
                        state.EmitLoadLocal(state.SctxLocal);
                        state.ReadArgv(argc);
                        state.EmitLdcI4((int) PCall.Get);
                        state.Il.Emit(OpCodes.Ldstr, id);
                        state.Il.EmitCall(OpCodes.Call, PVDynamicCallMethod, null);
                        if (justEffect)
                            state.Il.Emit(OpCodes.Pop);
                        break;

                    case OpCode.set:
                        state.FillArgv(argc);
                        state.EmitLoadLocal(state.SctxLocal);
                        state.ReadArgv(argc);
                        state.EmitLdcI4((int) PCall.Set);
                        state.Il.Emit(OpCodes.Ldstr, id);
                        state.Il.EmitCall(OpCodes.Call, PVDynamicCallMethod, null);
                        state.Il.Emit(OpCodes.Pop);
                        break;

                        #endregion

                        #region STATIC

                    case OpCode.sget:
                        //Stack:
                        //  arg
                        //   .
                        //   .
                        //   .
                        state.FillArgv(argc);
                        idx = id.LastIndexOf("::");
                        if (idx < 0)
                            throw new PrexoniteException
                                (
                                "Invalid sget instruction. Does not specify a method.");
                        methodId = id.Substring(idx + 2);
                        typeExpr = id.Substring(0, idx);
                        state.EmitLoadType(typeExpr);
                        state.EmitLoadLocal(state.SctxLocal);
                        state.ReadArgv(argc);
                        state.EmitLdcI4((int) PCall.Get);
                        state.Il.Emit(OpCodes.Ldstr, methodId);
                        state.EmitVirtualCall(Runtime.StaticCallMethod);
                        if (justEffect)
                            state.Il.Emit(OpCodes.Pop);
                        break;

                    case OpCode.sset:
                        state.FillArgv(argc);
                        idx = id.LastIndexOf("::");
                        if (idx < 0)
                            throw new PrexoniteException
                                (
                                "Invalid sset instruction. Does not specify a method.");
                        methodId = id.Substring(idx + 2);
                        typeExpr = id.Substring(0, idx);
                        state.EmitLoadType(typeExpr);
                        state.EmitLoadLocal(state.SctxLocal);
                        state.ReadArgv(argc);
                        state.EmitLdcI4((int) PCall.Set);
                        state.Il.Emit(OpCodes.Ldstr, methodId);
                        state.EmitVirtualCall(Runtime.StaticCallMethod);
                        state.Il.Emit(OpCodes.Pop);
                        break;

                        #endregion

                        #endregion

                        #region INDIRECT CALLS

                    case OpCode.indloc:
                        sym = state.Symbols[id];
                        if (sym == null)
                            throw new PrexoniteException(
                                "Internal CIL compiler error. Information about local entity " + id +
                                    " missing.");
                        state.FillArgv(argc);
                        sym.EmitLoad(state);
                        state.EmitIndirectCall(argc, justEffect);
                        break;

                    case OpCode.indloci:
                        idx = argc & ushort.MaxValue;
                        argc = (argc & (ushort.MaxValue << 16)) >> 16;
                        id = state.IndexMap[idx];
                        goto case OpCode.indloc;

                    case OpCode.indglob:
                        state.FillArgv(argc);
                        state.EmitLoadGlobalValue(id,moduleName);
                        state.EmitIndirectCall(argc, justEffect);
                        break;

                    case OpCode.indarg:
                        //Stack
                        //  obj
                        //  args
                        state.FillArgv(argc);
                        state.EmitIndirectCall(argc, justEffect);
                        break;

                    case OpCode.tail:
                        throw new PrexoniteException(
                            "Cannot compile tail instruction to CIL. Qualification should have failed.");

                        #endregion

                        #region ENGINE CALLS

                    case OpCode.func:
                        state.EmitFuncCall(argc, id, moduleName, justEffect);
                        break;
                    case OpCode.cmd:
                        state.EmitCommandCall(ins);
                        break;

                        #endregion

                        #region FLOW CONTROL

                        //FLOW CONTROL

                        #region JUMPS

                    case OpCode.jump:
                    case OpCode.jump_t:
                    case OpCode.jump_f:
                    case OpCode.ret_break:
                    case OpCode.ret_continue:
                        state.Seh.EmitJump(instructionIndex, ins);
                        break;

                        #endregion

                        #region RETURNS

                    case OpCode.ret_exit:
                        goto case OpCode.jump;

                    case OpCode.ret_value:
                        //return value is assigned by SEH
                        goto case OpCode.jump;

                    case OpCode.ret_set:
                        state.EmitSetReturnValue();
                        break;

                        #endregion

                        #region THROW

                    case OpCode.@throw:
                        state.EmitLoadLocal(state.SctxLocal);
                        state.Il.EmitCall(OpCodes.Call, Runtime.ThrowExceptionMethod, null);
                        break;

                        #endregion

                        #region LEAVE

                    case OpCode.@try:
                        //Is done via analysis of TryCatchFinally objects associated with the function
                        Debug.Assert(state.StackSize[instructionIndex] == 0,
                            "The stack should be empty when entering a try-block.",
                            "The stack is not empty when entering the try-block at instruction {0} in function {1}.",
                            instructionIndex, state.Source);
                        break;

                    case OpCode.leave:
                        //is handled by the CLR

                        #endregion

                        #region EXCEPTION

                    case OpCode.exc:
                        //is not implemented via Emit
                        // The exception is stored when the exception block is entered.
                        break;

                        #endregion

                        #endregion

                        #region STACK MANIPULATION

                        //STACK MANIPULATION
                    case OpCode.pop:
                        for (var i = 0; i < argc; i++)
                            state.Il.Emit(OpCodes.Pop);
                        break;
                    case OpCode.dup:
                        for (var i = 0; i < argc; i++)
                            state.Il.Emit(OpCodes.Dup);
                        break;
                    case OpCode.rot:
                        var values = (int) ins.GenericArgument;
                        var rotations = argc;
                        for (var i = 0; i < values; i++)
                            state.EmitStoreLocal
                                (
                                    state.TempLocals[(i + rotations)%values].LocalIndex);
                        for (var i = values - 1; i >= 0; i--)
                            state.EmitLoadLocal(state.TempLocals[i].LocalIndex);
                        break;

                        #endregion
                } //end of switch over opcode

                //DON'T ADD ANY CODE HERE, A LOT OF CASES USE `CONTINUE`
            } // end of loop over instructions

            //Close all pending try blocks, since the next instruction will never come
            //  (other closing try blocks are handled by the emitting the instruction immediately following 
            //  the try block)
            foreach (var block in state.TryBlocks)
            {
                if (block.HasCatch || block.HasFinally)
                    state.Il.EndExceptionBlock();
            }

            //Implicit return
            //Often instructions refer to a virtual instruction after the last real one.
            state.MarkInstruction(sourceCode.Count);
            state.Il.MarkLabel(state.ReturnLabel);
            state.Il.Emit(OpCodes.Ret);
        }
Beispiel #24
0
        public void SetMeta(string name = null, string content = null, string httpEquiv = null, string charset = null)
        {
            var metaEntry = new MetaEntry(name, content, httpEquiv, charset);

            SetMeta(metaEntry);
        }
Beispiel #25
0
 public void AddMeta(MetaEntry newEntry)
 {
     metas.Add(newEntry);
 }
Beispiel #26
0
 public virtual void AppendMeta(MetaEntry meta, string contentSeparator)
 {
     Html.GetWorkContext().Resolve <IResourceManager>().AppendMeta(meta, contentSeparator);
 }
Beispiel #27
0
 public MetaEntry[] GetFields()
 {
     var fields = new MetaEntry[EntryLength];
     fields[EnumVarIndex] = EnumVar;
     fields[CastAddressIndex] = CastAddress.ToString();
     fields[GetCurrentAddressIndex] = GetCurrentAddress.ToString();
     fields[MoveNextAddressIndex] = MoveNextAddress.ToString();
     fields[DisposeAddressIndex] = DisposeAddress.ToString();
     return fields;
 }
Beispiel #28
0
        private static void _analysisAndPreparation(CompilerState state)
        {
            var tempMaxOrder = 1; // 
            var needsSharedVariables = false;

            foreach (var ins in state.Source.Code.InReverse())
            {
                string toConvert;
                switch (ins.OpCode)
                {
                    case OpCode.ldr_loci:
                        //see ldr_loc
                        toConvert = state.IndexMap[ins.Arguments];
                        goto Convert;
                    case OpCode.ldr_loc:
                        toConvert = ins.Id;
                        Convert:

                        //Normal local variables are implemented as CIL locals.
                        // If the function uses variable references, they must be converted to reference variables.
                        state.Symbols[toConvert].Kind = SymbolKind.LocalRef;
                        break;
                    case OpCode.rot:
                        //Determine the maximum number of temporary variables for the implementation of rot[ate]
                        var order = (int) ins.GenericArgument;
                        if (order > tempMaxOrder)
                            tempMaxOrder = order;
                        break;
                    case OpCode.newclo:
                        MetaEntry[] entries;
                        var func = state.Source.ParentApplication.Functions[ins.Id];
                        MetaEntry entry;
                        if (func.Meta.ContainsKey(PFunction.SharedNamesKey) &&
                            (entry = func.Meta[PFunction.SharedNamesKey]).IsList)
                            entries = entry.List;
                        else
                            entries = new MetaEntry[] {};
                        foreach (var t in entries)
                        {
                            var symbolName = t.Text;
                            if (!state.Symbols.ContainsKey(symbolName))
                                throw new PrexoniteException
                                    (func + " does not contain a mapping for the symbol " +
                                        symbolName);

                            //In order for variables to be shared, they too, need to be converted to reference locals.
                            state.Symbols[symbolName].Kind = SymbolKind.LocalRef;
                        }

                        //Notify the compiler of the presence of closures with shared variables
                        needsSharedVariables = needsSharedVariables || entries.Length > 0;
                        break;
                }
            }

            //Create temporary variables for rotation
            state.TempLocals = new LocalBuilder[tempMaxOrder];
            for (var i = 0; i < tempMaxOrder; i++)
            {
                var rotTemp = state.Il.DeclareLocal(typeof (PValue));
                state.TempLocals[i] = rotTemp;
            }

            //Create temporary variable for argv and sharedVariables
            state.ArgvLocal = state.Il.DeclareLocal(typeof (PValue[]));
            state.SharedLocal = needsSharedVariables
                ? state.Il.DeclareLocal(typeof (PVariable[]))
                : null;

            //Create argc local variable and initialize it, if needed
            if (state.Source.Parameters.Count > 0)
            {
                state.ArgcLocal = state.Il.DeclareLocal(typeof (Int32));
                state.EmitLoadArg(CompilerState.ParamArgsIndex);
                state.Il.Emit(OpCodes.Ldlen);
                state.Il.Emit(OpCodes.Conv_I4);
                state.EmitStoreLocal(state.ArgcLocal);
            }

            //Determine stack size at every instruction
            _determineStackSize(state);
        }
Beispiel #29
0
 public virtual void AppendMeta(MetaEntry meta, string contentSeparator)
 {
     ResourceManager.AppendMeta(meta, contentSeparator);
 }
Beispiel #30
0
 public virtual void SetMeta(MetaEntry meta)
 {
     ResourceManager.SetMeta(meta);
 }
Beispiel #31
0
 private RefSpec _parseRefSpec(MetaEntry entry)
 {
     ModuleName moduleName;
     string text = null;
     if (entry.IsText && _fileReferencePattern.IsMatch(text = entry.Text))
     {
         // This is a file path reference specification
         return new RefSpec { RawPath = text };
     }
     else if (ModuleName.TryParse(entry, out moduleName))
     {
         // This is a module name reference specification
         return new RefSpec { ModuleName = moduleName };
     }
     else
     {
         // This is an invalid reference specification
         return new RefSpec
                    {
                        RawPath = text ?? entry.Text,
                        ErrorMessage = "The reference specification is neither a path nor a module name."
                    };
     }
 }
Beispiel #32
0
        protected override DriverResult Display(TwitterDataPart part, string displayType, dynamic shapeHelper)
        {
            if (displayType != "Detail")
            {
                return(null);
            }
            var resourceManager = _workContextAccessor.GetContext().Resolve <IResourceManager>();

            if (!String.IsNullOrWhiteSpace(part.TwitterCard))
            {
                var cardData = new MetaEntry
                {
                    Name    = "twitter:card",
                    Content = part.TwitterCard
                };
                resourceManager.SetMeta(cardData);
            }
            if (!String.IsNullOrWhiteSpace(part.TwitterSite))
            {
                var cardSite = new MetaEntry
                {
                    Name    = "twitter:site",
                    Content = part.TwitterSite
                };
                resourceManager.SetMeta(cardSite);
            }
            if (!String.IsNullOrWhiteSpace(part.TwitterTitle))
            {
                var cardTitle = new MetaEntry
                {
                    Name    = "twitter:title",
                    Content = part.TwitterTitle
                };
                resourceManager.SetMeta(cardTitle);
            }
            if (!String.IsNullOrWhiteSpace(part.TwitterDesc))
            {
                var cardDesc = new MetaEntry
                {
                    Name    = "twitter:description",
                    Content = part.TwitterDesc
                };
                resourceManager.SetMeta(cardDesc);
            }
            if (!String.IsNullOrWhiteSpace(part.Creator))
            {
                var cardCreator = new MetaEntry
                {
                    Name    = "twitter:creator",
                    Content = part.Creator
                };
                resourceManager.SetMeta(cardCreator);
            }
            if (!String.IsNullOrWhiteSpace(part.ImageUrl))
            {
                var cardImageUrl = new MetaEntry
                {
                    Name    = "twitter:image",
                    Content = part.ImageUrl
                };
                resourceManager.SetMeta(cardImageUrl);
            }
            return(null);
        }
Beispiel #33
0
 protected override void SetTransformed(string key, MetaEntry entry)
 {
     _table[key] = entry;
 }
Beispiel #34
0
 public static ForeachHint FromMetaEntry(MetaEntry[] entry)
 {
     return new ForeachHint(entry);
 }
Beispiel #35
0
 protected override bool TryGetValueTransformed(string key, out MetaEntry entry)
 {
     return _table.TryGetValue(key, out entry);
 }
Beispiel #36
0
 public virtual void SetMeta(MetaEntry meta)
 {
     Html.GetWorkContext().Resolve <IResourceManager>().SetMeta(meta);
 }
Beispiel #37
0
 protected override void AddTransformed(string key, MetaEntry item)
 {
     _table.Add(key,item);
 }
Beispiel #38
0
        private void ProcessMetaEntries()
        {
            var entry = MetaEntry.GetReader().ToJournalEntry <CompleteJournalEntry>();

            _filteredIndex.Add(entry);
        }
Beispiel #39
0
 /// <summary>
 /// Set meta data for page
 /// </summary>
 /// <param name="metaEntry"></param>
 /// <returns></returns>
 public MvcHtmlString SetMeta(MetaEntry metaEntry)
 {
     return(new MvcHtmlString(metaEntry.GetTag()));
 }